1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 54 using namespace clang; 55 using namespace sema; 56 using llvm::RoundingMode; 57 58 /// Determine whether the use of this declaration is valid, without 59 /// emitting diagnostics. 60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 61 // See if this is an auto-typed variable whose initializer we are parsing. 62 if (ParsingInitForAutoVars.count(D)) 63 return false; 64 65 // See if this is a deleted function. 66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 67 if (FD->isDeleted()) 68 return false; 69 70 // If the function has a deduced return type, and we can't deduce it, 71 // then we can't use it either. 72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 74 return false; 75 76 // See if this is an aligned allocation/deallocation function that is 77 // unavailable. 78 if (TreatUnavailableAsInvalid && 79 isUnavailableAlignedAllocationFunction(*FD)) 80 return false; 81 } 82 83 // See if this function is unavailable. 84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 86 return false; 87 88 if (isa<UnresolvedUsingIfExistsDecl>(D)) 89 return false; 90 91 return true; 92 } 93 94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 95 // Warn if this is used but marked unused. 96 if (const auto *A = D->getAttr<UnusedAttr>()) { 97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 98 // should diagnose them. 99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 102 if (DC && !DC->hasAttr<UnusedAttr>()) 103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 104 } 105 } 106 } 107 108 /// Emit a note explaining that this function is deleted. 109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 110 assert(Decl && Decl->isDeleted()); 111 112 if (Decl->isDefaulted()) { 113 // If the method was explicitly defaulted, point at that declaration. 114 if (!Decl->isImplicit()) 115 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 116 117 // Try to diagnose why this special member function was implicitly 118 // deleted. This might fail, if that reason no longer applies. 119 DiagnoseDeletedDefaultedFunction(Decl); 120 return; 121 } 122 123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 124 if (Ctor && Ctor->isInheritingConstructor()) 125 return NoteDeletedInheritingConstructor(Ctor); 126 127 Diag(Decl->getLocation(), diag::note_availability_specified_here) 128 << Decl << 1; 129 } 130 131 /// Determine whether a FunctionDecl was ever declared with an 132 /// explicit storage class. 133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 134 for (auto I : D->redecls()) { 135 if (I->getStorageClass() != SC_None) 136 return true; 137 } 138 return false; 139 } 140 141 /// Check whether we're in an extern inline function and referring to a 142 /// variable or function with internal linkage (C11 6.7.4p3). 143 /// 144 /// This is only a warning because we used to silently accept this code, but 145 /// in many cases it will not behave correctly. This is not enabled in C++ mode 146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 147 /// and so while there may still be user mistakes, most of the time we can't 148 /// prove that there are errors. 149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 150 const NamedDecl *D, 151 SourceLocation Loc) { 152 // This is disabled under C++; there are too many ways for this to fire in 153 // contexts where the warning is a false positive, or where it is technically 154 // correct but benign. 155 if (S.getLangOpts().CPlusPlus) 156 return; 157 158 // Check if this is an inlined function or method. 159 FunctionDecl *Current = S.getCurFunctionDecl(); 160 if (!Current) 161 return; 162 if (!Current->isInlined()) 163 return; 164 if (!Current->isExternallyVisible()) 165 return; 166 167 // Check if the decl has internal linkage. 168 if (D->getFormalLinkage() != InternalLinkage) 169 return; 170 171 // Downgrade from ExtWarn to Extension if 172 // (1) the supposedly external inline function is in the main file, 173 // and probably won't be included anywhere else. 174 // (2) the thing we're referencing is a pure function. 175 // (3) the thing we're referencing is another inline function. 176 // This last can give us false negatives, but it's better than warning on 177 // wrappers for simple C library functions. 178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 180 if (!DowngradeWarning && UsedFn) 181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 182 183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 184 : diag::ext_internal_in_extern_inline) 185 << /*IsVar=*/!UsedFn << D; 186 187 S.MaybeSuggestAddingStaticToDecl(Current); 188 189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 190 << D; 191 } 192 193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 194 const FunctionDecl *First = Cur->getFirstDecl(); 195 196 // Suggest "static" on the function, if possible. 197 if (!hasAnyExplicitStorageClass(First)) { 198 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 199 Diag(DeclBegin, diag::note_convert_inline_to_static) 200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 201 } 202 } 203 204 /// Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 217 const ObjCInterfaceDecl *UnknownObjCClass, 218 bool ObjCPropertyAccess, 219 bool AvoidPartialAvailabilityChecks, 220 ObjCInterfaceDecl *ClassReceiver) { 221 SourceLocation Loc = Locs.front(); 222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 223 // If there were any diagnostics suppressed by template argument deduction, 224 // emit them now. 225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 226 if (Pos != SuppressedDiagnostics.end()) { 227 for (const PartialDiagnosticAt &Suppressed : Pos->second) 228 Diag(Suppressed.first, Suppressed.second); 229 230 // Clear out the list of suppressed diagnostics, so that we don't emit 231 // them again for this specialization. However, we don't obsolete this 232 // entry from the table, because we want to avoid ever emitting these 233 // diagnostics again. 234 Pos->second.clear(); 235 } 236 237 // C++ [basic.start.main]p3: 238 // The function 'main' shall not be used within a program. 239 if (cast<FunctionDecl>(D)->isMain()) 240 Diag(Loc, diag::ext_main_used); 241 242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 243 } 244 245 // See if this is an auto-typed variable whose initializer we are parsing. 246 if (ParsingInitForAutoVars.count(D)) { 247 if (isa<BindingDecl>(D)) { 248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 249 << D->getDeclName(); 250 } else { 251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 252 << D->getDeclName() << cast<VarDecl>(D)->getType(); 253 } 254 return true; 255 } 256 257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 258 // See if this is a deleted function. 259 if (FD->isDeleted()) { 260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 261 if (Ctor && Ctor->isInheritingConstructor()) 262 Diag(Loc, diag::err_deleted_inherited_ctor_use) 263 << Ctor->getParent() 264 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 265 else 266 Diag(Loc, diag::err_deleted_function_use); 267 NoteDeletedFunction(FD); 268 return true; 269 } 270 271 // [expr.prim.id]p4 272 // A program that refers explicitly or implicitly to a function with a 273 // trailing requires-clause whose constraint-expression is not satisfied, 274 // other than to declare it, is ill-formed. [...] 275 // 276 // See if this is a function with constraints that need to be satisfied. 277 // Check this before deducing the return type, as it might instantiate the 278 // definition. 279 if (FD->getTrailingRequiresClause()) { 280 ConstraintSatisfaction Satisfaction; 281 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 282 // A diagnostic will have already been generated (non-constant 283 // constraint expression, for example) 284 return true; 285 if (!Satisfaction.IsSatisfied) { 286 Diag(Loc, 287 diag::err_reference_to_function_with_unsatisfied_constraints) 288 << D; 289 DiagnoseUnsatisfiedConstraint(Satisfaction); 290 return true; 291 } 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 301 return true; 302 303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 304 return true; 305 } 306 307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 308 // Lambdas are only default-constructible or assignable in C++2a onwards. 309 if (MD->getParent()->isLambda() && 310 ((isa<CXXConstructorDecl>(MD) && 311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 314 << !isa<CXXConstructorDecl>(MD); 315 } 316 } 317 318 auto getReferencedObjCProp = [](const NamedDecl *D) -> 319 const ObjCPropertyDecl * { 320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 321 return MD->findPropertyDecl(); 322 return nullptr; 323 }; 324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 326 return true; 327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 328 return true; 329 } 330 331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 332 // Only the variables omp_in and omp_out are allowed in the combiner. 333 // Only the variables omp_priv and omp_orig are allowed in the 334 // initializer-clause. 335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 337 isa<VarDecl>(D)) { 338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 339 << getCurFunction()->HasOMPDeclareReductionCombiner; 340 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 341 return true; 342 } 343 344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 345 // List-items in map clauses on this construct may only refer to the declared 346 // variable var and entities that could be referenced by a procedure defined 347 // at the same location 348 if (LangOpts.OpenMP && isa<VarDecl>(D) && 349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 351 << getOpenMPDeclareMapperVarName(); 352 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 353 return true; 354 } 355 356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 357 Diag(Loc, diag::err_use_of_empty_using_if_exists); 358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 359 return true; 360 } 361 362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 363 AvoidPartialAvailabilityChecks, ClassReceiver); 364 365 DiagnoseUnusedOfDecl(*this, D, Loc); 366 367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 368 369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkDeviceDecl(VD, Loc); 372 373 if (!Context.getTargetInfo().isTLSSupported()) 374 if (const auto *VD = dyn_cast<VarDecl>(D)) 375 if (VD->getTLSKind() != VarDecl::TLS_None) 376 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 377 } 378 379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 380 !isUnevaluatedContext()) { 381 // C++ [expr.prim.req.nested] p3 382 // A local parameter shall only appear as an unevaluated operand 383 // (Clause 8) within the constraint-expression. 384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 385 << D; 386 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 387 return true; 388 } 389 390 return false; 391 } 392 393 /// DiagnoseSentinelCalls - This routine checks whether a call or 394 /// message-send is to a declaration with the sentinel attribute, and 395 /// if so, it checks that the requirements of the sentinel are 396 /// satisfied. 397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 398 ArrayRef<Expr *> Args) { 399 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 400 if (!attr) 401 return; 402 403 // The number of formal parameters of the declaration. 404 unsigned numFormalParams; 405 406 // The kind of declaration. This is also an index into a %select in 407 // the diagnostic. 408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 409 410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 411 numFormalParams = MD->param_size(); 412 calleeType = CT_Method; 413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 numFormalParams = FD->param_size(); 415 calleeType = CT_Function; 416 } else if (isa<VarDecl>(D)) { 417 QualType type = cast<ValueDecl>(D)->getType(); 418 const FunctionType *fn = nullptr; 419 if (const PointerType *ptr = type->getAs<PointerType>()) { 420 fn = ptr->getPointeeType()->getAs<FunctionType>(); 421 if (!fn) return; 422 calleeType = CT_Function; 423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 424 fn = ptr->getPointeeType()->castAs<FunctionType>(); 425 calleeType = CT_Block; 426 } else { 427 return; 428 } 429 430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 431 numFormalParams = proto->getNumParams(); 432 } else { 433 numFormalParams = 0; 434 } 435 } else { 436 return; 437 } 438 439 // "nullPos" is the number of formal parameters at the end which 440 // effectively count as part of the variadic arguments. This is 441 // useful if you would prefer to not have *any* formal parameters, 442 // but the language forces you to have at least one. 443 unsigned nullPos = attr->getNullPos(); 444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 446 447 // The number of arguments which should follow the sentinel. 448 unsigned numArgsAfterSentinel = attr->getSentinel(); 449 450 // If there aren't enough arguments for all the formal parameters, 451 // the sentinel, and the args after the sentinel, complain. 452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 455 return; 456 } 457 458 // Otherwise, find the sentinel expression. 459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 460 if (!sentinelExpr) return; 461 if (sentinelExpr->isValueDependent()) return; 462 if (Context.isSentinelNullExpr(sentinelExpr)) return; 463 464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 465 // or 'NULL' if those are actually defined in the context. Only use 466 // 'nil' for ObjC methods, where it's much more likely that the 467 // variadic arguments form a list of object pointers. 468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 512 return ExprError(); 513 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 529 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay); 531 if (Res.isInvalid()) 532 return ExprError(); 533 E = Res.get(); 534 } 535 } 536 return E; 537 } 538 539 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 540 // Check to see if we are dereferencing a null pointer. If so, 541 // and if not volatile-qualified, this is undefined behavior that the 542 // optimizer will delete, so warn about it. People sometimes try to use this 543 // to get a deterministic trap and are surprised by clang's behavior. This 544 // only handles the pattern "*null", which is a very syntactic check. 545 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 546 if (UO && UO->getOpcode() == UO_Deref && 547 UO->getSubExpr()->getType()->isPointerType()) { 548 const LangAS AS = 549 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 550 if ((!isTargetAddressSpace(AS) || 551 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 552 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 553 S.Context, Expr::NPC_ValueDependentIsNotNull) && 554 !UO->getType().isVolatileQualified()) { 555 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 556 S.PDiag(diag::warn_indirection_through_null) 557 << UO->getSubExpr()->getSourceRange()); 558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 559 S.PDiag(diag::note_indirection_through_null)); 560 } 561 } 562 } 563 564 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 565 SourceLocation AssignLoc, 566 const Expr* RHS) { 567 const ObjCIvarDecl *IV = OIRE->getDecl(); 568 if (!IV) 569 return; 570 571 DeclarationName MemberName = IV->getDeclName(); 572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 573 if (!Member || !Member->isStr("isa")) 574 return; 575 576 const Expr *Base = OIRE->getBase(); 577 QualType BaseType = Base->getType(); 578 if (OIRE->isArrow()) 579 BaseType = BaseType->getPointeeType(); 580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 582 ObjCInterfaceDecl *ClassDeclared = nullptr; 583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 584 if (!ClassDeclared->getSuperClass() 585 && (*ClassDeclared->ivar_begin()) == IV) { 586 if (RHS) { 587 NamedDecl *ObjectSetClass = 588 S.LookupSingleName(S.TUScope, 589 &S.Context.Idents.get("object_setClass"), 590 SourceLocation(), S.LookupOrdinaryName); 591 if (ObjectSetClass) { 592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_setClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 598 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 599 } 600 else 601 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 602 } else { 603 NamedDecl *ObjectGetClass = 604 S.LookupSingleName(S.TUScope, 605 &S.Context.Idents.get("object_getClass"), 606 SourceLocation(), S.LookupOrdinaryName); 607 if (ObjectGetClass) 608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 609 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 610 "object_getClass(") 611 << FixItHint::CreateReplacement( 612 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 613 else 614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 615 } 616 S.Diag(IV->getLocation(), diag::note_ivar_decl); 617 } 618 } 619 } 620 621 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 622 // Handle any placeholder expressions which made it here. 623 if (E->getType()->isPlaceholderType()) { 624 ExprResult result = CheckPlaceholderExpr(E); 625 if (result.isInvalid()) return ExprError(); 626 E = result.get(); 627 } 628 629 // C++ [conv.lval]p1: 630 // A glvalue of a non-function, non-array type T can be 631 // converted to a prvalue. 632 if (!E->isGLValue()) return E; 633 634 QualType T = E->getType(); 635 assert(!T.isNull() && "r-value conversion on typeless expression?"); 636 637 // lvalue-to-rvalue conversion cannot be applied to function or array types. 638 if (T->isFunctionType() || T->isArrayType()) 639 return E; 640 641 // We don't want to throw lvalue-to-rvalue casts on top of 642 // expressions of certain types in C++. 643 if (getLangOpts().CPlusPlus && 644 (E->getType() == Context.OverloadTy || 645 T->isDependentType() || 646 T->isRecordType())) 647 return E; 648 649 // The C standard is actually really unclear on this point, and 650 // DR106 tells us what the result should be but not why. It's 651 // generally best to say that void types just doesn't undergo 652 // lvalue-to-rvalue at all. Note that expressions of unqualified 653 // 'void' type are never l-values, but qualified void can be. 654 if (T->isVoidType()) 655 return E; 656 657 // OpenCL usually rejects direct accesses to values of 'half' type. 658 if (getLangOpts().OpenCL && 659 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 660 T->isHalfType()) { 661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 662 << 0 << T; 663 return ExprError(); 664 } 665 666 CheckForNullPointerDereference(*this, E); 667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 669 &Context.Idents.get("object_getClass"), 670 SourceLocation(), LookupOrdinaryName); 671 if (ObjectGetClass) 672 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 673 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 674 << FixItHint::CreateReplacement( 675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 676 else 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 678 } 679 else if (const ObjCIvarRefExpr *OIRE = 680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 682 683 // C++ [conv.lval]p1: 684 // [...] If T is a non-class type, the type of the prvalue is the 685 // cv-unqualified version of T. Otherwise, the type of the 686 // rvalue is T. 687 // 688 // C99 6.3.2.1p2: 689 // If the lvalue has qualified type, the value has the unqualified 690 // version of the type of the lvalue; otherwise, the value has the 691 // type of the lvalue. 692 if (T.hasQualifiers()) 693 T = T.getUnqualifiedType(); 694 695 // Under the MS ABI, lock down the inheritance model now. 696 if (T->isMemberPointerType() && 697 Context.getTargetInfo().getCXXABI().isMicrosoft()) 698 (void)isCompleteType(E->getExprLoc(), T); 699 700 ExprResult Res = CheckLValueToRValueConversionOperand(E); 701 if (Res.isInvalid()) 702 return Res; 703 E = Res.get(); 704 705 // Loading a __weak object implicitly retains the value, so we need a cleanup to 706 // balance that. 707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 708 Cleanup.setExprNeedsCleanups(true); 709 710 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 711 Cleanup.setExprNeedsCleanups(true); 712 713 // C++ [conv.lval]p3: 714 // If T is cv std::nullptr_t, the result is a null pointer constant. 715 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 716 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 717 CurFPFeatureOverrides()); 718 719 // C11 6.3.2.1p2: 720 // ... if the lvalue has atomic type, the value has the non-atomic version 721 // of the type of the lvalue ... 722 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 723 T = Atomic->getValueType().getUnqualifiedType(); 724 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 725 nullptr, VK_PRValue, FPOptionsOverride()); 726 } 727 728 return Res; 729 } 730 731 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 732 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 733 if (Res.isInvalid()) 734 return ExprError(); 735 Res = DefaultLvalueConversion(Res.get()); 736 if (Res.isInvalid()) 737 return ExprError(); 738 return Res; 739 } 740 741 /// CallExprUnaryConversions - a special case of an unary conversion 742 /// performed on a function designator of a call expression. 743 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 744 QualType Ty = E->getType(); 745 ExprResult Res = E; 746 // Only do implicit cast for a function type, but not for a pointer 747 // to function type. 748 if (Ty->isFunctionType()) { 749 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 750 CK_FunctionToPointerDecay); 751 if (Res.isInvalid()) 752 return ExprError(); 753 } 754 Res = DefaultLvalueConversion(Res.get()); 755 if (Res.isInvalid()) 756 return ExprError(); 757 return Res.get(); 758 } 759 760 /// UsualUnaryConversions - Performs various conversions that are common to most 761 /// operators (C99 6.3). The conversions of array and function types are 762 /// sometimes suppressed. For example, the array->pointer conversion doesn't 763 /// apply if the array is an argument to the sizeof or address (&) operators. 764 /// In these instances, this routine should *not* be called. 765 ExprResult Sema::UsualUnaryConversions(Expr *E) { 766 // First, convert to an r-value. 767 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 768 if (Res.isInvalid()) 769 return ExprError(); 770 E = Res.get(); 771 772 QualType Ty = E->getType(); 773 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 774 775 // Half FP have to be promoted to float unless it is natively supported 776 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 777 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 778 779 // Try to perform integral promotions if the object has a theoretically 780 // promotable type. 781 if (Ty->isIntegralOrUnscopedEnumerationType()) { 782 // C99 6.3.1.1p2: 783 // 784 // The following may be used in an expression wherever an int or 785 // unsigned int may be used: 786 // - an object or expression with an integer type whose integer 787 // conversion rank is less than or equal to the rank of int 788 // and unsigned int. 789 // - A bit-field of type _Bool, int, signed int, or unsigned int. 790 // 791 // If an int can represent all values of the original type, the 792 // value is converted to an int; otherwise, it is converted to an 793 // unsigned int. These are called the integer promotions. All 794 // other types are unchanged by the integer promotions. 795 796 QualType PTy = Context.isPromotableBitField(E); 797 if (!PTy.isNull()) { 798 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 799 return E; 800 } 801 if (Ty->isPromotableIntegerType()) { 802 QualType PT = Context.getPromotedIntegerType(Ty); 803 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 804 return E; 805 } 806 } 807 return E; 808 } 809 810 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 811 /// do not have a prototype. Arguments that have type float or __fp16 812 /// are promoted to double. All other argument types are converted by 813 /// UsualUnaryConversions(). 814 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 815 QualType Ty = E->getType(); 816 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 817 818 ExprResult Res = UsualUnaryConversions(E); 819 if (Res.isInvalid()) 820 return ExprError(); 821 E = Res.get(); 822 823 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 824 // promote to double. 825 // Note that default argument promotion applies only to float (and 826 // half/fp16); it does not apply to _Float16. 827 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 828 if (BTy && (BTy->getKind() == BuiltinType::Half || 829 BTy->getKind() == BuiltinType::Float)) { 830 if (getLangOpts().OpenCL && 831 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 832 if (BTy->getKind() == BuiltinType::Half) { 833 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 834 } 835 } else { 836 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 837 } 838 } 839 if (BTy && 840 getLangOpts().getExtendIntArgs() == 841 LangOptions::ExtendArgsKind::ExtendTo64 && 842 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 843 Context.getTypeSizeInChars(BTy) < 844 Context.getTypeSizeInChars(Context.LongLongTy)) { 845 E = (Ty->isUnsignedIntegerType()) 846 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 847 .get() 848 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 849 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 850 "Unexpected typesize for LongLongTy"); 851 } 852 853 // C++ performs lvalue-to-rvalue conversion as a default argument 854 // promotion, even on class types, but note: 855 // C++11 [conv.lval]p2: 856 // When an lvalue-to-rvalue conversion occurs in an unevaluated 857 // operand or a subexpression thereof the value contained in the 858 // referenced object is not accessed. Otherwise, if the glvalue 859 // has a class type, the conversion copy-initializes a temporary 860 // of type T from the glvalue and the result of the conversion 861 // is a prvalue for the temporary. 862 // FIXME: add some way to gate this entire thing for correctness in 863 // potentially potentially evaluated contexts. 864 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 865 ExprResult Temp = PerformCopyInitialization( 866 InitializedEntity::InitializeTemporary(E->getType()), 867 E->getExprLoc(), E); 868 if (Temp.isInvalid()) 869 return ExprError(); 870 E = Temp.get(); 871 } 872 873 return E; 874 } 875 876 /// Determine the degree of POD-ness for an expression. 877 /// Incomplete types are considered POD, since this check can be performed 878 /// when we're in an unevaluated context. 879 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 880 if (Ty->isIncompleteType()) { 881 // C++11 [expr.call]p7: 882 // After these conversions, if the argument does not have arithmetic, 883 // enumeration, pointer, pointer to member, or class type, the program 884 // is ill-formed. 885 // 886 // Since we've already performed array-to-pointer and function-to-pointer 887 // decay, the only such type in C++ is cv void. This also handles 888 // initializer lists as variadic arguments. 889 if (Ty->isVoidType()) 890 return VAK_Invalid; 891 892 if (Ty->isObjCObjectType()) 893 return VAK_Invalid; 894 return VAK_Valid; 895 } 896 897 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 898 return VAK_Invalid; 899 900 if (Ty.isCXX98PODType(Context)) 901 return VAK_Valid; 902 903 // C++11 [expr.call]p7: 904 // Passing a potentially-evaluated argument of class type (Clause 9) 905 // having a non-trivial copy constructor, a non-trivial move constructor, 906 // or a non-trivial destructor, with no corresponding parameter, 907 // is conditionally-supported with implementation-defined semantics. 908 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 909 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 910 if (!Record->hasNonTrivialCopyConstructor() && 911 !Record->hasNonTrivialMoveConstructor() && 912 !Record->hasNonTrivialDestructor()) 913 return VAK_ValidInCXX11; 914 915 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 916 return VAK_Valid; 917 918 if (Ty->isObjCObjectType()) 919 return VAK_Invalid; 920 921 if (getLangOpts().MSVCCompat) 922 return VAK_MSVCUndefined; 923 924 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 925 // permitted to reject them. We should consider doing so. 926 return VAK_Undefined; 927 } 928 929 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 930 // Don't allow one to pass an Objective-C interface to a vararg. 931 const QualType &Ty = E->getType(); 932 VarArgKind VAK = isValidVarArgType(Ty); 933 934 // Complain about passing non-POD types through varargs. 935 switch (VAK) { 936 case VAK_ValidInCXX11: 937 DiagRuntimeBehavior( 938 E->getBeginLoc(), nullptr, 939 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 940 LLVM_FALLTHROUGH; 941 case VAK_Valid: 942 if (Ty->isRecordType()) { 943 // This is unlikely to be what the user intended. If the class has a 944 // 'c_str' member function, the user probably meant to call that. 945 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 946 PDiag(diag::warn_pass_class_arg_to_vararg) 947 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 948 } 949 break; 950 951 case VAK_Undefined: 952 case VAK_MSVCUndefined: 953 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 954 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 955 << getLangOpts().CPlusPlus11 << Ty << CT); 956 break; 957 958 case VAK_Invalid: 959 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 960 Diag(E->getBeginLoc(), 961 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 962 << Ty << CT; 963 else if (Ty->isObjCObjectType()) 964 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 965 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 966 << Ty << CT); 967 else 968 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 969 << isa<InitListExpr>(E) << Ty << CT; 970 break; 971 } 972 } 973 974 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 975 /// will create a trap if the resulting type is not a POD type. 976 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 977 FunctionDecl *FDecl) { 978 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 979 // Strip the unbridged-cast placeholder expression off, if applicable. 980 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 981 (CT == VariadicMethod || 982 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 983 E = stripARCUnbridgedCast(E); 984 985 // Otherwise, do normal placeholder checking. 986 } else { 987 ExprResult ExprRes = CheckPlaceholderExpr(E); 988 if (ExprRes.isInvalid()) 989 return ExprError(); 990 E = ExprRes.get(); 991 } 992 } 993 994 ExprResult ExprRes = DefaultArgumentPromotion(E); 995 if (ExprRes.isInvalid()) 996 return ExprError(); 997 998 // Copy blocks to the heap. 999 if (ExprRes.get()->getType()->isBlockPointerType()) 1000 maybeExtendBlockObject(ExprRes); 1001 1002 E = ExprRes.get(); 1003 1004 // Diagnostics regarding non-POD argument types are 1005 // emitted along with format string checking in Sema::CheckFunctionCall(). 1006 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1007 // Turn this into a trap. 1008 CXXScopeSpec SS; 1009 SourceLocation TemplateKWLoc; 1010 UnqualifiedId Name; 1011 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1012 E->getBeginLoc()); 1013 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1014 /*HasTrailingLParen=*/true, 1015 /*IsAddressOfOperand=*/false); 1016 if (TrapFn.isInvalid()) 1017 return ExprError(); 1018 1019 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1020 None, E->getEndLoc()); 1021 if (Call.isInvalid()) 1022 return ExprError(); 1023 1024 ExprResult Comma = 1025 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1026 if (Comma.isInvalid()) 1027 return ExprError(); 1028 return Comma.get(); 1029 } 1030 1031 if (!getLangOpts().CPlusPlus && 1032 RequireCompleteType(E->getExprLoc(), E->getType(), 1033 diag::err_call_incomplete_argument)) 1034 return ExprError(); 1035 1036 return E; 1037 } 1038 1039 /// Converts an integer to complex float type. Helper function of 1040 /// UsualArithmeticConversions() 1041 /// 1042 /// \return false if the integer expression is an integer type and is 1043 /// successfully converted to the complex type. 1044 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1045 ExprResult &ComplexExpr, 1046 QualType IntTy, 1047 QualType ComplexTy, 1048 bool SkipCast) { 1049 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1050 if (SkipCast) return false; 1051 if (IntTy->isIntegerType()) { 1052 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1053 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1055 CK_FloatingRealToComplex); 1056 } else { 1057 assert(IntTy->isComplexIntegerType()); 1058 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1059 CK_IntegralComplexToFloatingComplex); 1060 } 1061 return false; 1062 } 1063 1064 /// Handle arithmetic conversion with complex types. Helper function of 1065 /// UsualArithmeticConversions() 1066 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1067 ExprResult &RHS, QualType LHSType, 1068 QualType RHSType, 1069 bool IsCompAssign) { 1070 // if we have an integer operand, the result is the complex type. 1071 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1072 /*skipCast*/false)) 1073 return LHSType; 1074 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1075 /*skipCast*/IsCompAssign)) 1076 return RHSType; 1077 1078 // This handles complex/complex, complex/float, or float/complex. 1079 // When both operands are complex, the shorter operand is converted to the 1080 // type of the longer, and that is the type of the result. This corresponds 1081 // to what is done when combining two real floating-point operands. 1082 // The fun begins when size promotion occur across type domains. 1083 // From H&S 6.3.4: When one operand is complex and the other is a real 1084 // floating-point type, the less precise type is converted, within it's 1085 // real or complex domain, to the precision of the other type. For example, 1086 // when combining a "long double" with a "double _Complex", the 1087 // "double _Complex" is promoted to "long double _Complex". 1088 1089 // Compute the rank of the two types, regardless of whether they are complex. 1090 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1091 1092 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1093 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1094 QualType LHSElementType = 1095 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1096 QualType RHSElementType = 1097 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1098 1099 QualType ResultType = S.Context.getComplexType(LHSElementType); 1100 if (Order < 0) { 1101 // Promote the precision of the LHS if not an assignment. 1102 ResultType = S.Context.getComplexType(RHSElementType); 1103 if (!IsCompAssign) { 1104 if (LHSComplexType) 1105 LHS = 1106 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1107 else 1108 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1109 } 1110 } else if (Order > 0) { 1111 // Promote the precision of the RHS. 1112 if (RHSComplexType) 1113 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1114 else 1115 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1116 } 1117 return ResultType; 1118 } 1119 1120 /// Handle arithmetic conversion from integer to float. Helper function 1121 /// of UsualArithmeticConversions() 1122 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1123 ExprResult &IntExpr, 1124 QualType FloatTy, QualType IntTy, 1125 bool ConvertFloat, bool ConvertInt) { 1126 if (IntTy->isIntegerType()) { 1127 if (ConvertInt) 1128 // Convert intExpr to the lhs floating point type. 1129 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1130 CK_IntegralToFloating); 1131 return FloatTy; 1132 } 1133 1134 // Convert both sides to the appropriate complex float. 1135 assert(IntTy->isComplexIntegerType()); 1136 QualType result = S.Context.getComplexType(FloatTy); 1137 1138 // _Complex int -> _Complex float 1139 if (ConvertInt) 1140 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1141 CK_IntegralComplexToFloatingComplex); 1142 1143 // float -> _Complex float 1144 if (ConvertFloat) 1145 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1146 CK_FloatingRealToComplex); 1147 1148 return result; 1149 } 1150 1151 /// Handle arithmethic conversion with floating point types. Helper 1152 /// function of UsualArithmeticConversions() 1153 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1154 ExprResult &RHS, QualType LHSType, 1155 QualType RHSType, bool IsCompAssign) { 1156 bool LHSFloat = LHSType->isRealFloatingType(); 1157 bool RHSFloat = RHSType->isRealFloatingType(); 1158 1159 // N1169 4.1.4: If one of the operands has a floating type and the other 1160 // operand has a fixed-point type, the fixed-point operand 1161 // is converted to the floating type [...] 1162 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1163 if (LHSFloat) 1164 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1165 else if (!IsCompAssign) 1166 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1167 return LHSFloat ? LHSType : RHSType; 1168 } 1169 1170 // If we have two real floating types, convert the smaller operand 1171 // to the bigger result. 1172 if (LHSFloat && RHSFloat) { 1173 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1174 if (order > 0) { 1175 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1176 return LHSType; 1177 } 1178 1179 assert(order < 0 && "illegal float comparison"); 1180 if (!IsCompAssign) 1181 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1182 return RHSType; 1183 } 1184 1185 if (LHSFloat) { 1186 // Half FP has to be promoted to float unless it is natively supported 1187 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1188 LHSType = S.Context.FloatTy; 1189 1190 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1191 /*ConvertFloat=*/!IsCompAssign, 1192 /*ConvertInt=*/ true); 1193 } 1194 assert(RHSFloat); 1195 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1196 /*ConvertFloat=*/ true, 1197 /*ConvertInt=*/!IsCompAssign); 1198 } 1199 1200 /// Diagnose attempts to convert between __float128, __ibm128 and 1201 /// long double if there is no support for such conversion. 1202 /// Helper function of UsualArithmeticConversions(). 1203 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1204 QualType RHSType) { 1205 // No issue if either is not a floating point type. 1206 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1207 return false; 1208 1209 // No issue if both have the same 128-bit float semantics. 1210 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1211 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1212 1213 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1214 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1215 1216 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1217 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1218 1219 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1220 &RHSSem != &llvm::APFloat::IEEEquad()) && 1221 (&LHSSem != &llvm::APFloat::IEEEquad() || 1222 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1223 return false; 1224 1225 return true; 1226 } 1227 1228 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1229 1230 namespace { 1231 /// These helper callbacks are placed in an anonymous namespace to 1232 /// permit their use as function template parameters. 1233 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1234 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1235 } 1236 1237 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1238 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1239 CK_IntegralComplexCast); 1240 } 1241 } 1242 1243 /// Handle integer arithmetic conversions. Helper function of 1244 /// UsualArithmeticConversions() 1245 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1246 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1247 ExprResult &RHS, QualType LHSType, 1248 QualType RHSType, bool IsCompAssign) { 1249 // The rules for this case are in C99 6.3.1.8 1250 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1251 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1252 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1253 if (LHSSigned == RHSSigned) { 1254 // Same signedness; use the higher-ranked type 1255 if (order >= 0) { 1256 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1257 return LHSType; 1258 } else if (!IsCompAssign) 1259 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1260 return RHSType; 1261 } else if (order != (LHSSigned ? 1 : -1)) { 1262 // The unsigned type has greater than or equal rank to the 1263 // signed type, so use the unsigned type 1264 if (RHSSigned) { 1265 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1266 return LHSType; 1267 } else if (!IsCompAssign) 1268 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1269 return RHSType; 1270 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1271 // The two types are different widths; if we are here, that 1272 // means the signed type is larger than the unsigned type, so 1273 // use the signed type. 1274 if (LHSSigned) { 1275 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1276 return LHSType; 1277 } else if (!IsCompAssign) 1278 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1279 return RHSType; 1280 } else { 1281 // The signed type is higher-ranked than the unsigned type, 1282 // but isn't actually any bigger (like unsigned int and long 1283 // on most 32-bit systems). Use the unsigned type corresponding 1284 // to the signed type. 1285 QualType result = 1286 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1287 RHS = (*doRHSCast)(S, RHS.get(), result); 1288 if (!IsCompAssign) 1289 LHS = (*doLHSCast)(S, LHS.get(), result); 1290 return result; 1291 } 1292 } 1293 1294 /// Handle conversions with GCC complex int extension. Helper function 1295 /// of UsualArithmeticConversions() 1296 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1297 ExprResult &RHS, QualType LHSType, 1298 QualType RHSType, 1299 bool IsCompAssign) { 1300 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1301 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1302 1303 if (LHSComplexInt && RHSComplexInt) { 1304 QualType LHSEltType = LHSComplexInt->getElementType(); 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1309 1310 return S.Context.getComplexType(ScalarType); 1311 } 1312 1313 if (LHSComplexInt) { 1314 QualType LHSEltType = LHSComplexInt->getElementType(); 1315 QualType ScalarType = 1316 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1317 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1318 QualType ComplexType = S.Context.getComplexType(ScalarType); 1319 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1320 CK_IntegralRealToComplex); 1321 1322 return ComplexType; 1323 } 1324 1325 assert(RHSComplexInt); 1326 1327 QualType RHSEltType = RHSComplexInt->getElementType(); 1328 QualType ScalarType = 1329 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1330 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1331 QualType ComplexType = S.Context.getComplexType(ScalarType); 1332 1333 if (!IsCompAssign) 1334 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1335 CK_IntegralRealToComplex); 1336 return ComplexType; 1337 } 1338 1339 /// Return the rank of a given fixed point or integer type. The value itself 1340 /// doesn't matter, but the values must be increasing with proper increasing 1341 /// rank as described in N1169 4.1.1. 1342 static unsigned GetFixedPointRank(QualType Ty) { 1343 const auto *BTy = Ty->getAs<BuiltinType>(); 1344 assert(BTy && "Expected a builtin type."); 1345 1346 switch (BTy->getKind()) { 1347 case BuiltinType::ShortFract: 1348 case BuiltinType::UShortFract: 1349 case BuiltinType::SatShortFract: 1350 case BuiltinType::SatUShortFract: 1351 return 1; 1352 case BuiltinType::Fract: 1353 case BuiltinType::UFract: 1354 case BuiltinType::SatFract: 1355 case BuiltinType::SatUFract: 1356 return 2; 1357 case BuiltinType::LongFract: 1358 case BuiltinType::ULongFract: 1359 case BuiltinType::SatLongFract: 1360 case BuiltinType::SatULongFract: 1361 return 3; 1362 case BuiltinType::ShortAccum: 1363 case BuiltinType::UShortAccum: 1364 case BuiltinType::SatShortAccum: 1365 case BuiltinType::SatUShortAccum: 1366 return 4; 1367 case BuiltinType::Accum: 1368 case BuiltinType::UAccum: 1369 case BuiltinType::SatAccum: 1370 case BuiltinType::SatUAccum: 1371 return 5; 1372 case BuiltinType::LongAccum: 1373 case BuiltinType::ULongAccum: 1374 case BuiltinType::SatLongAccum: 1375 case BuiltinType::SatULongAccum: 1376 return 6; 1377 default: 1378 if (BTy->isInteger()) 1379 return 0; 1380 llvm_unreachable("Unexpected fixed point or integer type"); 1381 } 1382 } 1383 1384 /// handleFixedPointConversion - Fixed point operations between fixed 1385 /// point types and integers or other fixed point types do not fall under 1386 /// usual arithmetic conversion since these conversions could result in loss 1387 /// of precsision (N1169 4.1.4). These operations should be calculated with 1388 /// the full precision of their result type (N1169 4.1.6.2.1). 1389 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1390 QualType RHSTy) { 1391 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1392 "Expected at least one of the operands to be a fixed point type"); 1393 assert((LHSTy->isFixedPointOrIntegerType() || 1394 RHSTy->isFixedPointOrIntegerType()) && 1395 "Special fixed point arithmetic operation conversions are only " 1396 "applied to ints or other fixed point types"); 1397 1398 // If one operand has signed fixed-point type and the other operand has 1399 // unsigned fixed-point type, then the unsigned fixed-point operand is 1400 // converted to its corresponding signed fixed-point type and the resulting 1401 // type is the type of the converted operand. 1402 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1403 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1404 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1405 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1406 1407 // The result type is the type with the highest rank, whereby a fixed-point 1408 // conversion rank is always greater than an integer conversion rank; if the 1409 // type of either of the operands is a saturating fixedpoint type, the result 1410 // type shall be the saturating fixed-point type corresponding to the type 1411 // with the highest rank; the resulting value is converted (taking into 1412 // account rounding and overflow) to the precision of the resulting type. 1413 // Same ranks between signed and unsigned types are resolved earlier, so both 1414 // types are either signed or both unsigned at this point. 1415 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1416 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1417 1418 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1419 1420 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1421 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1422 1423 return ResultTy; 1424 } 1425 1426 /// Check that the usual arithmetic conversions can be performed on this pair of 1427 /// expressions that might be of enumeration type. 1428 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1429 SourceLocation Loc, 1430 Sema::ArithConvKind ACK) { 1431 // C++2a [expr.arith.conv]p1: 1432 // If one operand is of enumeration type and the other operand is of a 1433 // different enumeration type or a floating-point type, this behavior is 1434 // deprecated ([depr.arith.conv.enum]). 1435 // 1436 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1437 // Eventually we will presumably reject these cases (in C++23 onwards?). 1438 QualType L = LHS->getType(), R = RHS->getType(); 1439 bool LEnum = L->isUnscopedEnumerationType(), 1440 REnum = R->isUnscopedEnumerationType(); 1441 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1442 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1443 (REnum && L->isFloatingType())) { 1444 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1445 ? diag::warn_arith_conv_enum_float_cxx20 1446 : diag::warn_arith_conv_enum_float) 1447 << LHS->getSourceRange() << RHS->getSourceRange() 1448 << (int)ACK << LEnum << L << R; 1449 } else if (!IsCompAssign && LEnum && REnum && 1450 !S.Context.hasSameUnqualifiedType(L, R)) { 1451 unsigned DiagID; 1452 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1453 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1454 // If either enumeration type is unnamed, it's less likely that the 1455 // user cares about this, but this situation is still deprecated in 1456 // C++2a. Use a different warning group. 1457 DiagID = S.getLangOpts().CPlusPlus20 1458 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1459 : diag::warn_arith_conv_mixed_anon_enum_types; 1460 } else if (ACK == Sema::ACK_Conditional) { 1461 // Conditional expressions are separated out because they have 1462 // historically had a different warning flag. 1463 DiagID = S.getLangOpts().CPlusPlus20 1464 ? diag::warn_conditional_mixed_enum_types_cxx20 1465 : diag::warn_conditional_mixed_enum_types; 1466 } else if (ACK == Sema::ACK_Comparison) { 1467 // Comparison expressions are separated out because they have 1468 // historically had a different warning flag. 1469 DiagID = S.getLangOpts().CPlusPlus20 1470 ? diag::warn_comparison_mixed_enum_types_cxx20 1471 : diag::warn_comparison_mixed_enum_types; 1472 } else { 1473 DiagID = S.getLangOpts().CPlusPlus20 1474 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1475 : diag::warn_arith_conv_mixed_enum_types; 1476 } 1477 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1478 << (int)ACK << L << R; 1479 } 1480 } 1481 1482 /// UsualArithmeticConversions - Performs various conversions that are common to 1483 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1484 /// routine returns the first non-arithmetic type found. The client is 1485 /// responsible for emitting appropriate error diagnostics. 1486 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1487 SourceLocation Loc, 1488 ArithConvKind ACK) { 1489 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1490 1491 if (ACK != ACK_CompAssign) { 1492 LHS = UsualUnaryConversions(LHS.get()); 1493 if (LHS.isInvalid()) 1494 return QualType(); 1495 } 1496 1497 RHS = UsualUnaryConversions(RHS.get()); 1498 if (RHS.isInvalid()) 1499 return QualType(); 1500 1501 // For conversion purposes, we ignore any qualifiers. 1502 // For example, "const float" and "float" are equivalent. 1503 QualType LHSType = 1504 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1505 QualType RHSType = 1506 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1507 1508 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1509 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1510 LHSType = AtomicLHS->getValueType(); 1511 1512 // If both types are identical, no conversion is needed. 1513 if (LHSType == RHSType) 1514 return LHSType; 1515 1516 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1517 // The caller can deal with this (e.g. pointer + int). 1518 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1519 return QualType(); 1520 1521 // Apply unary and bitfield promotions to the LHS's type. 1522 QualType LHSUnpromotedType = LHSType; 1523 if (LHSType->isPromotableIntegerType()) 1524 LHSType = Context.getPromotedIntegerType(LHSType); 1525 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1526 if (!LHSBitfieldPromoteTy.isNull()) 1527 LHSType = LHSBitfieldPromoteTy; 1528 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1529 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1530 1531 // If both types are identical, no conversion is needed. 1532 if (LHSType == RHSType) 1533 return LHSType; 1534 1535 // At this point, we have two different arithmetic types. 1536 1537 // Diagnose attempts to convert between __ibm128, __float128 and long double 1538 // where such conversions currently can't be handled. 1539 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1540 return QualType(); 1541 1542 // Handle complex types first (C99 6.3.1.8p1). 1543 if (LHSType->isComplexType() || RHSType->isComplexType()) 1544 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1545 ACK == ACK_CompAssign); 1546 1547 // Now handle "real" floating types (i.e. float, double, long double). 1548 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1549 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1550 ACK == ACK_CompAssign); 1551 1552 // Handle GCC complex int extension. 1553 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1554 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1555 ACK == ACK_CompAssign); 1556 1557 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1558 return handleFixedPointConversion(*this, LHSType, RHSType); 1559 1560 // Finally, we have two differing integer types. 1561 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1562 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1563 } 1564 1565 //===----------------------------------------------------------------------===// 1566 // Semantic Analysis for various Expression Types 1567 //===----------------------------------------------------------------------===// 1568 1569 1570 ExprResult 1571 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1572 SourceLocation DefaultLoc, 1573 SourceLocation RParenLoc, 1574 Expr *ControllingExpr, 1575 ArrayRef<ParsedType> ArgTypes, 1576 ArrayRef<Expr *> ArgExprs) { 1577 unsigned NumAssocs = ArgTypes.size(); 1578 assert(NumAssocs == ArgExprs.size()); 1579 1580 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1581 for (unsigned i = 0; i < NumAssocs; ++i) { 1582 if (ArgTypes[i]) 1583 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1584 else 1585 Types[i] = nullptr; 1586 } 1587 1588 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1589 ControllingExpr, 1590 llvm::makeArrayRef(Types, NumAssocs), 1591 ArgExprs); 1592 delete [] Types; 1593 return ER; 1594 } 1595 1596 ExprResult 1597 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1598 SourceLocation DefaultLoc, 1599 SourceLocation RParenLoc, 1600 Expr *ControllingExpr, 1601 ArrayRef<TypeSourceInfo *> Types, 1602 ArrayRef<Expr *> Exprs) { 1603 unsigned NumAssocs = Types.size(); 1604 assert(NumAssocs == Exprs.size()); 1605 1606 // Decay and strip qualifiers for the controlling expression type, and handle 1607 // placeholder type replacement. See committee discussion from WG14 DR423. 1608 { 1609 EnterExpressionEvaluationContext Unevaluated( 1610 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1611 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1612 if (R.isInvalid()) 1613 return ExprError(); 1614 ControllingExpr = R.get(); 1615 } 1616 1617 // The controlling expression is an unevaluated operand, so side effects are 1618 // likely unintended. 1619 if (!inTemplateInstantiation() && 1620 ControllingExpr->HasSideEffects(Context, false)) 1621 Diag(ControllingExpr->getExprLoc(), 1622 diag::warn_side_effects_unevaluated_context); 1623 1624 bool TypeErrorFound = false, 1625 IsResultDependent = ControllingExpr->isTypeDependent(), 1626 ContainsUnexpandedParameterPack 1627 = ControllingExpr->containsUnexpandedParameterPack(); 1628 1629 for (unsigned i = 0; i < NumAssocs; ++i) { 1630 if (Exprs[i]->containsUnexpandedParameterPack()) 1631 ContainsUnexpandedParameterPack = true; 1632 1633 if (Types[i]) { 1634 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1635 ContainsUnexpandedParameterPack = true; 1636 1637 if (Types[i]->getType()->isDependentType()) { 1638 IsResultDependent = true; 1639 } else { 1640 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1641 // complete object type other than a variably modified type." 1642 unsigned D = 0; 1643 if (Types[i]->getType()->isIncompleteType()) 1644 D = diag::err_assoc_type_incomplete; 1645 else if (!Types[i]->getType()->isObjectType()) 1646 D = diag::err_assoc_type_nonobject; 1647 else if (Types[i]->getType()->isVariablyModifiedType()) 1648 D = diag::err_assoc_type_variably_modified; 1649 1650 if (D != 0) { 1651 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1652 << Types[i]->getTypeLoc().getSourceRange() 1653 << Types[i]->getType(); 1654 TypeErrorFound = true; 1655 } 1656 1657 // C11 6.5.1.1p2 "No two generic associations in the same generic 1658 // selection shall specify compatible types." 1659 for (unsigned j = i+1; j < NumAssocs; ++j) 1660 if (Types[j] && !Types[j]->getType()->isDependentType() && 1661 Context.typesAreCompatible(Types[i]->getType(), 1662 Types[j]->getType())) { 1663 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1664 diag::err_assoc_compatible_types) 1665 << Types[j]->getTypeLoc().getSourceRange() 1666 << Types[j]->getType() 1667 << Types[i]->getType(); 1668 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1669 diag::note_compat_assoc) 1670 << Types[i]->getTypeLoc().getSourceRange() 1671 << Types[i]->getType(); 1672 TypeErrorFound = true; 1673 } 1674 } 1675 } 1676 } 1677 if (TypeErrorFound) 1678 return ExprError(); 1679 1680 // If we determined that the generic selection is result-dependent, don't 1681 // try to compute the result expression. 1682 if (IsResultDependent) 1683 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1684 Exprs, DefaultLoc, RParenLoc, 1685 ContainsUnexpandedParameterPack); 1686 1687 SmallVector<unsigned, 1> CompatIndices; 1688 unsigned DefaultIndex = -1U; 1689 for (unsigned i = 0; i < NumAssocs; ++i) { 1690 if (!Types[i]) 1691 DefaultIndex = i; 1692 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1693 Types[i]->getType())) 1694 CompatIndices.push_back(i); 1695 } 1696 1697 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1698 // type compatible with at most one of the types named in its generic 1699 // association list." 1700 if (CompatIndices.size() > 1) { 1701 // We strip parens here because the controlling expression is typically 1702 // parenthesized in macro definitions. 1703 ControllingExpr = ControllingExpr->IgnoreParens(); 1704 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1705 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1706 << (unsigned)CompatIndices.size(); 1707 for (unsigned I : CompatIndices) { 1708 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1709 diag::note_compat_assoc) 1710 << Types[I]->getTypeLoc().getSourceRange() 1711 << Types[I]->getType(); 1712 } 1713 return ExprError(); 1714 } 1715 1716 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1717 // its controlling expression shall have type compatible with exactly one of 1718 // the types named in its generic association list." 1719 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1720 // We strip parens here because the controlling expression is typically 1721 // parenthesized in macro definitions. 1722 ControllingExpr = ControllingExpr->IgnoreParens(); 1723 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1724 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1725 return ExprError(); 1726 } 1727 1728 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1729 // type name that is compatible with the type of the controlling expression, 1730 // then the result expression of the generic selection is the expression 1731 // in that generic association. Otherwise, the result expression of the 1732 // generic selection is the expression in the default generic association." 1733 unsigned ResultIndex = 1734 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1735 1736 return GenericSelectionExpr::Create( 1737 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1738 ContainsUnexpandedParameterPack, ResultIndex); 1739 } 1740 1741 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1742 /// location of the token and the offset of the ud-suffix within it. 1743 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1744 unsigned Offset) { 1745 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1746 S.getLangOpts()); 1747 } 1748 1749 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1750 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1751 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1752 IdentifierInfo *UDSuffix, 1753 SourceLocation UDSuffixLoc, 1754 ArrayRef<Expr*> Args, 1755 SourceLocation LitEndLoc) { 1756 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1757 1758 QualType ArgTy[2]; 1759 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1760 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1761 if (ArgTy[ArgIdx]->isArrayType()) 1762 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1763 } 1764 1765 DeclarationName OpName = 1766 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1767 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1768 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1769 1770 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1771 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1772 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1773 /*AllowStringTemplatePack*/ false, 1774 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1775 return ExprError(); 1776 1777 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1778 } 1779 1780 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1781 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1782 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1783 /// multiple tokens. However, the common case is that StringToks points to one 1784 /// string. 1785 /// 1786 ExprResult 1787 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1788 assert(!StringToks.empty() && "Must have at least one string!"); 1789 1790 StringLiteralParser Literal(StringToks, PP); 1791 if (Literal.hadError) 1792 return ExprError(); 1793 1794 SmallVector<SourceLocation, 4> StringTokLocs; 1795 for (const Token &Tok : StringToks) 1796 StringTokLocs.push_back(Tok.getLocation()); 1797 1798 QualType CharTy = Context.CharTy; 1799 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1800 if (Literal.isWide()) { 1801 CharTy = Context.getWideCharType(); 1802 Kind = StringLiteral::Wide; 1803 } else if (Literal.isUTF8()) { 1804 if (getLangOpts().Char8) 1805 CharTy = Context.Char8Ty; 1806 Kind = StringLiteral::UTF8; 1807 } else if (Literal.isUTF16()) { 1808 CharTy = Context.Char16Ty; 1809 Kind = StringLiteral::UTF16; 1810 } else if (Literal.isUTF32()) { 1811 CharTy = Context.Char32Ty; 1812 Kind = StringLiteral::UTF32; 1813 } else if (Literal.isPascal()) { 1814 CharTy = Context.UnsignedCharTy; 1815 } 1816 1817 // Warn on initializing an array of char from a u8 string literal; this 1818 // becomes ill-formed in C++2a. 1819 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1820 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1821 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1822 1823 // Create removals for all 'u8' prefixes in the string literal(s). This 1824 // ensures C++2a compatibility (but may change the program behavior when 1825 // built by non-Clang compilers for which the execution character set is 1826 // not always UTF-8). 1827 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1828 SourceLocation RemovalDiagLoc; 1829 for (const Token &Tok : StringToks) { 1830 if (Tok.getKind() == tok::utf8_string_literal) { 1831 if (RemovalDiagLoc.isInvalid()) 1832 RemovalDiagLoc = Tok.getLocation(); 1833 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1834 Tok.getLocation(), 1835 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1836 getSourceManager(), getLangOpts()))); 1837 } 1838 } 1839 Diag(RemovalDiagLoc, RemovalDiag); 1840 } 1841 1842 QualType StrTy = 1843 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1844 1845 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1846 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1847 Kind, Literal.Pascal, StrTy, 1848 &StringTokLocs[0], 1849 StringTokLocs.size()); 1850 if (Literal.getUDSuffix().empty()) 1851 return Lit; 1852 1853 // We're building a user-defined literal. 1854 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1855 SourceLocation UDSuffixLoc = 1856 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1857 Literal.getUDSuffixOffset()); 1858 1859 // Make sure we're allowed user-defined literals here. 1860 if (!UDLScope) 1861 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1862 1863 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1864 // operator "" X (str, len) 1865 QualType SizeType = Context.getSizeType(); 1866 1867 DeclarationName OpName = 1868 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1869 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1870 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1871 1872 QualType ArgTy[] = { 1873 Context.getArrayDecayedType(StrTy), SizeType 1874 }; 1875 1876 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1877 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1878 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1879 /*AllowStringTemplatePack*/ true, 1880 /*DiagnoseMissing*/ true, Lit)) { 1881 1882 case LOLR_Cooked: { 1883 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1884 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1885 StringTokLocs[0]); 1886 Expr *Args[] = { Lit, LenArg }; 1887 1888 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1889 } 1890 1891 case LOLR_Template: { 1892 TemplateArgumentListInfo ExplicitArgs; 1893 TemplateArgument Arg(Lit); 1894 TemplateArgumentLocInfo ArgInfo(Lit); 1895 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1896 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1897 &ExplicitArgs); 1898 } 1899 1900 case LOLR_StringTemplatePack: { 1901 TemplateArgumentListInfo ExplicitArgs; 1902 1903 unsigned CharBits = Context.getIntWidth(CharTy); 1904 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1905 llvm::APSInt Value(CharBits, CharIsUnsigned); 1906 1907 TemplateArgument TypeArg(CharTy); 1908 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1909 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1910 1911 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1912 Value = Lit->getCodeUnit(I); 1913 TemplateArgument Arg(Context, Value, CharTy); 1914 TemplateArgumentLocInfo ArgInfo; 1915 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1916 } 1917 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1918 &ExplicitArgs); 1919 } 1920 case LOLR_Raw: 1921 case LOLR_ErrorNoDiagnostic: 1922 llvm_unreachable("unexpected literal operator lookup result"); 1923 case LOLR_Error: 1924 return ExprError(); 1925 } 1926 llvm_unreachable("unexpected literal operator lookup result"); 1927 } 1928 1929 DeclRefExpr * 1930 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1931 SourceLocation Loc, 1932 const CXXScopeSpec *SS) { 1933 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1934 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1935 } 1936 1937 DeclRefExpr * 1938 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1939 const DeclarationNameInfo &NameInfo, 1940 const CXXScopeSpec *SS, NamedDecl *FoundD, 1941 SourceLocation TemplateKWLoc, 1942 const TemplateArgumentListInfo *TemplateArgs) { 1943 NestedNameSpecifierLoc NNS = 1944 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1945 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1946 TemplateArgs); 1947 } 1948 1949 // CUDA/HIP: Check whether a captured reference variable is referencing a 1950 // host variable in a device or host device lambda. 1951 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1952 VarDecl *VD) { 1953 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1954 return false; 1955 assert(VD->getType()->isReferenceType()); 1956 1957 // Check whether the reference variable is referencing a host variable. 1958 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1959 if (!DRE) 1960 return false; 1961 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1962 if (!Referee || !Referee->hasGlobalStorage() || 1963 Referee->hasAttr<CUDADeviceAttr>()) 1964 return false; 1965 1966 // Check whether the current function is a device or host device lambda. 1967 // Check whether the reference variable is a capture by getDeclContext() 1968 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1969 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1970 if (MD && MD->getParent()->isLambda() && 1971 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1972 VD->getDeclContext() != MD) 1973 return true; 1974 1975 return false; 1976 } 1977 1978 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1979 // A declaration named in an unevaluated operand never constitutes an odr-use. 1980 if (isUnevaluatedContext()) 1981 return NOUR_Unevaluated; 1982 1983 // C++2a [basic.def.odr]p4: 1984 // A variable x whose name appears as a potentially-evaluated expression e 1985 // is odr-used by e unless [...] x is a reference that is usable in 1986 // constant expressions. 1987 // CUDA/HIP: 1988 // If a reference variable referencing a host variable is captured in a 1989 // device or host device lambda, the value of the referee must be copied 1990 // to the capture and the reference variable must be treated as odr-use 1991 // since the value of the referee is not known at compile time and must 1992 // be loaded from the captured. 1993 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1994 if (VD->getType()->isReferenceType() && 1995 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1996 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1997 VD->isUsableInConstantExpressions(Context)) 1998 return NOUR_Constant; 1999 } 2000 2001 // All remaining non-variable cases constitute an odr-use. For variables, we 2002 // need to wait and see how the expression is used. 2003 return NOUR_None; 2004 } 2005 2006 /// BuildDeclRefExpr - Build an expression that references a 2007 /// declaration that does not require a closure capture. 2008 DeclRefExpr * 2009 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2010 const DeclarationNameInfo &NameInfo, 2011 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2012 SourceLocation TemplateKWLoc, 2013 const TemplateArgumentListInfo *TemplateArgs) { 2014 bool RefersToCapturedVariable = 2015 isa<VarDecl>(D) && 2016 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2017 2018 DeclRefExpr *E = DeclRefExpr::Create( 2019 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2020 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2021 MarkDeclRefReferenced(E); 2022 2023 // C++ [except.spec]p17: 2024 // An exception-specification is considered to be needed when: 2025 // - in an expression, the function is the unique lookup result or 2026 // the selected member of a set of overloaded functions. 2027 // 2028 // We delay doing this until after we've built the function reference and 2029 // marked it as used so that: 2030 // a) if the function is defaulted, we get errors from defining it before / 2031 // instead of errors from computing its exception specification, and 2032 // b) if the function is a defaulted comparison, we can use the body we 2033 // build when defining it as input to the exception specification 2034 // computation rather than computing a new body. 2035 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2036 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2037 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2038 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2039 } 2040 } 2041 2042 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2043 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2044 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2045 getCurFunction()->recordUseOfWeak(E); 2046 2047 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2048 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2049 FD = IFD->getAnonField(); 2050 if (FD) { 2051 UnusedPrivateFields.remove(FD); 2052 // Just in case we're building an illegal pointer-to-member. 2053 if (FD->isBitField()) 2054 E->setObjectKind(OK_BitField); 2055 } 2056 2057 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2058 // designates a bit-field. 2059 if (auto *BD = dyn_cast<BindingDecl>(D)) 2060 if (auto *BE = BD->getBinding()) 2061 E->setObjectKind(BE->getObjectKind()); 2062 2063 return E; 2064 } 2065 2066 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2067 /// possibly a list of template arguments. 2068 /// 2069 /// If this produces template arguments, it is permitted to call 2070 /// DecomposeTemplateName. 2071 /// 2072 /// This actually loses a lot of source location information for 2073 /// non-standard name kinds; we should consider preserving that in 2074 /// some way. 2075 void 2076 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2077 TemplateArgumentListInfo &Buffer, 2078 DeclarationNameInfo &NameInfo, 2079 const TemplateArgumentListInfo *&TemplateArgs) { 2080 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2081 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2082 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2083 2084 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2085 Id.TemplateId->NumArgs); 2086 translateTemplateArguments(TemplateArgsPtr, Buffer); 2087 2088 TemplateName TName = Id.TemplateId->Template.get(); 2089 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2090 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2091 TemplateArgs = &Buffer; 2092 } else { 2093 NameInfo = GetNameFromUnqualifiedId(Id); 2094 TemplateArgs = nullptr; 2095 } 2096 } 2097 2098 static void emitEmptyLookupTypoDiagnostic( 2099 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2100 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2101 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2102 DeclContext *Ctx = 2103 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2104 if (!TC) { 2105 // Emit a special diagnostic for failed member lookups. 2106 // FIXME: computing the declaration context might fail here (?) 2107 if (Ctx) 2108 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2109 << SS.getRange(); 2110 else 2111 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2112 return; 2113 } 2114 2115 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2116 bool DroppedSpecifier = 2117 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2118 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2119 ? diag::note_implicit_param_decl 2120 : diag::note_previous_decl; 2121 if (!Ctx) 2122 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2123 SemaRef.PDiag(NoteID)); 2124 else 2125 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2126 << Typo << Ctx << DroppedSpecifier 2127 << SS.getRange(), 2128 SemaRef.PDiag(NoteID)); 2129 } 2130 2131 /// Diagnose a lookup that found results in an enclosing class during error 2132 /// recovery. This usually indicates that the results were found in a dependent 2133 /// base class that could not be searched as part of a template definition. 2134 /// Always issues a diagnostic (though this may be only a warning in MS 2135 /// compatibility mode). 2136 /// 2137 /// Return \c true if the error is unrecoverable, or \c false if the caller 2138 /// should attempt to recover using these lookup results. 2139 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2140 // During a default argument instantiation the CurContext points 2141 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2142 // function parameter list, hence add an explicit check. 2143 bool isDefaultArgument = 2144 !CodeSynthesisContexts.empty() && 2145 CodeSynthesisContexts.back().Kind == 2146 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2147 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2148 bool isInstance = CurMethod && CurMethod->isInstance() && 2149 R.getNamingClass() == CurMethod->getParent() && 2150 !isDefaultArgument; 2151 2152 // There are two ways we can find a class-scope declaration during template 2153 // instantiation that we did not find in the template definition: if it is a 2154 // member of a dependent base class, or if it is declared after the point of 2155 // use in the same class. Distinguish these by comparing the class in which 2156 // the member was found to the naming class of the lookup. 2157 unsigned DiagID = diag::err_found_in_dependent_base; 2158 unsigned NoteID = diag::note_member_declared_at; 2159 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2160 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2161 : diag::err_found_later_in_class; 2162 } else if (getLangOpts().MSVCCompat) { 2163 DiagID = diag::ext_found_in_dependent_base; 2164 NoteID = diag::note_dependent_member_use; 2165 } 2166 2167 if (isInstance) { 2168 // Give a code modification hint to insert 'this->'. 2169 Diag(R.getNameLoc(), DiagID) 2170 << R.getLookupName() 2171 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2172 CheckCXXThisCapture(R.getNameLoc()); 2173 } else { 2174 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2175 // they're not shadowed). 2176 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2177 } 2178 2179 for (NamedDecl *D : R) 2180 Diag(D->getLocation(), NoteID); 2181 2182 // Return true if we are inside a default argument instantiation 2183 // and the found name refers to an instance member function, otherwise 2184 // the caller will try to create an implicit member call and this is wrong 2185 // for default arguments. 2186 // 2187 // FIXME: Is this special case necessary? We could allow the caller to 2188 // diagnose this. 2189 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2190 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2191 return true; 2192 } 2193 2194 // Tell the callee to try to recover. 2195 return false; 2196 } 2197 2198 /// Diagnose an empty lookup. 2199 /// 2200 /// \return false if new lookup candidates were found 2201 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2202 CorrectionCandidateCallback &CCC, 2203 TemplateArgumentListInfo *ExplicitTemplateArgs, 2204 ArrayRef<Expr *> Args, TypoExpr **Out) { 2205 DeclarationName Name = R.getLookupName(); 2206 2207 unsigned diagnostic = diag::err_undeclared_var_use; 2208 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2209 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2210 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2211 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2212 diagnostic = diag::err_undeclared_use; 2213 diagnostic_suggest = diag::err_undeclared_use_suggest; 2214 } 2215 2216 // If the original lookup was an unqualified lookup, fake an 2217 // unqualified lookup. This is useful when (for example) the 2218 // original lookup would not have found something because it was a 2219 // dependent name. 2220 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2221 while (DC) { 2222 if (isa<CXXRecordDecl>(DC)) { 2223 LookupQualifiedName(R, DC); 2224 2225 if (!R.empty()) { 2226 // Don't give errors about ambiguities in this lookup. 2227 R.suppressDiagnostics(); 2228 2229 // If there's a best viable function among the results, only mention 2230 // that one in the notes. 2231 OverloadCandidateSet Candidates(R.getNameLoc(), 2232 OverloadCandidateSet::CSK_Normal); 2233 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2234 OverloadCandidateSet::iterator Best; 2235 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2236 OR_Success) { 2237 R.clear(); 2238 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2239 R.resolveKind(); 2240 } 2241 2242 return DiagnoseDependentMemberLookup(R); 2243 } 2244 2245 R.clear(); 2246 } 2247 2248 DC = DC->getLookupParent(); 2249 } 2250 2251 // We didn't find anything, so try to correct for a typo. 2252 TypoCorrection Corrected; 2253 if (S && Out) { 2254 SourceLocation TypoLoc = R.getNameLoc(); 2255 assert(!ExplicitTemplateArgs && 2256 "Diagnosing an empty lookup with explicit template args!"); 2257 *Out = CorrectTypoDelayed( 2258 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2259 [=](const TypoCorrection &TC) { 2260 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2261 diagnostic, diagnostic_suggest); 2262 }, 2263 nullptr, CTK_ErrorRecovery); 2264 if (*Out) 2265 return true; 2266 } else if (S && 2267 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2268 S, &SS, CCC, CTK_ErrorRecovery))) { 2269 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2270 bool DroppedSpecifier = 2271 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2272 R.setLookupName(Corrected.getCorrection()); 2273 2274 bool AcceptableWithRecovery = false; 2275 bool AcceptableWithoutRecovery = false; 2276 NamedDecl *ND = Corrected.getFoundDecl(); 2277 if (ND) { 2278 if (Corrected.isOverloaded()) { 2279 OverloadCandidateSet OCS(R.getNameLoc(), 2280 OverloadCandidateSet::CSK_Normal); 2281 OverloadCandidateSet::iterator Best; 2282 for (NamedDecl *CD : Corrected) { 2283 if (FunctionTemplateDecl *FTD = 2284 dyn_cast<FunctionTemplateDecl>(CD)) 2285 AddTemplateOverloadCandidate( 2286 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2287 Args, OCS); 2288 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2289 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2290 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2291 Args, OCS); 2292 } 2293 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2294 case OR_Success: 2295 ND = Best->FoundDecl; 2296 Corrected.setCorrectionDecl(ND); 2297 break; 2298 default: 2299 // FIXME: Arbitrarily pick the first declaration for the note. 2300 Corrected.setCorrectionDecl(ND); 2301 break; 2302 } 2303 } 2304 R.addDecl(ND); 2305 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2306 CXXRecordDecl *Record = nullptr; 2307 if (Corrected.getCorrectionSpecifier()) { 2308 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2309 Record = Ty->getAsCXXRecordDecl(); 2310 } 2311 if (!Record) 2312 Record = cast<CXXRecordDecl>( 2313 ND->getDeclContext()->getRedeclContext()); 2314 R.setNamingClass(Record); 2315 } 2316 2317 auto *UnderlyingND = ND->getUnderlyingDecl(); 2318 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2319 isa<FunctionTemplateDecl>(UnderlyingND); 2320 // FIXME: If we ended up with a typo for a type name or 2321 // Objective-C class name, we're in trouble because the parser 2322 // is in the wrong place to recover. Suggest the typo 2323 // correction, but don't make it a fix-it since we're not going 2324 // to recover well anyway. 2325 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2326 getAsTypeTemplateDecl(UnderlyingND) || 2327 isa<ObjCInterfaceDecl>(UnderlyingND); 2328 } else { 2329 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2330 // because we aren't able to recover. 2331 AcceptableWithoutRecovery = true; 2332 } 2333 2334 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2335 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2336 ? diag::note_implicit_param_decl 2337 : diag::note_previous_decl; 2338 if (SS.isEmpty()) 2339 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2340 PDiag(NoteID), AcceptableWithRecovery); 2341 else 2342 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2343 << Name << computeDeclContext(SS, false) 2344 << DroppedSpecifier << SS.getRange(), 2345 PDiag(NoteID), AcceptableWithRecovery); 2346 2347 // Tell the callee whether to try to recover. 2348 return !AcceptableWithRecovery; 2349 } 2350 } 2351 R.clear(); 2352 2353 // Emit a special diagnostic for failed member lookups. 2354 // FIXME: computing the declaration context might fail here (?) 2355 if (!SS.isEmpty()) { 2356 Diag(R.getNameLoc(), diag::err_no_member) 2357 << Name << computeDeclContext(SS, false) 2358 << SS.getRange(); 2359 return true; 2360 } 2361 2362 // Give up, we can't recover. 2363 Diag(R.getNameLoc(), diagnostic) << Name; 2364 return true; 2365 } 2366 2367 /// In Microsoft mode, if we are inside a template class whose parent class has 2368 /// dependent base classes, and we can't resolve an unqualified identifier, then 2369 /// assume the identifier is a member of a dependent base class. We can only 2370 /// recover successfully in static methods, instance methods, and other contexts 2371 /// where 'this' is available. This doesn't precisely match MSVC's 2372 /// instantiation model, but it's close enough. 2373 static Expr * 2374 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2375 DeclarationNameInfo &NameInfo, 2376 SourceLocation TemplateKWLoc, 2377 const TemplateArgumentListInfo *TemplateArgs) { 2378 // Only try to recover from lookup into dependent bases in static methods or 2379 // contexts where 'this' is available. 2380 QualType ThisType = S.getCurrentThisType(); 2381 const CXXRecordDecl *RD = nullptr; 2382 if (!ThisType.isNull()) 2383 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2384 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2385 RD = MD->getParent(); 2386 if (!RD || !RD->hasAnyDependentBases()) 2387 return nullptr; 2388 2389 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2390 // is available, suggest inserting 'this->' as a fixit. 2391 SourceLocation Loc = NameInfo.getLoc(); 2392 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2393 DB << NameInfo.getName() << RD; 2394 2395 if (!ThisType.isNull()) { 2396 DB << FixItHint::CreateInsertion(Loc, "this->"); 2397 return CXXDependentScopeMemberExpr::Create( 2398 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2399 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2400 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2401 } 2402 2403 // Synthesize a fake NNS that points to the derived class. This will 2404 // perform name lookup during template instantiation. 2405 CXXScopeSpec SS; 2406 auto *NNS = 2407 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2408 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2409 return DependentScopeDeclRefExpr::Create( 2410 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2411 TemplateArgs); 2412 } 2413 2414 ExprResult 2415 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2416 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2417 bool HasTrailingLParen, bool IsAddressOfOperand, 2418 CorrectionCandidateCallback *CCC, 2419 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2420 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2421 "cannot be direct & operand and have a trailing lparen"); 2422 if (SS.isInvalid()) 2423 return ExprError(); 2424 2425 TemplateArgumentListInfo TemplateArgsBuffer; 2426 2427 // Decompose the UnqualifiedId into the following data. 2428 DeclarationNameInfo NameInfo; 2429 const TemplateArgumentListInfo *TemplateArgs; 2430 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2431 2432 DeclarationName Name = NameInfo.getName(); 2433 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2434 SourceLocation NameLoc = NameInfo.getLoc(); 2435 2436 if (II && II->isEditorPlaceholder()) { 2437 // FIXME: When typed placeholders are supported we can create a typed 2438 // placeholder expression node. 2439 return ExprError(); 2440 } 2441 2442 // C++ [temp.dep.expr]p3: 2443 // An id-expression is type-dependent if it contains: 2444 // -- an identifier that was declared with a dependent type, 2445 // (note: handled after lookup) 2446 // -- a template-id that is dependent, 2447 // (note: handled in BuildTemplateIdExpr) 2448 // -- a conversion-function-id that specifies a dependent type, 2449 // -- a nested-name-specifier that contains a class-name that 2450 // names a dependent type. 2451 // Determine whether this is a member of an unknown specialization; 2452 // we need to handle these differently. 2453 bool DependentID = false; 2454 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2455 Name.getCXXNameType()->isDependentType()) { 2456 DependentID = true; 2457 } else if (SS.isSet()) { 2458 if (DeclContext *DC = computeDeclContext(SS, false)) { 2459 if (RequireCompleteDeclContext(SS, DC)) 2460 return ExprError(); 2461 } else { 2462 DependentID = true; 2463 } 2464 } 2465 2466 if (DependentID) 2467 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2468 IsAddressOfOperand, TemplateArgs); 2469 2470 // Perform the required lookup. 2471 LookupResult R(*this, NameInfo, 2472 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2473 ? LookupObjCImplicitSelfParam 2474 : LookupOrdinaryName); 2475 if (TemplateKWLoc.isValid() || TemplateArgs) { 2476 // Lookup the template name again to correctly establish the context in 2477 // which it was found. This is really unfortunate as we already did the 2478 // lookup to determine that it was a template name in the first place. If 2479 // this becomes a performance hit, we can work harder to preserve those 2480 // results until we get here but it's likely not worth it. 2481 bool MemberOfUnknownSpecialization; 2482 AssumedTemplateKind AssumedTemplate; 2483 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2484 MemberOfUnknownSpecialization, TemplateKWLoc, 2485 &AssumedTemplate)) 2486 return ExprError(); 2487 2488 if (MemberOfUnknownSpecialization || 2489 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2490 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2491 IsAddressOfOperand, TemplateArgs); 2492 } else { 2493 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2494 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2495 2496 // If the result might be in a dependent base class, this is a dependent 2497 // id-expression. 2498 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2499 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2500 IsAddressOfOperand, TemplateArgs); 2501 2502 // If this reference is in an Objective-C method, then we need to do 2503 // some special Objective-C lookup, too. 2504 if (IvarLookupFollowUp) { 2505 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2506 if (E.isInvalid()) 2507 return ExprError(); 2508 2509 if (Expr *Ex = E.getAs<Expr>()) 2510 return Ex; 2511 } 2512 } 2513 2514 if (R.isAmbiguous()) 2515 return ExprError(); 2516 2517 // This could be an implicitly declared function reference (legal in C90, 2518 // extension in C99, forbidden in C++). 2519 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2520 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2521 if (D) R.addDecl(D); 2522 } 2523 2524 // Determine whether this name might be a candidate for 2525 // argument-dependent lookup. 2526 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2527 2528 if (R.empty() && !ADL) { 2529 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2530 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2531 TemplateKWLoc, TemplateArgs)) 2532 return E; 2533 } 2534 2535 // Don't diagnose an empty lookup for inline assembly. 2536 if (IsInlineAsmIdentifier) 2537 return ExprError(); 2538 2539 // If this name wasn't predeclared and if this is not a function 2540 // call, diagnose the problem. 2541 TypoExpr *TE = nullptr; 2542 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2543 : nullptr); 2544 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2545 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2546 "Typo correction callback misconfigured"); 2547 if (CCC) { 2548 // Make sure the callback knows what the typo being diagnosed is. 2549 CCC->setTypoName(II); 2550 if (SS.isValid()) 2551 CCC->setTypoNNS(SS.getScopeRep()); 2552 } 2553 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2554 // a template name, but we happen to have always already looked up the name 2555 // before we get here if it must be a template name. 2556 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2557 None, &TE)) { 2558 if (TE && KeywordReplacement) { 2559 auto &State = getTypoExprState(TE); 2560 auto BestTC = State.Consumer->getNextCorrection(); 2561 if (BestTC.isKeyword()) { 2562 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2563 if (State.DiagHandler) 2564 State.DiagHandler(BestTC); 2565 KeywordReplacement->startToken(); 2566 KeywordReplacement->setKind(II->getTokenID()); 2567 KeywordReplacement->setIdentifierInfo(II); 2568 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2569 // Clean up the state associated with the TypoExpr, since it has 2570 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2571 clearDelayedTypo(TE); 2572 // Signal that a correction to a keyword was performed by returning a 2573 // valid-but-null ExprResult. 2574 return (Expr*)nullptr; 2575 } 2576 State.Consumer->resetCorrectionStream(); 2577 } 2578 return TE ? TE : ExprError(); 2579 } 2580 2581 assert(!R.empty() && 2582 "DiagnoseEmptyLookup returned false but added no results"); 2583 2584 // If we found an Objective-C instance variable, let 2585 // LookupInObjCMethod build the appropriate expression to 2586 // reference the ivar. 2587 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2588 R.clear(); 2589 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2590 // In a hopelessly buggy code, Objective-C instance variable 2591 // lookup fails and no expression will be built to reference it. 2592 if (!E.isInvalid() && !E.get()) 2593 return ExprError(); 2594 return E; 2595 } 2596 } 2597 2598 // This is guaranteed from this point on. 2599 assert(!R.empty() || ADL); 2600 2601 // Check whether this might be a C++ implicit instance member access. 2602 // C++ [class.mfct.non-static]p3: 2603 // When an id-expression that is not part of a class member access 2604 // syntax and not used to form a pointer to member is used in the 2605 // body of a non-static member function of class X, if name lookup 2606 // resolves the name in the id-expression to a non-static non-type 2607 // member of some class C, the id-expression is transformed into a 2608 // class member access expression using (*this) as the 2609 // postfix-expression to the left of the . operator. 2610 // 2611 // But we don't actually need to do this for '&' operands if R 2612 // resolved to a function or overloaded function set, because the 2613 // expression is ill-formed if it actually works out to be a 2614 // non-static member function: 2615 // 2616 // C++ [expr.ref]p4: 2617 // Otherwise, if E1.E2 refers to a non-static member function. . . 2618 // [t]he expression can be used only as the left-hand operand of a 2619 // member function call. 2620 // 2621 // There are other safeguards against such uses, but it's important 2622 // to get this right here so that we don't end up making a 2623 // spuriously dependent expression if we're inside a dependent 2624 // instance method. 2625 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2626 bool MightBeImplicitMember; 2627 if (!IsAddressOfOperand) 2628 MightBeImplicitMember = true; 2629 else if (!SS.isEmpty()) 2630 MightBeImplicitMember = false; 2631 else if (R.isOverloadedResult()) 2632 MightBeImplicitMember = false; 2633 else if (R.isUnresolvableResult()) 2634 MightBeImplicitMember = true; 2635 else 2636 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2637 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2638 isa<MSPropertyDecl>(R.getFoundDecl()); 2639 2640 if (MightBeImplicitMember) 2641 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2642 R, TemplateArgs, S); 2643 } 2644 2645 if (TemplateArgs || TemplateKWLoc.isValid()) { 2646 2647 // In C++1y, if this is a variable template id, then check it 2648 // in BuildTemplateIdExpr(). 2649 // The single lookup result must be a variable template declaration. 2650 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2651 Id.TemplateId->Kind == TNK_Var_template) { 2652 assert(R.getAsSingle<VarTemplateDecl>() && 2653 "There should only be one declaration found."); 2654 } 2655 2656 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2657 } 2658 2659 return BuildDeclarationNameExpr(SS, R, ADL); 2660 } 2661 2662 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2663 /// declaration name, generally during template instantiation. 2664 /// There's a large number of things which don't need to be done along 2665 /// this path. 2666 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2667 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2668 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2669 DeclContext *DC = computeDeclContext(SS, false); 2670 if (!DC) 2671 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2672 NameInfo, /*TemplateArgs=*/nullptr); 2673 2674 if (RequireCompleteDeclContext(SS, DC)) 2675 return ExprError(); 2676 2677 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2678 LookupQualifiedName(R, DC); 2679 2680 if (R.isAmbiguous()) 2681 return ExprError(); 2682 2683 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2684 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2685 NameInfo, /*TemplateArgs=*/nullptr); 2686 2687 if (R.empty()) { 2688 // Don't diagnose problems with invalid record decl, the secondary no_member 2689 // diagnostic during template instantiation is likely bogus, e.g. if a class 2690 // is invalid because it's derived from an invalid base class, then missing 2691 // members were likely supposed to be inherited. 2692 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2693 if (CD->isInvalidDecl()) 2694 return ExprError(); 2695 Diag(NameInfo.getLoc(), diag::err_no_member) 2696 << NameInfo.getName() << DC << SS.getRange(); 2697 return ExprError(); 2698 } 2699 2700 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2701 // Diagnose a missing typename if this resolved unambiguously to a type in 2702 // a dependent context. If we can recover with a type, downgrade this to 2703 // a warning in Microsoft compatibility mode. 2704 unsigned DiagID = diag::err_typename_missing; 2705 if (RecoveryTSI && getLangOpts().MSVCCompat) 2706 DiagID = diag::ext_typename_missing; 2707 SourceLocation Loc = SS.getBeginLoc(); 2708 auto D = Diag(Loc, DiagID); 2709 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2710 << SourceRange(Loc, NameInfo.getEndLoc()); 2711 2712 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2713 // context. 2714 if (!RecoveryTSI) 2715 return ExprError(); 2716 2717 // Only issue the fixit if we're prepared to recover. 2718 D << FixItHint::CreateInsertion(Loc, "typename "); 2719 2720 // Recover by pretending this was an elaborated type. 2721 QualType Ty = Context.getTypeDeclType(TD); 2722 TypeLocBuilder TLB; 2723 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2724 2725 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2726 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2727 QTL.setElaboratedKeywordLoc(SourceLocation()); 2728 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2729 2730 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2731 2732 return ExprEmpty(); 2733 } 2734 2735 // Defend against this resolving to an implicit member access. We usually 2736 // won't get here if this might be a legitimate a class member (we end up in 2737 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2738 // a pointer-to-member or in an unevaluated context in C++11. 2739 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2740 return BuildPossibleImplicitMemberExpr(SS, 2741 /*TemplateKWLoc=*/SourceLocation(), 2742 R, /*TemplateArgs=*/nullptr, S); 2743 2744 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2745 } 2746 2747 /// The parser has read a name in, and Sema has detected that we're currently 2748 /// inside an ObjC method. Perform some additional checks and determine if we 2749 /// should form a reference to an ivar. 2750 /// 2751 /// Ideally, most of this would be done by lookup, but there's 2752 /// actually quite a lot of extra work involved. 2753 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2754 IdentifierInfo *II) { 2755 SourceLocation Loc = Lookup.getNameLoc(); 2756 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2757 2758 // Check for error condition which is already reported. 2759 if (!CurMethod) 2760 return DeclResult(true); 2761 2762 // There are two cases to handle here. 1) scoped lookup could have failed, 2763 // in which case we should look for an ivar. 2) scoped lookup could have 2764 // found a decl, but that decl is outside the current instance method (i.e. 2765 // a global variable). In these two cases, we do a lookup for an ivar with 2766 // this name, if the lookup sucedes, we replace it our current decl. 2767 2768 // If we're in a class method, we don't normally want to look for 2769 // ivars. But if we don't find anything else, and there's an 2770 // ivar, that's an error. 2771 bool IsClassMethod = CurMethod->isClassMethod(); 2772 2773 bool LookForIvars; 2774 if (Lookup.empty()) 2775 LookForIvars = true; 2776 else if (IsClassMethod) 2777 LookForIvars = false; 2778 else 2779 LookForIvars = (Lookup.isSingleResult() && 2780 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2781 ObjCInterfaceDecl *IFace = nullptr; 2782 if (LookForIvars) { 2783 IFace = CurMethod->getClassInterface(); 2784 ObjCInterfaceDecl *ClassDeclared; 2785 ObjCIvarDecl *IV = nullptr; 2786 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2787 // Diagnose using an ivar in a class method. 2788 if (IsClassMethod) { 2789 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2790 return DeclResult(true); 2791 } 2792 2793 // Diagnose the use of an ivar outside of the declaring class. 2794 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2795 !declaresSameEntity(ClassDeclared, IFace) && 2796 !getLangOpts().DebuggerSupport) 2797 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2798 2799 // Success. 2800 return IV; 2801 } 2802 } else if (CurMethod->isInstanceMethod()) { 2803 // We should warn if a local variable hides an ivar. 2804 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2805 ObjCInterfaceDecl *ClassDeclared; 2806 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2807 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2808 declaresSameEntity(IFace, ClassDeclared)) 2809 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2810 } 2811 } 2812 } else if (Lookup.isSingleResult() && 2813 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2814 // If accessing a stand-alone ivar in a class method, this is an error. 2815 if (const ObjCIvarDecl *IV = 2816 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2817 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2818 return DeclResult(true); 2819 } 2820 } 2821 2822 // Didn't encounter an error, didn't find an ivar. 2823 return DeclResult(false); 2824 } 2825 2826 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2827 ObjCIvarDecl *IV) { 2828 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2829 assert(CurMethod && CurMethod->isInstanceMethod() && 2830 "should not reference ivar from this context"); 2831 2832 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2833 assert(IFace && "should not reference ivar from this context"); 2834 2835 // If we're referencing an invalid decl, just return this as a silent 2836 // error node. The error diagnostic was already emitted on the decl. 2837 if (IV->isInvalidDecl()) 2838 return ExprError(); 2839 2840 // Check if referencing a field with __attribute__((deprecated)). 2841 if (DiagnoseUseOfDecl(IV, Loc)) 2842 return ExprError(); 2843 2844 // FIXME: This should use a new expr for a direct reference, don't 2845 // turn this into Self->ivar, just return a BareIVarExpr or something. 2846 IdentifierInfo &II = Context.Idents.get("self"); 2847 UnqualifiedId SelfName; 2848 SelfName.setImplicitSelfParam(&II); 2849 CXXScopeSpec SelfScopeSpec; 2850 SourceLocation TemplateKWLoc; 2851 ExprResult SelfExpr = 2852 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2853 /*HasTrailingLParen=*/false, 2854 /*IsAddressOfOperand=*/false); 2855 if (SelfExpr.isInvalid()) 2856 return ExprError(); 2857 2858 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2859 if (SelfExpr.isInvalid()) 2860 return ExprError(); 2861 2862 MarkAnyDeclReferenced(Loc, IV, true); 2863 2864 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2865 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2866 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2867 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2868 2869 ObjCIvarRefExpr *Result = new (Context) 2870 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2871 IV->getLocation(), SelfExpr.get(), true, true); 2872 2873 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2874 if (!isUnevaluatedContext() && 2875 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2876 getCurFunction()->recordUseOfWeak(Result); 2877 } 2878 if (getLangOpts().ObjCAutoRefCount) 2879 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2880 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2881 2882 return Result; 2883 } 2884 2885 /// The parser has read a name in, and Sema has detected that we're currently 2886 /// inside an ObjC method. Perform some additional checks and determine if we 2887 /// should form a reference to an ivar. If so, build an expression referencing 2888 /// that ivar. 2889 ExprResult 2890 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2891 IdentifierInfo *II, bool AllowBuiltinCreation) { 2892 // FIXME: Integrate this lookup step into LookupParsedName. 2893 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2894 if (Ivar.isInvalid()) 2895 return ExprError(); 2896 if (Ivar.isUsable()) 2897 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2898 cast<ObjCIvarDecl>(Ivar.get())); 2899 2900 if (Lookup.empty() && II && AllowBuiltinCreation) 2901 LookupBuiltin(Lookup); 2902 2903 // Sentinel value saying that we didn't do anything special. 2904 return ExprResult(false); 2905 } 2906 2907 /// Cast a base object to a member's actual type. 2908 /// 2909 /// There are two relevant checks: 2910 /// 2911 /// C++ [class.access.base]p7: 2912 /// 2913 /// If a class member access operator [...] is used to access a non-static 2914 /// data member or non-static member function, the reference is ill-formed if 2915 /// the left operand [...] cannot be implicitly converted to a pointer to the 2916 /// naming class of the right operand. 2917 /// 2918 /// C++ [expr.ref]p7: 2919 /// 2920 /// If E2 is a non-static data member or a non-static member function, the 2921 /// program is ill-formed if the class of which E2 is directly a member is an 2922 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2923 /// 2924 /// Note that the latter check does not consider access; the access of the 2925 /// "real" base class is checked as appropriate when checking the access of the 2926 /// member name. 2927 ExprResult 2928 Sema::PerformObjectMemberConversion(Expr *From, 2929 NestedNameSpecifier *Qualifier, 2930 NamedDecl *FoundDecl, 2931 NamedDecl *Member) { 2932 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2933 if (!RD) 2934 return From; 2935 2936 QualType DestRecordType; 2937 QualType DestType; 2938 QualType FromRecordType; 2939 QualType FromType = From->getType(); 2940 bool PointerConversions = false; 2941 if (isa<FieldDecl>(Member)) { 2942 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2943 auto FromPtrType = FromType->getAs<PointerType>(); 2944 DestRecordType = Context.getAddrSpaceQualType( 2945 DestRecordType, FromPtrType 2946 ? FromType->getPointeeType().getAddressSpace() 2947 : FromType.getAddressSpace()); 2948 2949 if (FromPtrType) { 2950 DestType = Context.getPointerType(DestRecordType); 2951 FromRecordType = FromPtrType->getPointeeType(); 2952 PointerConversions = true; 2953 } else { 2954 DestType = DestRecordType; 2955 FromRecordType = FromType; 2956 } 2957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2958 if (Method->isStatic()) 2959 return From; 2960 2961 DestType = Method->getThisType(); 2962 DestRecordType = DestType->getPointeeType(); 2963 2964 if (FromType->getAs<PointerType>()) { 2965 FromRecordType = FromType->getPointeeType(); 2966 PointerConversions = true; 2967 } else { 2968 FromRecordType = FromType; 2969 DestType = DestRecordType; 2970 } 2971 2972 LangAS FromAS = FromRecordType.getAddressSpace(); 2973 LangAS DestAS = DestRecordType.getAddressSpace(); 2974 if (FromAS != DestAS) { 2975 QualType FromRecordTypeWithoutAS = 2976 Context.removeAddrSpaceQualType(FromRecordType); 2977 QualType FromTypeWithDestAS = 2978 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2979 if (PointerConversions) 2980 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2981 From = ImpCastExprToType(From, FromTypeWithDestAS, 2982 CK_AddressSpaceConversion, From->getValueKind()) 2983 .get(); 2984 } 2985 } else { 2986 // No conversion necessary. 2987 return From; 2988 } 2989 2990 if (DestType->isDependentType() || FromType->isDependentType()) 2991 return From; 2992 2993 // If the unqualified types are the same, no conversion is necessary. 2994 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2995 return From; 2996 2997 SourceRange FromRange = From->getSourceRange(); 2998 SourceLocation FromLoc = FromRange.getBegin(); 2999 3000 ExprValueKind VK = From->getValueKind(); 3001 3002 // C++ [class.member.lookup]p8: 3003 // [...] Ambiguities can often be resolved by qualifying a name with its 3004 // class name. 3005 // 3006 // If the member was a qualified name and the qualified referred to a 3007 // specific base subobject type, we'll cast to that intermediate type 3008 // first and then to the object in which the member is declared. That allows 3009 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3010 // 3011 // class Base { public: int x; }; 3012 // class Derived1 : public Base { }; 3013 // class Derived2 : public Base { }; 3014 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3015 // 3016 // void VeryDerived::f() { 3017 // x = 17; // error: ambiguous base subobjects 3018 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3019 // } 3020 if (Qualifier && Qualifier->getAsType()) { 3021 QualType QType = QualType(Qualifier->getAsType(), 0); 3022 assert(QType->isRecordType() && "lookup done with non-record type"); 3023 3024 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3025 3026 // In C++98, the qualifier type doesn't actually have to be a base 3027 // type of the object type, in which case we just ignore it. 3028 // Otherwise build the appropriate casts. 3029 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3030 CXXCastPath BasePath; 3031 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3032 FromLoc, FromRange, &BasePath)) 3033 return ExprError(); 3034 3035 if (PointerConversions) 3036 QType = Context.getPointerType(QType); 3037 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3038 VK, &BasePath).get(); 3039 3040 FromType = QType; 3041 FromRecordType = QRecordType; 3042 3043 // If the qualifier type was the same as the destination type, 3044 // we're done. 3045 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3046 return From; 3047 } 3048 } 3049 3050 CXXCastPath BasePath; 3051 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3052 FromLoc, FromRange, &BasePath, 3053 /*IgnoreAccess=*/true)) 3054 return ExprError(); 3055 3056 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3057 VK, &BasePath); 3058 } 3059 3060 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3061 const LookupResult &R, 3062 bool HasTrailingLParen) { 3063 // Only when used directly as the postfix-expression of a call. 3064 if (!HasTrailingLParen) 3065 return false; 3066 3067 // Never if a scope specifier was provided. 3068 if (SS.isSet()) 3069 return false; 3070 3071 // Only in C++ or ObjC++. 3072 if (!getLangOpts().CPlusPlus) 3073 return false; 3074 3075 // Turn off ADL when we find certain kinds of declarations during 3076 // normal lookup: 3077 for (NamedDecl *D : R) { 3078 // C++0x [basic.lookup.argdep]p3: 3079 // -- a declaration of a class member 3080 // Since using decls preserve this property, we check this on the 3081 // original decl. 3082 if (D->isCXXClassMember()) 3083 return false; 3084 3085 // C++0x [basic.lookup.argdep]p3: 3086 // -- a block-scope function declaration that is not a 3087 // using-declaration 3088 // NOTE: we also trigger this for function templates (in fact, we 3089 // don't check the decl type at all, since all other decl types 3090 // turn off ADL anyway). 3091 if (isa<UsingShadowDecl>(D)) 3092 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3093 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3094 return false; 3095 3096 // C++0x [basic.lookup.argdep]p3: 3097 // -- a declaration that is neither a function or a function 3098 // template 3099 // And also for builtin functions. 3100 if (isa<FunctionDecl>(D)) { 3101 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3102 3103 // But also builtin functions. 3104 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3105 return false; 3106 } else if (!isa<FunctionTemplateDecl>(D)) 3107 return false; 3108 } 3109 3110 return true; 3111 } 3112 3113 3114 /// Diagnoses obvious problems with the use of the given declaration 3115 /// as an expression. This is only actually called for lookups that 3116 /// were not overloaded, and it doesn't promise that the declaration 3117 /// will in fact be used. 3118 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3119 if (D->isInvalidDecl()) 3120 return true; 3121 3122 if (isa<TypedefNameDecl>(D)) { 3123 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3124 return true; 3125 } 3126 3127 if (isa<ObjCInterfaceDecl>(D)) { 3128 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3129 return true; 3130 } 3131 3132 if (isa<NamespaceDecl>(D)) { 3133 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3134 return true; 3135 } 3136 3137 return false; 3138 } 3139 3140 // Certain multiversion types should be treated as overloaded even when there is 3141 // only one result. 3142 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3143 assert(R.isSingleResult() && "Expected only a single result"); 3144 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3145 return FD && 3146 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3147 } 3148 3149 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3150 LookupResult &R, bool NeedsADL, 3151 bool AcceptInvalidDecl) { 3152 // If this is a single, fully-resolved result and we don't need ADL, 3153 // just build an ordinary singleton decl ref. 3154 if (!NeedsADL && R.isSingleResult() && 3155 !R.getAsSingle<FunctionTemplateDecl>() && 3156 !ShouldLookupResultBeMultiVersionOverload(R)) 3157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3158 R.getRepresentativeDecl(), nullptr, 3159 AcceptInvalidDecl); 3160 3161 // We only need to check the declaration if there's exactly one 3162 // result, because in the overloaded case the results can only be 3163 // functions and function templates. 3164 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3165 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3166 return ExprError(); 3167 3168 // Otherwise, just build an unresolved lookup expression. Suppress 3169 // any lookup-related diagnostics; we'll hash these out later, when 3170 // we've picked a target. 3171 R.suppressDiagnostics(); 3172 3173 UnresolvedLookupExpr *ULE 3174 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3175 SS.getWithLocInContext(Context), 3176 R.getLookupNameInfo(), 3177 NeedsADL, R.isOverloadedResult(), 3178 R.begin(), R.end()); 3179 3180 return ULE; 3181 } 3182 3183 static void 3184 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3185 ValueDecl *var, DeclContext *DC); 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, CurContext); 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.isNullValue() && !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::ExtInt: 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::Auto: 4446 case Type::DeducedTemplateSpecialization: 4447 T = cast<DeducedType>(Ty)->getDeducedType(); 4448 break; 4449 case Type::TypeOfExpr: 4450 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4451 break; 4452 case Type::Atomic: 4453 T = cast<AtomicType>(Ty)->getValueType(); 4454 break; 4455 } 4456 } while (!T.isNull() && T->isVariablyModifiedType()); 4457 } 4458 4459 /// Build a sizeof or alignof expression given a type operand. 4460 ExprResult 4461 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4462 SourceLocation OpLoc, 4463 UnaryExprOrTypeTrait ExprKind, 4464 SourceRange R) { 4465 if (!TInfo) 4466 return ExprError(); 4467 4468 QualType T = TInfo->getType(); 4469 4470 if (!T->isDependentType() && 4471 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4472 return ExprError(); 4473 4474 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4475 if (auto *TT = T->getAs<TypedefType>()) { 4476 for (auto I = FunctionScopes.rbegin(), 4477 E = std::prev(FunctionScopes.rend()); 4478 I != E; ++I) { 4479 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4480 if (CSI == nullptr) 4481 break; 4482 DeclContext *DC = nullptr; 4483 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4484 DC = LSI->CallOperator; 4485 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4486 DC = CRSI->TheCapturedDecl; 4487 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4488 DC = BSI->TheDecl; 4489 if (DC) { 4490 if (DC->containsDecl(TT->getDecl())) 4491 break; 4492 captureVariablyModifiedType(Context, T, CSI); 4493 } 4494 } 4495 } 4496 } 4497 4498 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4499 return new (Context) UnaryExprOrTypeTraitExpr( 4500 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4501 } 4502 4503 /// Build a sizeof or alignof expression given an expression 4504 /// operand. 4505 ExprResult 4506 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4507 UnaryExprOrTypeTrait ExprKind) { 4508 ExprResult PE = CheckPlaceholderExpr(E); 4509 if (PE.isInvalid()) 4510 return ExprError(); 4511 4512 E = PE.get(); 4513 4514 // Verify that the operand is valid. 4515 bool isInvalid = false; 4516 if (E->isTypeDependent()) { 4517 // Delay type-checking for type-dependent expressions. 4518 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4519 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4520 } else if (ExprKind == UETT_VecStep) { 4521 isInvalid = CheckVecStepExpr(E); 4522 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4523 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4524 isInvalid = true; 4525 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4526 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4527 isInvalid = true; 4528 } else { 4529 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4530 } 4531 4532 if (isInvalid) 4533 return ExprError(); 4534 4535 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4536 PE = TransformToPotentiallyEvaluated(E); 4537 if (PE.isInvalid()) return ExprError(); 4538 E = PE.get(); 4539 } 4540 4541 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4542 return new (Context) UnaryExprOrTypeTraitExpr( 4543 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4544 } 4545 4546 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4547 /// expr and the same for @c alignof and @c __alignof 4548 /// Note that the ArgRange is invalid if isType is false. 4549 ExprResult 4550 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4551 UnaryExprOrTypeTrait ExprKind, bool IsType, 4552 void *TyOrEx, SourceRange ArgRange) { 4553 // If error parsing type, ignore. 4554 if (!TyOrEx) return ExprError(); 4555 4556 if (IsType) { 4557 TypeSourceInfo *TInfo; 4558 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4559 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4560 } 4561 4562 Expr *ArgEx = (Expr *)TyOrEx; 4563 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4564 return Result; 4565 } 4566 4567 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4568 bool IsReal) { 4569 if (V.get()->isTypeDependent()) 4570 return S.Context.DependentTy; 4571 4572 // _Real and _Imag are only l-values for normal l-values. 4573 if (V.get()->getObjectKind() != OK_Ordinary) { 4574 V = S.DefaultLvalueConversion(V.get()); 4575 if (V.isInvalid()) 4576 return QualType(); 4577 } 4578 4579 // These operators return the element type of a complex type. 4580 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4581 return CT->getElementType(); 4582 4583 // Otherwise they pass through real integer and floating point types here. 4584 if (V.get()->getType()->isArithmeticType()) 4585 return V.get()->getType(); 4586 4587 // Test for placeholders. 4588 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4589 if (PR.isInvalid()) return QualType(); 4590 if (PR.get() != V.get()) { 4591 V = PR; 4592 return CheckRealImagOperand(S, V, Loc, IsReal); 4593 } 4594 4595 // Reject anything else. 4596 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4597 << (IsReal ? "__real" : "__imag"); 4598 return QualType(); 4599 } 4600 4601 4602 4603 ExprResult 4604 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4605 tok::TokenKind Kind, Expr *Input) { 4606 UnaryOperatorKind Opc; 4607 switch (Kind) { 4608 default: llvm_unreachable("Unknown unary op!"); 4609 case tok::plusplus: Opc = UO_PostInc; break; 4610 case tok::minusminus: Opc = UO_PostDec; break; 4611 } 4612 4613 // Since this might is a postfix expression, get rid of ParenListExprs. 4614 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4615 if (Result.isInvalid()) return ExprError(); 4616 Input = Result.get(); 4617 4618 return BuildUnaryOp(S, OpLoc, Opc, Input); 4619 } 4620 4621 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4622 /// 4623 /// \return true on error 4624 static bool checkArithmeticOnObjCPointer(Sema &S, 4625 SourceLocation opLoc, 4626 Expr *op) { 4627 assert(op->getType()->isObjCObjectPointerType()); 4628 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4629 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4630 return false; 4631 4632 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4633 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4634 << op->getSourceRange(); 4635 return true; 4636 } 4637 4638 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4639 auto *BaseNoParens = Base->IgnoreParens(); 4640 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4641 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4642 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4643 } 4644 4645 ExprResult 4646 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4647 Expr *idx, SourceLocation rbLoc) { 4648 if (base && !base->getType().isNull() && 4649 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4650 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4651 SourceLocation(), /*Length*/ nullptr, 4652 /*Stride=*/nullptr, rbLoc); 4653 4654 // Since this might be a postfix expression, get rid of ParenListExprs. 4655 if (isa<ParenListExpr>(base)) { 4656 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4657 if (result.isInvalid()) return ExprError(); 4658 base = result.get(); 4659 } 4660 4661 // Check if base and idx form a MatrixSubscriptExpr. 4662 // 4663 // Helper to check for comma expressions, which are not allowed as indices for 4664 // matrix subscript expressions. 4665 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4666 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4667 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4668 << SourceRange(base->getBeginLoc(), rbLoc); 4669 return true; 4670 } 4671 return false; 4672 }; 4673 // The matrix subscript operator ([][])is considered a single operator. 4674 // Separating the index expressions by parenthesis is not allowed. 4675 if (base->getType()->isSpecificPlaceholderType( 4676 BuiltinType::IncompleteMatrixIdx) && 4677 !isa<MatrixSubscriptExpr>(base)) { 4678 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4679 << SourceRange(base->getBeginLoc(), rbLoc); 4680 return ExprError(); 4681 } 4682 // If the base is a MatrixSubscriptExpr, try to create a new 4683 // MatrixSubscriptExpr. 4684 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4685 if (matSubscriptE) { 4686 if (CheckAndReportCommaError(idx)) 4687 return ExprError(); 4688 4689 assert(matSubscriptE->isIncomplete() && 4690 "base has to be an incomplete matrix subscript"); 4691 return CreateBuiltinMatrixSubscriptExpr( 4692 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4693 } 4694 4695 // Handle any non-overload placeholder types in the base and index 4696 // expressions. We can't handle overloads here because the other 4697 // operand might be an overloadable type, in which case the overload 4698 // resolution for the operator overload should get the first crack 4699 // at the overload. 4700 bool IsMSPropertySubscript = false; 4701 if (base->getType()->isNonOverloadPlaceholderType()) { 4702 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4703 if (!IsMSPropertySubscript) { 4704 ExprResult result = CheckPlaceholderExpr(base); 4705 if (result.isInvalid()) 4706 return ExprError(); 4707 base = result.get(); 4708 } 4709 } 4710 4711 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4712 if (base->getType()->isMatrixType()) { 4713 if (CheckAndReportCommaError(idx)) 4714 return ExprError(); 4715 4716 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4717 } 4718 4719 // A comma-expression as the index is deprecated in C++2a onwards. 4720 if (getLangOpts().CPlusPlus20 && 4721 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4722 (isa<CXXOperatorCallExpr>(idx) && 4723 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4724 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4725 << SourceRange(base->getBeginLoc(), rbLoc); 4726 } 4727 4728 if (idx->getType()->isNonOverloadPlaceholderType()) { 4729 ExprResult result = CheckPlaceholderExpr(idx); 4730 if (result.isInvalid()) return ExprError(); 4731 idx = result.get(); 4732 } 4733 4734 // Build an unanalyzed expression if either operand is type-dependent. 4735 if (getLangOpts().CPlusPlus && 4736 (base->isTypeDependent() || idx->isTypeDependent())) { 4737 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4738 VK_LValue, OK_Ordinary, rbLoc); 4739 } 4740 4741 // MSDN, property (C++) 4742 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4743 // This attribute can also be used in the declaration of an empty array in a 4744 // class or structure definition. For example: 4745 // __declspec(property(get=GetX, put=PutX)) int x[]; 4746 // The above statement indicates that x[] can be used with one or more array 4747 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4748 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4749 if (IsMSPropertySubscript) { 4750 // Build MS property subscript expression if base is MS property reference 4751 // or MS property subscript. 4752 return new (Context) MSPropertySubscriptExpr( 4753 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4754 } 4755 4756 // Use C++ overloaded-operator rules if either operand has record 4757 // type. The spec says to do this if either type is *overloadable*, 4758 // but enum types can't declare subscript operators or conversion 4759 // operators, so there's nothing interesting for overload resolution 4760 // to do if there aren't any record types involved. 4761 // 4762 // ObjC pointers have their own subscripting logic that is not tied 4763 // to overload resolution and so should not take this path. 4764 if (getLangOpts().CPlusPlus && 4765 (base->getType()->isRecordType() || 4766 (!base->getType()->isObjCObjectPointerType() && 4767 idx->getType()->isRecordType()))) { 4768 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4769 } 4770 4771 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4772 4773 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4774 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4775 4776 return Res; 4777 } 4778 4779 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4780 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4781 InitializationKind Kind = 4782 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4783 InitializationSequence InitSeq(*this, Entity, Kind, E); 4784 return InitSeq.Perform(*this, Entity, Kind, E); 4785 } 4786 4787 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4788 Expr *ColumnIdx, 4789 SourceLocation RBLoc) { 4790 ExprResult BaseR = CheckPlaceholderExpr(Base); 4791 if (BaseR.isInvalid()) 4792 return BaseR; 4793 Base = BaseR.get(); 4794 4795 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4796 if (RowR.isInvalid()) 4797 return RowR; 4798 RowIdx = RowR.get(); 4799 4800 if (!ColumnIdx) 4801 return new (Context) MatrixSubscriptExpr( 4802 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4803 4804 // Build an unanalyzed expression if any of the operands is type-dependent. 4805 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4806 ColumnIdx->isTypeDependent()) 4807 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4808 Context.DependentTy, RBLoc); 4809 4810 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4811 if (ColumnR.isInvalid()) 4812 return ColumnR; 4813 ColumnIdx = ColumnR.get(); 4814 4815 // Check that IndexExpr is an integer expression. If it is a constant 4816 // expression, check that it is less than Dim (= the number of elements in the 4817 // corresponding dimension). 4818 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4819 bool IsColumnIdx) -> Expr * { 4820 if (!IndexExpr->getType()->isIntegerType() && 4821 !IndexExpr->isTypeDependent()) { 4822 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4823 << IsColumnIdx; 4824 return nullptr; 4825 } 4826 4827 if (Optional<llvm::APSInt> Idx = 4828 IndexExpr->getIntegerConstantExpr(Context)) { 4829 if ((*Idx < 0 || *Idx >= Dim)) { 4830 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4831 << IsColumnIdx << Dim; 4832 return nullptr; 4833 } 4834 } 4835 4836 ExprResult ConvExpr = 4837 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4838 assert(!ConvExpr.isInvalid() && 4839 "should be able to convert any integer type to size type"); 4840 return ConvExpr.get(); 4841 }; 4842 4843 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4844 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4845 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4846 if (!RowIdx || !ColumnIdx) 4847 return ExprError(); 4848 4849 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4850 MTy->getElementType(), RBLoc); 4851 } 4852 4853 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4854 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4855 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4856 4857 // For expressions like `&(*s).b`, the base is recorded and what should be 4858 // checked. 4859 const MemberExpr *Member = nullptr; 4860 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4861 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4862 4863 LastRecord.PossibleDerefs.erase(StrippedExpr); 4864 } 4865 4866 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4867 if (isUnevaluatedContext()) 4868 return; 4869 4870 QualType ResultTy = E->getType(); 4871 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4872 4873 // Bail if the element is an array since it is not memory access. 4874 if (isa<ArrayType>(ResultTy)) 4875 return; 4876 4877 if (ResultTy->hasAttr(attr::NoDeref)) { 4878 LastRecord.PossibleDerefs.insert(E); 4879 return; 4880 } 4881 4882 // Check if the base type is a pointer to a member access of a struct 4883 // marked with noderef. 4884 const Expr *Base = E->getBase(); 4885 QualType BaseTy = Base->getType(); 4886 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4887 // Not a pointer access 4888 return; 4889 4890 const MemberExpr *Member = nullptr; 4891 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4892 Member->isArrow()) 4893 Base = Member->getBase(); 4894 4895 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4896 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4897 LastRecord.PossibleDerefs.insert(E); 4898 } 4899 } 4900 4901 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4902 Expr *LowerBound, 4903 SourceLocation ColonLocFirst, 4904 SourceLocation ColonLocSecond, 4905 Expr *Length, Expr *Stride, 4906 SourceLocation RBLoc) { 4907 if (Base->getType()->isPlaceholderType() && 4908 !Base->getType()->isSpecificPlaceholderType( 4909 BuiltinType::OMPArraySection)) { 4910 ExprResult Result = CheckPlaceholderExpr(Base); 4911 if (Result.isInvalid()) 4912 return ExprError(); 4913 Base = Result.get(); 4914 } 4915 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4916 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4917 if (Result.isInvalid()) 4918 return ExprError(); 4919 Result = DefaultLvalueConversion(Result.get()); 4920 if (Result.isInvalid()) 4921 return ExprError(); 4922 LowerBound = Result.get(); 4923 } 4924 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4925 ExprResult Result = CheckPlaceholderExpr(Length); 4926 if (Result.isInvalid()) 4927 return ExprError(); 4928 Result = DefaultLvalueConversion(Result.get()); 4929 if (Result.isInvalid()) 4930 return ExprError(); 4931 Length = Result.get(); 4932 } 4933 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4934 ExprResult Result = CheckPlaceholderExpr(Stride); 4935 if (Result.isInvalid()) 4936 return ExprError(); 4937 Result = DefaultLvalueConversion(Result.get()); 4938 if (Result.isInvalid()) 4939 return ExprError(); 4940 Stride = Result.get(); 4941 } 4942 4943 // Build an unanalyzed expression if either operand is type-dependent. 4944 if (Base->isTypeDependent() || 4945 (LowerBound && 4946 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4947 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4948 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4949 return new (Context) OMPArraySectionExpr( 4950 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4951 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4952 } 4953 4954 // Perform default conversions. 4955 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4956 QualType ResultTy; 4957 if (OriginalTy->isAnyPointerType()) { 4958 ResultTy = OriginalTy->getPointeeType(); 4959 } else if (OriginalTy->isArrayType()) { 4960 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4961 } else { 4962 return ExprError( 4963 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4964 << Base->getSourceRange()); 4965 } 4966 // C99 6.5.2.1p1 4967 if (LowerBound) { 4968 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4969 LowerBound); 4970 if (Res.isInvalid()) 4971 return ExprError(Diag(LowerBound->getExprLoc(), 4972 diag::err_omp_typecheck_section_not_integer) 4973 << 0 << LowerBound->getSourceRange()); 4974 LowerBound = Res.get(); 4975 4976 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4977 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4978 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4979 << 0 << LowerBound->getSourceRange(); 4980 } 4981 if (Length) { 4982 auto Res = 4983 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4984 if (Res.isInvalid()) 4985 return ExprError(Diag(Length->getExprLoc(), 4986 diag::err_omp_typecheck_section_not_integer) 4987 << 1 << Length->getSourceRange()); 4988 Length = Res.get(); 4989 4990 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4991 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4992 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4993 << 1 << Length->getSourceRange(); 4994 } 4995 if (Stride) { 4996 ExprResult Res = 4997 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4998 if (Res.isInvalid()) 4999 return ExprError(Diag(Stride->getExprLoc(), 5000 diag::err_omp_typecheck_section_not_integer) 5001 << 1 << Stride->getSourceRange()); 5002 Stride = Res.get(); 5003 5004 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5005 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5006 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5007 << 1 << Stride->getSourceRange(); 5008 } 5009 5010 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5011 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5012 // type. Note that functions are not objects, and that (in C99 parlance) 5013 // incomplete types are not object types. 5014 if (ResultTy->isFunctionType()) { 5015 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5016 << ResultTy << Base->getSourceRange(); 5017 return ExprError(); 5018 } 5019 5020 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5021 diag::err_omp_section_incomplete_type, Base)) 5022 return ExprError(); 5023 5024 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5025 Expr::EvalResult Result; 5026 if (LowerBound->EvaluateAsInt(Result, Context)) { 5027 // OpenMP 5.0, [2.1.5 Array Sections] 5028 // The array section must be a subset of the original array. 5029 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5030 if (LowerBoundValue.isNegative()) { 5031 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5032 << LowerBound->getSourceRange(); 5033 return ExprError(); 5034 } 5035 } 5036 } 5037 5038 if (Length) { 5039 Expr::EvalResult Result; 5040 if (Length->EvaluateAsInt(Result, Context)) { 5041 // OpenMP 5.0, [2.1.5 Array Sections] 5042 // The length must evaluate to non-negative integers. 5043 llvm::APSInt LengthValue = Result.Val.getInt(); 5044 if (LengthValue.isNegative()) { 5045 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5046 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5047 << Length->getSourceRange(); 5048 return ExprError(); 5049 } 5050 } 5051 } else if (ColonLocFirst.isValid() && 5052 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5053 !OriginalTy->isVariableArrayType()))) { 5054 // OpenMP 5.0, [2.1.5 Array Sections] 5055 // When the size of the array dimension is not known, the length must be 5056 // specified explicitly. 5057 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5058 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5059 return ExprError(); 5060 } 5061 5062 if (Stride) { 5063 Expr::EvalResult Result; 5064 if (Stride->EvaluateAsInt(Result, Context)) { 5065 // OpenMP 5.0, [2.1.5 Array Sections] 5066 // The stride must evaluate to a positive integer. 5067 llvm::APSInt StrideValue = Result.Val.getInt(); 5068 if (!StrideValue.isStrictlyPositive()) { 5069 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5070 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5071 << Stride->getSourceRange(); 5072 return ExprError(); 5073 } 5074 } 5075 } 5076 5077 if (!Base->getType()->isSpecificPlaceholderType( 5078 BuiltinType::OMPArraySection)) { 5079 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5080 if (Result.isInvalid()) 5081 return ExprError(); 5082 Base = Result.get(); 5083 } 5084 return new (Context) OMPArraySectionExpr( 5085 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5086 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5087 } 5088 5089 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5090 SourceLocation RParenLoc, 5091 ArrayRef<Expr *> Dims, 5092 ArrayRef<SourceRange> Brackets) { 5093 if (Base->getType()->isPlaceholderType()) { 5094 ExprResult Result = CheckPlaceholderExpr(Base); 5095 if (Result.isInvalid()) 5096 return ExprError(); 5097 Result = DefaultLvalueConversion(Result.get()); 5098 if (Result.isInvalid()) 5099 return ExprError(); 5100 Base = Result.get(); 5101 } 5102 QualType BaseTy = Base->getType(); 5103 // Delay analysis of the types/expressions if instantiation/specialization is 5104 // required. 5105 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5106 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5107 LParenLoc, RParenLoc, Dims, Brackets); 5108 if (!BaseTy->isPointerType() || 5109 (!Base->isTypeDependent() && 5110 BaseTy->getPointeeType()->isIncompleteType())) 5111 return ExprError(Diag(Base->getExprLoc(), 5112 diag::err_omp_non_pointer_type_array_shaping_base) 5113 << Base->getSourceRange()); 5114 5115 SmallVector<Expr *, 4> NewDims; 5116 bool ErrorFound = false; 5117 for (Expr *Dim : Dims) { 5118 if (Dim->getType()->isPlaceholderType()) { 5119 ExprResult Result = CheckPlaceholderExpr(Dim); 5120 if (Result.isInvalid()) { 5121 ErrorFound = true; 5122 continue; 5123 } 5124 Result = DefaultLvalueConversion(Result.get()); 5125 if (Result.isInvalid()) { 5126 ErrorFound = true; 5127 continue; 5128 } 5129 Dim = Result.get(); 5130 } 5131 if (!Dim->isTypeDependent()) { 5132 ExprResult Result = 5133 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5134 if (Result.isInvalid()) { 5135 ErrorFound = true; 5136 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5137 << Dim->getSourceRange(); 5138 continue; 5139 } 5140 Dim = Result.get(); 5141 Expr::EvalResult EvResult; 5142 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5143 // OpenMP 5.0, [2.1.4 Array Shaping] 5144 // Each si is an integral type expression that must evaluate to a 5145 // positive integer. 5146 llvm::APSInt Value = EvResult.Val.getInt(); 5147 if (!Value.isStrictlyPositive()) { 5148 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5149 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5150 << Dim->getSourceRange(); 5151 ErrorFound = true; 5152 continue; 5153 } 5154 } 5155 } 5156 NewDims.push_back(Dim); 5157 } 5158 if (ErrorFound) 5159 return ExprError(); 5160 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5161 LParenLoc, RParenLoc, NewDims, Brackets); 5162 } 5163 5164 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5165 SourceLocation LLoc, SourceLocation RLoc, 5166 ArrayRef<OMPIteratorData> Data) { 5167 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5168 bool IsCorrect = true; 5169 for (const OMPIteratorData &D : Data) { 5170 TypeSourceInfo *TInfo = nullptr; 5171 SourceLocation StartLoc; 5172 QualType DeclTy; 5173 if (!D.Type.getAsOpaquePtr()) { 5174 // OpenMP 5.0, 2.1.6 Iterators 5175 // In an iterator-specifier, if the iterator-type is not specified then 5176 // the type of that iterator is of int type. 5177 DeclTy = Context.IntTy; 5178 StartLoc = D.DeclIdentLoc; 5179 } else { 5180 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5181 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5182 } 5183 5184 bool IsDeclTyDependent = DeclTy->isDependentType() || 5185 DeclTy->containsUnexpandedParameterPack() || 5186 DeclTy->isInstantiationDependentType(); 5187 if (!IsDeclTyDependent) { 5188 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5189 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5190 // The iterator-type must be an integral or pointer type. 5191 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5192 << DeclTy; 5193 IsCorrect = false; 5194 continue; 5195 } 5196 if (DeclTy.isConstant(Context)) { 5197 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5198 // The iterator-type must not be const qualified. 5199 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5200 << DeclTy; 5201 IsCorrect = false; 5202 continue; 5203 } 5204 } 5205 5206 // Iterator declaration. 5207 assert(D.DeclIdent && "Identifier expected."); 5208 // Always try to create iterator declarator to avoid extra error messages 5209 // about unknown declarations use. 5210 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5211 D.DeclIdent, DeclTy, TInfo, SC_None); 5212 VD->setImplicit(); 5213 if (S) { 5214 // Check for conflicting previous declaration. 5215 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5216 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5217 ForVisibleRedeclaration); 5218 Previous.suppressDiagnostics(); 5219 LookupName(Previous, S); 5220 5221 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5222 /*AllowInlineNamespace=*/false); 5223 if (!Previous.empty()) { 5224 NamedDecl *Old = Previous.getRepresentativeDecl(); 5225 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5226 Diag(Old->getLocation(), diag::note_previous_definition); 5227 } else { 5228 PushOnScopeChains(VD, S); 5229 } 5230 } else { 5231 CurContext->addDecl(VD); 5232 } 5233 Expr *Begin = D.Range.Begin; 5234 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5235 ExprResult BeginRes = 5236 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5237 Begin = BeginRes.get(); 5238 } 5239 Expr *End = D.Range.End; 5240 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5241 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5242 End = EndRes.get(); 5243 } 5244 Expr *Step = D.Range.Step; 5245 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5246 if (!Step->getType()->isIntegralType(Context)) { 5247 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5248 << Step << Step->getSourceRange(); 5249 IsCorrect = false; 5250 continue; 5251 } 5252 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5253 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5254 // If the step expression of a range-specification equals zero, the 5255 // behavior is unspecified. 5256 if (Result && Result->isNullValue()) { 5257 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5258 << Step << Step->getSourceRange(); 5259 IsCorrect = false; 5260 continue; 5261 } 5262 } 5263 if (!Begin || !End || !IsCorrect) { 5264 IsCorrect = false; 5265 continue; 5266 } 5267 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5268 IDElem.IteratorDecl = VD; 5269 IDElem.AssignmentLoc = D.AssignLoc; 5270 IDElem.Range.Begin = Begin; 5271 IDElem.Range.End = End; 5272 IDElem.Range.Step = Step; 5273 IDElem.ColonLoc = D.ColonLoc; 5274 IDElem.SecondColonLoc = D.SecColonLoc; 5275 } 5276 if (!IsCorrect) { 5277 // Invalidate all created iterator declarations if error is found. 5278 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5279 if (Decl *ID = D.IteratorDecl) 5280 ID->setInvalidDecl(); 5281 } 5282 return ExprError(); 5283 } 5284 SmallVector<OMPIteratorHelperData, 4> Helpers; 5285 if (!CurContext->isDependentContext()) { 5286 // Build number of ityeration for each iteration range. 5287 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5288 // ((Begini-Stepi-1-Endi) / -Stepi); 5289 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5290 // (Endi - Begini) 5291 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5292 D.Range.Begin); 5293 if(!Res.isUsable()) { 5294 IsCorrect = false; 5295 continue; 5296 } 5297 ExprResult St, St1; 5298 if (D.Range.Step) { 5299 St = D.Range.Step; 5300 // (Endi - Begini) + Stepi 5301 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5302 if (!Res.isUsable()) { 5303 IsCorrect = false; 5304 continue; 5305 } 5306 // (Endi - Begini) + Stepi - 1 5307 Res = 5308 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5309 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5310 if (!Res.isUsable()) { 5311 IsCorrect = false; 5312 continue; 5313 } 5314 // ((Endi - Begini) + Stepi - 1) / Stepi 5315 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5316 if (!Res.isUsable()) { 5317 IsCorrect = false; 5318 continue; 5319 } 5320 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5321 // (Begini - Endi) 5322 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5323 D.Range.Begin, D.Range.End); 5324 if (!Res1.isUsable()) { 5325 IsCorrect = false; 5326 continue; 5327 } 5328 // (Begini - Endi) - Stepi 5329 Res1 = 5330 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5331 if (!Res1.isUsable()) { 5332 IsCorrect = false; 5333 continue; 5334 } 5335 // (Begini - Endi) - Stepi - 1 5336 Res1 = 5337 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5338 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5339 if (!Res1.isUsable()) { 5340 IsCorrect = false; 5341 continue; 5342 } 5343 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5344 Res1 = 5345 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5346 if (!Res1.isUsable()) { 5347 IsCorrect = false; 5348 continue; 5349 } 5350 // Stepi > 0. 5351 ExprResult CmpRes = 5352 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5353 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5354 if (!CmpRes.isUsable()) { 5355 IsCorrect = false; 5356 continue; 5357 } 5358 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5359 Res.get(), Res1.get()); 5360 if (!Res.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 } 5365 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5366 if (!Res.isUsable()) { 5367 IsCorrect = false; 5368 continue; 5369 } 5370 5371 // Build counter update. 5372 // Build counter. 5373 auto *CounterVD = 5374 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5375 D.IteratorDecl->getBeginLoc(), nullptr, 5376 Res.get()->getType(), nullptr, SC_None); 5377 CounterVD->setImplicit(); 5378 ExprResult RefRes = 5379 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5380 D.IteratorDecl->getBeginLoc()); 5381 // Build counter update. 5382 // I = Begini + counter * Stepi; 5383 ExprResult UpdateRes; 5384 if (D.Range.Step) { 5385 UpdateRes = CreateBuiltinBinOp( 5386 D.AssignmentLoc, BO_Mul, 5387 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5388 } else { 5389 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5390 } 5391 if (!UpdateRes.isUsable()) { 5392 IsCorrect = false; 5393 continue; 5394 } 5395 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5396 UpdateRes.get()); 5397 if (!UpdateRes.isUsable()) { 5398 IsCorrect = false; 5399 continue; 5400 } 5401 ExprResult VDRes = 5402 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5403 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5404 D.IteratorDecl->getBeginLoc()); 5405 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5406 UpdateRes.get()); 5407 if (!UpdateRes.isUsable()) { 5408 IsCorrect = false; 5409 continue; 5410 } 5411 UpdateRes = 5412 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5413 if (!UpdateRes.isUsable()) { 5414 IsCorrect = false; 5415 continue; 5416 } 5417 ExprResult CounterUpdateRes = 5418 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5419 if (!CounterUpdateRes.isUsable()) { 5420 IsCorrect = false; 5421 continue; 5422 } 5423 CounterUpdateRes = 5424 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5425 if (!CounterUpdateRes.isUsable()) { 5426 IsCorrect = false; 5427 continue; 5428 } 5429 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5430 HD.CounterVD = CounterVD; 5431 HD.Upper = Res.get(); 5432 HD.Update = UpdateRes.get(); 5433 HD.CounterUpdate = CounterUpdateRes.get(); 5434 } 5435 } else { 5436 Helpers.assign(ID.size(), {}); 5437 } 5438 if (!IsCorrect) { 5439 // Invalidate all created iterator declarations if error is found. 5440 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5441 if (Decl *ID = D.IteratorDecl) 5442 ID->setInvalidDecl(); 5443 } 5444 return ExprError(); 5445 } 5446 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5447 LLoc, RLoc, ID, Helpers); 5448 } 5449 5450 ExprResult 5451 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5452 Expr *Idx, SourceLocation RLoc) { 5453 Expr *LHSExp = Base; 5454 Expr *RHSExp = Idx; 5455 5456 ExprValueKind VK = VK_LValue; 5457 ExprObjectKind OK = OK_Ordinary; 5458 5459 // Per C++ core issue 1213, the result is an xvalue if either operand is 5460 // a non-lvalue array, and an lvalue otherwise. 5461 if (getLangOpts().CPlusPlus11) { 5462 for (auto *Op : {LHSExp, RHSExp}) { 5463 Op = Op->IgnoreImplicit(); 5464 if (Op->getType()->isArrayType() && !Op->isLValue()) 5465 VK = VK_XValue; 5466 } 5467 } 5468 5469 // Perform default conversions. 5470 if (!LHSExp->getType()->getAs<VectorType>()) { 5471 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5472 if (Result.isInvalid()) 5473 return ExprError(); 5474 LHSExp = Result.get(); 5475 } 5476 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5477 if (Result.isInvalid()) 5478 return ExprError(); 5479 RHSExp = Result.get(); 5480 5481 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5482 5483 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5484 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5485 // in the subscript position. As a result, we need to derive the array base 5486 // and index from the expression types. 5487 Expr *BaseExpr, *IndexExpr; 5488 QualType ResultType; 5489 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5490 BaseExpr = LHSExp; 5491 IndexExpr = RHSExp; 5492 ResultType = Context.DependentTy; 5493 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5494 BaseExpr = LHSExp; 5495 IndexExpr = RHSExp; 5496 ResultType = PTy->getPointeeType(); 5497 } else if (const ObjCObjectPointerType *PTy = 5498 LHSTy->getAs<ObjCObjectPointerType>()) { 5499 BaseExpr = LHSExp; 5500 IndexExpr = RHSExp; 5501 5502 // Use custom logic if this should be the pseudo-object subscript 5503 // expression. 5504 if (!LangOpts.isSubscriptPointerArithmetic()) 5505 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5506 nullptr); 5507 5508 ResultType = PTy->getPointeeType(); 5509 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5510 // Handle the uncommon case of "123[Ptr]". 5511 BaseExpr = RHSExp; 5512 IndexExpr = LHSExp; 5513 ResultType = PTy->getPointeeType(); 5514 } else if (const ObjCObjectPointerType *PTy = 5515 RHSTy->getAs<ObjCObjectPointerType>()) { 5516 // Handle the uncommon case of "123[Ptr]". 5517 BaseExpr = RHSExp; 5518 IndexExpr = LHSExp; 5519 ResultType = PTy->getPointeeType(); 5520 if (!LangOpts.isSubscriptPointerArithmetic()) { 5521 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5522 << ResultType << BaseExpr->getSourceRange(); 5523 return ExprError(); 5524 } 5525 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5526 BaseExpr = LHSExp; // vectors: V[123] 5527 IndexExpr = RHSExp; 5528 // We apply C++ DR1213 to vector subscripting too. 5529 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5530 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5531 if (Materialized.isInvalid()) 5532 return ExprError(); 5533 LHSExp = Materialized.get(); 5534 } 5535 VK = LHSExp->getValueKind(); 5536 if (VK != VK_PRValue) 5537 OK = OK_VectorComponent; 5538 5539 ResultType = VTy->getElementType(); 5540 QualType BaseType = BaseExpr->getType(); 5541 Qualifiers BaseQuals = BaseType.getQualifiers(); 5542 Qualifiers MemberQuals = ResultType.getQualifiers(); 5543 Qualifiers Combined = BaseQuals + MemberQuals; 5544 if (Combined != MemberQuals) 5545 ResultType = Context.getQualifiedType(ResultType, Combined); 5546 } else if (LHSTy->isArrayType()) { 5547 // If we see an array that wasn't promoted by 5548 // DefaultFunctionArrayLvalueConversion, it must be an array that 5549 // wasn't promoted because of the C90 rule that doesn't 5550 // allow promoting non-lvalue arrays. Warn, then 5551 // force the promotion here. 5552 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5553 << LHSExp->getSourceRange(); 5554 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5555 CK_ArrayToPointerDecay).get(); 5556 LHSTy = LHSExp->getType(); 5557 5558 BaseExpr = LHSExp; 5559 IndexExpr = RHSExp; 5560 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5561 } else if (RHSTy->isArrayType()) { 5562 // Same as previous, except for 123[f().a] case 5563 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5564 << RHSExp->getSourceRange(); 5565 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5566 CK_ArrayToPointerDecay).get(); 5567 RHSTy = RHSExp->getType(); 5568 5569 BaseExpr = RHSExp; 5570 IndexExpr = LHSExp; 5571 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5572 } else { 5573 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5574 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5575 } 5576 // C99 6.5.2.1p1 5577 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5578 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5579 << IndexExpr->getSourceRange()); 5580 5581 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5582 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5583 && !IndexExpr->isTypeDependent()) 5584 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5585 5586 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5587 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5588 // type. Note that Functions are not objects, and that (in C99 parlance) 5589 // incomplete types are not object types. 5590 if (ResultType->isFunctionType()) { 5591 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5592 << ResultType << BaseExpr->getSourceRange(); 5593 return ExprError(); 5594 } 5595 5596 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5597 // GNU extension: subscripting on pointer to void 5598 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5599 << BaseExpr->getSourceRange(); 5600 5601 // C forbids expressions of unqualified void type from being l-values. 5602 // See IsCForbiddenLValueType. 5603 if (!ResultType.hasQualifiers()) 5604 VK = VK_PRValue; 5605 } else if (!ResultType->isDependentType() && 5606 RequireCompleteSizedType( 5607 LLoc, ResultType, 5608 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5609 return ExprError(); 5610 5611 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5612 !ResultType.isCForbiddenLValueType()); 5613 5614 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5615 FunctionScopes.size() > 1) { 5616 if (auto *TT = 5617 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5618 for (auto I = FunctionScopes.rbegin(), 5619 E = std::prev(FunctionScopes.rend()); 5620 I != E; ++I) { 5621 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5622 if (CSI == nullptr) 5623 break; 5624 DeclContext *DC = nullptr; 5625 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5626 DC = LSI->CallOperator; 5627 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5628 DC = CRSI->TheCapturedDecl; 5629 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5630 DC = BSI->TheDecl; 5631 if (DC) { 5632 if (DC->containsDecl(TT->getDecl())) 5633 break; 5634 captureVariablyModifiedType( 5635 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5636 } 5637 } 5638 } 5639 } 5640 5641 return new (Context) 5642 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5643 } 5644 5645 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5646 ParmVarDecl *Param) { 5647 if (Param->hasUnparsedDefaultArg()) { 5648 // If we've already cleared out the location for the default argument, 5649 // that means we're parsing it right now. 5650 if (!UnparsedDefaultArgLocs.count(Param)) { 5651 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5652 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5653 Param->setInvalidDecl(); 5654 return true; 5655 } 5656 5657 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5658 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5659 Diag(UnparsedDefaultArgLocs[Param], 5660 diag::note_default_argument_declared_here); 5661 return true; 5662 } 5663 5664 if (Param->hasUninstantiatedDefaultArg() && 5665 InstantiateDefaultArgument(CallLoc, FD, Param)) 5666 return true; 5667 5668 assert(Param->hasInit() && "default argument but no initializer?"); 5669 5670 // If the default expression creates temporaries, we need to 5671 // push them to the current stack of expression temporaries so they'll 5672 // be properly destroyed. 5673 // FIXME: We should really be rebuilding the default argument with new 5674 // bound temporaries; see the comment in PR5810. 5675 // We don't need to do that with block decls, though, because 5676 // blocks in default argument expression can never capture anything. 5677 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5678 // Set the "needs cleanups" bit regardless of whether there are 5679 // any explicit objects. 5680 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5681 5682 // Append all the objects to the cleanup list. Right now, this 5683 // should always be a no-op, because blocks in default argument 5684 // expressions should never be able to capture anything. 5685 assert(!Init->getNumObjects() && 5686 "default argument expression has capturing blocks?"); 5687 } 5688 5689 // We already type-checked the argument, so we know it works. 5690 // Just mark all of the declarations in this potentially-evaluated expression 5691 // as being "referenced". 5692 EnterExpressionEvaluationContext EvalContext( 5693 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5694 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5695 /*SkipLocalVariables=*/true); 5696 return false; 5697 } 5698 5699 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5700 FunctionDecl *FD, ParmVarDecl *Param) { 5701 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5702 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5703 return ExprError(); 5704 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5705 } 5706 5707 Sema::VariadicCallType 5708 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5709 Expr *Fn) { 5710 if (Proto && Proto->isVariadic()) { 5711 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5712 return VariadicConstructor; 5713 else if (Fn && Fn->getType()->isBlockPointerType()) 5714 return VariadicBlock; 5715 else if (FDecl) { 5716 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5717 if (Method->isInstance()) 5718 return VariadicMethod; 5719 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5720 return VariadicMethod; 5721 return VariadicFunction; 5722 } 5723 return VariadicDoesNotApply; 5724 } 5725 5726 namespace { 5727 class FunctionCallCCC final : public FunctionCallFilterCCC { 5728 public: 5729 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5730 unsigned NumArgs, MemberExpr *ME) 5731 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5732 FunctionName(FuncName) {} 5733 5734 bool ValidateCandidate(const TypoCorrection &candidate) override { 5735 if (!candidate.getCorrectionSpecifier() || 5736 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5737 return false; 5738 } 5739 5740 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5741 } 5742 5743 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5744 return std::make_unique<FunctionCallCCC>(*this); 5745 } 5746 5747 private: 5748 const IdentifierInfo *const FunctionName; 5749 }; 5750 } 5751 5752 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5753 FunctionDecl *FDecl, 5754 ArrayRef<Expr *> Args) { 5755 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5756 DeclarationName FuncName = FDecl->getDeclName(); 5757 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5758 5759 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5760 if (TypoCorrection Corrected = S.CorrectTypo( 5761 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5762 S.getScopeForContext(S.CurContext), nullptr, CCC, 5763 Sema::CTK_ErrorRecovery)) { 5764 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5765 if (Corrected.isOverloaded()) { 5766 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5767 OverloadCandidateSet::iterator Best; 5768 for (NamedDecl *CD : Corrected) { 5769 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5770 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5771 OCS); 5772 } 5773 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5774 case OR_Success: 5775 ND = Best->FoundDecl; 5776 Corrected.setCorrectionDecl(ND); 5777 break; 5778 default: 5779 break; 5780 } 5781 } 5782 ND = ND->getUnderlyingDecl(); 5783 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5784 return Corrected; 5785 } 5786 } 5787 return TypoCorrection(); 5788 } 5789 5790 /// ConvertArgumentsForCall - Converts the arguments specified in 5791 /// Args/NumArgs to the parameter types of the function FDecl with 5792 /// function prototype Proto. Call is the call expression itself, and 5793 /// Fn is the function expression. For a C++ member function, this 5794 /// routine does not attempt to convert the object argument. Returns 5795 /// true if the call is ill-formed. 5796 bool 5797 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5798 FunctionDecl *FDecl, 5799 const FunctionProtoType *Proto, 5800 ArrayRef<Expr *> Args, 5801 SourceLocation RParenLoc, 5802 bool IsExecConfig) { 5803 // Bail out early if calling a builtin with custom typechecking. 5804 if (FDecl) 5805 if (unsigned ID = FDecl->getBuiltinID()) 5806 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5807 return false; 5808 5809 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5810 // assignment, to the types of the corresponding parameter, ... 5811 unsigned NumParams = Proto->getNumParams(); 5812 bool Invalid = false; 5813 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5814 unsigned FnKind = Fn->getType()->isBlockPointerType() 5815 ? 1 /* block */ 5816 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5817 : 0 /* function */); 5818 5819 // If too few arguments are available (and we don't have default 5820 // arguments for the remaining parameters), don't make the call. 5821 if (Args.size() < NumParams) { 5822 if (Args.size() < MinArgs) { 5823 TypoCorrection TC; 5824 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5825 unsigned diag_id = 5826 MinArgs == NumParams && !Proto->isVariadic() 5827 ? diag::err_typecheck_call_too_few_args_suggest 5828 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5829 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5830 << static_cast<unsigned>(Args.size()) 5831 << TC.getCorrectionRange()); 5832 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5833 Diag(RParenLoc, 5834 MinArgs == NumParams && !Proto->isVariadic() 5835 ? diag::err_typecheck_call_too_few_args_one 5836 : diag::err_typecheck_call_too_few_args_at_least_one) 5837 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5838 else 5839 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5840 ? diag::err_typecheck_call_too_few_args 5841 : diag::err_typecheck_call_too_few_args_at_least) 5842 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5843 << Fn->getSourceRange(); 5844 5845 // Emit the location of the prototype. 5846 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5847 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5848 5849 return true; 5850 } 5851 // We reserve space for the default arguments when we create 5852 // the call expression, before calling ConvertArgumentsForCall. 5853 assert((Call->getNumArgs() == NumParams) && 5854 "We should have reserved space for the default arguments before!"); 5855 } 5856 5857 // If too many are passed and not variadic, error on the extras and drop 5858 // them. 5859 if (Args.size() > NumParams) { 5860 if (!Proto->isVariadic()) { 5861 TypoCorrection TC; 5862 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5863 unsigned diag_id = 5864 MinArgs == NumParams && !Proto->isVariadic() 5865 ? diag::err_typecheck_call_too_many_args_suggest 5866 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5867 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5868 << static_cast<unsigned>(Args.size()) 5869 << TC.getCorrectionRange()); 5870 } else if (NumParams == 1 && FDecl && 5871 FDecl->getParamDecl(0)->getDeclName()) 5872 Diag(Args[NumParams]->getBeginLoc(), 5873 MinArgs == NumParams 5874 ? diag::err_typecheck_call_too_many_args_one 5875 : diag::err_typecheck_call_too_many_args_at_most_one) 5876 << FnKind << FDecl->getParamDecl(0) 5877 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5878 << SourceRange(Args[NumParams]->getBeginLoc(), 5879 Args.back()->getEndLoc()); 5880 else 5881 Diag(Args[NumParams]->getBeginLoc(), 5882 MinArgs == NumParams 5883 ? diag::err_typecheck_call_too_many_args 5884 : diag::err_typecheck_call_too_many_args_at_most) 5885 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5886 << Fn->getSourceRange() 5887 << SourceRange(Args[NumParams]->getBeginLoc(), 5888 Args.back()->getEndLoc()); 5889 5890 // Emit the location of the prototype. 5891 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5892 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5893 5894 // This deletes the extra arguments. 5895 Call->shrinkNumArgs(NumParams); 5896 return true; 5897 } 5898 } 5899 SmallVector<Expr *, 8> AllArgs; 5900 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5901 5902 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5903 AllArgs, CallType); 5904 if (Invalid) 5905 return true; 5906 unsigned TotalNumArgs = AllArgs.size(); 5907 for (unsigned i = 0; i < TotalNumArgs; ++i) 5908 Call->setArg(i, AllArgs[i]); 5909 5910 Call->computeDependence(); 5911 return false; 5912 } 5913 5914 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5915 const FunctionProtoType *Proto, 5916 unsigned FirstParam, ArrayRef<Expr *> Args, 5917 SmallVectorImpl<Expr *> &AllArgs, 5918 VariadicCallType CallType, bool AllowExplicit, 5919 bool IsListInitialization) { 5920 unsigned NumParams = Proto->getNumParams(); 5921 bool Invalid = false; 5922 size_t ArgIx = 0; 5923 // Continue to check argument types (even if we have too few/many args). 5924 for (unsigned i = FirstParam; i < NumParams; i++) { 5925 QualType ProtoArgType = Proto->getParamType(i); 5926 5927 Expr *Arg; 5928 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5929 if (ArgIx < Args.size()) { 5930 Arg = Args[ArgIx++]; 5931 5932 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5933 diag::err_call_incomplete_argument, Arg)) 5934 return true; 5935 5936 // Strip the unbridged-cast placeholder expression off, if applicable. 5937 bool CFAudited = false; 5938 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5939 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5940 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5941 Arg = stripARCUnbridgedCast(Arg); 5942 else if (getLangOpts().ObjCAutoRefCount && 5943 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5944 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5945 CFAudited = true; 5946 5947 if (Proto->getExtParameterInfo(i).isNoEscape() && 5948 ProtoArgType->isBlockPointerType()) 5949 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5950 BE->getBlockDecl()->setDoesNotEscape(); 5951 5952 InitializedEntity Entity = 5953 Param ? InitializedEntity::InitializeParameter(Context, Param, 5954 ProtoArgType) 5955 : InitializedEntity::InitializeParameter( 5956 Context, ProtoArgType, Proto->isParamConsumed(i)); 5957 5958 // Remember that parameter belongs to a CF audited API. 5959 if (CFAudited) 5960 Entity.setParameterCFAudited(); 5961 5962 ExprResult ArgE = PerformCopyInitialization( 5963 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5964 if (ArgE.isInvalid()) 5965 return true; 5966 5967 Arg = ArgE.getAs<Expr>(); 5968 } else { 5969 assert(Param && "can't use default arguments without a known callee"); 5970 5971 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5972 if (ArgExpr.isInvalid()) 5973 return true; 5974 5975 Arg = ArgExpr.getAs<Expr>(); 5976 } 5977 5978 // Check for array bounds violations for each argument to the call. This 5979 // check only triggers warnings when the argument isn't a more complex Expr 5980 // with its own checking, such as a BinaryOperator. 5981 CheckArrayAccess(Arg); 5982 5983 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5984 CheckStaticArrayArgument(CallLoc, Param, Arg); 5985 5986 AllArgs.push_back(Arg); 5987 } 5988 5989 // If this is a variadic call, handle args passed through "...". 5990 if (CallType != VariadicDoesNotApply) { 5991 // Assume that extern "C" functions with variadic arguments that 5992 // return __unknown_anytype aren't *really* variadic. 5993 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5994 FDecl->isExternC()) { 5995 for (Expr *A : Args.slice(ArgIx)) { 5996 QualType paramType; // ignored 5997 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5998 Invalid |= arg.isInvalid(); 5999 AllArgs.push_back(arg.get()); 6000 } 6001 6002 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6003 } else { 6004 for (Expr *A : Args.slice(ArgIx)) { 6005 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6006 Invalid |= Arg.isInvalid(); 6007 AllArgs.push_back(Arg.get()); 6008 } 6009 } 6010 6011 // Check for array bounds violations. 6012 for (Expr *A : Args.slice(ArgIx)) 6013 CheckArrayAccess(A); 6014 } 6015 return Invalid; 6016 } 6017 6018 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6019 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6020 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6021 TL = DTL.getOriginalLoc(); 6022 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6023 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6024 << ATL.getLocalSourceRange(); 6025 } 6026 6027 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6028 /// array parameter, check that it is non-null, and that if it is formed by 6029 /// array-to-pointer decay, the underlying array is sufficiently large. 6030 /// 6031 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6032 /// array type derivation, then for each call to the function, the value of the 6033 /// corresponding actual argument shall provide access to the first element of 6034 /// an array with at least as many elements as specified by the size expression. 6035 void 6036 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6037 ParmVarDecl *Param, 6038 const Expr *ArgExpr) { 6039 // Static array parameters are not supported in C++. 6040 if (!Param || getLangOpts().CPlusPlus) 6041 return; 6042 6043 QualType OrigTy = Param->getOriginalType(); 6044 6045 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6046 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6047 return; 6048 6049 if (ArgExpr->isNullPointerConstant(Context, 6050 Expr::NPC_NeverValueDependent)) { 6051 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6052 DiagnoseCalleeStaticArrayParam(*this, Param); 6053 return; 6054 } 6055 6056 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6057 if (!CAT) 6058 return; 6059 6060 const ConstantArrayType *ArgCAT = 6061 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6062 if (!ArgCAT) 6063 return; 6064 6065 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6066 ArgCAT->getElementType())) { 6067 if (ArgCAT->getSize().ult(CAT->getSize())) { 6068 Diag(CallLoc, diag::warn_static_array_too_small) 6069 << ArgExpr->getSourceRange() 6070 << (unsigned)ArgCAT->getSize().getZExtValue() 6071 << (unsigned)CAT->getSize().getZExtValue() << 0; 6072 DiagnoseCalleeStaticArrayParam(*this, Param); 6073 } 6074 return; 6075 } 6076 6077 Optional<CharUnits> ArgSize = 6078 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6079 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6080 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6081 Diag(CallLoc, diag::warn_static_array_too_small) 6082 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6083 << (unsigned)ParmSize->getQuantity() << 1; 6084 DiagnoseCalleeStaticArrayParam(*this, Param); 6085 } 6086 } 6087 6088 /// Given a function expression of unknown-any type, try to rebuild it 6089 /// to have a function type. 6090 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6091 6092 /// Is the given type a placeholder that we need to lower out 6093 /// immediately during argument processing? 6094 static bool isPlaceholderToRemoveAsArg(QualType type) { 6095 // Placeholders are never sugared. 6096 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6097 if (!placeholder) return false; 6098 6099 switch (placeholder->getKind()) { 6100 // Ignore all the non-placeholder types. 6101 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6102 case BuiltinType::Id: 6103 #include "clang/Basic/OpenCLImageTypes.def" 6104 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6105 case BuiltinType::Id: 6106 #include "clang/Basic/OpenCLExtensionTypes.def" 6107 // In practice we'll never use this, since all SVE types are sugared 6108 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6109 #define SVE_TYPE(Name, Id, SingletonId) \ 6110 case BuiltinType::Id: 6111 #include "clang/Basic/AArch64SVEACLETypes.def" 6112 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6113 case BuiltinType::Id: 6114 #include "clang/Basic/PPCTypes.def" 6115 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6116 #include "clang/Basic/RISCVVTypes.def" 6117 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6118 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6119 #include "clang/AST/BuiltinTypes.def" 6120 return false; 6121 6122 // We cannot lower out overload sets; they might validly be resolved 6123 // by the call machinery. 6124 case BuiltinType::Overload: 6125 return false; 6126 6127 // Unbridged casts in ARC can be handled in some call positions and 6128 // should be left in place. 6129 case BuiltinType::ARCUnbridgedCast: 6130 return false; 6131 6132 // Pseudo-objects should be converted as soon as possible. 6133 case BuiltinType::PseudoObject: 6134 return true; 6135 6136 // The debugger mode could theoretically but currently does not try 6137 // to resolve unknown-typed arguments based on known parameter types. 6138 case BuiltinType::UnknownAny: 6139 return true; 6140 6141 // These are always invalid as call arguments and should be reported. 6142 case BuiltinType::BoundMember: 6143 case BuiltinType::BuiltinFn: 6144 case BuiltinType::IncompleteMatrixIdx: 6145 case BuiltinType::OMPArraySection: 6146 case BuiltinType::OMPArrayShaping: 6147 case BuiltinType::OMPIterator: 6148 return true; 6149 6150 } 6151 llvm_unreachable("bad builtin type kind"); 6152 } 6153 6154 /// Check an argument list for placeholders that we won't try to 6155 /// handle later. 6156 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6157 // Apply this processing to all the arguments at once instead of 6158 // dying at the first failure. 6159 bool hasInvalid = false; 6160 for (size_t i = 0, e = args.size(); i != e; i++) { 6161 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6162 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6163 if (result.isInvalid()) hasInvalid = true; 6164 else args[i] = result.get(); 6165 } 6166 } 6167 return hasInvalid; 6168 } 6169 6170 /// If a builtin function has a pointer argument with no explicit address 6171 /// space, then it should be able to accept a pointer to any address 6172 /// space as input. In order to do this, we need to replace the 6173 /// standard builtin declaration with one that uses the same address space 6174 /// as the call. 6175 /// 6176 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6177 /// it does not contain any pointer arguments without 6178 /// an address space qualifer. Otherwise the rewritten 6179 /// FunctionDecl is returned. 6180 /// TODO: Handle pointer return types. 6181 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6182 FunctionDecl *FDecl, 6183 MultiExprArg ArgExprs) { 6184 6185 QualType DeclType = FDecl->getType(); 6186 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6187 6188 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6189 ArgExprs.size() < FT->getNumParams()) 6190 return nullptr; 6191 6192 bool NeedsNewDecl = false; 6193 unsigned i = 0; 6194 SmallVector<QualType, 8> OverloadParams; 6195 6196 for (QualType ParamType : FT->param_types()) { 6197 6198 // Convert array arguments to pointer to simplify type lookup. 6199 ExprResult ArgRes = 6200 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6201 if (ArgRes.isInvalid()) 6202 return nullptr; 6203 Expr *Arg = ArgRes.get(); 6204 QualType ArgType = Arg->getType(); 6205 if (!ParamType->isPointerType() || 6206 ParamType.hasAddressSpace() || 6207 !ArgType->isPointerType() || 6208 !ArgType->getPointeeType().hasAddressSpace()) { 6209 OverloadParams.push_back(ParamType); 6210 continue; 6211 } 6212 6213 QualType PointeeType = ParamType->getPointeeType(); 6214 if (PointeeType.hasAddressSpace()) 6215 continue; 6216 6217 NeedsNewDecl = true; 6218 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6219 6220 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6221 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6222 } 6223 6224 if (!NeedsNewDecl) 6225 return nullptr; 6226 6227 FunctionProtoType::ExtProtoInfo EPI; 6228 EPI.Variadic = FT->isVariadic(); 6229 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6230 OverloadParams, EPI); 6231 DeclContext *Parent = FDecl->getParent(); 6232 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6233 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6234 FDecl->getIdentifier(), OverloadTy, 6235 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6236 false, 6237 /*hasPrototype=*/true); 6238 SmallVector<ParmVarDecl*, 16> Params; 6239 FT = cast<FunctionProtoType>(OverloadTy); 6240 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6241 QualType ParamType = FT->getParamType(i); 6242 ParmVarDecl *Parm = 6243 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6244 SourceLocation(), nullptr, ParamType, 6245 /*TInfo=*/nullptr, SC_None, nullptr); 6246 Parm->setScopeInfo(0, i); 6247 Params.push_back(Parm); 6248 } 6249 OverloadDecl->setParams(Params); 6250 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6251 return OverloadDecl; 6252 } 6253 6254 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6255 FunctionDecl *Callee, 6256 MultiExprArg ArgExprs) { 6257 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6258 // similar attributes) really don't like it when functions are called with an 6259 // invalid number of args. 6260 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6261 /*PartialOverloading=*/false) && 6262 !Callee->isVariadic()) 6263 return; 6264 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6265 return; 6266 6267 if (const EnableIfAttr *Attr = 6268 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6269 S.Diag(Fn->getBeginLoc(), 6270 isa<CXXMethodDecl>(Callee) 6271 ? diag::err_ovl_no_viable_member_function_in_call 6272 : diag::err_ovl_no_viable_function_in_call) 6273 << Callee << Callee->getSourceRange(); 6274 S.Diag(Callee->getLocation(), 6275 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6276 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6277 return; 6278 } 6279 } 6280 6281 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6282 const UnresolvedMemberExpr *const UME, Sema &S) { 6283 6284 const auto GetFunctionLevelDCIfCXXClass = 6285 [](Sema &S) -> const CXXRecordDecl * { 6286 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6287 if (!DC || !DC->getParent()) 6288 return nullptr; 6289 6290 // If the call to some member function was made from within a member 6291 // function body 'M' return return 'M's parent. 6292 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6293 return MD->getParent()->getCanonicalDecl(); 6294 // else the call was made from within a default member initializer of a 6295 // class, so return the class. 6296 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6297 return RD->getCanonicalDecl(); 6298 return nullptr; 6299 }; 6300 // If our DeclContext is neither a member function nor a class (in the 6301 // case of a lambda in a default member initializer), we can't have an 6302 // enclosing 'this'. 6303 6304 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6305 if (!CurParentClass) 6306 return false; 6307 6308 // The naming class for implicit member functions call is the class in which 6309 // name lookup starts. 6310 const CXXRecordDecl *const NamingClass = 6311 UME->getNamingClass()->getCanonicalDecl(); 6312 assert(NamingClass && "Must have naming class even for implicit access"); 6313 6314 // If the unresolved member functions were found in a 'naming class' that is 6315 // related (either the same or derived from) to the class that contains the 6316 // member function that itself contained the implicit member access. 6317 6318 return CurParentClass == NamingClass || 6319 CurParentClass->isDerivedFrom(NamingClass); 6320 } 6321 6322 static void 6323 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6324 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6325 6326 if (!UME) 6327 return; 6328 6329 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6330 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6331 // already been captured, or if this is an implicit member function call (if 6332 // it isn't, an attempt to capture 'this' should already have been made). 6333 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6334 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6335 return; 6336 6337 // Check if the naming class in which the unresolved members were found is 6338 // related (same as or is a base of) to the enclosing class. 6339 6340 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6341 return; 6342 6343 6344 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6345 // If the enclosing function is not dependent, then this lambda is 6346 // capture ready, so if we can capture this, do so. 6347 if (!EnclosingFunctionCtx->isDependentContext()) { 6348 // If the current lambda and all enclosing lambdas can capture 'this' - 6349 // then go ahead and capture 'this' (since our unresolved overload set 6350 // contains at least one non-static member function). 6351 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6352 S.CheckCXXThisCapture(CallLoc); 6353 } else if (S.CurContext->isDependentContext()) { 6354 // ... since this is an implicit member reference, that might potentially 6355 // involve a 'this' capture, mark 'this' for potential capture in 6356 // enclosing lambdas. 6357 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6358 CurLSI->addPotentialThisCapture(CallLoc); 6359 } 6360 } 6361 6362 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6363 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6364 Expr *ExecConfig) { 6365 ExprResult Call = 6366 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6367 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6368 if (Call.isInvalid()) 6369 return Call; 6370 6371 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6372 // language modes. 6373 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6374 if (ULE->hasExplicitTemplateArgs() && 6375 ULE->decls_begin() == ULE->decls_end()) { 6376 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6377 ? diag::warn_cxx17_compat_adl_only_template_id 6378 : diag::ext_adl_only_template_id) 6379 << ULE->getName(); 6380 } 6381 } 6382 6383 if (LangOpts.OpenMP) 6384 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6385 ExecConfig); 6386 6387 return Call; 6388 } 6389 6390 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6391 /// This provides the location of the left/right parens and a list of comma 6392 /// locations. 6393 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6394 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6395 Expr *ExecConfig, bool IsExecConfig, 6396 bool AllowRecovery) { 6397 // Since this might be a postfix expression, get rid of ParenListExprs. 6398 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6399 if (Result.isInvalid()) return ExprError(); 6400 Fn = Result.get(); 6401 6402 if (checkArgsForPlaceholders(*this, ArgExprs)) 6403 return ExprError(); 6404 6405 if (getLangOpts().CPlusPlus) { 6406 // If this is a pseudo-destructor expression, build the call immediately. 6407 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6408 if (!ArgExprs.empty()) { 6409 // Pseudo-destructor calls should not have any arguments. 6410 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6411 << FixItHint::CreateRemoval( 6412 SourceRange(ArgExprs.front()->getBeginLoc(), 6413 ArgExprs.back()->getEndLoc())); 6414 } 6415 6416 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6417 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6418 } 6419 if (Fn->getType() == Context.PseudoObjectTy) { 6420 ExprResult result = CheckPlaceholderExpr(Fn); 6421 if (result.isInvalid()) return ExprError(); 6422 Fn = result.get(); 6423 } 6424 6425 // Determine whether this is a dependent call inside a C++ template, 6426 // in which case we won't do any semantic analysis now. 6427 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6428 if (ExecConfig) { 6429 return CUDAKernelCallExpr::Create(Context, Fn, 6430 cast<CallExpr>(ExecConfig), ArgExprs, 6431 Context.DependentTy, VK_PRValue, 6432 RParenLoc, CurFPFeatureOverrides()); 6433 } else { 6434 6435 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6436 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6437 Fn->getBeginLoc()); 6438 6439 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6440 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6441 } 6442 } 6443 6444 // Determine whether this is a call to an object (C++ [over.call.object]). 6445 if (Fn->getType()->isRecordType()) 6446 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6447 RParenLoc); 6448 6449 if (Fn->getType() == Context.UnknownAnyTy) { 6450 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6451 if (result.isInvalid()) return ExprError(); 6452 Fn = result.get(); 6453 } 6454 6455 if (Fn->getType() == Context.BoundMemberTy) { 6456 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6457 RParenLoc, ExecConfig, IsExecConfig, 6458 AllowRecovery); 6459 } 6460 } 6461 6462 // Check for overloaded calls. This can happen even in C due to extensions. 6463 if (Fn->getType() == Context.OverloadTy) { 6464 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6465 6466 // We aren't supposed to apply this logic if there's an '&' involved. 6467 if (!find.HasFormOfMemberPointer) { 6468 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6469 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6470 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6471 OverloadExpr *ovl = find.Expression; 6472 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6473 return BuildOverloadedCallExpr( 6474 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6475 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6476 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6477 RParenLoc, ExecConfig, IsExecConfig, 6478 AllowRecovery); 6479 } 6480 } 6481 6482 // If we're directly calling a function, get the appropriate declaration. 6483 if (Fn->getType() == Context.UnknownAnyTy) { 6484 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6485 if (result.isInvalid()) return ExprError(); 6486 Fn = result.get(); 6487 } 6488 6489 Expr *NakedFn = Fn->IgnoreParens(); 6490 6491 bool CallingNDeclIndirectly = false; 6492 NamedDecl *NDecl = nullptr; 6493 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6494 if (UnOp->getOpcode() == UO_AddrOf) { 6495 CallingNDeclIndirectly = true; 6496 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6497 } 6498 } 6499 6500 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6501 NDecl = DRE->getDecl(); 6502 6503 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6504 if (FDecl && FDecl->getBuiltinID()) { 6505 // Rewrite the function decl for this builtin by replacing parameters 6506 // with no explicit address space with the address space of the arguments 6507 // in ArgExprs. 6508 if ((FDecl = 6509 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6510 NDecl = FDecl; 6511 Fn = DeclRefExpr::Create( 6512 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6513 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6514 nullptr, DRE->isNonOdrUse()); 6515 } 6516 } 6517 } else if (isa<MemberExpr>(NakedFn)) 6518 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6519 6520 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6521 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6522 FD, /*Complain=*/true, Fn->getBeginLoc())) 6523 return ExprError(); 6524 6525 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6526 6527 // If this expression is a call to a builtin function in HIP device 6528 // compilation, allow a pointer-type argument to default address space to be 6529 // passed as a pointer-type parameter to a non-default address space. 6530 // If Arg is declared in the default address space and Param is declared 6531 // in a non-default address space, perform an implicit address space cast to 6532 // the parameter type. 6533 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6534 FD->getBuiltinID()) { 6535 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6536 ParmVarDecl *Param = FD->getParamDecl(Idx); 6537 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6538 !ArgExprs[Idx]->getType()->isPointerType()) 6539 continue; 6540 6541 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6542 auto ArgTy = ArgExprs[Idx]->getType(); 6543 auto ArgPtTy = ArgTy->getPointeeType(); 6544 auto ArgAS = ArgPtTy.getAddressSpace(); 6545 6546 // Only allow implicit casting from a non-default address space pointee 6547 // type to a default address space pointee type 6548 if (ArgAS != LangAS::Default || ParamAS == LangAS::Default) 6549 continue; 6550 6551 // First, ensure that the Arg is an RValue. 6552 if (ArgExprs[Idx]->isGLValue()) { 6553 ArgExprs[Idx] = ImplicitCastExpr::Create( 6554 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6555 nullptr, VK_PRValue, FPOptionsOverride()); 6556 } 6557 6558 // Construct a new arg type with address space of Param 6559 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6560 ArgPtQuals.setAddressSpace(ParamAS); 6561 auto NewArgPtTy = 6562 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6563 auto NewArgTy = 6564 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6565 ArgTy.getQualifiers()); 6566 6567 // Finally perform an implicit address space cast 6568 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6569 CK_AddressSpaceConversion) 6570 .get(); 6571 } 6572 } 6573 } 6574 6575 if (Context.isDependenceAllowed() && 6576 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6577 assert(!getLangOpts().CPlusPlus); 6578 assert((Fn->containsErrors() || 6579 llvm::any_of(ArgExprs, 6580 [](clang::Expr *E) { return E->containsErrors(); })) && 6581 "should only occur in error-recovery path."); 6582 QualType ReturnType = 6583 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6584 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6585 : Context.DependentTy; 6586 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6587 Expr::getValueKindForType(ReturnType), RParenLoc, 6588 CurFPFeatureOverrides()); 6589 } 6590 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6591 ExecConfig, IsExecConfig); 6592 } 6593 6594 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6595 // with the specified CallArgs 6596 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6597 MultiExprArg CallArgs) { 6598 StringRef Name = Context.BuiltinInfo.getName(Id); 6599 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6600 Sema::LookupOrdinaryName); 6601 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6602 6603 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6604 assert(BuiltInDecl && "failed to find builtin declaration"); 6605 6606 ExprResult DeclRef = 6607 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6608 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6609 6610 ExprResult Call = 6611 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6612 6613 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6614 return Call.get(); 6615 } 6616 6617 /// Parse a __builtin_astype expression. 6618 /// 6619 /// __builtin_astype( value, dst type ) 6620 /// 6621 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6622 SourceLocation BuiltinLoc, 6623 SourceLocation RParenLoc) { 6624 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6625 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6626 } 6627 6628 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6629 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6630 SourceLocation BuiltinLoc, 6631 SourceLocation RParenLoc) { 6632 ExprValueKind VK = VK_PRValue; 6633 ExprObjectKind OK = OK_Ordinary; 6634 QualType SrcTy = E->getType(); 6635 if (!SrcTy->isDependentType() && 6636 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6637 return ExprError( 6638 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6639 << DestTy << SrcTy << E->getSourceRange()); 6640 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6641 } 6642 6643 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6644 /// provided arguments. 6645 /// 6646 /// __builtin_convertvector( value, dst type ) 6647 /// 6648 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6649 SourceLocation BuiltinLoc, 6650 SourceLocation RParenLoc) { 6651 TypeSourceInfo *TInfo; 6652 GetTypeFromParser(ParsedDestTy, &TInfo); 6653 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6654 } 6655 6656 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6657 /// i.e. an expression not of \p OverloadTy. The expression should 6658 /// unary-convert to an expression of function-pointer or 6659 /// block-pointer type. 6660 /// 6661 /// \param NDecl the declaration being called, if available 6662 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6663 SourceLocation LParenLoc, 6664 ArrayRef<Expr *> Args, 6665 SourceLocation RParenLoc, Expr *Config, 6666 bool IsExecConfig, ADLCallKind UsesADL) { 6667 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6668 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6669 6670 // Functions with 'interrupt' attribute cannot be called directly. 6671 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6672 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6673 return ExprError(); 6674 } 6675 6676 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6677 // so there's some risk when calling out to non-interrupt handler functions 6678 // that the callee might not preserve them. This is easy to diagnose here, 6679 // but can be very challenging to debug. 6680 // Likewise, X86 interrupt handlers may only call routines with attribute 6681 // no_caller_saved_registers since there is no efficient way to 6682 // save and restore the non-GPR state. 6683 if (auto *Caller = getCurFunctionDecl()) { 6684 if (Caller->hasAttr<ARMInterruptAttr>()) { 6685 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6686 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6687 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6688 if (FDecl) 6689 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6690 } 6691 } 6692 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6693 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6694 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6695 if (FDecl) 6696 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6697 } 6698 } 6699 6700 // Promote the function operand. 6701 // We special-case function promotion here because we only allow promoting 6702 // builtin functions to function pointers in the callee of a call. 6703 ExprResult Result; 6704 QualType ResultTy; 6705 if (BuiltinID && 6706 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6707 // Extract the return type from the (builtin) function pointer type. 6708 // FIXME Several builtins still have setType in 6709 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6710 // Builtins.def to ensure they are correct before removing setType calls. 6711 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6712 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6713 ResultTy = FDecl->getCallResultType(); 6714 } else { 6715 Result = CallExprUnaryConversions(Fn); 6716 ResultTy = Context.BoolTy; 6717 } 6718 if (Result.isInvalid()) 6719 return ExprError(); 6720 Fn = Result.get(); 6721 6722 // Check for a valid function type, but only if it is not a builtin which 6723 // requires custom type checking. These will be handled by 6724 // CheckBuiltinFunctionCall below just after creation of the call expression. 6725 const FunctionType *FuncT = nullptr; 6726 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6727 retry: 6728 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6729 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6730 // have type pointer to function". 6731 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6732 if (!FuncT) 6733 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6734 << Fn->getType() << Fn->getSourceRange()); 6735 } else if (const BlockPointerType *BPT = 6736 Fn->getType()->getAs<BlockPointerType>()) { 6737 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6738 } else { 6739 // Handle calls to expressions of unknown-any type. 6740 if (Fn->getType() == Context.UnknownAnyTy) { 6741 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6742 if (rewrite.isInvalid()) 6743 return ExprError(); 6744 Fn = rewrite.get(); 6745 goto retry; 6746 } 6747 6748 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6749 << Fn->getType() << Fn->getSourceRange()); 6750 } 6751 } 6752 6753 // Get the number of parameters in the function prototype, if any. 6754 // We will allocate space for max(Args.size(), NumParams) arguments 6755 // in the call expression. 6756 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6757 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6758 6759 CallExpr *TheCall; 6760 if (Config) { 6761 assert(UsesADL == ADLCallKind::NotADL && 6762 "CUDAKernelCallExpr should not use ADL"); 6763 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6764 Args, ResultTy, VK_PRValue, RParenLoc, 6765 CurFPFeatureOverrides(), NumParams); 6766 } else { 6767 TheCall = 6768 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6769 CurFPFeatureOverrides(), NumParams, UsesADL); 6770 } 6771 6772 if (!Context.isDependenceAllowed()) { 6773 // Forget about the nulled arguments since typo correction 6774 // do not handle them well. 6775 TheCall->shrinkNumArgs(Args.size()); 6776 // C cannot always handle TypoExpr nodes in builtin calls and direct 6777 // function calls as their argument checking don't necessarily handle 6778 // dependent types properly, so make sure any TypoExprs have been 6779 // dealt with. 6780 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6781 if (!Result.isUsable()) return ExprError(); 6782 CallExpr *TheOldCall = TheCall; 6783 TheCall = dyn_cast<CallExpr>(Result.get()); 6784 bool CorrectedTypos = TheCall != TheOldCall; 6785 if (!TheCall) return Result; 6786 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6787 6788 // A new call expression node was created if some typos were corrected. 6789 // However it may not have been constructed with enough storage. In this 6790 // case, rebuild the node with enough storage. The waste of space is 6791 // immaterial since this only happens when some typos were corrected. 6792 if (CorrectedTypos && Args.size() < NumParams) { 6793 if (Config) 6794 TheCall = CUDAKernelCallExpr::Create( 6795 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6796 RParenLoc, CurFPFeatureOverrides(), NumParams); 6797 else 6798 TheCall = 6799 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6800 CurFPFeatureOverrides(), NumParams, UsesADL); 6801 } 6802 // We can now handle the nulled arguments for the default arguments. 6803 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6804 } 6805 6806 // Bail out early if calling a builtin with custom type checking. 6807 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6808 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6809 6810 if (getLangOpts().CUDA) { 6811 if (Config) { 6812 // CUDA: Kernel calls must be to global functions 6813 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6814 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6815 << FDecl << Fn->getSourceRange()); 6816 6817 // CUDA: Kernel function must have 'void' return type 6818 if (!FuncT->getReturnType()->isVoidType() && 6819 !FuncT->getReturnType()->getAs<AutoType>() && 6820 !FuncT->getReturnType()->isInstantiationDependentType()) 6821 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6822 << Fn->getType() << Fn->getSourceRange()); 6823 } else { 6824 // CUDA: Calls to global functions must be configured 6825 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6826 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6827 << FDecl << Fn->getSourceRange()); 6828 } 6829 } 6830 6831 // Check for a valid return type 6832 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6833 FDecl)) 6834 return ExprError(); 6835 6836 // We know the result type of the call, set it. 6837 TheCall->setType(FuncT->getCallResultType(Context)); 6838 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6839 6840 if (Proto) { 6841 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6842 IsExecConfig)) 6843 return ExprError(); 6844 } else { 6845 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6846 6847 if (FDecl) { 6848 // Check if we have too few/too many template arguments, based 6849 // on our knowledge of the function definition. 6850 const FunctionDecl *Def = nullptr; 6851 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6852 Proto = Def->getType()->getAs<FunctionProtoType>(); 6853 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6854 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6855 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6856 } 6857 6858 // If the function we're calling isn't a function prototype, but we have 6859 // a function prototype from a prior declaratiom, use that prototype. 6860 if (!FDecl->hasPrototype()) 6861 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6862 } 6863 6864 // Promote the arguments (C99 6.5.2.2p6). 6865 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6866 Expr *Arg = Args[i]; 6867 6868 if (Proto && i < Proto->getNumParams()) { 6869 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6870 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6871 ExprResult ArgE = 6872 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6873 if (ArgE.isInvalid()) 6874 return true; 6875 6876 Arg = ArgE.getAs<Expr>(); 6877 6878 } else { 6879 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6880 6881 if (ArgE.isInvalid()) 6882 return true; 6883 6884 Arg = ArgE.getAs<Expr>(); 6885 } 6886 6887 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6888 diag::err_call_incomplete_argument, Arg)) 6889 return ExprError(); 6890 6891 TheCall->setArg(i, Arg); 6892 } 6893 TheCall->computeDependence(); 6894 } 6895 6896 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6897 if (!Method->isStatic()) 6898 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6899 << Fn->getSourceRange()); 6900 6901 // Check for sentinels 6902 if (NDecl) 6903 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6904 6905 // Warn for unions passing across security boundary (CMSE). 6906 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6907 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6908 if (const auto *RT = 6909 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6910 if (RT->getDecl()->isOrContainsUnion()) 6911 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6912 << 0 << i; 6913 } 6914 } 6915 } 6916 6917 // Do special checking on direct calls to functions. 6918 if (FDecl) { 6919 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6920 return ExprError(); 6921 6922 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6923 6924 if (BuiltinID) 6925 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6926 } else if (NDecl) { 6927 if (CheckPointerCall(NDecl, TheCall, Proto)) 6928 return ExprError(); 6929 } else { 6930 if (CheckOtherCall(TheCall, Proto)) 6931 return ExprError(); 6932 } 6933 6934 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6935 } 6936 6937 ExprResult 6938 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6939 SourceLocation RParenLoc, Expr *InitExpr) { 6940 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6941 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6942 6943 TypeSourceInfo *TInfo; 6944 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6945 if (!TInfo) 6946 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6947 6948 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6949 } 6950 6951 ExprResult 6952 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6953 SourceLocation RParenLoc, Expr *LiteralExpr) { 6954 QualType literalType = TInfo->getType(); 6955 6956 if (literalType->isArrayType()) { 6957 if (RequireCompleteSizedType( 6958 LParenLoc, Context.getBaseElementType(literalType), 6959 diag::err_array_incomplete_or_sizeless_type, 6960 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6961 return ExprError(); 6962 if (literalType->isVariableArrayType()) { 6963 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6964 diag::err_variable_object_no_init)) { 6965 return ExprError(); 6966 } 6967 } 6968 } else if (!literalType->isDependentType() && 6969 RequireCompleteType(LParenLoc, literalType, 6970 diag::err_typecheck_decl_incomplete_type, 6971 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6972 return ExprError(); 6973 6974 InitializedEntity Entity 6975 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6976 InitializationKind Kind 6977 = InitializationKind::CreateCStyleCast(LParenLoc, 6978 SourceRange(LParenLoc, RParenLoc), 6979 /*InitList=*/true); 6980 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6981 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6982 &literalType); 6983 if (Result.isInvalid()) 6984 return ExprError(); 6985 LiteralExpr = Result.get(); 6986 6987 bool isFileScope = !CurContext->isFunctionOrMethod(); 6988 6989 // In C, compound literals are l-values for some reason. 6990 // For GCC compatibility, in C++, file-scope array compound literals with 6991 // constant initializers are also l-values, and compound literals are 6992 // otherwise prvalues. 6993 // 6994 // (GCC also treats C++ list-initialized file-scope array prvalues with 6995 // constant initializers as l-values, but that's non-conforming, so we don't 6996 // follow it there.) 6997 // 6998 // FIXME: It would be better to handle the lvalue cases as materializing and 6999 // lifetime-extending a temporary object, but our materialized temporaries 7000 // representation only supports lifetime extension from a variable, not "out 7001 // of thin air". 7002 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7003 // is bound to the result of applying array-to-pointer decay to the compound 7004 // literal. 7005 // FIXME: GCC supports compound literals of reference type, which should 7006 // obviously have a value kind derived from the kind of reference involved. 7007 ExprValueKind VK = 7008 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7009 ? VK_PRValue 7010 : VK_LValue; 7011 7012 if (isFileScope) 7013 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7014 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7015 Expr *Init = ILE->getInit(i); 7016 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7017 } 7018 7019 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7020 VK, LiteralExpr, isFileScope); 7021 if (isFileScope) { 7022 if (!LiteralExpr->isTypeDependent() && 7023 !LiteralExpr->isValueDependent() && 7024 !literalType->isDependentType()) // C99 6.5.2.5p3 7025 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7026 return ExprError(); 7027 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7028 literalType.getAddressSpace() != LangAS::Default) { 7029 // Embedded-C extensions to C99 6.5.2.5: 7030 // "If the compound literal occurs inside the body of a function, the 7031 // type name shall not be qualified by an address-space qualifier." 7032 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7033 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7034 return ExprError(); 7035 } 7036 7037 if (!isFileScope && !getLangOpts().CPlusPlus) { 7038 // Compound literals that have automatic storage duration are destroyed at 7039 // the end of the scope in C; in C++, they're just temporaries. 7040 7041 // Emit diagnostics if it is or contains a C union type that is non-trivial 7042 // to destruct. 7043 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7044 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7045 NTCUC_CompoundLiteral, NTCUK_Destruct); 7046 7047 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7048 if (literalType.isDestructedType()) { 7049 Cleanup.setExprNeedsCleanups(true); 7050 ExprCleanupObjects.push_back(E); 7051 getCurFunction()->setHasBranchProtectedScope(); 7052 } 7053 } 7054 7055 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7056 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7057 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7058 E->getInitializer()->getExprLoc()); 7059 7060 return MaybeBindToTemporary(E); 7061 } 7062 7063 ExprResult 7064 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7065 SourceLocation RBraceLoc) { 7066 // Only produce each kind of designated initialization diagnostic once. 7067 SourceLocation FirstDesignator; 7068 bool DiagnosedArrayDesignator = false; 7069 bool DiagnosedNestedDesignator = false; 7070 bool DiagnosedMixedDesignator = false; 7071 7072 // Check that any designated initializers are syntactically valid in the 7073 // current language mode. 7074 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7075 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7076 if (FirstDesignator.isInvalid()) 7077 FirstDesignator = DIE->getBeginLoc(); 7078 7079 if (!getLangOpts().CPlusPlus) 7080 break; 7081 7082 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7083 DiagnosedNestedDesignator = true; 7084 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7085 << DIE->getDesignatorsSourceRange(); 7086 } 7087 7088 for (auto &Desig : DIE->designators()) { 7089 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7090 DiagnosedArrayDesignator = true; 7091 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7092 << Desig.getSourceRange(); 7093 } 7094 } 7095 7096 if (!DiagnosedMixedDesignator && 7097 !isa<DesignatedInitExpr>(InitArgList[0])) { 7098 DiagnosedMixedDesignator = true; 7099 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7100 << DIE->getSourceRange(); 7101 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7102 << InitArgList[0]->getSourceRange(); 7103 } 7104 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7105 isa<DesignatedInitExpr>(InitArgList[0])) { 7106 DiagnosedMixedDesignator = true; 7107 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7108 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7109 << DIE->getSourceRange(); 7110 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7111 << InitArgList[I]->getSourceRange(); 7112 } 7113 } 7114 7115 if (FirstDesignator.isValid()) { 7116 // Only diagnose designated initiaization as a C++20 extension if we didn't 7117 // already diagnose use of (non-C++20) C99 designator syntax. 7118 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7119 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7120 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7121 ? diag::warn_cxx17_compat_designated_init 7122 : diag::ext_cxx_designated_init); 7123 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7124 Diag(FirstDesignator, diag::ext_designated_init); 7125 } 7126 } 7127 7128 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7129 } 7130 7131 ExprResult 7132 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7133 SourceLocation RBraceLoc) { 7134 // Semantic analysis for initializers is done by ActOnDeclarator() and 7135 // CheckInitializer() - it requires knowledge of the object being initialized. 7136 7137 // Immediately handle non-overload placeholders. Overloads can be 7138 // resolved contextually, but everything else here can't. 7139 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7140 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7141 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7142 7143 // Ignore failures; dropping the entire initializer list because 7144 // of one failure would be terrible for indexing/etc. 7145 if (result.isInvalid()) continue; 7146 7147 InitArgList[I] = result.get(); 7148 } 7149 } 7150 7151 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7152 RBraceLoc); 7153 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7154 return E; 7155 } 7156 7157 /// Do an explicit extend of the given block pointer if we're in ARC. 7158 void Sema::maybeExtendBlockObject(ExprResult &E) { 7159 assert(E.get()->getType()->isBlockPointerType()); 7160 assert(E.get()->isPRValue()); 7161 7162 // Only do this in an r-value context. 7163 if (!getLangOpts().ObjCAutoRefCount) return; 7164 7165 E = ImplicitCastExpr::Create( 7166 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7167 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7168 Cleanup.setExprNeedsCleanups(true); 7169 } 7170 7171 /// Prepare a conversion of the given expression to an ObjC object 7172 /// pointer type. 7173 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7174 QualType type = E.get()->getType(); 7175 if (type->isObjCObjectPointerType()) { 7176 return CK_BitCast; 7177 } else if (type->isBlockPointerType()) { 7178 maybeExtendBlockObject(E); 7179 return CK_BlockPointerToObjCPointerCast; 7180 } else { 7181 assert(type->isPointerType()); 7182 return CK_CPointerToObjCPointerCast; 7183 } 7184 } 7185 7186 /// Prepares for a scalar cast, performing all the necessary stages 7187 /// except the final cast and returning the kind required. 7188 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7189 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7190 // Also, callers should have filtered out the invalid cases with 7191 // pointers. Everything else should be possible. 7192 7193 QualType SrcTy = Src.get()->getType(); 7194 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7195 return CK_NoOp; 7196 7197 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7198 case Type::STK_MemberPointer: 7199 llvm_unreachable("member pointer type in C"); 7200 7201 case Type::STK_CPointer: 7202 case Type::STK_BlockPointer: 7203 case Type::STK_ObjCObjectPointer: 7204 switch (DestTy->getScalarTypeKind()) { 7205 case Type::STK_CPointer: { 7206 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7207 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7208 if (SrcAS != DestAS) 7209 return CK_AddressSpaceConversion; 7210 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7211 return CK_NoOp; 7212 return CK_BitCast; 7213 } 7214 case Type::STK_BlockPointer: 7215 return (SrcKind == Type::STK_BlockPointer 7216 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7217 case Type::STK_ObjCObjectPointer: 7218 if (SrcKind == Type::STK_ObjCObjectPointer) 7219 return CK_BitCast; 7220 if (SrcKind == Type::STK_CPointer) 7221 return CK_CPointerToObjCPointerCast; 7222 maybeExtendBlockObject(Src); 7223 return CK_BlockPointerToObjCPointerCast; 7224 case Type::STK_Bool: 7225 return CK_PointerToBoolean; 7226 case Type::STK_Integral: 7227 return CK_PointerToIntegral; 7228 case Type::STK_Floating: 7229 case Type::STK_FloatingComplex: 7230 case Type::STK_IntegralComplex: 7231 case Type::STK_MemberPointer: 7232 case Type::STK_FixedPoint: 7233 llvm_unreachable("illegal cast from pointer"); 7234 } 7235 llvm_unreachable("Should have returned before this"); 7236 7237 case Type::STK_FixedPoint: 7238 switch (DestTy->getScalarTypeKind()) { 7239 case Type::STK_FixedPoint: 7240 return CK_FixedPointCast; 7241 case Type::STK_Bool: 7242 return CK_FixedPointToBoolean; 7243 case Type::STK_Integral: 7244 return CK_FixedPointToIntegral; 7245 case Type::STK_Floating: 7246 return CK_FixedPointToFloating; 7247 case Type::STK_IntegralComplex: 7248 case Type::STK_FloatingComplex: 7249 Diag(Src.get()->getExprLoc(), 7250 diag::err_unimplemented_conversion_with_fixed_point_type) 7251 << DestTy; 7252 return CK_IntegralCast; 7253 case Type::STK_CPointer: 7254 case Type::STK_ObjCObjectPointer: 7255 case Type::STK_BlockPointer: 7256 case Type::STK_MemberPointer: 7257 llvm_unreachable("illegal cast to pointer type"); 7258 } 7259 llvm_unreachable("Should have returned before this"); 7260 7261 case Type::STK_Bool: // casting from bool is like casting from an integer 7262 case Type::STK_Integral: 7263 switch (DestTy->getScalarTypeKind()) { 7264 case Type::STK_CPointer: 7265 case Type::STK_ObjCObjectPointer: 7266 case Type::STK_BlockPointer: 7267 if (Src.get()->isNullPointerConstant(Context, 7268 Expr::NPC_ValueDependentIsNull)) 7269 return CK_NullToPointer; 7270 return CK_IntegralToPointer; 7271 case Type::STK_Bool: 7272 return CK_IntegralToBoolean; 7273 case Type::STK_Integral: 7274 return CK_IntegralCast; 7275 case Type::STK_Floating: 7276 return CK_IntegralToFloating; 7277 case Type::STK_IntegralComplex: 7278 Src = ImpCastExprToType(Src.get(), 7279 DestTy->castAs<ComplexType>()->getElementType(), 7280 CK_IntegralCast); 7281 return CK_IntegralRealToComplex; 7282 case Type::STK_FloatingComplex: 7283 Src = ImpCastExprToType(Src.get(), 7284 DestTy->castAs<ComplexType>()->getElementType(), 7285 CK_IntegralToFloating); 7286 return CK_FloatingRealToComplex; 7287 case Type::STK_MemberPointer: 7288 llvm_unreachable("member pointer type in C"); 7289 case Type::STK_FixedPoint: 7290 return CK_IntegralToFixedPoint; 7291 } 7292 llvm_unreachable("Should have returned before this"); 7293 7294 case Type::STK_Floating: 7295 switch (DestTy->getScalarTypeKind()) { 7296 case Type::STK_Floating: 7297 return CK_FloatingCast; 7298 case Type::STK_Bool: 7299 return CK_FloatingToBoolean; 7300 case Type::STK_Integral: 7301 return CK_FloatingToIntegral; 7302 case Type::STK_FloatingComplex: 7303 Src = ImpCastExprToType(Src.get(), 7304 DestTy->castAs<ComplexType>()->getElementType(), 7305 CK_FloatingCast); 7306 return CK_FloatingRealToComplex; 7307 case Type::STK_IntegralComplex: 7308 Src = ImpCastExprToType(Src.get(), 7309 DestTy->castAs<ComplexType>()->getElementType(), 7310 CK_FloatingToIntegral); 7311 return CK_IntegralRealToComplex; 7312 case Type::STK_CPointer: 7313 case Type::STK_ObjCObjectPointer: 7314 case Type::STK_BlockPointer: 7315 llvm_unreachable("valid float->pointer cast?"); 7316 case Type::STK_MemberPointer: 7317 llvm_unreachable("member pointer type in C"); 7318 case Type::STK_FixedPoint: 7319 return CK_FloatingToFixedPoint; 7320 } 7321 llvm_unreachable("Should have returned before this"); 7322 7323 case Type::STK_FloatingComplex: 7324 switch (DestTy->getScalarTypeKind()) { 7325 case Type::STK_FloatingComplex: 7326 return CK_FloatingComplexCast; 7327 case Type::STK_IntegralComplex: 7328 return CK_FloatingComplexToIntegralComplex; 7329 case Type::STK_Floating: { 7330 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7331 if (Context.hasSameType(ET, DestTy)) 7332 return CK_FloatingComplexToReal; 7333 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7334 return CK_FloatingCast; 7335 } 7336 case Type::STK_Bool: 7337 return CK_FloatingComplexToBoolean; 7338 case Type::STK_Integral: 7339 Src = ImpCastExprToType(Src.get(), 7340 SrcTy->castAs<ComplexType>()->getElementType(), 7341 CK_FloatingComplexToReal); 7342 return CK_FloatingToIntegral; 7343 case Type::STK_CPointer: 7344 case Type::STK_ObjCObjectPointer: 7345 case Type::STK_BlockPointer: 7346 llvm_unreachable("valid complex float->pointer cast?"); 7347 case Type::STK_MemberPointer: 7348 llvm_unreachable("member pointer type in C"); 7349 case Type::STK_FixedPoint: 7350 Diag(Src.get()->getExprLoc(), 7351 diag::err_unimplemented_conversion_with_fixed_point_type) 7352 << SrcTy; 7353 return CK_IntegralCast; 7354 } 7355 llvm_unreachable("Should have returned before this"); 7356 7357 case Type::STK_IntegralComplex: 7358 switch (DestTy->getScalarTypeKind()) { 7359 case Type::STK_FloatingComplex: 7360 return CK_IntegralComplexToFloatingComplex; 7361 case Type::STK_IntegralComplex: 7362 return CK_IntegralComplexCast; 7363 case Type::STK_Integral: { 7364 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7365 if (Context.hasSameType(ET, DestTy)) 7366 return CK_IntegralComplexToReal; 7367 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7368 return CK_IntegralCast; 7369 } 7370 case Type::STK_Bool: 7371 return CK_IntegralComplexToBoolean; 7372 case Type::STK_Floating: 7373 Src = ImpCastExprToType(Src.get(), 7374 SrcTy->castAs<ComplexType>()->getElementType(), 7375 CK_IntegralComplexToReal); 7376 return CK_IntegralToFloating; 7377 case Type::STK_CPointer: 7378 case Type::STK_ObjCObjectPointer: 7379 case Type::STK_BlockPointer: 7380 llvm_unreachable("valid complex int->pointer cast?"); 7381 case Type::STK_MemberPointer: 7382 llvm_unreachable("member pointer type in C"); 7383 case Type::STK_FixedPoint: 7384 Diag(Src.get()->getExprLoc(), 7385 diag::err_unimplemented_conversion_with_fixed_point_type) 7386 << SrcTy; 7387 return CK_IntegralCast; 7388 } 7389 llvm_unreachable("Should have returned before this"); 7390 } 7391 7392 llvm_unreachable("Unhandled scalar cast"); 7393 } 7394 7395 static bool breakDownVectorType(QualType type, uint64_t &len, 7396 QualType &eltType) { 7397 // Vectors are simple. 7398 if (const VectorType *vecType = type->getAs<VectorType>()) { 7399 len = vecType->getNumElements(); 7400 eltType = vecType->getElementType(); 7401 assert(eltType->isScalarType()); 7402 return true; 7403 } 7404 7405 // We allow lax conversion to and from non-vector types, but only if 7406 // they're real types (i.e. non-complex, non-pointer scalar types). 7407 if (!type->isRealType()) return false; 7408 7409 len = 1; 7410 eltType = type; 7411 return true; 7412 } 7413 7414 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7415 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7416 /// allowed? 7417 /// 7418 /// This will also return false if the two given types do not make sense from 7419 /// the perspective of SVE bitcasts. 7420 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7421 assert(srcTy->isVectorType() || destTy->isVectorType()); 7422 7423 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7424 if (!FirstType->isSizelessBuiltinType()) 7425 return false; 7426 7427 const auto *VecTy = SecondType->getAs<VectorType>(); 7428 return VecTy && 7429 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7430 }; 7431 7432 return ValidScalableConversion(srcTy, destTy) || 7433 ValidScalableConversion(destTy, srcTy); 7434 } 7435 7436 /// Are the two types matrix types and do they have the same dimensions i.e. 7437 /// do they have the same number of rows and the same number of columns? 7438 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7439 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7440 return false; 7441 7442 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7443 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7444 7445 return matSrcType->getNumRows() == matDestType->getNumRows() && 7446 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7447 } 7448 7449 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7450 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7451 7452 uint64_t SrcLen, DestLen; 7453 QualType SrcEltTy, DestEltTy; 7454 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7455 return false; 7456 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7457 return false; 7458 7459 // ASTContext::getTypeSize will return the size rounded up to a 7460 // power of 2, so instead of using that, we need to use the raw 7461 // element size multiplied by the element count. 7462 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7463 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7464 7465 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7466 } 7467 7468 /// Are the two types lax-compatible vector types? That is, given 7469 /// that one of them is a vector, do they have equal storage sizes, 7470 /// where the storage size is the number of elements times the element 7471 /// size? 7472 /// 7473 /// This will also return false if either of the types is neither a 7474 /// vector nor a real type. 7475 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7476 assert(destTy->isVectorType() || srcTy->isVectorType()); 7477 7478 // Disallow lax conversions between scalars and ExtVectors (these 7479 // conversions are allowed for other vector types because common headers 7480 // depend on them). Most scalar OP ExtVector cases are handled by the 7481 // splat path anyway, which does what we want (convert, not bitcast). 7482 // What this rules out for ExtVectors is crazy things like char4*float. 7483 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7484 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7485 7486 return areVectorTypesSameSize(srcTy, destTy); 7487 } 7488 7489 /// Is this a legal conversion between two types, one of which is 7490 /// known to be a vector type? 7491 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7492 assert(destTy->isVectorType() || srcTy->isVectorType()); 7493 7494 switch (Context.getLangOpts().getLaxVectorConversions()) { 7495 case LangOptions::LaxVectorConversionKind::None: 7496 return false; 7497 7498 case LangOptions::LaxVectorConversionKind::Integer: 7499 if (!srcTy->isIntegralOrEnumerationType()) { 7500 auto *Vec = srcTy->getAs<VectorType>(); 7501 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7502 return false; 7503 } 7504 if (!destTy->isIntegralOrEnumerationType()) { 7505 auto *Vec = destTy->getAs<VectorType>(); 7506 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7507 return false; 7508 } 7509 // OK, integer (vector) -> integer (vector) bitcast. 7510 break; 7511 7512 case LangOptions::LaxVectorConversionKind::All: 7513 break; 7514 } 7515 7516 return areLaxCompatibleVectorTypes(srcTy, destTy); 7517 } 7518 7519 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7520 CastKind &Kind) { 7521 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7522 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7523 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7524 << DestTy << SrcTy << R; 7525 } 7526 } else if (SrcTy->isMatrixType()) { 7527 return Diag(R.getBegin(), 7528 diag::err_invalid_conversion_between_matrix_and_type) 7529 << SrcTy << DestTy << R; 7530 } else if (DestTy->isMatrixType()) { 7531 return Diag(R.getBegin(), 7532 diag::err_invalid_conversion_between_matrix_and_type) 7533 << DestTy << SrcTy << R; 7534 } 7535 7536 Kind = CK_MatrixCast; 7537 return false; 7538 } 7539 7540 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7541 CastKind &Kind) { 7542 assert(VectorTy->isVectorType() && "Not a vector type!"); 7543 7544 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7545 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7546 return Diag(R.getBegin(), 7547 Ty->isVectorType() ? 7548 diag::err_invalid_conversion_between_vectors : 7549 diag::err_invalid_conversion_between_vector_and_integer) 7550 << VectorTy << Ty << R; 7551 } else 7552 return Diag(R.getBegin(), 7553 diag::err_invalid_conversion_between_vector_and_scalar) 7554 << VectorTy << Ty << R; 7555 7556 Kind = CK_BitCast; 7557 return false; 7558 } 7559 7560 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7561 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7562 7563 if (DestElemTy == SplattedExpr->getType()) 7564 return SplattedExpr; 7565 7566 assert(DestElemTy->isFloatingType() || 7567 DestElemTy->isIntegralOrEnumerationType()); 7568 7569 CastKind CK; 7570 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7571 // OpenCL requires that we convert `true` boolean expressions to -1, but 7572 // only when splatting vectors. 7573 if (DestElemTy->isFloatingType()) { 7574 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7575 // in two steps: boolean to signed integral, then to floating. 7576 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7577 CK_BooleanToSignedIntegral); 7578 SplattedExpr = CastExprRes.get(); 7579 CK = CK_IntegralToFloating; 7580 } else { 7581 CK = CK_BooleanToSignedIntegral; 7582 } 7583 } else { 7584 ExprResult CastExprRes = SplattedExpr; 7585 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7586 if (CastExprRes.isInvalid()) 7587 return ExprError(); 7588 SplattedExpr = CastExprRes.get(); 7589 } 7590 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7591 } 7592 7593 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7594 Expr *CastExpr, CastKind &Kind) { 7595 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7596 7597 QualType SrcTy = CastExpr->getType(); 7598 7599 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7600 // an ExtVectorType. 7601 // In OpenCL, casts between vectors of different types are not allowed. 7602 // (See OpenCL 6.2). 7603 if (SrcTy->isVectorType()) { 7604 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7605 (getLangOpts().OpenCL && 7606 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7607 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7608 << DestTy << SrcTy << R; 7609 return ExprError(); 7610 } 7611 Kind = CK_BitCast; 7612 return CastExpr; 7613 } 7614 7615 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7616 // conversion will take place first from scalar to elt type, and then 7617 // splat from elt type to vector. 7618 if (SrcTy->isPointerType()) 7619 return Diag(R.getBegin(), 7620 diag::err_invalid_conversion_between_vector_and_scalar) 7621 << DestTy << SrcTy << R; 7622 7623 Kind = CK_VectorSplat; 7624 return prepareVectorSplat(DestTy, CastExpr); 7625 } 7626 7627 ExprResult 7628 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7629 Declarator &D, ParsedType &Ty, 7630 SourceLocation RParenLoc, Expr *CastExpr) { 7631 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7632 "ActOnCastExpr(): missing type or expr"); 7633 7634 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7635 if (D.isInvalidType()) 7636 return ExprError(); 7637 7638 if (getLangOpts().CPlusPlus) { 7639 // Check that there are no default arguments (C++ only). 7640 CheckExtraCXXDefaultArguments(D); 7641 } else { 7642 // Make sure any TypoExprs have been dealt with. 7643 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7644 if (!Res.isUsable()) 7645 return ExprError(); 7646 CastExpr = Res.get(); 7647 } 7648 7649 checkUnusedDeclAttributes(D); 7650 7651 QualType castType = castTInfo->getType(); 7652 Ty = CreateParsedType(castType, castTInfo); 7653 7654 bool isVectorLiteral = false; 7655 7656 // Check for an altivec or OpenCL literal, 7657 // i.e. all the elements are integer constants. 7658 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7659 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7660 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7661 && castType->isVectorType() && (PE || PLE)) { 7662 if (PLE && PLE->getNumExprs() == 0) { 7663 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7664 return ExprError(); 7665 } 7666 if (PE || PLE->getNumExprs() == 1) { 7667 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7668 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7669 isVectorLiteral = true; 7670 } 7671 else 7672 isVectorLiteral = true; 7673 } 7674 7675 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7676 // then handle it as such. 7677 if (isVectorLiteral) 7678 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7679 7680 // If the Expr being casted is a ParenListExpr, handle it specially. 7681 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7682 // sequence of BinOp comma operators. 7683 if (isa<ParenListExpr>(CastExpr)) { 7684 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7685 if (Result.isInvalid()) return ExprError(); 7686 CastExpr = Result.get(); 7687 } 7688 7689 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7690 !getSourceManager().isInSystemMacro(LParenLoc)) 7691 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7692 7693 CheckTollFreeBridgeCast(castType, CastExpr); 7694 7695 CheckObjCBridgeRelatedCast(castType, CastExpr); 7696 7697 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7698 7699 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7700 } 7701 7702 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7703 SourceLocation RParenLoc, Expr *E, 7704 TypeSourceInfo *TInfo) { 7705 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7706 "Expected paren or paren list expression"); 7707 7708 Expr **exprs; 7709 unsigned numExprs; 7710 Expr *subExpr; 7711 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7712 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7713 LiteralLParenLoc = PE->getLParenLoc(); 7714 LiteralRParenLoc = PE->getRParenLoc(); 7715 exprs = PE->getExprs(); 7716 numExprs = PE->getNumExprs(); 7717 } else { // isa<ParenExpr> by assertion at function entrance 7718 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7719 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7720 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7721 exprs = &subExpr; 7722 numExprs = 1; 7723 } 7724 7725 QualType Ty = TInfo->getType(); 7726 assert(Ty->isVectorType() && "Expected vector type"); 7727 7728 SmallVector<Expr *, 8> initExprs; 7729 const VectorType *VTy = Ty->castAs<VectorType>(); 7730 unsigned numElems = VTy->getNumElements(); 7731 7732 // '(...)' form of vector initialization in AltiVec: the number of 7733 // initializers must be one or must match the size of the vector. 7734 // If a single value is specified in the initializer then it will be 7735 // replicated to all the components of the vector 7736 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7737 VTy->getElementType())) 7738 return ExprError(); 7739 if (ShouldSplatAltivecScalarInCast(VTy)) { 7740 // The number of initializers must be one or must match the size of the 7741 // vector. If a single value is specified in the initializer then it will 7742 // be replicated to all the components of the vector 7743 if (numExprs == 1) { 7744 QualType ElemTy = VTy->getElementType(); 7745 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7746 if (Literal.isInvalid()) 7747 return ExprError(); 7748 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7749 PrepareScalarCast(Literal, ElemTy)); 7750 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7751 } 7752 else if (numExprs < numElems) { 7753 Diag(E->getExprLoc(), 7754 diag::err_incorrect_number_of_vector_initializers); 7755 return ExprError(); 7756 } 7757 else 7758 initExprs.append(exprs, exprs + numExprs); 7759 } 7760 else { 7761 // For OpenCL, when the number of initializers is a single value, 7762 // it will be replicated to all components of the vector. 7763 if (getLangOpts().OpenCL && 7764 VTy->getVectorKind() == VectorType::GenericVector && 7765 numExprs == 1) { 7766 QualType ElemTy = VTy->getElementType(); 7767 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7768 if (Literal.isInvalid()) 7769 return ExprError(); 7770 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7771 PrepareScalarCast(Literal, ElemTy)); 7772 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7773 } 7774 7775 initExprs.append(exprs, exprs + numExprs); 7776 } 7777 // FIXME: This means that pretty-printing the final AST will produce curly 7778 // braces instead of the original commas. 7779 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7780 initExprs, LiteralRParenLoc); 7781 initE->setType(Ty); 7782 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7783 } 7784 7785 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7786 /// the ParenListExpr into a sequence of comma binary operators. 7787 ExprResult 7788 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7789 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7790 if (!E) 7791 return OrigExpr; 7792 7793 ExprResult Result(E->getExpr(0)); 7794 7795 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7796 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7797 E->getExpr(i)); 7798 7799 if (Result.isInvalid()) return ExprError(); 7800 7801 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7802 } 7803 7804 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7805 SourceLocation R, 7806 MultiExprArg Val) { 7807 return ParenListExpr::Create(Context, L, Val, R); 7808 } 7809 7810 /// Emit a specialized diagnostic when one expression is a null pointer 7811 /// constant and the other is not a pointer. Returns true if a diagnostic is 7812 /// emitted. 7813 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7814 SourceLocation QuestionLoc) { 7815 Expr *NullExpr = LHSExpr; 7816 Expr *NonPointerExpr = RHSExpr; 7817 Expr::NullPointerConstantKind NullKind = 7818 NullExpr->isNullPointerConstant(Context, 7819 Expr::NPC_ValueDependentIsNotNull); 7820 7821 if (NullKind == Expr::NPCK_NotNull) { 7822 NullExpr = RHSExpr; 7823 NonPointerExpr = LHSExpr; 7824 NullKind = 7825 NullExpr->isNullPointerConstant(Context, 7826 Expr::NPC_ValueDependentIsNotNull); 7827 } 7828 7829 if (NullKind == Expr::NPCK_NotNull) 7830 return false; 7831 7832 if (NullKind == Expr::NPCK_ZeroExpression) 7833 return false; 7834 7835 if (NullKind == Expr::NPCK_ZeroLiteral) { 7836 // In this case, check to make sure that we got here from a "NULL" 7837 // string in the source code. 7838 NullExpr = NullExpr->IgnoreParenImpCasts(); 7839 SourceLocation loc = NullExpr->getExprLoc(); 7840 if (!findMacroSpelling(loc, "NULL")) 7841 return false; 7842 } 7843 7844 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7845 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7846 << NonPointerExpr->getType() << DiagType 7847 << NonPointerExpr->getSourceRange(); 7848 return true; 7849 } 7850 7851 /// Return false if the condition expression is valid, true otherwise. 7852 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7853 QualType CondTy = Cond->getType(); 7854 7855 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7856 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7857 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7858 << CondTy << Cond->getSourceRange(); 7859 return true; 7860 } 7861 7862 // C99 6.5.15p2 7863 if (CondTy->isScalarType()) return false; 7864 7865 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7866 << CondTy << Cond->getSourceRange(); 7867 return true; 7868 } 7869 7870 /// Handle when one or both operands are void type. 7871 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7872 ExprResult &RHS) { 7873 Expr *LHSExpr = LHS.get(); 7874 Expr *RHSExpr = RHS.get(); 7875 7876 if (!LHSExpr->getType()->isVoidType()) 7877 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7878 << RHSExpr->getSourceRange(); 7879 if (!RHSExpr->getType()->isVoidType()) 7880 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7881 << LHSExpr->getSourceRange(); 7882 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7883 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7884 return S.Context.VoidTy; 7885 } 7886 7887 /// Return false if the NullExpr can be promoted to PointerTy, 7888 /// true otherwise. 7889 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7890 QualType PointerTy) { 7891 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7892 !NullExpr.get()->isNullPointerConstant(S.Context, 7893 Expr::NPC_ValueDependentIsNull)) 7894 return true; 7895 7896 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7897 return false; 7898 } 7899 7900 /// Checks compatibility between two pointers and return the resulting 7901 /// type. 7902 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7903 ExprResult &RHS, 7904 SourceLocation Loc) { 7905 QualType LHSTy = LHS.get()->getType(); 7906 QualType RHSTy = RHS.get()->getType(); 7907 7908 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7909 // Two identical pointers types are always compatible. 7910 return LHSTy; 7911 } 7912 7913 QualType lhptee, rhptee; 7914 7915 // Get the pointee types. 7916 bool IsBlockPointer = false; 7917 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7918 lhptee = LHSBTy->getPointeeType(); 7919 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7920 IsBlockPointer = true; 7921 } else { 7922 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7923 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7924 } 7925 7926 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7927 // differently qualified versions of compatible types, the result type is 7928 // a pointer to an appropriately qualified version of the composite 7929 // type. 7930 7931 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7932 // clause doesn't make sense for our extensions. E.g. address space 2 should 7933 // be incompatible with address space 3: they may live on different devices or 7934 // anything. 7935 Qualifiers lhQual = lhptee.getQualifiers(); 7936 Qualifiers rhQual = rhptee.getQualifiers(); 7937 7938 LangAS ResultAddrSpace = LangAS::Default; 7939 LangAS LAddrSpace = lhQual.getAddressSpace(); 7940 LangAS RAddrSpace = rhQual.getAddressSpace(); 7941 7942 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7943 // spaces is disallowed. 7944 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7945 ResultAddrSpace = LAddrSpace; 7946 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7947 ResultAddrSpace = RAddrSpace; 7948 else { 7949 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7950 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7951 << RHS.get()->getSourceRange(); 7952 return QualType(); 7953 } 7954 7955 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7956 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7957 lhQual.removeCVRQualifiers(); 7958 rhQual.removeCVRQualifiers(); 7959 7960 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7961 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7962 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7963 // qual types are compatible iff 7964 // * corresponded types are compatible 7965 // * CVR qualifiers are equal 7966 // * address spaces are equal 7967 // Thus for conditional operator we merge CVR and address space unqualified 7968 // pointees and if there is a composite type we return a pointer to it with 7969 // merged qualifiers. 7970 LHSCastKind = 7971 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7972 RHSCastKind = 7973 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7974 lhQual.removeAddressSpace(); 7975 rhQual.removeAddressSpace(); 7976 7977 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7978 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7979 7980 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7981 7982 if (CompositeTy.isNull()) { 7983 // In this situation, we assume void* type. No especially good 7984 // reason, but this is what gcc does, and we do have to pick 7985 // to get a consistent AST. 7986 QualType incompatTy; 7987 incompatTy = S.Context.getPointerType( 7988 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7989 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7990 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7991 7992 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7993 // for casts between types with incompatible address space qualifiers. 7994 // For the following code the compiler produces casts between global and 7995 // local address spaces of the corresponded innermost pointees: 7996 // local int *global *a; 7997 // global int *global *b; 7998 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7999 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8000 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8001 << RHS.get()->getSourceRange(); 8002 8003 return incompatTy; 8004 } 8005 8006 // The pointer types are compatible. 8007 // In case of OpenCL ResultTy should have the address space qualifier 8008 // which is a superset of address spaces of both the 2nd and the 3rd 8009 // operands of the conditional operator. 8010 QualType ResultTy = [&, ResultAddrSpace]() { 8011 if (S.getLangOpts().OpenCL) { 8012 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8013 CompositeQuals.setAddressSpace(ResultAddrSpace); 8014 return S.Context 8015 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8016 .withCVRQualifiers(MergedCVRQual); 8017 } 8018 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8019 }(); 8020 if (IsBlockPointer) 8021 ResultTy = S.Context.getBlockPointerType(ResultTy); 8022 else 8023 ResultTy = S.Context.getPointerType(ResultTy); 8024 8025 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8026 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8027 return ResultTy; 8028 } 8029 8030 /// Return the resulting type when the operands are both block pointers. 8031 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8032 ExprResult &LHS, 8033 ExprResult &RHS, 8034 SourceLocation Loc) { 8035 QualType LHSTy = LHS.get()->getType(); 8036 QualType RHSTy = RHS.get()->getType(); 8037 8038 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8039 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8040 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8041 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8042 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8043 return destType; 8044 } 8045 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8046 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8047 << RHS.get()->getSourceRange(); 8048 return QualType(); 8049 } 8050 8051 // We have 2 block pointer types. 8052 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8053 } 8054 8055 /// Return the resulting type when the operands are both pointers. 8056 static QualType 8057 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8058 ExprResult &RHS, 8059 SourceLocation Loc) { 8060 // get the pointer types 8061 QualType LHSTy = LHS.get()->getType(); 8062 QualType RHSTy = RHS.get()->getType(); 8063 8064 // get the "pointed to" types 8065 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8066 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8067 8068 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8069 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8070 // Figure out necessary qualifiers (C99 6.5.15p6) 8071 QualType destPointee 8072 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8073 QualType destType = S.Context.getPointerType(destPointee); 8074 // Add qualifiers if necessary. 8075 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8076 // Promote to void*. 8077 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8078 return destType; 8079 } 8080 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8081 QualType destPointee 8082 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8083 QualType destType = S.Context.getPointerType(destPointee); 8084 // Add qualifiers if necessary. 8085 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8086 // Promote to void*. 8087 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8088 return destType; 8089 } 8090 8091 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8092 } 8093 8094 /// Return false if the first expression is not an integer and the second 8095 /// expression is not a pointer, true otherwise. 8096 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8097 Expr* PointerExpr, SourceLocation Loc, 8098 bool IsIntFirstExpr) { 8099 if (!PointerExpr->getType()->isPointerType() || 8100 !Int.get()->getType()->isIntegerType()) 8101 return false; 8102 8103 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8104 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8105 8106 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8107 << Expr1->getType() << Expr2->getType() 8108 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8109 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8110 CK_IntegralToPointer); 8111 return true; 8112 } 8113 8114 /// Simple conversion between integer and floating point types. 8115 /// 8116 /// Used when handling the OpenCL conditional operator where the 8117 /// condition is a vector while the other operands are scalar. 8118 /// 8119 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8120 /// types are either integer or floating type. Between the two 8121 /// operands, the type with the higher rank is defined as the "result 8122 /// type". The other operand needs to be promoted to the same type. No 8123 /// other type promotion is allowed. We cannot use 8124 /// UsualArithmeticConversions() for this purpose, since it always 8125 /// promotes promotable types. 8126 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8127 ExprResult &RHS, 8128 SourceLocation QuestionLoc) { 8129 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8130 if (LHS.isInvalid()) 8131 return QualType(); 8132 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8133 if (RHS.isInvalid()) 8134 return QualType(); 8135 8136 // For conversion purposes, we ignore any qualifiers. 8137 // For example, "const float" and "float" are equivalent. 8138 QualType LHSType = 8139 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8140 QualType RHSType = 8141 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8142 8143 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8144 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8145 << LHSType << LHS.get()->getSourceRange(); 8146 return QualType(); 8147 } 8148 8149 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8150 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8151 << RHSType << RHS.get()->getSourceRange(); 8152 return QualType(); 8153 } 8154 8155 // If both types are identical, no conversion is needed. 8156 if (LHSType == RHSType) 8157 return LHSType; 8158 8159 // Now handle "real" floating types (i.e. float, double, long double). 8160 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8161 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8162 /*IsCompAssign = */ false); 8163 8164 // Finally, we have two differing integer types. 8165 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8166 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8167 } 8168 8169 /// Convert scalar operands to a vector that matches the 8170 /// condition in length. 8171 /// 8172 /// Used when handling the OpenCL conditional operator where the 8173 /// condition is a vector while the other operands are scalar. 8174 /// 8175 /// We first compute the "result type" for the scalar operands 8176 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8177 /// into a vector of that type where the length matches the condition 8178 /// vector type. s6.11.6 requires that the element types of the result 8179 /// and the condition must have the same number of bits. 8180 static QualType 8181 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8182 QualType CondTy, SourceLocation QuestionLoc) { 8183 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8184 if (ResTy.isNull()) return QualType(); 8185 8186 const VectorType *CV = CondTy->getAs<VectorType>(); 8187 assert(CV); 8188 8189 // Determine the vector result type 8190 unsigned NumElements = CV->getNumElements(); 8191 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8192 8193 // Ensure that all types have the same number of bits 8194 if (S.Context.getTypeSize(CV->getElementType()) 8195 != S.Context.getTypeSize(ResTy)) { 8196 // Since VectorTy is created internally, it does not pretty print 8197 // with an OpenCL name. Instead, we just print a description. 8198 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8199 SmallString<64> Str; 8200 llvm::raw_svector_ostream OS(Str); 8201 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8202 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8203 << CondTy << OS.str(); 8204 return QualType(); 8205 } 8206 8207 // Convert operands to the vector result type 8208 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8209 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8210 8211 return VectorTy; 8212 } 8213 8214 /// Return false if this is a valid OpenCL condition vector 8215 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8216 SourceLocation QuestionLoc) { 8217 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8218 // integral type. 8219 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8220 assert(CondTy); 8221 QualType EleTy = CondTy->getElementType(); 8222 if (EleTy->isIntegerType()) return false; 8223 8224 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8225 << Cond->getType() << Cond->getSourceRange(); 8226 return true; 8227 } 8228 8229 /// Return false if the vector condition type and the vector 8230 /// result type are compatible. 8231 /// 8232 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8233 /// number of elements, and their element types have the same number 8234 /// of bits. 8235 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8236 SourceLocation QuestionLoc) { 8237 const VectorType *CV = CondTy->getAs<VectorType>(); 8238 const VectorType *RV = VecResTy->getAs<VectorType>(); 8239 assert(CV && RV); 8240 8241 if (CV->getNumElements() != RV->getNumElements()) { 8242 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8243 << CondTy << VecResTy; 8244 return true; 8245 } 8246 8247 QualType CVE = CV->getElementType(); 8248 QualType RVE = RV->getElementType(); 8249 8250 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8251 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8252 << CondTy << VecResTy; 8253 return true; 8254 } 8255 8256 return false; 8257 } 8258 8259 /// Return the resulting type for the conditional operator in 8260 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8261 /// s6.3.i) when the condition is a vector type. 8262 static QualType 8263 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8264 ExprResult &LHS, ExprResult &RHS, 8265 SourceLocation QuestionLoc) { 8266 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8267 if (Cond.isInvalid()) 8268 return QualType(); 8269 QualType CondTy = Cond.get()->getType(); 8270 8271 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8272 return QualType(); 8273 8274 // If either operand is a vector then find the vector type of the 8275 // result as specified in OpenCL v1.1 s6.3.i. 8276 if (LHS.get()->getType()->isVectorType() || 8277 RHS.get()->getType()->isVectorType()) { 8278 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8279 /*isCompAssign*/false, 8280 /*AllowBothBool*/true, 8281 /*AllowBoolConversions*/false); 8282 if (VecResTy.isNull()) return QualType(); 8283 // The result type must match the condition type as specified in 8284 // OpenCL v1.1 s6.11.6. 8285 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8286 return QualType(); 8287 return VecResTy; 8288 } 8289 8290 // Both operands are scalar. 8291 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8292 } 8293 8294 /// Return true if the Expr is block type 8295 static bool checkBlockType(Sema &S, const Expr *E) { 8296 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8297 QualType Ty = CE->getCallee()->getType(); 8298 if (Ty->isBlockPointerType()) { 8299 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8300 return true; 8301 } 8302 } 8303 return false; 8304 } 8305 8306 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8307 /// In that case, LHS = cond. 8308 /// C99 6.5.15 8309 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8310 ExprResult &RHS, ExprValueKind &VK, 8311 ExprObjectKind &OK, 8312 SourceLocation QuestionLoc) { 8313 8314 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8315 if (!LHSResult.isUsable()) return QualType(); 8316 LHS = LHSResult; 8317 8318 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8319 if (!RHSResult.isUsable()) return QualType(); 8320 RHS = RHSResult; 8321 8322 // C++ is sufficiently different to merit its own checker. 8323 if (getLangOpts().CPlusPlus) 8324 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8325 8326 VK = VK_PRValue; 8327 OK = OK_Ordinary; 8328 8329 if (Context.isDependenceAllowed() && 8330 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8331 RHS.get()->isTypeDependent())) { 8332 assert(!getLangOpts().CPlusPlus); 8333 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8334 RHS.get()->containsErrors()) && 8335 "should only occur in error-recovery path."); 8336 return Context.DependentTy; 8337 } 8338 8339 // The OpenCL operator with a vector condition is sufficiently 8340 // different to merit its own checker. 8341 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8342 Cond.get()->getType()->isExtVectorType()) 8343 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8344 8345 // First, check the condition. 8346 Cond = UsualUnaryConversions(Cond.get()); 8347 if (Cond.isInvalid()) 8348 return QualType(); 8349 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8350 return QualType(); 8351 8352 // Now check the two expressions. 8353 if (LHS.get()->getType()->isVectorType() || 8354 RHS.get()->getType()->isVectorType()) 8355 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8356 /*AllowBothBool*/true, 8357 /*AllowBoolConversions*/false); 8358 8359 QualType ResTy = 8360 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8361 if (LHS.isInvalid() || RHS.isInvalid()) 8362 return QualType(); 8363 8364 QualType LHSTy = LHS.get()->getType(); 8365 QualType RHSTy = RHS.get()->getType(); 8366 8367 // Diagnose attempts to convert between __ibm128, __float128 and long double 8368 // where such conversions currently can't be handled. 8369 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8370 Diag(QuestionLoc, 8371 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8373 return QualType(); 8374 } 8375 8376 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8377 // selection operator (?:). 8378 if (getLangOpts().OpenCL && 8379 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8380 return QualType(); 8381 } 8382 8383 // If both operands have arithmetic type, do the usual arithmetic conversions 8384 // to find a common type: C99 6.5.15p3,5. 8385 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8386 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8387 // different sizes, or between ExtInts and other types. 8388 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8389 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8390 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8391 << RHS.get()->getSourceRange(); 8392 return QualType(); 8393 } 8394 8395 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8396 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8397 8398 return ResTy; 8399 } 8400 8401 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8402 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8403 return LHSTy; 8404 } 8405 8406 // If both operands are the same structure or union type, the result is that 8407 // type. 8408 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8409 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8410 if (LHSRT->getDecl() == RHSRT->getDecl()) 8411 // "If both the operands have structure or union type, the result has 8412 // that type." This implies that CV qualifiers are dropped. 8413 return LHSTy.getUnqualifiedType(); 8414 // FIXME: Type of conditional expression must be complete in C mode. 8415 } 8416 8417 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8418 // The following || allows only one side to be void (a GCC-ism). 8419 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8420 return checkConditionalVoidType(*this, LHS, RHS); 8421 } 8422 8423 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8424 // the type of the other operand." 8425 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8426 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8427 8428 // All objective-c pointer type analysis is done here. 8429 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8430 QuestionLoc); 8431 if (LHS.isInvalid() || RHS.isInvalid()) 8432 return QualType(); 8433 if (!compositeType.isNull()) 8434 return compositeType; 8435 8436 8437 // Handle block pointer types. 8438 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8439 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8440 QuestionLoc); 8441 8442 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8443 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8444 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8445 QuestionLoc); 8446 8447 // GCC compatibility: soften pointer/integer mismatch. Note that 8448 // null pointers have been filtered out by this point. 8449 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8450 /*IsIntFirstExpr=*/true)) 8451 return RHSTy; 8452 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8453 /*IsIntFirstExpr=*/false)) 8454 return LHSTy; 8455 8456 // Allow ?: operations in which both operands have the same 8457 // built-in sizeless type. 8458 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8459 return LHSTy; 8460 8461 // Emit a better diagnostic if one of the expressions is a null pointer 8462 // constant and the other is not a pointer type. In this case, the user most 8463 // likely forgot to take the address of the other expression. 8464 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8465 return QualType(); 8466 8467 // Otherwise, the operands are not compatible. 8468 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8469 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8470 << RHS.get()->getSourceRange(); 8471 return QualType(); 8472 } 8473 8474 /// FindCompositeObjCPointerType - Helper method to find composite type of 8475 /// two objective-c pointer types of the two input expressions. 8476 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8477 SourceLocation QuestionLoc) { 8478 QualType LHSTy = LHS.get()->getType(); 8479 QualType RHSTy = RHS.get()->getType(); 8480 8481 // Handle things like Class and struct objc_class*. Here we case the result 8482 // to the pseudo-builtin, because that will be implicitly cast back to the 8483 // redefinition type if an attempt is made to access its fields. 8484 if (LHSTy->isObjCClassType() && 8485 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8486 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8487 return LHSTy; 8488 } 8489 if (RHSTy->isObjCClassType() && 8490 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8491 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8492 return RHSTy; 8493 } 8494 // And the same for struct objc_object* / id 8495 if (LHSTy->isObjCIdType() && 8496 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8497 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8498 return LHSTy; 8499 } 8500 if (RHSTy->isObjCIdType() && 8501 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8502 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8503 return RHSTy; 8504 } 8505 // And the same for struct objc_selector* / SEL 8506 if (Context.isObjCSelType(LHSTy) && 8507 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8508 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8509 return LHSTy; 8510 } 8511 if (Context.isObjCSelType(RHSTy) && 8512 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8513 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8514 return RHSTy; 8515 } 8516 // Check constraints for Objective-C object pointers types. 8517 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8518 8519 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8520 // Two identical object pointer types are always compatible. 8521 return LHSTy; 8522 } 8523 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8524 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8525 QualType compositeType = LHSTy; 8526 8527 // If both operands are interfaces and either operand can be 8528 // assigned to the other, use that type as the composite 8529 // type. This allows 8530 // xxx ? (A*) a : (B*) b 8531 // where B is a subclass of A. 8532 // 8533 // Additionally, as for assignment, if either type is 'id' 8534 // allow silent coercion. Finally, if the types are 8535 // incompatible then make sure to use 'id' as the composite 8536 // type so the result is acceptable for sending messages to. 8537 8538 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8539 // It could return the composite type. 8540 if (!(compositeType = 8541 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8542 // Nothing more to do. 8543 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8544 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8545 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8546 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8547 } else if ((LHSOPT->isObjCQualifiedIdType() || 8548 RHSOPT->isObjCQualifiedIdType()) && 8549 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8550 true)) { 8551 // Need to handle "id<xx>" explicitly. 8552 // GCC allows qualified id and any Objective-C type to devolve to 8553 // id. Currently localizing to here until clear this should be 8554 // part of ObjCQualifiedIdTypesAreCompatible. 8555 compositeType = Context.getObjCIdType(); 8556 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8557 compositeType = Context.getObjCIdType(); 8558 } else { 8559 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8560 << LHSTy << RHSTy 8561 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8562 QualType incompatTy = Context.getObjCIdType(); 8563 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8564 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8565 return incompatTy; 8566 } 8567 // The object pointer types are compatible. 8568 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8569 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8570 return compositeType; 8571 } 8572 // Check Objective-C object pointer types and 'void *' 8573 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8574 if (getLangOpts().ObjCAutoRefCount) { 8575 // ARC forbids the implicit conversion of object pointers to 'void *', 8576 // so these types are not compatible. 8577 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8578 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8579 LHS = RHS = true; 8580 return QualType(); 8581 } 8582 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8583 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8584 QualType destPointee 8585 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8586 QualType destType = Context.getPointerType(destPointee); 8587 // Add qualifiers if necessary. 8588 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8589 // Promote to void*. 8590 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8591 return destType; 8592 } 8593 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8594 if (getLangOpts().ObjCAutoRefCount) { 8595 // ARC forbids the implicit conversion of object pointers to 'void *', 8596 // so these types are not compatible. 8597 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8599 LHS = RHS = true; 8600 return QualType(); 8601 } 8602 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8603 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8604 QualType destPointee 8605 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8606 QualType destType = Context.getPointerType(destPointee); 8607 // Add qualifiers if necessary. 8608 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8609 // Promote to void*. 8610 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8611 return destType; 8612 } 8613 return QualType(); 8614 } 8615 8616 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8617 /// ParenRange in parentheses. 8618 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8619 const PartialDiagnostic &Note, 8620 SourceRange ParenRange) { 8621 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8622 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8623 EndLoc.isValid()) { 8624 Self.Diag(Loc, Note) 8625 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8626 << FixItHint::CreateInsertion(EndLoc, ")"); 8627 } else { 8628 // We can't display the parentheses, so just show the bare note. 8629 Self.Diag(Loc, Note) << ParenRange; 8630 } 8631 } 8632 8633 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8634 return BinaryOperator::isAdditiveOp(Opc) || 8635 BinaryOperator::isMultiplicativeOp(Opc) || 8636 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8637 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8638 // not any of the logical operators. Bitwise-xor is commonly used as a 8639 // logical-xor because there is no logical-xor operator. The logical 8640 // operators, including uses of xor, have a high false positive rate for 8641 // precedence warnings. 8642 } 8643 8644 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8645 /// expression, either using a built-in or overloaded operator, 8646 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8647 /// expression. 8648 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8649 Expr **RHSExprs) { 8650 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8651 E = E->IgnoreImpCasts(); 8652 E = E->IgnoreConversionOperatorSingleStep(); 8653 E = E->IgnoreImpCasts(); 8654 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8655 E = MTE->getSubExpr(); 8656 E = E->IgnoreImpCasts(); 8657 } 8658 8659 // Built-in binary operator. 8660 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8661 if (IsArithmeticOp(OP->getOpcode())) { 8662 *Opcode = OP->getOpcode(); 8663 *RHSExprs = OP->getRHS(); 8664 return true; 8665 } 8666 } 8667 8668 // Overloaded operator. 8669 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8670 if (Call->getNumArgs() != 2) 8671 return false; 8672 8673 // Make sure this is really a binary operator that is safe to pass into 8674 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8675 OverloadedOperatorKind OO = Call->getOperator(); 8676 if (OO < OO_Plus || OO > OO_Arrow || 8677 OO == OO_PlusPlus || OO == OO_MinusMinus) 8678 return false; 8679 8680 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8681 if (IsArithmeticOp(OpKind)) { 8682 *Opcode = OpKind; 8683 *RHSExprs = Call->getArg(1); 8684 return true; 8685 } 8686 } 8687 8688 return false; 8689 } 8690 8691 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8692 /// or is a logical expression such as (x==y) which has int type, but is 8693 /// commonly interpreted as boolean. 8694 static bool ExprLooksBoolean(Expr *E) { 8695 E = E->IgnoreParenImpCasts(); 8696 8697 if (E->getType()->isBooleanType()) 8698 return true; 8699 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8700 return OP->isComparisonOp() || OP->isLogicalOp(); 8701 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8702 return OP->getOpcode() == UO_LNot; 8703 if (E->getType()->isPointerType()) 8704 return true; 8705 // FIXME: What about overloaded operator calls returning "unspecified boolean 8706 // type"s (commonly pointer-to-members)? 8707 8708 return false; 8709 } 8710 8711 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8712 /// and binary operator are mixed in a way that suggests the programmer assumed 8713 /// the conditional operator has higher precedence, for example: 8714 /// "int x = a + someBinaryCondition ? 1 : 2". 8715 static void DiagnoseConditionalPrecedence(Sema &Self, 8716 SourceLocation OpLoc, 8717 Expr *Condition, 8718 Expr *LHSExpr, 8719 Expr *RHSExpr) { 8720 BinaryOperatorKind CondOpcode; 8721 Expr *CondRHS; 8722 8723 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8724 return; 8725 if (!ExprLooksBoolean(CondRHS)) 8726 return; 8727 8728 // The condition is an arithmetic binary expression, with a right- 8729 // hand side that looks boolean, so warn. 8730 8731 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8732 ? diag::warn_precedence_bitwise_conditional 8733 : diag::warn_precedence_conditional; 8734 8735 Self.Diag(OpLoc, DiagID) 8736 << Condition->getSourceRange() 8737 << BinaryOperator::getOpcodeStr(CondOpcode); 8738 8739 SuggestParentheses( 8740 Self, OpLoc, 8741 Self.PDiag(diag::note_precedence_silence) 8742 << BinaryOperator::getOpcodeStr(CondOpcode), 8743 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8744 8745 SuggestParentheses(Self, OpLoc, 8746 Self.PDiag(diag::note_precedence_conditional_first), 8747 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8748 } 8749 8750 /// Compute the nullability of a conditional expression. 8751 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8752 QualType LHSTy, QualType RHSTy, 8753 ASTContext &Ctx) { 8754 if (!ResTy->isAnyPointerType()) 8755 return ResTy; 8756 8757 auto GetNullability = [&Ctx](QualType Ty) { 8758 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8759 if (Kind) { 8760 // For our purposes, treat _Nullable_result as _Nullable. 8761 if (*Kind == NullabilityKind::NullableResult) 8762 return NullabilityKind::Nullable; 8763 return *Kind; 8764 } 8765 return NullabilityKind::Unspecified; 8766 }; 8767 8768 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8769 NullabilityKind MergedKind; 8770 8771 // Compute nullability of a binary conditional expression. 8772 if (IsBin) { 8773 if (LHSKind == NullabilityKind::NonNull) 8774 MergedKind = NullabilityKind::NonNull; 8775 else 8776 MergedKind = RHSKind; 8777 // Compute nullability of a normal conditional expression. 8778 } else { 8779 if (LHSKind == NullabilityKind::Nullable || 8780 RHSKind == NullabilityKind::Nullable) 8781 MergedKind = NullabilityKind::Nullable; 8782 else if (LHSKind == NullabilityKind::NonNull) 8783 MergedKind = RHSKind; 8784 else if (RHSKind == NullabilityKind::NonNull) 8785 MergedKind = LHSKind; 8786 else 8787 MergedKind = NullabilityKind::Unspecified; 8788 } 8789 8790 // Return if ResTy already has the correct nullability. 8791 if (GetNullability(ResTy) == MergedKind) 8792 return ResTy; 8793 8794 // Strip all nullability from ResTy. 8795 while (ResTy->getNullability(Ctx)) 8796 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8797 8798 // Create a new AttributedType with the new nullability kind. 8799 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8800 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8801 } 8802 8803 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8804 /// in the case of a the GNU conditional expr extension. 8805 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8806 SourceLocation ColonLoc, 8807 Expr *CondExpr, Expr *LHSExpr, 8808 Expr *RHSExpr) { 8809 if (!Context.isDependenceAllowed()) { 8810 // C cannot handle TypoExpr nodes in the condition because it 8811 // doesn't handle dependent types properly, so make sure any TypoExprs have 8812 // been dealt with before checking the operands. 8813 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8814 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8815 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8816 8817 if (!CondResult.isUsable()) 8818 return ExprError(); 8819 8820 if (LHSExpr) { 8821 if (!LHSResult.isUsable()) 8822 return ExprError(); 8823 } 8824 8825 if (!RHSResult.isUsable()) 8826 return ExprError(); 8827 8828 CondExpr = CondResult.get(); 8829 LHSExpr = LHSResult.get(); 8830 RHSExpr = RHSResult.get(); 8831 } 8832 8833 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8834 // was the condition. 8835 OpaqueValueExpr *opaqueValue = nullptr; 8836 Expr *commonExpr = nullptr; 8837 if (!LHSExpr) { 8838 commonExpr = CondExpr; 8839 // Lower out placeholder types first. This is important so that we don't 8840 // try to capture a placeholder. This happens in few cases in C++; such 8841 // as Objective-C++'s dictionary subscripting syntax. 8842 if (commonExpr->hasPlaceholderType()) { 8843 ExprResult result = CheckPlaceholderExpr(commonExpr); 8844 if (!result.isUsable()) return ExprError(); 8845 commonExpr = result.get(); 8846 } 8847 // We usually want to apply unary conversions *before* saving, except 8848 // in the special case of a C++ l-value conditional. 8849 if (!(getLangOpts().CPlusPlus 8850 && !commonExpr->isTypeDependent() 8851 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8852 && commonExpr->isGLValue() 8853 && commonExpr->isOrdinaryOrBitFieldObject() 8854 && RHSExpr->isOrdinaryOrBitFieldObject() 8855 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8856 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8857 if (commonRes.isInvalid()) 8858 return ExprError(); 8859 commonExpr = commonRes.get(); 8860 } 8861 8862 // If the common expression is a class or array prvalue, materialize it 8863 // so that we can safely refer to it multiple times. 8864 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8865 commonExpr->getType()->isArrayType())) { 8866 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8867 if (MatExpr.isInvalid()) 8868 return ExprError(); 8869 commonExpr = MatExpr.get(); 8870 } 8871 8872 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8873 commonExpr->getType(), 8874 commonExpr->getValueKind(), 8875 commonExpr->getObjectKind(), 8876 commonExpr); 8877 LHSExpr = CondExpr = opaqueValue; 8878 } 8879 8880 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8881 ExprValueKind VK = VK_PRValue; 8882 ExprObjectKind OK = OK_Ordinary; 8883 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8884 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8885 VK, OK, QuestionLoc); 8886 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8887 RHS.isInvalid()) 8888 return ExprError(); 8889 8890 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8891 RHS.get()); 8892 8893 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8894 8895 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8896 Context); 8897 8898 if (!commonExpr) 8899 return new (Context) 8900 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8901 RHS.get(), result, VK, OK); 8902 8903 return new (Context) BinaryConditionalOperator( 8904 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8905 ColonLoc, result, VK, OK); 8906 } 8907 8908 // Check if we have a conversion between incompatible cmse function pointer 8909 // types, that is, a conversion between a function pointer with the 8910 // cmse_nonsecure_call attribute and one without. 8911 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8912 QualType ToType) { 8913 if (const auto *ToFn = 8914 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8915 if (const auto *FromFn = 8916 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8917 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8918 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8919 8920 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8921 } 8922 } 8923 return false; 8924 } 8925 8926 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8927 // being closely modeled after the C99 spec:-). The odd characteristic of this 8928 // routine is it effectively iqnores the qualifiers on the top level pointee. 8929 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8930 // FIXME: add a couple examples in this comment. 8931 static Sema::AssignConvertType 8932 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8933 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8934 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8935 8936 // get the "pointed to" type (ignoring qualifiers at the top level) 8937 const Type *lhptee, *rhptee; 8938 Qualifiers lhq, rhq; 8939 std::tie(lhptee, lhq) = 8940 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8941 std::tie(rhptee, rhq) = 8942 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8943 8944 Sema::AssignConvertType ConvTy = Sema::Compatible; 8945 8946 // C99 6.5.16.1p1: This following citation is common to constraints 8947 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8948 // qualifiers of the type *pointed to* by the right; 8949 8950 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8951 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8952 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8953 // Ignore lifetime for further calculation. 8954 lhq.removeObjCLifetime(); 8955 rhq.removeObjCLifetime(); 8956 } 8957 8958 if (!lhq.compatiblyIncludes(rhq)) { 8959 // Treat address-space mismatches as fatal. 8960 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8961 return Sema::IncompatiblePointerDiscardsQualifiers; 8962 8963 // It's okay to add or remove GC or lifetime qualifiers when converting to 8964 // and from void*. 8965 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8966 .compatiblyIncludes( 8967 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8968 && (lhptee->isVoidType() || rhptee->isVoidType())) 8969 ; // keep old 8970 8971 // Treat lifetime mismatches as fatal. 8972 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8973 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8974 8975 // For GCC/MS compatibility, other qualifier mismatches are treated 8976 // as still compatible in C. 8977 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8978 } 8979 8980 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8981 // incomplete type and the other is a pointer to a qualified or unqualified 8982 // version of void... 8983 if (lhptee->isVoidType()) { 8984 if (rhptee->isIncompleteOrObjectType()) 8985 return ConvTy; 8986 8987 // As an extension, we allow cast to/from void* to function pointer. 8988 assert(rhptee->isFunctionType()); 8989 return Sema::FunctionVoidPointer; 8990 } 8991 8992 if (rhptee->isVoidType()) { 8993 if (lhptee->isIncompleteOrObjectType()) 8994 return ConvTy; 8995 8996 // As an extension, we allow cast to/from void* to function pointer. 8997 assert(lhptee->isFunctionType()); 8998 return Sema::FunctionVoidPointer; 8999 } 9000 9001 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9002 // unqualified versions of compatible types, ... 9003 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9004 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9005 // Check if the pointee types are compatible ignoring the sign. 9006 // We explicitly check for char so that we catch "char" vs 9007 // "unsigned char" on systems where "char" is unsigned. 9008 if (lhptee->isCharType()) 9009 ltrans = S.Context.UnsignedCharTy; 9010 else if (lhptee->hasSignedIntegerRepresentation()) 9011 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9012 9013 if (rhptee->isCharType()) 9014 rtrans = S.Context.UnsignedCharTy; 9015 else if (rhptee->hasSignedIntegerRepresentation()) 9016 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9017 9018 if (ltrans == rtrans) { 9019 // Types are compatible ignoring the sign. Qualifier incompatibility 9020 // takes priority over sign incompatibility because the sign 9021 // warning can be disabled. 9022 if (ConvTy != Sema::Compatible) 9023 return ConvTy; 9024 9025 return Sema::IncompatiblePointerSign; 9026 } 9027 9028 // If we are a multi-level pointer, it's possible that our issue is simply 9029 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9030 // the eventual target type is the same and the pointers have the same 9031 // level of indirection, this must be the issue. 9032 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9033 do { 9034 std::tie(lhptee, lhq) = 9035 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9036 std::tie(rhptee, rhq) = 9037 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9038 9039 // Inconsistent address spaces at this point is invalid, even if the 9040 // address spaces would be compatible. 9041 // FIXME: This doesn't catch address space mismatches for pointers of 9042 // different nesting levels, like: 9043 // __local int *** a; 9044 // int ** b = a; 9045 // It's not clear how to actually determine when such pointers are 9046 // invalidly incompatible. 9047 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9048 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9049 9050 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9051 9052 if (lhptee == rhptee) 9053 return Sema::IncompatibleNestedPointerQualifiers; 9054 } 9055 9056 // General pointer incompatibility takes priority over qualifiers. 9057 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9058 return Sema::IncompatibleFunctionPointer; 9059 return Sema::IncompatiblePointer; 9060 } 9061 if (!S.getLangOpts().CPlusPlus && 9062 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9063 return Sema::IncompatibleFunctionPointer; 9064 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9065 return Sema::IncompatibleFunctionPointer; 9066 return ConvTy; 9067 } 9068 9069 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9070 /// block pointer types are compatible or whether a block and normal pointer 9071 /// are compatible. It is more restrict than comparing two function pointer 9072 // types. 9073 static Sema::AssignConvertType 9074 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9075 QualType RHSType) { 9076 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9077 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9078 9079 QualType lhptee, rhptee; 9080 9081 // get the "pointed to" type (ignoring qualifiers at the top level) 9082 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9083 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9084 9085 // In C++, the types have to match exactly. 9086 if (S.getLangOpts().CPlusPlus) 9087 return Sema::IncompatibleBlockPointer; 9088 9089 Sema::AssignConvertType ConvTy = Sema::Compatible; 9090 9091 // For blocks we enforce that qualifiers are identical. 9092 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9093 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9094 if (S.getLangOpts().OpenCL) { 9095 LQuals.removeAddressSpace(); 9096 RQuals.removeAddressSpace(); 9097 } 9098 if (LQuals != RQuals) 9099 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9100 9101 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9102 // assignment. 9103 // The current behavior is similar to C++ lambdas. A block might be 9104 // assigned to a variable iff its return type and parameters are compatible 9105 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9106 // an assignment. Presumably it should behave in way that a function pointer 9107 // assignment does in C, so for each parameter and return type: 9108 // * CVR and address space of LHS should be a superset of CVR and address 9109 // space of RHS. 9110 // * unqualified types should be compatible. 9111 if (S.getLangOpts().OpenCL) { 9112 if (!S.Context.typesAreBlockPointerCompatible( 9113 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9114 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9115 return Sema::IncompatibleBlockPointer; 9116 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9117 return Sema::IncompatibleBlockPointer; 9118 9119 return ConvTy; 9120 } 9121 9122 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9123 /// for assignment compatibility. 9124 static Sema::AssignConvertType 9125 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9126 QualType RHSType) { 9127 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9128 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9129 9130 if (LHSType->isObjCBuiltinType()) { 9131 // Class is not compatible with ObjC object pointers. 9132 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9133 !RHSType->isObjCQualifiedClassType()) 9134 return Sema::IncompatiblePointer; 9135 return Sema::Compatible; 9136 } 9137 if (RHSType->isObjCBuiltinType()) { 9138 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9139 !LHSType->isObjCQualifiedClassType()) 9140 return Sema::IncompatiblePointer; 9141 return Sema::Compatible; 9142 } 9143 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9144 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9145 9146 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9147 // make an exception for id<P> 9148 !LHSType->isObjCQualifiedIdType()) 9149 return Sema::CompatiblePointerDiscardsQualifiers; 9150 9151 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9152 return Sema::Compatible; 9153 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9154 return Sema::IncompatibleObjCQualifiedId; 9155 return Sema::IncompatiblePointer; 9156 } 9157 9158 Sema::AssignConvertType 9159 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9160 QualType LHSType, QualType RHSType) { 9161 // Fake up an opaque expression. We don't actually care about what 9162 // cast operations are required, so if CheckAssignmentConstraints 9163 // adds casts to this they'll be wasted, but fortunately that doesn't 9164 // usually happen on valid code. 9165 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9166 ExprResult RHSPtr = &RHSExpr; 9167 CastKind K; 9168 9169 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9170 } 9171 9172 /// This helper function returns true if QT is a vector type that has element 9173 /// type ElementType. 9174 static bool isVector(QualType QT, QualType ElementType) { 9175 if (const VectorType *VT = QT->getAs<VectorType>()) 9176 return VT->getElementType().getCanonicalType() == ElementType; 9177 return false; 9178 } 9179 9180 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9181 /// has code to accommodate several GCC extensions when type checking 9182 /// pointers. Here are some objectionable examples that GCC considers warnings: 9183 /// 9184 /// int a, *pint; 9185 /// short *pshort; 9186 /// struct foo *pfoo; 9187 /// 9188 /// pint = pshort; // warning: assignment from incompatible pointer type 9189 /// a = pint; // warning: assignment makes integer from pointer without a cast 9190 /// pint = a; // warning: assignment makes pointer from integer without a cast 9191 /// pint = pfoo; // warning: assignment from incompatible pointer type 9192 /// 9193 /// As a result, the code for dealing with pointers is more complex than the 9194 /// C99 spec dictates. 9195 /// 9196 /// Sets 'Kind' for any result kind except Incompatible. 9197 Sema::AssignConvertType 9198 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9199 CastKind &Kind, bool ConvertRHS) { 9200 QualType RHSType = RHS.get()->getType(); 9201 QualType OrigLHSType = LHSType; 9202 9203 // Get canonical types. We're not formatting these types, just comparing 9204 // them. 9205 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9206 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9207 9208 // Common case: no conversion required. 9209 if (LHSType == RHSType) { 9210 Kind = CK_NoOp; 9211 return Compatible; 9212 } 9213 9214 // If we have an atomic type, try a non-atomic assignment, then just add an 9215 // atomic qualification step. 9216 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9217 Sema::AssignConvertType result = 9218 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9219 if (result != Compatible) 9220 return result; 9221 if (Kind != CK_NoOp && ConvertRHS) 9222 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9223 Kind = CK_NonAtomicToAtomic; 9224 return Compatible; 9225 } 9226 9227 // If the left-hand side is a reference type, then we are in a 9228 // (rare!) case where we've allowed the use of references in C, 9229 // e.g., as a parameter type in a built-in function. In this case, 9230 // just make sure that the type referenced is compatible with the 9231 // right-hand side type. The caller is responsible for adjusting 9232 // LHSType so that the resulting expression does not have reference 9233 // type. 9234 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9235 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9236 Kind = CK_LValueBitCast; 9237 return Compatible; 9238 } 9239 return Incompatible; 9240 } 9241 9242 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9243 // to the same ExtVector type. 9244 if (LHSType->isExtVectorType()) { 9245 if (RHSType->isExtVectorType()) 9246 return Incompatible; 9247 if (RHSType->isArithmeticType()) { 9248 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9249 if (ConvertRHS) 9250 RHS = prepareVectorSplat(LHSType, RHS.get()); 9251 Kind = CK_VectorSplat; 9252 return Compatible; 9253 } 9254 } 9255 9256 // Conversions to or from vector type. 9257 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9258 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9259 // Allow assignments of an AltiVec vector type to an equivalent GCC 9260 // vector type and vice versa 9261 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9262 Kind = CK_BitCast; 9263 return Compatible; 9264 } 9265 9266 // If we are allowing lax vector conversions, and LHS and RHS are both 9267 // vectors, the total size only needs to be the same. This is a bitcast; 9268 // no bits are changed but the result type is different. 9269 if (isLaxVectorConversion(RHSType, LHSType)) { 9270 Kind = CK_BitCast; 9271 return IncompatibleVectors; 9272 } 9273 } 9274 9275 // When the RHS comes from another lax conversion (e.g. binops between 9276 // scalars and vectors) the result is canonicalized as a vector. When the 9277 // LHS is also a vector, the lax is allowed by the condition above. Handle 9278 // the case where LHS is a scalar. 9279 if (LHSType->isScalarType()) { 9280 const VectorType *VecType = RHSType->getAs<VectorType>(); 9281 if (VecType && VecType->getNumElements() == 1 && 9282 isLaxVectorConversion(RHSType, LHSType)) { 9283 ExprResult *VecExpr = &RHS; 9284 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9285 Kind = CK_BitCast; 9286 return Compatible; 9287 } 9288 } 9289 9290 // Allow assignments between fixed-length and sizeless SVE vectors. 9291 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9292 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9293 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9294 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9295 Kind = CK_BitCast; 9296 return Compatible; 9297 } 9298 9299 return Incompatible; 9300 } 9301 9302 // Diagnose attempts to convert between __ibm128, __float128 and long double 9303 // where such conversions currently can't be handled. 9304 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9305 return Incompatible; 9306 9307 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9308 // discards the imaginary part. 9309 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9310 !LHSType->getAs<ComplexType>()) 9311 return Incompatible; 9312 9313 // Arithmetic conversions. 9314 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9315 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9316 if (ConvertRHS) 9317 Kind = PrepareScalarCast(RHS, LHSType); 9318 return Compatible; 9319 } 9320 9321 // Conversions to normal pointers. 9322 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9323 // U* -> T* 9324 if (isa<PointerType>(RHSType)) { 9325 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9326 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9327 if (AddrSpaceL != AddrSpaceR) 9328 Kind = CK_AddressSpaceConversion; 9329 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9330 Kind = CK_NoOp; 9331 else 9332 Kind = CK_BitCast; 9333 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9334 } 9335 9336 // int -> T* 9337 if (RHSType->isIntegerType()) { 9338 Kind = CK_IntegralToPointer; // FIXME: null? 9339 return IntToPointer; 9340 } 9341 9342 // C pointers are not compatible with ObjC object pointers, 9343 // with two exceptions: 9344 if (isa<ObjCObjectPointerType>(RHSType)) { 9345 // - conversions to void* 9346 if (LHSPointer->getPointeeType()->isVoidType()) { 9347 Kind = CK_BitCast; 9348 return Compatible; 9349 } 9350 9351 // - conversions from 'Class' to the redefinition type 9352 if (RHSType->isObjCClassType() && 9353 Context.hasSameType(LHSType, 9354 Context.getObjCClassRedefinitionType())) { 9355 Kind = CK_BitCast; 9356 return Compatible; 9357 } 9358 9359 Kind = CK_BitCast; 9360 return IncompatiblePointer; 9361 } 9362 9363 // U^ -> void* 9364 if (RHSType->getAs<BlockPointerType>()) { 9365 if (LHSPointer->getPointeeType()->isVoidType()) { 9366 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9367 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9368 ->getPointeeType() 9369 .getAddressSpace(); 9370 Kind = 9371 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9372 return Compatible; 9373 } 9374 } 9375 9376 return Incompatible; 9377 } 9378 9379 // Conversions to block pointers. 9380 if (isa<BlockPointerType>(LHSType)) { 9381 // U^ -> T^ 9382 if (RHSType->isBlockPointerType()) { 9383 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9384 ->getPointeeType() 9385 .getAddressSpace(); 9386 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9387 ->getPointeeType() 9388 .getAddressSpace(); 9389 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9390 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9391 } 9392 9393 // int or null -> T^ 9394 if (RHSType->isIntegerType()) { 9395 Kind = CK_IntegralToPointer; // FIXME: null 9396 return IntToBlockPointer; 9397 } 9398 9399 // id -> T^ 9400 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9401 Kind = CK_AnyPointerToBlockPointerCast; 9402 return Compatible; 9403 } 9404 9405 // void* -> T^ 9406 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9407 if (RHSPT->getPointeeType()->isVoidType()) { 9408 Kind = CK_AnyPointerToBlockPointerCast; 9409 return Compatible; 9410 } 9411 9412 return Incompatible; 9413 } 9414 9415 // Conversions to Objective-C pointers. 9416 if (isa<ObjCObjectPointerType>(LHSType)) { 9417 // A* -> B* 9418 if (RHSType->isObjCObjectPointerType()) { 9419 Kind = CK_BitCast; 9420 Sema::AssignConvertType result = 9421 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9422 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9423 result == Compatible && 9424 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9425 result = IncompatibleObjCWeakRef; 9426 return result; 9427 } 9428 9429 // int or null -> A* 9430 if (RHSType->isIntegerType()) { 9431 Kind = CK_IntegralToPointer; // FIXME: null 9432 return IntToPointer; 9433 } 9434 9435 // In general, C pointers are not compatible with ObjC object pointers, 9436 // with two exceptions: 9437 if (isa<PointerType>(RHSType)) { 9438 Kind = CK_CPointerToObjCPointerCast; 9439 9440 // - conversions from 'void*' 9441 if (RHSType->isVoidPointerType()) { 9442 return Compatible; 9443 } 9444 9445 // - conversions to 'Class' from its redefinition type 9446 if (LHSType->isObjCClassType() && 9447 Context.hasSameType(RHSType, 9448 Context.getObjCClassRedefinitionType())) { 9449 return Compatible; 9450 } 9451 9452 return IncompatiblePointer; 9453 } 9454 9455 // Only under strict condition T^ is compatible with an Objective-C pointer. 9456 if (RHSType->isBlockPointerType() && 9457 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9458 if (ConvertRHS) 9459 maybeExtendBlockObject(RHS); 9460 Kind = CK_BlockPointerToObjCPointerCast; 9461 return Compatible; 9462 } 9463 9464 return Incompatible; 9465 } 9466 9467 // Conversions from pointers that are not covered by the above. 9468 if (isa<PointerType>(RHSType)) { 9469 // T* -> _Bool 9470 if (LHSType == Context.BoolTy) { 9471 Kind = CK_PointerToBoolean; 9472 return Compatible; 9473 } 9474 9475 // T* -> int 9476 if (LHSType->isIntegerType()) { 9477 Kind = CK_PointerToIntegral; 9478 return PointerToInt; 9479 } 9480 9481 return Incompatible; 9482 } 9483 9484 // Conversions from Objective-C pointers that are not covered by the above. 9485 if (isa<ObjCObjectPointerType>(RHSType)) { 9486 // T* -> _Bool 9487 if (LHSType == Context.BoolTy) { 9488 Kind = CK_PointerToBoolean; 9489 return Compatible; 9490 } 9491 9492 // T* -> int 9493 if (LHSType->isIntegerType()) { 9494 Kind = CK_PointerToIntegral; 9495 return PointerToInt; 9496 } 9497 9498 return Incompatible; 9499 } 9500 9501 // struct A -> struct B 9502 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9503 if (Context.typesAreCompatible(LHSType, RHSType)) { 9504 Kind = CK_NoOp; 9505 return Compatible; 9506 } 9507 } 9508 9509 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9510 Kind = CK_IntToOCLSampler; 9511 return Compatible; 9512 } 9513 9514 return Incompatible; 9515 } 9516 9517 /// Constructs a transparent union from an expression that is 9518 /// used to initialize the transparent union. 9519 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9520 ExprResult &EResult, QualType UnionType, 9521 FieldDecl *Field) { 9522 // Build an initializer list that designates the appropriate member 9523 // of the transparent union. 9524 Expr *E = EResult.get(); 9525 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9526 E, SourceLocation()); 9527 Initializer->setType(UnionType); 9528 Initializer->setInitializedFieldInUnion(Field); 9529 9530 // Build a compound literal constructing a value of the transparent 9531 // union type from this initializer list. 9532 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9533 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9534 VK_PRValue, Initializer, false); 9535 } 9536 9537 Sema::AssignConvertType 9538 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9539 ExprResult &RHS) { 9540 QualType RHSType = RHS.get()->getType(); 9541 9542 // If the ArgType is a Union type, we want to handle a potential 9543 // transparent_union GCC extension. 9544 const RecordType *UT = ArgType->getAsUnionType(); 9545 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9546 return Incompatible; 9547 9548 // The field to initialize within the transparent union. 9549 RecordDecl *UD = UT->getDecl(); 9550 FieldDecl *InitField = nullptr; 9551 // It's compatible if the expression matches any of the fields. 9552 for (auto *it : UD->fields()) { 9553 if (it->getType()->isPointerType()) { 9554 // If the transparent union contains a pointer type, we allow: 9555 // 1) void pointer 9556 // 2) null pointer constant 9557 if (RHSType->isPointerType()) 9558 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9559 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9560 InitField = it; 9561 break; 9562 } 9563 9564 if (RHS.get()->isNullPointerConstant(Context, 9565 Expr::NPC_ValueDependentIsNull)) { 9566 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9567 CK_NullToPointer); 9568 InitField = it; 9569 break; 9570 } 9571 } 9572 9573 CastKind Kind; 9574 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9575 == Compatible) { 9576 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9577 InitField = it; 9578 break; 9579 } 9580 } 9581 9582 if (!InitField) 9583 return Incompatible; 9584 9585 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9586 return Compatible; 9587 } 9588 9589 Sema::AssignConvertType 9590 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9591 bool Diagnose, 9592 bool DiagnoseCFAudited, 9593 bool ConvertRHS) { 9594 // We need to be able to tell the caller whether we diagnosed a problem, if 9595 // they ask us to issue diagnostics. 9596 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9597 9598 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9599 // we can't avoid *all* modifications at the moment, so we need some somewhere 9600 // to put the updated value. 9601 ExprResult LocalRHS = CallerRHS; 9602 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9603 9604 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9605 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9606 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9607 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9608 Diag(RHS.get()->getExprLoc(), 9609 diag::warn_noderef_to_dereferenceable_pointer) 9610 << RHS.get()->getSourceRange(); 9611 } 9612 } 9613 } 9614 9615 if (getLangOpts().CPlusPlus) { 9616 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9617 // C++ 5.17p3: If the left operand is not of class type, the 9618 // expression is implicitly converted (C++ 4) to the 9619 // cv-unqualified type of the left operand. 9620 QualType RHSType = RHS.get()->getType(); 9621 if (Diagnose) { 9622 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9623 AA_Assigning); 9624 } else { 9625 ImplicitConversionSequence ICS = 9626 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9627 /*SuppressUserConversions=*/false, 9628 AllowedExplicit::None, 9629 /*InOverloadResolution=*/false, 9630 /*CStyle=*/false, 9631 /*AllowObjCWritebackConversion=*/false); 9632 if (ICS.isFailure()) 9633 return Incompatible; 9634 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9635 ICS, AA_Assigning); 9636 } 9637 if (RHS.isInvalid()) 9638 return Incompatible; 9639 Sema::AssignConvertType result = Compatible; 9640 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9641 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9642 result = IncompatibleObjCWeakRef; 9643 return result; 9644 } 9645 9646 // FIXME: Currently, we fall through and treat C++ classes like C 9647 // structures. 9648 // FIXME: We also fall through for atomics; not sure what should 9649 // happen there, though. 9650 } else if (RHS.get()->getType() == Context.OverloadTy) { 9651 // As a set of extensions to C, we support overloading on functions. These 9652 // functions need to be resolved here. 9653 DeclAccessPair DAP; 9654 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9655 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9656 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9657 else 9658 return Incompatible; 9659 } 9660 9661 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9662 // a null pointer constant. 9663 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9664 LHSType->isBlockPointerType()) && 9665 RHS.get()->isNullPointerConstant(Context, 9666 Expr::NPC_ValueDependentIsNull)) { 9667 if (Diagnose || ConvertRHS) { 9668 CastKind Kind; 9669 CXXCastPath Path; 9670 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9671 /*IgnoreBaseAccess=*/false, Diagnose); 9672 if (ConvertRHS) 9673 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9674 } 9675 return Compatible; 9676 } 9677 9678 // OpenCL queue_t type assignment. 9679 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9680 Context, Expr::NPC_ValueDependentIsNull)) { 9681 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9682 return Compatible; 9683 } 9684 9685 // This check seems unnatural, however it is necessary to ensure the proper 9686 // conversion of functions/arrays. If the conversion were done for all 9687 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9688 // expressions that suppress this implicit conversion (&, sizeof). 9689 // 9690 // Suppress this for references: C++ 8.5.3p5. 9691 if (!LHSType->isReferenceType()) { 9692 // FIXME: We potentially allocate here even if ConvertRHS is false. 9693 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9694 if (RHS.isInvalid()) 9695 return Incompatible; 9696 } 9697 CastKind Kind; 9698 Sema::AssignConvertType result = 9699 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9700 9701 // C99 6.5.16.1p2: The value of the right operand is converted to the 9702 // type of the assignment expression. 9703 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9704 // so that we can use references in built-in functions even in C. 9705 // The getNonReferenceType() call makes sure that the resulting expression 9706 // does not have reference type. 9707 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9708 QualType Ty = LHSType.getNonLValueExprType(Context); 9709 Expr *E = RHS.get(); 9710 9711 // Check for various Objective-C errors. If we are not reporting 9712 // diagnostics and just checking for errors, e.g., during overload 9713 // resolution, return Incompatible to indicate the failure. 9714 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9715 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9716 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9717 if (!Diagnose) 9718 return Incompatible; 9719 } 9720 if (getLangOpts().ObjC && 9721 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9722 E->getType(), E, Diagnose) || 9723 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9724 if (!Diagnose) 9725 return Incompatible; 9726 // Replace the expression with a corrected version and continue so we 9727 // can find further errors. 9728 RHS = E; 9729 return Compatible; 9730 } 9731 9732 if (ConvertRHS) 9733 RHS = ImpCastExprToType(E, Ty, Kind); 9734 } 9735 9736 return result; 9737 } 9738 9739 namespace { 9740 /// The original operand to an operator, prior to the application of the usual 9741 /// arithmetic conversions and converting the arguments of a builtin operator 9742 /// candidate. 9743 struct OriginalOperand { 9744 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9745 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9746 Op = MTE->getSubExpr(); 9747 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9748 Op = BTE->getSubExpr(); 9749 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9750 Orig = ICE->getSubExprAsWritten(); 9751 Conversion = ICE->getConversionFunction(); 9752 } 9753 } 9754 9755 QualType getType() const { return Orig->getType(); } 9756 9757 Expr *Orig; 9758 NamedDecl *Conversion; 9759 }; 9760 } 9761 9762 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9763 ExprResult &RHS) { 9764 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9765 9766 Diag(Loc, diag::err_typecheck_invalid_operands) 9767 << OrigLHS.getType() << OrigRHS.getType() 9768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9769 9770 // If a user-defined conversion was applied to either of the operands prior 9771 // to applying the built-in operator rules, tell the user about it. 9772 if (OrigLHS.Conversion) { 9773 Diag(OrigLHS.Conversion->getLocation(), 9774 diag::note_typecheck_invalid_operands_converted) 9775 << 0 << LHS.get()->getType(); 9776 } 9777 if (OrigRHS.Conversion) { 9778 Diag(OrigRHS.Conversion->getLocation(), 9779 diag::note_typecheck_invalid_operands_converted) 9780 << 1 << RHS.get()->getType(); 9781 } 9782 9783 return QualType(); 9784 } 9785 9786 // Diagnose cases where a scalar was implicitly converted to a vector and 9787 // diagnose the underlying types. Otherwise, diagnose the error 9788 // as invalid vector logical operands for non-C++ cases. 9789 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9790 ExprResult &RHS) { 9791 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9792 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9793 9794 bool LHSNatVec = LHSType->isVectorType(); 9795 bool RHSNatVec = RHSType->isVectorType(); 9796 9797 if (!(LHSNatVec && RHSNatVec)) { 9798 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9799 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9800 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9801 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9802 << Vector->getSourceRange(); 9803 return QualType(); 9804 } 9805 9806 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9807 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9808 << RHS.get()->getSourceRange(); 9809 9810 return QualType(); 9811 } 9812 9813 /// Try to convert a value of non-vector type to a vector type by converting 9814 /// the type to the element type of the vector and then performing a splat. 9815 /// If the language is OpenCL, we only use conversions that promote scalar 9816 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9817 /// for float->int. 9818 /// 9819 /// OpenCL V2.0 6.2.6.p2: 9820 /// An error shall occur if any scalar operand type has greater rank 9821 /// than the type of the vector element. 9822 /// 9823 /// \param scalar - if non-null, actually perform the conversions 9824 /// \return true if the operation fails (but without diagnosing the failure) 9825 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9826 QualType scalarTy, 9827 QualType vectorEltTy, 9828 QualType vectorTy, 9829 unsigned &DiagID) { 9830 // The conversion to apply to the scalar before splatting it, 9831 // if necessary. 9832 CastKind scalarCast = CK_NoOp; 9833 9834 if (vectorEltTy->isIntegralType(S.Context)) { 9835 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9836 (scalarTy->isIntegerType() && 9837 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9838 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9839 return true; 9840 } 9841 if (!scalarTy->isIntegralType(S.Context)) 9842 return true; 9843 scalarCast = CK_IntegralCast; 9844 } else if (vectorEltTy->isRealFloatingType()) { 9845 if (scalarTy->isRealFloatingType()) { 9846 if (S.getLangOpts().OpenCL && 9847 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9848 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9849 return true; 9850 } 9851 scalarCast = CK_FloatingCast; 9852 } 9853 else if (scalarTy->isIntegralType(S.Context)) 9854 scalarCast = CK_IntegralToFloating; 9855 else 9856 return true; 9857 } else { 9858 return true; 9859 } 9860 9861 // Adjust scalar if desired. 9862 if (scalar) { 9863 if (scalarCast != CK_NoOp) 9864 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9865 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9866 } 9867 return false; 9868 } 9869 9870 /// Convert vector E to a vector with the same number of elements but different 9871 /// element type. 9872 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9873 const auto *VecTy = E->getType()->getAs<VectorType>(); 9874 assert(VecTy && "Expression E must be a vector"); 9875 QualType NewVecTy = S.Context.getVectorType(ElementType, 9876 VecTy->getNumElements(), 9877 VecTy->getVectorKind()); 9878 9879 // Look through the implicit cast. Return the subexpression if its type is 9880 // NewVecTy. 9881 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9882 if (ICE->getSubExpr()->getType() == NewVecTy) 9883 return ICE->getSubExpr(); 9884 9885 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9886 return S.ImpCastExprToType(E, NewVecTy, Cast); 9887 } 9888 9889 /// Test if a (constant) integer Int can be casted to another integer type 9890 /// IntTy without losing precision. 9891 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9892 QualType OtherIntTy) { 9893 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9894 9895 // Reject cases where the value of the Int is unknown as that would 9896 // possibly cause truncation, but accept cases where the scalar can be 9897 // demoted without loss of precision. 9898 Expr::EvalResult EVResult; 9899 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9900 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9901 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9902 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9903 9904 if (CstInt) { 9905 // If the scalar is constant and is of a higher order and has more active 9906 // bits that the vector element type, reject it. 9907 llvm::APSInt Result = EVResult.Val.getInt(); 9908 unsigned NumBits = IntSigned 9909 ? (Result.isNegative() ? Result.getMinSignedBits() 9910 : Result.getActiveBits()) 9911 : Result.getActiveBits(); 9912 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9913 return true; 9914 9915 // If the signedness of the scalar type and the vector element type 9916 // differs and the number of bits is greater than that of the vector 9917 // element reject it. 9918 return (IntSigned != OtherIntSigned && 9919 NumBits > S.Context.getIntWidth(OtherIntTy)); 9920 } 9921 9922 // Reject cases where the value of the scalar is not constant and it's 9923 // order is greater than that of the vector element type. 9924 return (Order < 0); 9925 } 9926 9927 /// Test if a (constant) integer Int can be casted to floating point type 9928 /// FloatTy without losing precision. 9929 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9930 QualType FloatTy) { 9931 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9932 9933 // Determine if the integer constant can be expressed as a floating point 9934 // number of the appropriate type. 9935 Expr::EvalResult EVResult; 9936 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9937 9938 uint64_t Bits = 0; 9939 if (CstInt) { 9940 // Reject constants that would be truncated if they were converted to 9941 // the floating point type. Test by simple to/from conversion. 9942 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9943 // could be avoided if there was a convertFromAPInt method 9944 // which could signal back if implicit truncation occurred. 9945 llvm::APSInt Result = EVResult.Val.getInt(); 9946 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9947 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9948 llvm::APFloat::rmTowardZero); 9949 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9950 !IntTy->hasSignedIntegerRepresentation()); 9951 bool Ignored = false; 9952 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9953 &Ignored); 9954 if (Result != ConvertBack) 9955 return true; 9956 } else { 9957 // Reject types that cannot be fully encoded into the mantissa of 9958 // the float. 9959 Bits = S.Context.getTypeSize(IntTy); 9960 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9961 S.Context.getFloatTypeSemantics(FloatTy)); 9962 if (Bits > FloatPrec) 9963 return true; 9964 } 9965 9966 return false; 9967 } 9968 9969 /// Attempt to convert and splat Scalar into a vector whose types matches 9970 /// Vector following GCC conversion rules. The rule is that implicit 9971 /// conversion can occur when Scalar can be casted to match Vector's element 9972 /// type without causing truncation of Scalar. 9973 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9974 ExprResult *Vector) { 9975 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9976 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9977 const VectorType *VT = VectorTy->getAs<VectorType>(); 9978 9979 assert(!isa<ExtVectorType>(VT) && 9980 "ExtVectorTypes should not be handled here!"); 9981 9982 QualType VectorEltTy = VT->getElementType(); 9983 9984 // Reject cases where the vector element type or the scalar element type are 9985 // not integral or floating point types. 9986 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9987 return true; 9988 9989 // The conversion to apply to the scalar before splatting it, 9990 // if necessary. 9991 CastKind ScalarCast = CK_NoOp; 9992 9993 // Accept cases where the vector elements are integers and the scalar is 9994 // an integer. 9995 // FIXME: Notionally if the scalar was a floating point value with a precise 9996 // integral representation, we could cast it to an appropriate integer 9997 // type and then perform the rest of the checks here. GCC will perform 9998 // this conversion in some cases as determined by the input language. 9999 // We should accept it on a language independent basis. 10000 if (VectorEltTy->isIntegralType(S.Context) && 10001 ScalarTy->isIntegralType(S.Context) && 10002 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10003 10004 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10005 return true; 10006 10007 ScalarCast = CK_IntegralCast; 10008 } else if (VectorEltTy->isIntegralType(S.Context) && 10009 ScalarTy->isRealFloatingType()) { 10010 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10011 ScalarCast = CK_FloatingToIntegral; 10012 else 10013 return true; 10014 } else if (VectorEltTy->isRealFloatingType()) { 10015 if (ScalarTy->isRealFloatingType()) { 10016 10017 // Reject cases where the scalar type is not a constant and has a higher 10018 // Order than the vector element type. 10019 llvm::APFloat Result(0.0); 10020 10021 // Determine whether this is a constant scalar. In the event that the 10022 // value is dependent (and thus cannot be evaluated by the constant 10023 // evaluator), skip the evaluation. This will then diagnose once the 10024 // expression is instantiated. 10025 bool CstScalar = Scalar->get()->isValueDependent() || 10026 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10027 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10028 if (!CstScalar && Order < 0) 10029 return true; 10030 10031 // If the scalar cannot be safely casted to the vector element type, 10032 // reject it. 10033 if (CstScalar) { 10034 bool Truncated = false; 10035 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10036 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10037 if (Truncated) 10038 return true; 10039 } 10040 10041 ScalarCast = CK_FloatingCast; 10042 } else if (ScalarTy->isIntegralType(S.Context)) { 10043 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10044 return true; 10045 10046 ScalarCast = CK_IntegralToFloating; 10047 } else 10048 return true; 10049 } else if (ScalarTy->isEnumeralType()) 10050 return true; 10051 10052 // Adjust scalar if desired. 10053 if (Scalar) { 10054 if (ScalarCast != CK_NoOp) 10055 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10056 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10057 } 10058 return false; 10059 } 10060 10061 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10062 SourceLocation Loc, bool IsCompAssign, 10063 bool AllowBothBool, 10064 bool AllowBoolConversions) { 10065 if (!IsCompAssign) { 10066 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10067 if (LHS.isInvalid()) 10068 return QualType(); 10069 } 10070 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10071 if (RHS.isInvalid()) 10072 return QualType(); 10073 10074 // For conversion purposes, we ignore any qualifiers. 10075 // For example, "const float" and "float" are equivalent. 10076 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10077 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10078 10079 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10080 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10081 assert(LHSVecType || RHSVecType); 10082 10083 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10084 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10085 return InvalidOperands(Loc, LHS, RHS); 10086 10087 // AltiVec-style "vector bool op vector bool" combinations are allowed 10088 // for some operators but not others. 10089 if (!AllowBothBool && 10090 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10091 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10092 return InvalidOperands(Loc, LHS, RHS); 10093 10094 // If the vector types are identical, return. 10095 if (Context.hasSameType(LHSType, RHSType)) 10096 return LHSType; 10097 10098 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10099 if (LHSVecType && RHSVecType && 10100 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10101 if (isa<ExtVectorType>(LHSVecType)) { 10102 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10103 return LHSType; 10104 } 10105 10106 if (!IsCompAssign) 10107 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10108 return RHSType; 10109 } 10110 10111 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10112 // can be mixed, with the result being the non-bool type. The non-bool 10113 // operand must have integer element type. 10114 if (AllowBoolConversions && LHSVecType && RHSVecType && 10115 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10116 (Context.getTypeSize(LHSVecType->getElementType()) == 10117 Context.getTypeSize(RHSVecType->getElementType()))) { 10118 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10119 LHSVecType->getElementType()->isIntegerType() && 10120 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10121 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10122 return LHSType; 10123 } 10124 if (!IsCompAssign && 10125 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10126 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10127 RHSVecType->getElementType()->isIntegerType()) { 10128 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10129 return RHSType; 10130 } 10131 } 10132 10133 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10134 // since the ambiguity can affect the ABI. 10135 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10136 const VectorType *VecType = SecondType->getAs<VectorType>(); 10137 return FirstType->isSizelessBuiltinType() && VecType && 10138 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10139 VecType->getVectorKind() == 10140 VectorType::SveFixedLengthPredicateVector); 10141 }; 10142 10143 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10144 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10145 return QualType(); 10146 } 10147 10148 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10149 // since the ambiguity can affect the ABI. 10150 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10151 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10152 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10153 10154 if (FirstVecType && SecondVecType) 10155 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10156 (SecondVecType->getVectorKind() == 10157 VectorType::SveFixedLengthDataVector || 10158 SecondVecType->getVectorKind() == 10159 VectorType::SveFixedLengthPredicateVector); 10160 10161 return FirstType->isSizelessBuiltinType() && SecondVecType && 10162 SecondVecType->getVectorKind() == VectorType::GenericVector; 10163 }; 10164 10165 if (IsSveGnuConversion(LHSType, RHSType) || 10166 IsSveGnuConversion(RHSType, LHSType)) { 10167 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10168 return QualType(); 10169 } 10170 10171 // If there's a vector type and a scalar, try to convert the scalar to 10172 // the vector element type and splat. 10173 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10174 if (!RHSVecType) { 10175 if (isa<ExtVectorType>(LHSVecType)) { 10176 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10177 LHSVecType->getElementType(), LHSType, 10178 DiagID)) 10179 return LHSType; 10180 } else { 10181 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10182 return LHSType; 10183 } 10184 } 10185 if (!LHSVecType) { 10186 if (isa<ExtVectorType>(RHSVecType)) { 10187 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10188 LHSType, RHSVecType->getElementType(), 10189 RHSType, DiagID)) 10190 return RHSType; 10191 } else { 10192 if (LHS.get()->isLValue() || 10193 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10194 return RHSType; 10195 } 10196 } 10197 10198 // FIXME: The code below also handles conversion between vectors and 10199 // non-scalars, we should break this down into fine grained specific checks 10200 // and emit proper diagnostics. 10201 QualType VecType = LHSVecType ? LHSType : RHSType; 10202 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10203 QualType OtherType = LHSVecType ? RHSType : LHSType; 10204 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10205 if (isLaxVectorConversion(OtherType, VecType)) { 10206 // If we're allowing lax vector conversions, only the total (data) size 10207 // needs to be the same. For non compound assignment, if one of the types is 10208 // scalar, the result is always the vector type. 10209 if (!IsCompAssign) { 10210 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10211 return VecType; 10212 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10213 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10214 // type. Note that this is already done by non-compound assignments in 10215 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10216 // <1 x T> -> T. The result is also a vector type. 10217 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10218 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10219 ExprResult *RHSExpr = &RHS; 10220 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10221 return VecType; 10222 } 10223 } 10224 10225 // Okay, the expression is invalid. 10226 10227 // If there's a non-vector, non-real operand, diagnose that. 10228 if ((!RHSVecType && !RHSType->isRealType()) || 10229 (!LHSVecType && !LHSType->isRealType())) { 10230 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10231 << LHSType << RHSType 10232 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10233 return QualType(); 10234 } 10235 10236 // OpenCL V1.1 6.2.6.p1: 10237 // If the operands are of more than one vector type, then an error shall 10238 // occur. Implicit conversions between vector types are not permitted, per 10239 // section 6.2.1. 10240 if (getLangOpts().OpenCL && 10241 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10242 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10243 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10244 << RHSType; 10245 return QualType(); 10246 } 10247 10248 10249 // If there is a vector type that is not a ExtVector and a scalar, we reach 10250 // this point if scalar could not be converted to the vector's element type 10251 // without truncation. 10252 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10253 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10254 QualType Scalar = LHSVecType ? RHSType : LHSType; 10255 QualType Vector = LHSVecType ? LHSType : RHSType; 10256 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10257 Diag(Loc, 10258 diag::err_typecheck_vector_not_convertable_implict_truncation) 10259 << ScalarOrVector << Scalar << Vector; 10260 10261 return QualType(); 10262 } 10263 10264 // Otherwise, use the generic diagnostic. 10265 Diag(Loc, DiagID) 10266 << LHSType << RHSType 10267 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10268 return QualType(); 10269 } 10270 10271 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10272 // expression. These are mainly cases where the null pointer is used as an 10273 // integer instead of a pointer. 10274 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10275 SourceLocation Loc, bool IsCompare) { 10276 // The canonical way to check for a GNU null is with isNullPointerConstant, 10277 // but we use a bit of a hack here for speed; this is a relatively 10278 // hot path, and isNullPointerConstant is slow. 10279 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10280 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10281 10282 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10283 10284 // Avoid analyzing cases where the result will either be invalid (and 10285 // diagnosed as such) or entirely valid and not something to warn about. 10286 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10287 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10288 return; 10289 10290 // Comparison operations would not make sense with a null pointer no matter 10291 // what the other expression is. 10292 if (!IsCompare) { 10293 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10294 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10295 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10296 return; 10297 } 10298 10299 // The rest of the operations only make sense with a null pointer 10300 // if the other expression is a pointer. 10301 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10302 NonNullType->canDecayToPointerType()) 10303 return; 10304 10305 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10306 << LHSNull /* LHS is NULL */ << NonNullType 10307 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10308 } 10309 10310 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10311 SourceLocation Loc) { 10312 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10313 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10314 if (!LUE || !RUE) 10315 return; 10316 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10317 RUE->getKind() != UETT_SizeOf) 10318 return; 10319 10320 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10321 QualType LHSTy = LHSArg->getType(); 10322 QualType RHSTy; 10323 10324 if (RUE->isArgumentType()) 10325 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10326 else 10327 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10328 10329 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10330 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10331 return; 10332 10333 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10334 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10335 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10336 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10337 << LHSArgDecl; 10338 } 10339 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10340 QualType ArrayElemTy = ArrayTy->getElementType(); 10341 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10342 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10343 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10344 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10345 return; 10346 S.Diag(Loc, diag::warn_division_sizeof_array) 10347 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10348 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10349 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10350 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10351 << LHSArgDecl; 10352 } 10353 10354 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10355 } 10356 } 10357 10358 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10359 ExprResult &RHS, 10360 SourceLocation Loc, bool IsDiv) { 10361 // Check for division/remainder by zero. 10362 Expr::EvalResult RHSValue; 10363 if (!RHS.get()->isValueDependent() && 10364 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10365 RHSValue.Val.getInt() == 0) 10366 S.DiagRuntimeBehavior(Loc, RHS.get(), 10367 S.PDiag(diag::warn_remainder_division_by_zero) 10368 << IsDiv << RHS.get()->getSourceRange()); 10369 } 10370 10371 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10372 SourceLocation Loc, 10373 bool IsCompAssign, bool IsDiv) { 10374 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10375 10376 QualType LHSTy = LHS.get()->getType(); 10377 QualType RHSTy = RHS.get()->getType(); 10378 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10379 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10380 /*AllowBothBool*/getLangOpts().AltiVec, 10381 /*AllowBoolConversions*/false); 10382 if (!IsDiv && 10383 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10384 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10385 // For division, only matrix-by-scalar is supported. Other combinations with 10386 // matrix types are invalid. 10387 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10388 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10389 10390 QualType compType = UsualArithmeticConversions( 10391 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10392 if (LHS.isInvalid() || RHS.isInvalid()) 10393 return QualType(); 10394 10395 10396 if (compType.isNull() || !compType->isArithmeticType()) 10397 return InvalidOperands(Loc, LHS, RHS); 10398 if (IsDiv) { 10399 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10400 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10401 } 10402 return compType; 10403 } 10404 10405 QualType Sema::CheckRemainderOperands( 10406 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10407 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10408 10409 if (LHS.get()->getType()->isVectorType() || 10410 RHS.get()->getType()->isVectorType()) { 10411 if (LHS.get()->getType()->hasIntegerRepresentation() && 10412 RHS.get()->getType()->hasIntegerRepresentation()) 10413 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10414 /*AllowBothBool*/getLangOpts().AltiVec, 10415 /*AllowBoolConversions*/false); 10416 return InvalidOperands(Loc, LHS, RHS); 10417 } 10418 10419 QualType compType = UsualArithmeticConversions( 10420 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10421 if (LHS.isInvalid() || RHS.isInvalid()) 10422 return QualType(); 10423 10424 if (compType.isNull() || !compType->isIntegerType()) 10425 return InvalidOperands(Loc, LHS, RHS); 10426 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10427 return compType; 10428 } 10429 10430 /// Diagnose invalid arithmetic on two void pointers. 10431 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10432 Expr *LHSExpr, Expr *RHSExpr) { 10433 S.Diag(Loc, S.getLangOpts().CPlusPlus 10434 ? diag::err_typecheck_pointer_arith_void_type 10435 : diag::ext_gnu_void_ptr) 10436 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10437 << RHSExpr->getSourceRange(); 10438 } 10439 10440 /// Diagnose invalid arithmetic on a void pointer. 10441 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10442 Expr *Pointer) { 10443 S.Diag(Loc, S.getLangOpts().CPlusPlus 10444 ? diag::err_typecheck_pointer_arith_void_type 10445 : diag::ext_gnu_void_ptr) 10446 << 0 /* one pointer */ << Pointer->getSourceRange(); 10447 } 10448 10449 /// Diagnose invalid arithmetic on a null pointer. 10450 /// 10451 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10452 /// idiom, which we recognize as a GNU extension. 10453 /// 10454 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10455 Expr *Pointer, bool IsGNUIdiom) { 10456 if (IsGNUIdiom) 10457 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10458 << Pointer->getSourceRange(); 10459 else 10460 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10461 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10462 } 10463 10464 /// Diagnose invalid subraction on a null pointer. 10465 /// 10466 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10467 Expr *Pointer, bool BothNull) { 10468 // Null - null is valid in C++ [expr.add]p7 10469 if (BothNull && S.getLangOpts().CPlusPlus) 10470 return; 10471 10472 // Is this s a macro from a system header? 10473 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10474 return; 10475 10476 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10477 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10478 } 10479 10480 /// Diagnose invalid arithmetic on two function pointers. 10481 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10482 Expr *LHS, Expr *RHS) { 10483 assert(LHS->getType()->isAnyPointerType()); 10484 assert(RHS->getType()->isAnyPointerType()); 10485 S.Diag(Loc, S.getLangOpts().CPlusPlus 10486 ? diag::err_typecheck_pointer_arith_function_type 10487 : diag::ext_gnu_ptr_func_arith) 10488 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10489 // We only show the second type if it differs from the first. 10490 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10491 RHS->getType()) 10492 << RHS->getType()->getPointeeType() 10493 << LHS->getSourceRange() << RHS->getSourceRange(); 10494 } 10495 10496 /// Diagnose invalid arithmetic on a function pointer. 10497 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10498 Expr *Pointer) { 10499 assert(Pointer->getType()->isAnyPointerType()); 10500 S.Diag(Loc, S.getLangOpts().CPlusPlus 10501 ? diag::err_typecheck_pointer_arith_function_type 10502 : diag::ext_gnu_ptr_func_arith) 10503 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10504 << 0 /* one pointer, so only one type */ 10505 << Pointer->getSourceRange(); 10506 } 10507 10508 /// Emit error if Operand is incomplete pointer type 10509 /// 10510 /// \returns True if pointer has incomplete type 10511 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10512 Expr *Operand) { 10513 QualType ResType = Operand->getType(); 10514 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10515 ResType = ResAtomicType->getValueType(); 10516 10517 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10518 QualType PointeeTy = ResType->getPointeeType(); 10519 return S.RequireCompleteSizedType( 10520 Loc, PointeeTy, 10521 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10522 Operand->getSourceRange()); 10523 } 10524 10525 /// Check the validity of an arithmetic pointer operand. 10526 /// 10527 /// If the operand has pointer type, this code will check for pointer types 10528 /// which are invalid in arithmetic operations. These will be diagnosed 10529 /// appropriately, including whether or not the use is supported as an 10530 /// extension. 10531 /// 10532 /// \returns True when the operand is valid to use (even if as an extension). 10533 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10534 Expr *Operand) { 10535 QualType ResType = Operand->getType(); 10536 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10537 ResType = ResAtomicType->getValueType(); 10538 10539 if (!ResType->isAnyPointerType()) return true; 10540 10541 QualType PointeeTy = ResType->getPointeeType(); 10542 if (PointeeTy->isVoidType()) { 10543 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10544 return !S.getLangOpts().CPlusPlus; 10545 } 10546 if (PointeeTy->isFunctionType()) { 10547 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10548 return !S.getLangOpts().CPlusPlus; 10549 } 10550 10551 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10552 10553 return true; 10554 } 10555 10556 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10557 /// operands. 10558 /// 10559 /// This routine will diagnose any invalid arithmetic on pointer operands much 10560 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10561 /// for emitting a single diagnostic even for operations where both LHS and RHS 10562 /// are (potentially problematic) pointers. 10563 /// 10564 /// \returns True when the operand is valid to use (even if as an extension). 10565 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10566 Expr *LHSExpr, Expr *RHSExpr) { 10567 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10568 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10569 if (!isLHSPointer && !isRHSPointer) return true; 10570 10571 QualType LHSPointeeTy, RHSPointeeTy; 10572 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10573 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10574 10575 // if both are pointers check if operation is valid wrt address spaces 10576 if (isLHSPointer && isRHSPointer) { 10577 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10578 S.Diag(Loc, 10579 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10580 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10581 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10582 return false; 10583 } 10584 } 10585 10586 // Check for arithmetic on pointers to incomplete types. 10587 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10588 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10589 if (isLHSVoidPtr || isRHSVoidPtr) { 10590 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10591 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10592 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10593 10594 return !S.getLangOpts().CPlusPlus; 10595 } 10596 10597 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10598 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10599 if (isLHSFuncPtr || isRHSFuncPtr) { 10600 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10601 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10602 RHSExpr); 10603 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10604 10605 return !S.getLangOpts().CPlusPlus; 10606 } 10607 10608 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10609 return false; 10610 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10611 return false; 10612 10613 return true; 10614 } 10615 10616 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10617 /// literal. 10618 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10619 Expr *LHSExpr, Expr *RHSExpr) { 10620 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10621 Expr* IndexExpr = RHSExpr; 10622 if (!StrExpr) { 10623 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10624 IndexExpr = LHSExpr; 10625 } 10626 10627 bool IsStringPlusInt = StrExpr && 10628 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10629 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10630 return; 10631 10632 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10633 Self.Diag(OpLoc, diag::warn_string_plus_int) 10634 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10635 10636 // Only print a fixit for "str" + int, not for int + "str". 10637 if (IndexExpr == RHSExpr) { 10638 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10639 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10640 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10641 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10642 << FixItHint::CreateInsertion(EndLoc, "]"); 10643 } else 10644 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10645 } 10646 10647 /// Emit a warning when adding a char literal to a string. 10648 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10649 Expr *LHSExpr, Expr *RHSExpr) { 10650 const Expr *StringRefExpr = LHSExpr; 10651 const CharacterLiteral *CharExpr = 10652 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10653 10654 if (!CharExpr) { 10655 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10656 StringRefExpr = RHSExpr; 10657 } 10658 10659 if (!CharExpr || !StringRefExpr) 10660 return; 10661 10662 const QualType StringType = StringRefExpr->getType(); 10663 10664 // Return if not a PointerType. 10665 if (!StringType->isAnyPointerType()) 10666 return; 10667 10668 // Return if not a CharacterType. 10669 if (!StringType->getPointeeType()->isAnyCharacterType()) 10670 return; 10671 10672 ASTContext &Ctx = Self.getASTContext(); 10673 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10674 10675 const QualType CharType = CharExpr->getType(); 10676 if (!CharType->isAnyCharacterType() && 10677 CharType->isIntegerType() && 10678 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10679 Self.Diag(OpLoc, diag::warn_string_plus_char) 10680 << DiagRange << Ctx.CharTy; 10681 } else { 10682 Self.Diag(OpLoc, diag::warn_string_plus_char) 10683 << DiagRange << CharExpr->getType(); 10684 } 10685 10686 // Only print a fixit for str + char, not for char + str. 10687 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10688 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10689 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10690 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10691 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10692 << FixItHint::CreateInsertion(EndLoc, "]"); 10693 } else { 10694 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10695 } 10696 } 10697 10698 /// Emit error when two pointers are incompatible. 10699 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10700 Expr *LHSExpr, Expr *RHSExpr) { 10701 assert(LHSExpr->getType()->isAnyPointerType()); 10702 assert(RHSExpr->getType()->isAnyPointerType()); 10703 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10704 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10705 << RHSExpr->getSourceRange(); 10706 } 10707 10708 // C99 6.5.6 10709 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10710 SourceLocation Loc, BinaryOperatorKind Opc, 10711 QualType* CompLHSTy) { 10712 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10713 10714 if (LHS.get()->getType()->isVectorType() || 10715 RHS.get()->getType()->isVectorType()) { 10716 QualType compType = CheckVectorOperands( 10717 LHS, RHS, Loc, CompLHSTy, 10718 /*AllowBothBool*/getLangOpts().AltiVec, 10719 /*AllowBoolConversions*/getLangOpts().ZVector); 10720 if (CompLHSTy) *CompLHSTy = compType; 10721 return compType; 10722 } 10723 10724 if (LHS.get()->getType()->isConstantMatrixType() || 10725 RHS.get()->getType()->isConstantMatrixType()) { 10726 QualType compType = 10727 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10728 if (CompLHSTy) 10729 *CompLHSTy = compType; 10730 return compType; 10731 } 10732 10733 QualType compType = UsualArithmeticConversions( 10734 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10735 if (LHS.isInvalid() || RHS.isInvalid()) 10736 return QualType(); 10737 10738 // Diagnose "string literal" '+' int and string '+' "char literal". 10739 if (Opc == BO_Add) { 10740 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10741 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10742 } 10743 10744 // handle the common case first (both operands are arithmetic). 10745 if (!compType.isNull() && compType->isArithmeticType()) { 10746 if (CompLHSTy) *CompLHSTy = compType; 10747 return compType; 10748 } 10749 10750 // Type-checking. Ultimately the pointer's going to be in PExp; 10751 // note that we bias towards the LHS being the pointer. 10752 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10753 10754 bool isObjCPointer; 10755 if (PExp->getType()->isPointerType()) { 10756 isObjCPointer = false; 10757 } else if (PExp->getType()->isObjCObjectPointerType()) { 10758 isObjCPointer = true; 10759 } else { 10760 std::swap(PExp, IExp); 10761 if (PExp->getType()->isPointerType()) { 10762 isObjCPointer = false; 10763 } else if (PExp->getType()->isObjCObjectPointerType()) { 10764 isObjCPointer = true; 10765 } else { 10766 return InvalidOperands(Loc, LHS, RHS); 10767 } 10768 } 10769 assert(PExp->getType()->isAnyPointerType()); 10770 10771 if (!IExp->getType()->isIntegerType()) 10772 return InvalidOperands(Loc, LHS, RHS); 10773 10774 // Adding to a null pointer results in undefined behavior. 10775 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10776 Context, Expr::NPC_ValueDependentIsNotNull)) { 10777 // In C++ adding zero to a null pointer is defined. 10778 Expr::EvalResult KnownVal; 10779 if (!getLangOpts().CPlusPlus || 10780 (!IExp->isValueDependent() && 10781 (!IExp->EvaluateAsInt(KnownVal, Context) || 10782 KnownVal.Val.getInt() != 0))) { 10783 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10784 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10785 Context, BO_Add, PExp, IExp); 10786 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10787 } 10788 } 10789 10790 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10791 return QualType(); 10792 10793 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10794 return QualType(); 10795 10796 // Check array bounds for pointer arithemtic 10797 CheckArrayAccess(PExp, IExp); 10798 10799 if (CompLHSTy) { 10800 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10801 if (LHSTy.isNull()) { 10802 LHSTy = LHS.get()->getType(); 10803 if (LHSTy->isPromotableIntegerType()) 10804 LHSTy = Context.getPromotedIntegerType(LHSTy); 10805 } 10806 *CompLHSTy = LHSTy; 10807 } 10808 10809 return PExp->getType(); 10810 } 10811 10812 // C99 6.5.6 10813 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10814 SourceLocation Loc, 10815 QualType* CompLHSTy) { 10816 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10817 10818 if (LHS.get()->getType()->isVectorType() || 10819 RHS.get()->getType()->isVectorType()) { 10820 QualType compType = CheckVectorOperands( 10821 LHS, RHS, Loc, CompLHSTy, 10822 /*AllowBothBool*/getLangOpts().AltiVec, 10823 /*AllowBoolConversions*/getLangOpts().ZVector); 10824 if (CompLHSTy) *CompLHSTy = compType; 10825 return compType; 10826 } 10827 10828 if (LHS.get()->getType()->isConstantMatrixType() || 10829 RHS.get()->getType()->isConstantMatrixType()) { 10830 QualType compType = 10831 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10832 if (CompLHSTy) 10833 *CompLHSTy = compType; 10834 return compType; 10835 } 10836 10837 QualType compType = UsualArithmeticConversions( 10838 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10839 if (LHS.isInvalid() || RHS.isInvalid()) 10840 return QualType(); 10841 10842 // Enforce type constraints: C99 6.5.6p3. 10843 10844 // Handle the common case first (both operands are arithmetic). 10845 if (!compType.isNull() && compType->isArithmeticType()) { 10846 if (CompLHSTy) *CompLHSTy = compType; 10847 return compType; 10848 } 10849 10850 // Either ptr - int or ptr - ptr. 10851 if (LHS.get()->getType()->isAnyPointerType()) { 10852 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10853 10854 // Diagnose bad cases where we step over interface counts. 10855 if (LHS.get()->getType()->isObjCObjectPointerType() && 10856 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10857 return QualType(); 10858 10859 // The result type of a pointer-int computation is the pointer type. 10860 if (RHS.get()->getType()->isIntegerType()) { 10861 // Subtracting from a null pointer should produce a warning. 10862 // The last argument to the diagnose call says this doesn't match the 10863 // GNU int-to-pointer idiom. 10864 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10865 Expr::NPC_ValueDependentIsNotNull)) { 10866 // In C++ adding zero to a null pointer is defined. 10867 Expr::EvalResult KnownVal; 10868 if (!getLangOpts().CPlusPlus || 10869 (!RHS.get()->isValueDependent() && 10870 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10871 KnownVal.Val.getInt() != 0))) { 10872 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10873 } 10874 } 10875 10876 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10877 return QualType(); 10878 10879 // Check array bounds for pointer arithemtic 10880 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10881 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10882 10883 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10884 return LHS.get()->getType(); 10885 } 10886 10887 // Handle pointer-pointer subtractions. 10888 if (const PointerType *RHSPTy 10889 = RHS.get()->getType()->getAs<PointerType>()) { 10890 QualType rpointee = RHSPTy->getPointeeType(); 10891 10892 if (getLangOpts().CPlusPlus) { 10893 // Pointee types must be the same: C++ [expr.add] 10894 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10895 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10896 } 10897 } else { 10898 // Pointee types must be compatible C99 6.5.6p3 10899 if (!Context.typesAreCompatible( 10900 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10901 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10902 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10903 return QualType(); 10904 } 10905 } 10906 10907 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10908 LHS.get(), RHS.get())) 10909 return QualType(); 10910 10911 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10912 Context, Expr::NPC_ValueDependentIsNotNull); 10913 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10914 Context, Expr::NPC_ValueDependentIsNotNull); 10915 10916 // Subtracting nullptr or from nullptr is suspect 10917 if (LHSIsNullPtr) 10918 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10919 if (RHSIsNullPtr) 10920 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10921 10922 // The pointee type may have zero size. As an extension, a structure or 10923 // union may have zero size or an array may have zero length. In this 10924 // case subtraction does not make sense. 10925 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10926 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10927 if (ElementSize.isZero()) { 10928 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10929 << rpointee.getUnqualifiedType() 10930 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10931 } 10932 } 10933 10934 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10935 return Context.getPointerDiffType(); 10936 } 10937 } 10938 10939 return InvalidOperands(Loc, LHS, RHS); 10940 } 10941 10942 static bool isScopedEnumerationType(QualType T) { 10943 if (const EnumType *ET = T->getAs<EnumType>()) 10944 return ET->getDecl()->isScoped(); 10945 return false; 10946 } 10947 10948 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10949 SourceLocation Loc, BinaryOperatorKind Opc, 10950 QualType LHSType) { 10951 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10952 // so skip remaining warnings as we don't want to modify values within Sema. 10953 if (S.getLangOpts().OpenCL) 10954 return; 10955 10956 // Check right/shifter operand 10957 Expr::EvalResult RHSResult; 10958 if (RHS.get()->isValueDependent() || 10959 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10960 return; 10961 llvm::APSInt Right = RHSResult.Val.getInt(); 10962 10963 if (Right.isNegative()) { 10964 S.DiagRuntimeBehavior(Loc, RHS.get(), 10965 S.PDiag(diag::warn_shift_negative) 10966 << RHS.get()->getSourceRange()); 10967 return; 10968 } 10969 10970 QualType LHSExprType = LHS.get()->getType(); 10971 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10972 if (LHSExprType->isExtIntType()) 10973 LeftSize = S.Context.getIntWidth(LHSExprType); 10974 else if (LHSExprType->isFixedPointType()) { 10975 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10976 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10977 } 10978 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10979 if (Right.uge(LeftBits)) { 10980 S.DiagRuntimeBehavior(Loc, RHS.get(), 10981 S.PDiag(diag::warn_shift_gt_typewidth) 10982 << RHS.get()->getSourceRange()); 10983 return; 10984 } 10985 10986 // FIXME: We probably need to handle fixed point types specially here. 10987 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10988 return; 10989 10990 // When left shifting an ICE which is signed, we can check for overflow which 10991 // according to C++ standards prior to C++2a has undefined behavior 10992 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10993 // more than the maximum value representable in the result type, so never 10994 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10995 // expression is still probably a bug.) 10996 Expr::EvalResult LHSResult; 10997 if (LHS.get()->isValueDependent() || 10998 LHSType->hasUnsignedIntegerRepresentation() || 10999 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11000 return; 11001 llvm::APSInt Left = LHSResult.Val.getInt(); 11002 11003 // If LHS does not have a signed type and non-negative value 11004 // then, the behavior is undefined before C++2a. Warn about it. 11005 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11006 !S.getLangOpts().CPlusPlus20) { 11007 S.DiagRuntimeBehavior(Loc, LHS.get(), 11008 S.PDiag(diag::warn_shift_lhs_negative) 11009 << LHS.get()->getSourceRange()); 11010 return; 11011 } 11012 11013 llvm::APInt ResultBits = 11014 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11015 if (LeftBits.uge(ResultBits)) 11016 return; 11017 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11018 Result = Result.shl(Right); 11019 11020 // Print the bit representation of the signed integer as an unsigned 11021 // hexadecimal number. 11022 SmallString<40> HexResult; 11023 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11024 11025 // If we are only missing a sign bit, this is less likely to result in actual 11026 // bugs -- if the result is cast back to an unsigned type, it will have the 11027 // expected value. Thus we place this behind a different warning that can be 11028 // turned off separately if needed. 11029 if (LeftBits == ResultBits - 1) { 11030 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11031 << HexResult << LHSType 11032 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11033 return; 11034 } 11035 11036 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11037 << HexResult.str() << Result.getMinSignedBits() << LHSType 11038 << Left.getBitWidth() << LHS.get()->getSourceRange() 11039 << RHS.get()->getSourceRange(); 11040 } 11041 11042 /// Return the resulting type when a vector is shifted 11043 /// by a scalar or vector shift amount. 11044 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11045 SourceLocation Loc, bool IsCompAssign) { 11046 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11047 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11048 !LHS.get()->getType()->isVectorType()) { 11049 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11050 << RHS.get()->getType() << LHS.get()->getType() 11051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11052 return QualType(); 11053 } 11054 11055 if (!IsCompAssign) { 11056 LHS = S.UsualUnaryConversions(LHS.get()); 11057 if (LHS.isInvalid()) return QualType(); 11058 } 11059 11060 RHS = S.UsualUnaryConversions(RHS.get()); 11061 if (RHS.isInvalid()) return QualType(); 11062 11063 QualType LHSType = LHS.get()->getType(); 11064 // Note that LHS might be a scalar because the routine calls not only in 11065 // OpenCL case. 11066 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11067 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11068 11069 // Note that RHS might not be a vector. 11070 QualType RHSType = RHS.get()->getType(); 11071 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11072 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11073 11074 // The operands need to be integers. 11075 if (!LHSEleType->isIntegerType()) { 11076 S.Diag(Loc, diag::err_typecheck_expect_int) 11077 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11078 return QualType(); 11079 } 11080 11081 if (!RHSEleType->isIntegerType()) { 11082 S.Diag(Loc, diag::err_typecheck_expect_int) 11083 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11084 return QualType(); 11085 } 11086 11087 if (!LHSVecTy) { 11088 assert(RHSVecTy); 11089 if (IsCompAssign) 11090 return RHSType; 11091 if (LHSEleType != RHSEleType) { 11092 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11093 LHSEleType = RHSEleType; 11094 } 11095 QualType VecTy = 11096 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11097 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11098 LHSType = VecTy; 11099 } else if (RHSVecTy) { 11100 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11101 // are applied component-wise. So if RHS is a vector, then ensure 11102 // that the number of elements is the same as LHS... 11103 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11104 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11105 << LHS.get()->getType() << RHS.get()->getType() 11106 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11107 return QualType(); 11108 } 11109 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11110 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11111 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11112 if (LHSBT != RHSBT && 11113 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11114 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11115 << LHS.get()->getType() << RHS.get()->getType() 11116 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11117 } 11118 } 11119 } else { 11120 // ...else expand RHS to match the number of elements in LHS. 11121 QualType VecTy = 11122 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11123 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11124 } 11125 11126 return LHSType; 11127 } 11128 11129 // C99 6.5.7 11130 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11131 SourceLocation Loc, BinaryOperatorKind Opc, 11132 bool IsCompAssign) { 11133 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11134 11135 // Vector shifts promote their scalar inputs to vector type. 11136 if (LHS.get()->getType()->isVectorType() || 11137 RHS.get()->getType()->isVectorType()) { 11138 if (LangOpts.ZVector) { 11139 // The shift operators for the z vector extensions work basically 11140 // like general shifts, except that neither the LHS nor the RHS is 11141 // allowed to be a "vector bool". 11142 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11143 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11144 return InvalidOperands(Loc, LHS, RHS); 11145 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11146 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11147 return InvalidOperands(Loc, LHS, RHS); 11148 } 11149 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11150 } 11151 11152 // Shifts don't perform usual arithmetic conversions, they just do integer 11153 // promotions on each operand. C99 6.5.7p3 11154 11155 // For the LHS, do usual unary conversions, but then reset them away 11156 // if this is a compound assignment. 11157 ExprResult OldLHS = LHS; 11158 LHS = UsualUnaryConversions(LHS.get()); 11159 if (LHS.isInvalid()) 11160 return QualType(); 11161 QualType LHSType = LHS.get()->getType(); 11162 if (IsCompAssign) LHS = OldLHS; 11163 11164 // The RHS is simpler. 11165 RHS = UsualUnaryConversions(RHS.get()); 11166 if (RHS.isInvalid()) 11167 return QualType(); 11168 QualType RHSType = RHS.get()->getType(); 11169 11170 // C99 6.5.7p2: Each of the operands shall have integer type. 11171 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11172 if ((!LHSType->isFixedPointOrIntegerType() && 11173 !LHSType->hasIntegerRepresentation()) || 11174 !RHSType->hasIntegerRepresentation()) 11175 return InvalidOperands(Loc, LHS, RHS); 11176 11177 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11178 // hasIntegerRepresentation() above instead of this. 11179 if (isScopedEnumerationType(LHSType) || 11180 isScopedEnumerationType(RHSType)) { 11181 return InvalidOperands(Loc, LHS, RHS); 11182 } 11183 // Sanity-check shift operands 11184 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11185 11186 // "The type of the result is that of the promoted left operand." 11187 return LHSType; 11188 } 11189 11190 /// Diagnose bad pointer comparisons. 11191 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11192 ExprResult &LHS, ExprResult &RHS, 11193 bool IsError) { 11194 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11195 : diag::ext_typecheck_comparison_of_distinct_pointers) 11196 << LHS.get()->getType() << RHS.get()->getType() 11197 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11198 } 11199 11200 /// Returns false if the pointers are converted to a composite type, 11201 /// true otherwise. 11202 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11203 ExprResult &LHS, ExprResult &RHS) { 11204 // C++ [expr.rel]p2: 11205 // [...] Pointer conversions (4.10) and qualification 11206 // conversions (4.4) are performed on pointer operands (or on 11207 // a pointer operand and a null pointer constant) to bring 11208 // them to their composite pointer type. [...] 11209 // 11210 // C++ [expr.eq]p1 uses the same notion for (in)equality 11211 // comparisons of pointers. 11212 11213 QualType LHSType = LHS.get()->getType(); 11214 QualType RHSType = RHS.get()->getType(); 11215 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11216 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11217 11218 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11219 if (T.isNull()) { 11220 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11221 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11222 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11223 else 11224 S.InvalidOperands(Loc, LHS, RHS); 11225 return true; 11226 } 11227 11228 return false; 11229 } 11230 11231 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11232 ExprResult &LHS, 11233 ExprResult &RHS, 11234 bool IsError) { 11235 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11236 : diag::ext_typecheck_comparison_of_fptr_to_void) 11237 << LHS.get()->getType() << RHS.get()->getType() 11238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11239 } 11240 11241 static bool isObjCObjectLiteral(ExprResult &E) { 11242 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11243 case Stmt::ObjCArrayLiteralClass: 11244 case Stmt::ObjCDictionaryLiteralClass: 11245 case Stmt::ObjCStringLiteralClass: 11246 case Stmt::ObjCBoxedExprClass: 11247 return true; 11248 default: 11249 // Note that ObjCBoolLiteral is NOT an object literal! 11250 return false; 11251 } 11252 } 11253 11254 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11255 const ObjCObjectPointerType *Type = 11256 LHS->getType()->getAs<ObjCObjectPointerType>(); 11257 11258 // If this is not actually an Objective-C object, bail out. 11259 if (!Type) 11260 return false; 11261 11262 // Get the LHS object's interface type. 11263 QualType InterfaceType = Type->getPointeeType(); 11264 11265 // If the RHS isn't an Objective-C object, bail out. 11266 if (!RHS->getType()->isObjCObjectPointerType()) 11267 return false; 11268 11269 // Try to find the -isEqual: method. 11270 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11271 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11272 InterfaceType, 11273 /*IsInstance=*/true); 11274 if (!Method) { 11275 if (Type->isObjCIdType()) { 11276 // For 'id', just check the global pool. 11277 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11278 /*receiverId=*/true); 11279 } else { 11280 // Check protocols. 11281 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11282 /*IsInstance=*/true); 11283 } 11284 } 11285 11286 if (!Method) 11287 return false; 11288 11289 QualType T = Method->parameters()[0]->getType(); 11290 if (!T->isObjCObjectPointerType()) 11291 return false; 11292 11293 QualType R = Method->getReturnType(); 11294 if (!R->isScalarType()) 11295 return false; 11296 11297 return true; 11298 } 11299 11300 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11301 FromE = FromE->IgnoreParenImpCasts(); 11302 switch (FromE->getStmtClass()) { 11303 default: 11304 break; 11305 case Stmt::ObjCStringLiteralClass: 11306 // "string literal" 11307 return LK_String; 11308 case Stmt::ObjCArrayLiteralClass: 11309 // "array literal" 11310 return LK_Array; 11311 case Stmt::ObjCDictionaryLiteralClass: 11312 // "dictionary literal" 11313 return LK_Dictionary; 11314 case Stmt::BlockExprClass: 11315 return LK_Block; 11316 case Stmt::ObjCBoxedExprClass: { 11317 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11318 switch (Inner->getStmtClass()) { 11319 case Stmt::IntegerLiteralClass: 11320 case Stmt::FloatingLiteralClass: 11321 case Stmt::CharacterLiteralClass: 11322 case Stmt::ObjCBoolLiteralExprClass: 11323 case Stmt::CXXBoolLiteralExprClass: 11324 // "numeric literal" 11325 return LK_Numeric; 11326 case Stmt::ImplicitCastExprClass: { 11327 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11328 // Boolean literals can be represented by implicit casts. 11329 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11330 return LK_Numeric; 11331 break; 11332 } 11333 default: 11334 break; 11335 } 11336 return LK_Boxed; 11337 } 11338 } 11339 return LK_None; 11340 } 11341 11342 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11343 ExprResult &LHS, ExprResult &RHS, 11344 BinaryOperator::Opcode Opc){ 11345 Expr *Literal; 11346 Expr *Other; 11347 if (isObjCObjectLiteral(LHS)) { 11348 Literal = LHS.get(); 11349 Other = RHS.get(); 11350 } else { 11351 Literal = RHS.get(); 11352 Other = LHS.get(); 11353 } 11354 11355 // Don't warn on comparisons against nil. 11356 Other = Other->IgnoreParenCasts(); 11357 if (Other->isNullPointerConstant(S.getASTContext(), 11358 Expr::NPC_ValueDependentIsNotNull)) 11359 return; 11360 11361 // This should be kept in sync with warn_objc_literal_comparison. 11362 // LK_String should always be after the other literals, since it has its own 11363 // warning flag. 11364 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11365 assert(LiteralKind != Sema::LK_Block); 11366 if (LiteralKind == Sema::LK_None) { 11367 llvm_unreachable("Unknown Objective-C object literal kind"); 11368 } 11369 11370 if (LiteralKind == Sema::LK_String) 11371 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11372 << Literal->getSourceRange(); 11373 else 11374 S.Diag(Loc, diag::warn_objc_literal_comparison) 11375 << LiteralKind << Literal->getSourceRange(); 11376 11377 if (BinaryOperator::isEqualityOp(Opc) && 11378 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11379 SourceLocation Start = LHS.get()->getBeginLoc(); 11380 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11381 CharSourceRange OpRange = 11382 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11383 11384 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11385 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11386 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11387 << FixItHint::CreateInsertion(End, "]"); 11388 } 11389 } 11390 11391 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11392 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11393 ExprResult &RHS, SourceLocation Loc, 11394 BinaryOperatorKind Opc) { 11395 // Check that left hand side is !something. 11396 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11397 if (!UO || UO->getOpcode() != UO_LNot) return; 11398 11399 // Only check if the right hand side is non-bool arithmetic type. 11400 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11401 11402 // Make sure that the something in !something is not bool. 11403 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11404 if (SubExpr->isKnownToHaveBooleanValue()) return; 11405 11406 // Emit warning. 11407 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11408 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11409 << Loc << IsBitwiseOp; 11410 11411 // First note suggest !(x < y) 11412 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11413 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11414 FirstClose = S.getLocForEndOfToken(FirstClose); 11415 if (FirstClose.isInvalid()) 11416 FirstOpen = SourceLocation(); 11417 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11418 << IsBitwiseOp 11419 << FixItHint::CreateInsertion(FirstOpen, "(") 11420 << FixItHint::CreateInsertion(FirstClose, ")"); 11421 11422 // Second note suggests (!x) < y 11423 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11424 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11425 SecondClose = S.getLocForEndOfToken(SecondClose); 11426 if (SecondClose.isInvalid()) 11427 SecondOpen = SourceLocation(); 11428 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11429 << FixItHint::CreateInsertion(SecondOpen, "(") 11430 << FixItHint::CreateInsertion(SecondClose, ")"); 11431 } 11432 11433 // Returns true if E refers to a non-weak array. 11434 static bool checkForArray(const Expr *E) { 11435 const ValueDecl *D = nullptr; 11436 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11437 D = DR->getDecl(); 11438 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11439 if (Mem->isImplicitAccess()) 11440 D = Mem->getMemberDecl(); 11441 } 11442 if (!D) 11443 return false; 11444 return D->getType()->isArrayType() && !D->isWeak(); 11445 } 11446 11447 /// Diagnose some forms of syntactically-obvious tautological comparison. 11448 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11449 Expr *LHS, Expr *RHS, 11450 BinaryOperatorKind Opc) { 11451 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11452 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11453 11454 QualType LHSType = LHS->getType(); 11455 QualType RHSType = RHS->getType(); 11456 if (LHSType->hasFloatingRepresentation() || 11457 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11458 S.inTemplateInstantiation()) 11459 return; 11460 11461 // Comparisons between two array types are ill-formed for operator<=>, so 11462 // we shouldn't emit any additional warnings about it. 11463 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11464 return; 11465 11466 // For non-floating point types, check for self-comparisons of the form 11467 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11468 // often indicate logic errors in the program. 11469 // 11470 // NOTE: Don't warn about comparison expressions resulting from macro 11471 // expansion. Also don't warn about comparisons which are only self 11472 // comparisons within a template instantiation. The warnings should catch 11473 // obvious cases in the definition of the template anyways. The idea is to 11474 // warn when the typed comparison operator will always evaluate to the same 11475 // result. 11476 11477 // Used for indexing into %select in warn_comparison_always 11478 enum { 11479 AlwaysConstant, 11480 AlwaysTrue, 11481 AlwaysFalse, 11482 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11483 }; 11484 11485 // C++2a [depr.array.comp]: 11486 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11487 // operands of array type are deprecated. 11488 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11489 RHSStripped->getType()->isArrayType()) { 11490 S.Diag(Loc, diag::warn_depr_array_comparison) 11491 << LHS->getSourceRange() << RHS->getSourceRange() 11492 << LHSStripped->getType() << RHSStripped->getType(); 11493 // Carry on to produce the tautological comparison warning, if this 11494 // expression is potentially-evaluated, we can resolve the array to a 11495 // non-weak declaration, and so on. 11496 } 11497 11498 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11499 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11500 unsigned Result; 11501 switch (Opc) { 11502 case BO_EQ: 11503 case BO_LE: 11504 case BO_GE: 11505 Result = AlwaysTrue; 11506 break; 11507 case BO_NE: 11508 case BO_LT: 11509 case BO_GT: 11510 Result = AlwaysFalse; 11511 break; 11512 case BO_Cmp: 11513 Result = AlwaysEqual; 11514 break; 11515 default: 11516 Result = AlwaysConstant; 11517 break; 11518 } 11519 S.DiagRuntimeBehavior(Loc, nullptr, 11520 S.PDiag(diag::warn_comparison_always) 11521 << 0 /*self-comparison*/ 11522 << Result); 11523 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11524 // What is it always going to evaluate to? 11525 unsigned Result; 11526 switch (Opc) { 11527 case BO_EQ: // e.g. array1 == array2 11528 Result = AlwaysFalse; 11529 break; 11530 case BO_NE: // e.g. array1 != array2 11531 Result = AlwaysTrue; 11532 break; 11533 default: // e.g. array1 <= array2 11534 // The best we can say is 'a constant' 11535 Result = AlwaysConstant; 11536 break; 11537 } 11538 S.DiagRuntimeBehavior(Loc, nullptr, 11539 S.PDiag(diag::warn_comparison_always) 11540 << 1 /*array comparison*/ 11541 << Result); 11542 } 11543 } 11544 11545 if (isa<CastExpr>(LHSStripped)) 11546 LHSStripped = LHSStripped->IgnoreParenCasts(); 11547 if (isa<CastExpr>(RHSStripped)) 11548 RHSStripped = RHSStripped->IgnoreParenCasts(); 11549 11550 // Warn about comparisons against a string constant (unless the other 11551 // operand is null); the user probably wants string comparison function. 11552 Expr *LiteralString = nullptr; 11553 Expr *LiteralStringStripped = nullptr; 11554 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11555 !RHSStripped->isNullPointerConstant(S.Context, 11556 Expr::NPC_ValueDependentIsNull)) { 11557 LiteralString = LHS; 11558 LiteralStringStripped = LHSStripped; 11559 } else if ((isa<StringLiteral>(RHSStripped) || 11560 isa<ObjCEncodeExpr>(RHSStripped)) && 11561 !LHSStripped->isNullPointerConstant(S.Context, 11562 Expr::NPC_ValueDependentIsNull)) { 11563 LiteralString = RHS; 11564 LiteralStringStripped = RHSStripped; 11565 } 11566 11567 if (LiteralString) { 11568 S.DiagRuntimeBehavior(Loc, nullptr, 11569 S.PDiag(diag::warn_stringcompare) 11570 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11571 << LiteralString->getSourceRange()); 11572 } 11573 } 11574 11575 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11576 switch (CK) { 11577 default: { 11578 #ifndef NDEBUG 11579 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11580 << "\n"; 11581 #endif 11582 llvm_unreachable("unhandled cast kind"); 11583 } 11584 case CK_UserDefinedConversion: 11585 return ICK_Identity; 11586 case CK_LValueToRValue: 11587 return ICK_Lvalue_To_Rvalue; 11588 case CK_ArrayToPointerDecay: 11589 return ICK_Array_To_Pointer; 11590 case CK_FunctionToPointerDecay: 11591 return ICK_Function_To_Pointer; 11592 case CK_IntegralCast: 11593 return ICK_Integral_Conversion; 11594 case CK_FloatingCast: 11595 return ICK_Floating_Conversion; 11596 case CK_IntegralToFloating: 11597 case CK_FloatingToIntegral: 11598 return ICK_Floating_Integral; 11599 case CK_IntegralComplexCast: 11600 case CK_FloatingComplexCast: 11601 case CK_FloatingComplexToIntegralComplex: 11602 case CK_IntegralComplexToFloatingComplex: 11603 return ICK_Complex_Conversion; 11604 case CK_FloatingComplexToReal: 11605 case CK_FloatingRealToComplex: 11606 case CK_IntegralComplexToReal: 11607 case CK_IntegralRealToComplex: 11608 return ICK_Complex_Real; 11609 } 11610 } 11611 11612 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11613 QualType FromType, 11614 SourceLocation Loc) { 11615 // Check for a narrowing implicit conversion. 11616 StandardConversionSequence SCS; 11617 SCS.setAsIdentityConversion(); 11618 SCS.setToType(0, FromType); 11619 SCS.setToType(1, ToType); 11620 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11621 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11622 11623 APValue PreNarrowingValue; 11624 QualType PreNarrowingType; 11625 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11626 PreNarrowingType, 11627 /*IgnoreFloatToIntegralConversion*/ true)) { 11628 case NK_Dependent_Narrowing: 11629 // Implicit conversion to a narrower type, but the expression is 11630 // value-dependent so we can't tell whether it's actually narrowing. 11631 case NK_Not_Narrowing: 11632 return false; 11633 11634 case NK_Constant_Narrowing: 11635 // Implicit conversion to a narrower type, and the value is not a constant 11636 // expression. 11637 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11638 << /*Constant*/ 1 11639 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11640 return true; 11641 11642 case NK_Variable_Narrowing: 11643 // Implicit conversion to a narrower type, and the value is not a constant 11644 // expression. 11645 case NK_Type_Narrowing: 11646 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11647 << /*Constant*/ 0 << FromType << ToType; 11648 // TODO: It's not a constant expression, but what if the user intended it 11649 // to be? Can we produce notes to help them figure out why it isn't? 11650 return true; 11651 } 11652 llvm_unreachable("unhandled case in switch"); 11653 } 11654 11655 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11656 ExprResult &LHS, 11657 ExprResult &RHS, 11658 SourceLocation Loc) { 11659 QualType LHSType = LHS.get()->getType(); 11660 QualType RHSType = RHS.get()->getType(); 11661 // Dig out the original argument type and expression before implicit casts 11662 // were applied. These are the types/expressions we need to check the 11663 // [expr.spaceship] requirements against. 11664 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11665 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11666 QualType LHSStrippedType = LHSStripped.get()->getType(); 11667 QualType RHSStrippedType = RHSStripped.get()->getType(); 11668 11669 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11670 // other is not, the program is ill-formed. 11671 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11672 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11673 return QualType(); 11674 } 11675 11676 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11677 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11678 RHSStrippedType->isEnumeralType(); 11679 if (NumEnumArgs == 1) { 11680 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11681 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11682 if (OtherTy->hasFloatingRepresentation()) { 11683 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11684 return QualType(); 11685 } 11686 } 11687 if (NumEnumArgs == 2) { 11688 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11689 // type E, the operator yields the result of converting the operands 11690 // to the underlying type of E and applying <=> to the converted operands. 11691 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11692 S.InvalidOperands(Loc, LHS, RHS); 11693 return QualType(); 11694 } 11695 QualType IntType = 11696 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11697 assert(IntType->isArithmeticType()); 11698 11699 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11700 // promote the boolean type, and all other promotable integer types, to 11701 // avoid this. 11702 if (IntType->isPromotableIntegerType()) 11703 IntType = S.Context.getPromotedIntegerType(IntType); 11704 11705 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11706 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11707 LHSType = RHSType = IntType; 11708 } 11709 11710 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11711 // usual arithmetic conversions are applied to the operands. 11712 QualType Type = 11713 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11714 if (LHS.isInvalid() || RHS.isInvalid()) 11715 return QualType(); 11716 if (Type.isNull()) 11717 return S.InvalidOperands(Loc, LHS, RHS); 11718 11719 Optional<ComparisonCategoryType> CCT = 11720 getComparisonCategoryForBuiltinCmp(Type); 11721 if (!CCT) 11722 return S.InvalidOperands(Loc, LHS, RHS); 11723 11724 bool HasNarrowing = checkThreeWayNarrowingConversion( 11725 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11726 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11727 RHS.get()->getBeginLoc()); 11728 if (HasNarrowing) 11729 return QualType(); 11730 11731 assert(!Type.isNull() && "composite type for <=> has not been set"); 11732 11733 return S.CheckComparisonCategoryType( 11734 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11735 } 11736 11737 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11738 ExprResult &RHS, 11739 SourceLocation Loc, 11740 BinaryOperatorKind Opc) { 11741 if (Opc == BO_Cmp) 11742 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11743 11744 // C99 6.5.8p3 / C99 6.5.9p4 11745 QualType Type = 11746 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11747 if (LHS.isInvalid() || RHS.isInvalid()) 11748 return QualType(); 11749 if (Type.isNull()) 11750 return S.InvalidOperands(Loc, LHS, RHS); 11751 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11752 11753 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11754 return S.InvalidOperands(Loc, LHS, RHS); 11755 11756 // Check for comparisons of floating point operands using != and ==. 11757 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11758 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11759 11760 // The result of comparisons is 'bool' in C++, 'int' in C. 11761 return S.Context.getLogicalOperationType(); 11762 } 11763 11764 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11765 if (!NullE.get()->getType()->isAnyPointerType()) 11766 return; 11767 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11768 if (!E.get()->getType()->isAnyPointerType() && 11769 E.get()->isNullPointerConstant(Context, 11770 Expr::NPC_ValueDependentIsNotNull) == 11771 Expr::NPCK_ZeroExpression) { 11772 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11773 if (CL->getValue() == 0) 11774 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11775 << NullValue 11776 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11777 NullValue ? "NULL" : "(void *)0"); 11778 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11779 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11780 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11781 if (T == Context.CharTy) 11782 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11783 << NullValue 11784 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11785 NullValue ? "NULL" : "(void *)0"); 11786 } 11787 } 11788 } 11789 11790 // C99 6.5.8, C++ [expr.rel] 11791 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11792 SourceLocation Loc, 11793 BinaryOperatorKind Opc) { 11794 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11795 bool IsThreeWay = Opc == BO_Cmp; 11796 bool IsOrdered = IsRelational || IsThreeWay; 11797 auto IsAnyPointerType = [](ExprResult E) { 11798 QualType Ty = E.get()->getType(); 11799 return Ty->isPointerType() || Ty->isMemberPointerType(); 11800 }; 11801 11802 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11803 // type, array-to-pointer, ..., conversions are performed on both operands to 11804 // bring them to their composite type. 11805 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11806 // any type-related checks. 11807 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11808 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11809 if (LHS.isInvalid()) 11810 return QualType(); 11811 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11812 if (RHS.isInvalid()) 11813 return QualType(); 11814 } else { 11815 LHS = DefaultLvalueConversion(LHS.get()); 11816 if (LHS.isInvalid()) 11817 return QualType(); 11818 RHS = DefaultLvalueConversion(RHS.get()); 11819 if (RHS.isInvalid()) 11820 return QualType(); 11821 } 11822 11823 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11824 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11825 CheckPtrComparisonWithNullChar(LHS, RHS); 11826 CheckPtrComparisonWithNullChar(RHS, LHS); 11827 } 11828 11829 // Handle vector comparisons separately. 11830 if (LHS.get()->getType()->isVectorType() || 11831 RHS.get()->getType()->isVectorType()) 11832 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11833 11834 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11835 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11836 11837 QualType LHSType = LHS.get()->getType(); 11838 QualType RHSType = RHS.get()->getType(); 11839 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11840 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11841 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11842 11843 const Expr::NullPointerConstantKind LHSNullKind = 11844 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11845 const Expr::NullPointerConstantKind RHSNullKind = 11846 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11847 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11848 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11849 11850 auto computeResultTy = [&]() { 11851 if (Opc != BO_Cmp) 11852 return Context.getLogicalOperationType(); 11853 assert(getLangOpts().CPlusPlus); 11854 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11855 11856 QualType CompositeTy = LHS.get()->getType(); 11857 assert(!CompositeTy->isReferenceType()); 11858 11859 Optional<ComparisonCategoryType> CCT = 11860 getComparisonCategoryForBuiltinCmp(CompositeTy); 11861 if (!CCT) 11862 return InvalidOperands(Loc, LHS, RHS); 11863 11864 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11865 // P0946R0: Comparisons between a null pointer constant and an object 11866 // pointer result in std::strong_equality, which is ill-formed under 11867 // P1959R0. 11868 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11869 << (LHSIsNull ? LHS.get()->getSourceRange() 11870 : RHS.get()->getSourceRange()); 11871 return QualType(); 11872 } 11873 11874 return CheckComparisonCategoryType( 11875 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11876 }; 11877 11878 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11879 bool IsEquality = Opc == BO_EQ; 11880 if (RHSIsNull) 11881 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11882 RHS.get()->getSourceRange()); 11883 else 11884 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11885 LHS.get()->getSourceRange()); 11886 } 11887 11888 if (IsOrdered && LHSType->isFunctionPointerType() && 11889 RHSType->isFunctionPointerType()) { 11890 // Valid unless a relational comparison of function pointers 11891 bool IsError = Opc == BO_Cmp; 11892 auto DiagID = 11893 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11894 : getLangOpts().CPlusPlus 11895 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11896 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11897 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11898 << RHS.get()->getSourceRange(); 11899 if (IsError) 11900 return QualType(); 11901 } 11902 11903 if ((LHSType->isIntegerType() && !LHSIsNull) || 11904 (RHSType->isIntegerType() && !RHSIsNull)) { 11905 // Skip normal pointer conversion checks in this case; we have better 11906 // diagnostics for this below. 11907 } else if (getLangOpts().CPlusPlus) { 11908 // Equality comparison of a function pointer to a void pointer is invalid, 11909 // but we allow it as an extension. 11910 // FIXME: If we really want to allow this, should it be part of composite 11911 // pointer type computation so it works in conditionals too? 11912 if (!IsOrdered && 11913 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11914 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11915 // This is a gcc extension compatibility comparison. 11916 // In a SFINAE context, we treat this as a hard error to maintain 11917 // conformance with the C++ standard. 11918 diagnoseFunctionPointerToVoidComparison( 11919 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11920 11921 if (isSFINAEContext()) 11922 return QualType(); 11923 11924 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11925 return computeResultTy(); 11926 } 11927 11928 // C++ [expr.eq]p2: 11929 // If at least one operand is a pointer [...] bring them to their 11930 // composite pointer type. 11931 // C++ [expr.spaceship]p6 11932 // If at least one of the operands is of pointer type, [...] bring them 11933 // to their composite pointer type. 11934 // C++ [expr.rel]p2: 11935 // If both operands are pointers, [...] bring them to their composite 11936 // pointer type. 11937 // For <=>, the only valid non-pointer types are arrays and functions, and 11938 // we already decayed those, so this is really the same as the relational 11939 // comparison rule. 11940 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11941 (IsOrdered ? 2 : 1) && 11942 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11943 RHSType->isObjCObjectPointerType()))) { 11944 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11945 return QualType(); 11946 return computeResultTy(); 11947 } 11948 } else if (LHSType->isPointerType() && 11949 RHSType->isPointerType()) { // C99 6.5.8p2 11950 // All of the following pointer-related warnings are GCC extensions, except 11951 // when handling null pointer constants. 11952 QualType LCanPointeeTy = 11953 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11954 QualType RCanPointeeTy = 11955 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11956 11957 // C99 6.5.9p2 and C99 6.5.8p2 11958 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11959 RCanPointeeTy.getUnqualifiedType())) { 11960 if (IsRelational) { 11961 // Pointers both need to point to complete or incomplete types 11962 if ((LCanPointeeTy->isIncompleteType() != 11963 RCanPointeeTy->isIncompleteType()) && 11964 !getLangOpts().C11) { 11965 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11966 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11967 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11968 << RCanPointeeTy->isIncompleteType(); 11969 } 11970 } 11971 } else if (!IsRelational && 11972 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11973 // Valid unless comparison between non-null pointer and function pointer 11974 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11975 && !LHSIsNull && !RHSIsNull) 11976 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11977 /*isError*/false); 11978 } else { 11979 // Invalid 11980 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11981 } 11982 if (LCanPointeeTy != RCanPointeeTy) { 11983 // Treat NULL constant as a special case in OpenCL. 11984 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11985 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11986 Diag(Loc, 11987 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11988 << LHSType << RHSType << 0 /* comparison */ 11989 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11990 } 11991 } 11992 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11993 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11994 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11995 : CK_BitCast; 11996 if (LHSIsNull && !RHSIsNull) 11997 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11998 else 11999 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12000 } 12001 return computeResultTy(); 12002 } 12003 12004 if (getLangOpts().CPlusPlus) { 12005 // C++ [expr.eq]p4: 12006 // Two operands of type std::nullptr_t or one operand of type 12007 // std::nullptr_t and the other a null pointer constant compare equal. 12008 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12009 if (LHSType->isNullPtrType()) { 12010 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12011 return computeResultTy(); 12012 } 12013 if (RHSType->isNullPtrType()) { 12014 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12015 return computeResultTy(); 12016 } 12017 } 12018 12019 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12020 // These aren't covered by the composite pointer type rules. 12021 if (!IsOrdered && RHSType->isNullPtrType() && 12022 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12023 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12024 return computeResultTy(); 12025 } 12026 if (!IsOrdered && LHSType->isNullPtrType() && 12027 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12028 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12029 return computeResultTy(); 12030 } 12031 12032 if (IsRelational && 12033 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12034 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12035 // HACK: Relational comparison of nullptr_t against a pointer type is 12036 // invalid per DR583, but we allow it within std::less<> and friends, 12037 // since otherwise common uses of it break. 12038 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12039 // friends to have std::nullptr_t overload candidates. 12040 DeclContext *DC = CurContext; 12041 if (isa<FunctionDecl>(DC)) 12042 DC = DC->getParent(); 12043 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12044 if (CTSD->isInStdNamespace() && 12045 llvm::StringSwitch<bool>(CTSD->getName()) 12046 .Cases("less", "less_equal", "greater", "greater_equal", true) 12047 .Default(false)) { 12048 if (RHSType->isNullPtrType()) 12049 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12050 else 12051 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12052 return computeResultTy(); 12053 } 12054 } 12055 } 12056 12057 // C++ [expr.eq]p2: 12058 // If at least one operand is a pointer to member, [...] bring them to 12059 // their composite pointer type. 12060 if (!IsOrdered && 12061 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12062 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12063 return QualType(); 12064 else 12065 return computeResultTy(); 12066 } 12067 } 12068 12069 // Handle block pointer types. 12070 if (!IsOrdered && LHSType->isBlockPointerType() && 12071 RHSType->isBlockPointerType()) { 12072 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12073 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12074 12075 if (!LHSIsNull && !RHSIsNull && 12076 !Context.typesAreCompatible(lpointee, rpointee)) { 12077 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12078 << LHSType << RHSType << LHS.get()->getSourceRange() 12079 << RHS.get()->getSourceRange(); 12080 } 12081 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12082 return computeResultTy(); 12083 } 12084 12085 // Allow block pointers to be compared with null pointer constants. 12086 if (!IsOrdered 12087 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12088 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12089 if (!LHSIsNull && !RHSIsNull) { 12090 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12091 ->getPointeeType()->isVoidType()) 12092 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12093 ->getPointeeType()->isVoidType()))) 12094 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12095 << LHSType << RHSType << LHS.get()->getSourceRange() 12096 << RHS.get()->getSourceRange(); 12097 } 12098 if (LHSIsNull && !RHSIsNull) 12099 LHS = ImpCastExprToType(LHS.get(), RHSType, 12100 RHSType->isPointerType() ? CK_BitCast 12101 : CK_AnyPointerToBlockPointerCast); 12102 else 12103 RHS = ImpCastExprToType(RHS.get(), LHSType, 12104 LHSType->isPointerType() ? CK_BitCast 12105 : CK_AnyPointerToBlockPointerCast); 12106 return computeResultTy(); 12107 } 12108 12109 if (LHSType->isObjCObjectPointerType() || 12110 RHSType->isObjCObjectPointerType()) { 12111 const PointerType *LPT = LHSType->getAs<PointerType>(); 12112 const PointerType *RPT = RHSType->getAs<PointerType>(); 12113 if (LPT || RPT) { 12114 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12115 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12116 12117 if (!LPtrToVoid && !RPtrToVoid && 12118 !Context.typesAreCompatible(LHSType, RHSType)) { 12119 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12120 /*isError*/false); 12121 } 12122 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12123 // the RHS, but we have test coverage for this behavior. 12124 // FIXME: Consider using convertPointersToCompositeType in C++. 12125 if (LHSIsNull && !RHSIsNull) { 12126 Expr *E = LHS.get(); 12127 if (getLangOpts().ObjCAutoRefCount) 12128 CheckObjCConversion(SourceRange(), RHSType, E, 12129 CCK_ImplicitConversion); 12130 LHS = ImpCastExprToType(E, RHSType, 12131 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12132 } 12133 else { 12134 Expr *E = RHS.get(); 12135 if (getLangOpts().ObjCAutoRefCount) 12136 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12137 /*Diagnose=*/true, 12138 /*DiagnoseCFAudited=*/false, Opc); 12139 RHS = ImpCastExprToType(E, LHSType, 12140 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12141 } 12142 return computeResultTy(); 12143 } 12144 if (LHSType->isObjCObjectPointerType() && 12145 RHSType->isObjCObjectPointerType()) { 12146 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12147 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12148 /*isError*/false); 12149 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12150 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12151 12152 if (LHSIsNull && !RHSIsNull) 12153 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12154 else 12155 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12156 return computeResultTy(); 12157 } 12158 12159 if (!IsOrdered && LHSType->isBlockPointerType() && 12160 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12161 LHS = ImpCastExprToType(LHS.get(), RHSType, 12162 CK_BlockPointerToObjCPointerCast); 12163 return computeResultTy(); 12164 } else if (!IsOrdered && 12165 LHSType->isBlockCompatibleObjCPointerType(Context) && 12166 RHSType->isBlockPointerType()) { 12167 RHS = ImpCastExprToType(RHS.get(), LHSType, 12168 CK_BlockPointerToObjCPointerCast); 12169 return computeResultTy(); 12170 } 12171 } 12172 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12173 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12174 unsigned DiagID = 0; 12175 bool isError = false; 12176 if (LangOpts.DebuggerSupport) { 12177 // Under a debugger, allow the comparison of pointers to integers, 12178 // since users tend to want to compare addresses. 12179 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12180 (RHSIsNull && RHSType->isIntegerType())) { 12181 if (IsOrdered) { 12182 isError = getLangOpts().CPlusPlus; 12183 DiagID = 12184 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12185 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12186 } 12187 } else if (getLangOpts().CPlusPlus) { 12188 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12189 isError = true; 12190 } else if (IsOrdered) 12191 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12192 else 12193 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12194 12195 if (DiagID) { 12196 Diag(Loc, DiagID) 12197 << LHSType << RHSType << LHS.get()->getSourceRange() 12198 << RHS.get()->getSourceRange(); 12199 if (isError) 12200 return QualType(); 12201 } 12202 12203 if (LHSType->isIntegerType()) 12204 LHS = ImpCastExprToType(LHS.get(), RHSType, 12205 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12206 else 12207 RHS = ImpCastExprToType(RHS.get(), LHSType, 12208 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12209 return computeResultTy(); 12210 } 12211 12212 // Handle block pointers. 12213 if (!IsOrdered && RHSIsNull 12214 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12215 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12216 return computeResultTy(); 12217 } 12218 if (!IsOrdered && LHSIsNull 12219 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12220 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12221 return computeResultTy(); 12222 } 12223 12224 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12225 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12226 return computeResultTy(); 12227 } 12228 12229 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12230 return computeResultTy(); 12231 } 12232 12233 if (LHSIsNull && RHSType->isQueueT()) { 12234 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12235 return computeResultTy(); 12236 } 12237 12238 if (LHSType->isQueueT() && RHSIsNull) { 12239 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12240 return computeResultTy(); 12241 } 12242 } 12243 12244 return InvalidOperands(Loc, LHS, RHS); 12245 } 12246 12247 // Return a signed ext_vector_type that is of identical size and number of 12248 // elements. For floating point vectors, return an integer type of identical 12249 // size and number of elements. In the non ext_vector_type case, search from 12250 // the largest type to the smallest type to avoid cases where long long == long, 12251 // where long gets picked over long long. 12252 QualType Sema::GetSignedVectorType(QualType V) { 12253 const VectorType *VTy = V->castAs<VectorType>(); 12254 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12255 12256 if (isa<ExtVectorType>(VTy)) { 12257 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12258 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12259 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12260 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12261 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12262 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12263 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12264 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12265 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12266 "Unhandled vector element size in vector compare"); 12267 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12268 } 12269 12270 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12271 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12272 VectorType::GenericVector); 12273 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12274 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12275 VectorType::GenericVector); 12276 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12277 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12278 VectorType::GenericVector); 12279 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12280 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12281 VectorType::GenericVector); 12282 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12283 "Unhandled vector element size in vector compare"); 12284 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12285 VectorType::GenericVector); 12286 } 12287 12288 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12289 /// operates on extended vector types. Instead of producing an IntTy result, 12290 /// like a scalar comparison, a vector comparison produces a vector of integer 12291 /// types. 12292 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12293 SourceLocation Loc, 12294 BinaryOperatorKind Opc) { 12295 if (Opc == BO_Cmp) { 12296 Diag(Loc, diag::err_three_way_vector_comparison); 12297 return QualType(); 12298 } 12299 12300 // Check to make sure we're operating on vectors of the same type and width, 12301 // Allowing one side to be a scalar of element type. 12302 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12303 /*AllowBothBool*/true, 12304 /*AllowBoolConversions*/getLangOpts().ZVector); 12305 if (vType.isNull()) 12306 return vType; 12307 12308 QualType LHSType = LHS.get()->getType(); 12309 12310 // Determine the return type of a vector compare. By default clang will return 12311 // a scalar for all vector compares except vector bool and vector pixel. 12312 // With the gcc compiler we will always return a vector type and with the xl 12313 // compiler we will always return a scalar type. This switch allows choosing 12314 // which behavior is prefered. 12315 if (getLangOpts().AltiVec) { 12316 switch (getLangOpts().getAltivecSrcCompat()) { 12317 case LangOptions::AltivecSrcCompatKind::Mixed: 12318 // If AltiVec, the comparison results in a numeric type, i.e. 12319 // bool for C++, int for C 12320 if (vType->castAs<VectorType>()->getVectorKind() == 12321 VectorType::AltiVecVector) 12322 return Context.getLogicalOperationType(); 12323 else 12324 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12325 break; 12326 case LangOptions::AltivecSrcCompatKind::GCC: 12327 // For GCC we always return the vector type. 12328 break; 12329 case LangOptions::AltivecSrcCompatKind::XL: 12330 return Context.getLogicalOperationType(); 12331 break; 12332 } 12333 } 12334 12335 // For non-floating point types, check for self-comparisons of the form 12336 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12337 // often indicate logic errors in the program. 12338 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12339 12340 // Check for comparisons of floating point operands using != and ==. 12341 if (BinaryOperator::isEqualityOp(Opc) && 12342 LHSType->hasFloatingRepresentation()) { 12343 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12344 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12345 } 12346 12347 // Return a signed type for the vector. 12348 return GetSignedVectorType(vType); 12349 } 12350 12351 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12352 const ExprResult &XorRHS, 12353 const SourceLocation Loc) { 12354 // Do not diagnose macros. 12355 if (Loc.isMacroID()) 12356 return; 12357 12358 // Do not diagnose if both LHS and RHS are macros. 12359 if (XorLHS.get()->getExprLoc().isMacroID() && 12360 XorRHS.get()->getExprLoc().isMacroID()) 12361 return; 12362 12363 bool Negative = false; 12364 bool ExplicitPlus = false; 12365 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12366 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12367 12368 if (!LHSInt) 12369 return; 12370 if (!RHSInt) { 12371 // Check negative literals. 12372 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12373 UnaryOperatorKind Opc = UO->getOpcode(); 12374 if (Opc != UO_Minus && Opc != UO_Plus) 12375 return; 12376 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12377 if (!RHSInt) 12378 return; 12379 Negative = (Opc == UO_Minus); 12380 ExplicitPlus = !Negative; 12381 } else { 12382 return; 12383 } 12384 } 12385 12386 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12387 llvm::APInt RightSideValue = RHSInt->getValue(); 12388 if (LeftSideValue != 2 && LeftSideValue != 10) 12389 return; 12390 12391 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12392 return; 12393 12394 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12395 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12396 llvm::StringRef ExprStr = 12397 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12398 12399 CharSourceRange XorRange = 12400 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12401 llvm::StringRef XorStr = 12402 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12403 // Do not diagnose if xor keyword/macro is used. 12404 if (XorStr == "xor") 12405 return; 12406 12407 std::string LHSStr = std::string(Lexer::getSourceText( 12408 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12409 S.getSourceManager(), S.getLangOpts())); 12410 std::string RHSStr = std::string(Lexer::getSourceText( 12411 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12412 S.getSourceManager(), S.getLangOpts())); 12413 12414 if (Negative) { 12415 RightSideValue = -RightSideValue; 12416 RHSStr = "-" + RHSStr; 12417 } else if (ExplicitPlus) { 12418 RHSStr = "+" + RHSStr; 12419 } 12420 12421 StringRef LHSStrRef = LHSStr; 12422 StringRef RHSStrRef = RHSStr; 12423 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12424 // literals. 12425 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12426 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12427 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12428 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12429 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12430 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12431 LHSStrRef.find('\'') != StringRef::npos || 12432 RHSStrRef.find('\'') != StringRef::npos) 12433 return; 12434 12435 bool SuggestXor = 12436 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12437 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12438 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12439 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12440 std::string SuggestedExpr = "1 << " + RHSStr; 12441 bool Overflow = false; 12442 llvm::APInt One = (LeftSideValue - 1); 12443 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12444 if (Overflow) { 12445 if (RightSideIntValue < 64) 12446 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12447 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12448 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12449 else if (RightSideIntValue == 64) 12450 S.Diag(Loc, diag::warn_xor_used_as_pow) 12451 << ExprStr << toString(XorValue, 10, true); 12452 else 12453 return; 12454 } else { 12455 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12456 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12457 << toString(PowValue, 10, true) 12458 << FixItHint::CreateReplacement( 12459 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12460 } 12461 12462 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12463 << ("0x2 ^ " + RHSStr) << SuggestXor; 12464 } else if (LeftSideValue == 10) { 12465 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12466 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12467 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12468 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12469 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12470 << ("0xA ^ " + RHSStr) << SuggestXor; 12471 } 12472 } 12473 12474 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12475 SourceLocation Loc) { 12476 // Ensure that either both operands are of the same vector type, or 12477 // one operand is of a vector type and the other is of its element type. 12478 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12479 /*AllowBothBool*/true, 12480 /*AllowBoolConversions*/false); 12481 if (vType.isNull()) 12482 return InvalidOperands(Loc, LHS, RHS); 12483 if (getLangOpts().OpenCL && 12484 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12485 vType->hasFloatingRepresentation()) 12486 return InvalidOperands(Loc, LHS, RHS); 12487 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12488 // usage of the logical operators && and || with vectors in C. This 12489 // check could be notionally dropped. 12490 if (!getLangOpts().CPlusPlus && 12491 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12492 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12493 12494 return GetSignedVectorType(LHS.get()->getType()); 12495 } 12496 12497 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12498 SourceLocation Loc, 12499 bool IsCompAssign) { 12500 if (!IsCompAssign) { 12501 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12502 if (LHS.isInvalid()) 12503 return QualType(); 12504 } 12505 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12506 if (RHS.isInvalid()) 12507 return QualType(); 12508 12509 // For conversion purposes, we ignore any qualifiers. 12510 // For example, "const float" and "float" are equivalent. 12511 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12512 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12513 12514 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12515 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12516 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12517 12518 if (Context.hasSameType(LHSType, RHSType)) 12519 return LHSType; 12520 12521 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12522 // case we have to return InvalidOperands. 12523 ExprResult OriginalLHS = LHS; 12524 ExprResult OriginalRHS = RHS; 12525 if (LHSMatType && !RHSMatType) { 12526 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12527 if (!RHS.isInvalid()) 12528 return LHSType; 12529 12530 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12531 } 12532 12533 if (!LHSMatType && RHSMatType) { 12534 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12535 if (!LHS.isInvalid()) 12536 return RHSType; 12537 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12538 } 12539 12540 return InvalidOperands(Loc, LHS, RHS); 12541 } 12542 12543 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12544 SourceLocation Loc, 12545 bool IsCompAssign) { 12546 if (!IsCompAssign) { 12547 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12548 if (LHS.isInvalid()) 12549 return QualType(); 12550 } 12551 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12552 if (RHS.isInvalid()) 12553 return QualType(); 12554 12555 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12556 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12557 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12558 12559 if (LHSMatType && RHSMatType) { 12560 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12561 return InvalidOperands(Loc, LHS, RHS); 12562 12563 if (!Context.hasSameType(LHSMatType->getElementType(), 12564 RHSMatType->getElementType())) 12565 return InvalidOperands(Loc, LHS, RHS); 12566 12567 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12568 LHSMatType->getNumRows(), 12569 RHSMatType->getNumColumns()); 12570 } 12571 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12572 } 12573 12574 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12575 SourceLocation Loc, 12576 BinaryOperatorKind Opc) { 12577 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12578 12579 bool IsCompAssign = 12580 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12581 12582 if (LHS.get()->getType()->isVectorType() || 12583 RHS.get()->getType()->isVectorType()) { 12584 if (LHS.get()->getType()->hasIntegerRepresentation() && 12585 RHS.get()->getType()->hasIntegerRepresentation()) 12586 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12587 /*AllowBothBool*/true, 12588 /*AllowBoolConversions*/getLangOpts().ZVector); 12589 return InvalidOperands(Loc, LHS, RHS); 12590 } 12591 12592 if (Opc == BO_And) 12593 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12594 12595 if (LHS.get()->getType()->hasFloatingRepresentation() || 12596 RHS.get()->getType()->hasFloatingRepresentation()) 12597 return InvalidOperands(Loc, LHS, RHS); 12598 12599 ExprResult LHSResult = LHS, RHSResult = RHS; 12600 QualType compType = UsualArithmeticConversions( 12601 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12602 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12603 return QualType(); 12604 LHS = LHSResult.get(); 12605 RHS = RHSResult.get(); 12606 12607 if (Opc == BO_Xor) 12608 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12609 12610 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12611 return compType; 12612 return InvalidOperands(Loc, LHS, RHS); 12613 } 12614 12615 // C99 6.5.[13,14] 12616 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12617 SourceLocation Loc, 12618 BinaryOperatorKind Opc) { 12619 // Check vector operands differently. 12620 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12621 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12622 12623 bool EnumConstantInBoolContext = false; 12624 for (const ExprResult &HS : {LHS, RHS}) { 12625 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12626 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12627 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12628 EnumConstantInBoolContext = true; 12629 } 12630 } 12631 12632 if (EnumConstantInBoolContext) 12633 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12634 12635 // Diagnose cases where the user write a logical and/or but probably meant a 12636 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12637 // is a constant. 12638 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12639 !LHS.get()->getType()->isBooleanType() && 12640 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12641 // Don't warn in macros or template instantiations. 12642 !Loc.isMacroID() && !inTemplateInstantiation()) { 12643 // If the RHS can be constant folded, and if it constant folds to something 12644 // that isn't 0 or 1 (which indicate a potential logical operation that 12645 // happened to fold to true/false) then warn. 12646 // Parens on the RHS are ignored. 12647 Expr::EvalResult EVResult; 12648 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12649 llvm::APSInt Result = EVResult.Val.getInt(); 12650 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12651 !RHS.get()->getExprLoc().isMacroID()) || 12652 (Result != 0 && Result != 1)) { 12653 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12654 << RHS.get()->getSourceRange() 12655 << (Opc == BO_LAnd ? "&&" : "||"); 12656 // Suggest replacing the logical operator with the bitwise version 12657 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12658 << (Opc == BO_LAnd ? "&" : "|") 12659 << FixItHint::CreateReplacement(SourceRange( 12660 Loc, getLocForEndOfToken(Loc)), 12661 Opc == BO_LAnd ? "&" : "|"); 12662 if (Opc == BO_LAnd) 12663 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12664 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12665 << FixItHint::CreateRemoval( 12666 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12667 RHS.get()->getEndLoc())); 12668 } 12669 } 12670 } 12671 12672 if (!Context.getLangOpts().CPlusPlus) { 12673 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12674 // not operate on the built-in scalar and vector float types. 12675 if (Context.getLangOpts().OpenCL && 12676 Context.getLangOpts().OpenCLVersion < 120) { 12677 if (LHS.get()->getType()->isFloatingType() || 12678 RHS.get()->getType()->isFloatingType()) 12679 return InvalidOperands(Loc, LHS, RHS); 12680 } 12681 12682 LHS = UsualUnaryConversions(LHS.get()); 12683 if (LHS.isInvalid()) 12684 return QualType(); 12685 12686 RHS = UsualUnaryConversions(RHS.get()); 12687 if (RHS.isInvalid()) 12688 return QualType(); 12689 12690 if (!LHS.get()->getType()->isScalarType() || 12691 !RHS.get()->getType()->isScalarType()) 12692 return InvalidOperands(Loc, LHS, RHS); 12693 12694 return Context.IntTy; 12695 } 12696 12697 // The following is safe because we only use this method for 12698 // non-overloadable operands. 12699 12700 // C++ [expr.log.and]p1 12701 // C++ [expr.log.or]p1 12702 // The operands are both contextually converted to type bool. 12703 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12704 if (LHSRes.isInvalid()) 12705 return InvalidOperands(Loc, LHS, RHS); 12706 LHS = LHSRes; 12707 12708 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12709 if (RHSRes.isInvalid()) 12710 return InvalidOperands(Loc, LHS, RHS); 12711 RHS = RHSRes; 12712 12713 // C++ [expr.log.and]p2 12714 // C++ [expr.log.or]p2 12715 // The result is a bool. 12716 return Context.BoolTy; 12717 } 12718 12719 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12720 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12721 if (!ME) return false; 12722 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12723 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12724 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12725 if (!Base) return false; 12726 return Base->getMethodDecl() != nullptr; 12727 } 12728 12729 /// Is the given expression (which must be 'const') a reference to a 12730 /// variable which was originally non-const, but which has become 12731 /// 'const' due to being captured within a block? 12732 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12733 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12734 assert(E->isLValue() && E->getType().isConstQualified()); 12735 E = E->IgnoreParens(); 12736 12737 // Must be a reference to a declaration from an enclosing scope. 12738 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12739 if (!DRE) return NCCK_None; 12740 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12741 12742 // The declaration must be a variable which is not declared 'const'. 12743 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12744 if (!var) return NCCK_None; 12745 if (var->getType().isConstQualified()) return NCCK_None; 12746 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12747 12748 // Decide whether the first capture was for a block or a lambda. 12749 DeclContext *DC = S.CurContext, *Prev = nullptr; 12750 // Decide whether the first capture was for a block or a lambda. 12751 while (DC) { 12752 // For init-capture, it is possible that the variable belongs to the 12753 // template pattern of the current context. 12754 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12755 if (var->isInitCapture() && 12756 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12757 break; 12758 if (DC == var->getDeclContext()) 12759 break; 12760 Prev = DC; 12761 DC = DC->getParent(); 12762 } 12763 // Unless we have an init-capture, we've gone one step too far. 12764 if (!var->isInitCapture()) 12765 DC = Prev; 12766 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12767 } 12768 12769 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12770 Ty = Ty.getNonReferenceType(); 12771 if (IsDereference && Ty->isPointerType()) 12772 Ty = Ty->getPointeeType(); 12773 return !Ty.isConstQualified(); 12774 } 12775 12776 // Update err_typecheck_assign_const and note_typecheck_assign_const 12777 // when this enum is changed. 12778 enum { 12779 ConstFunction, 12780 ConstVariable, 12781 ConstMember, 12782 ConstMethod, 12783 NestedConstMember, 12784 ConstUnknown, // Keep as last element 12785 }; 12786 12787 /// Emit the "read-only variable not assignable" error and print notes to give 12788 /// more information about why the variable is not assignable, such as pointing 12789 /// to the declaration of a const variable, showing that a method is const, or 12790 /// that the function is returning a const reference. 12791 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12792 SourceLocation Loc) { 12793 SourceRange ExprRange = E->getSourceRange(); 12794 12795 // Only emit one error on the first const found. All other consts will emit 12796 // a note to the error. 12797 bool DiagnosticEmitted = false; 12798 12799 // Track if the current expression is the result of a dereference, and if the 12800 // next checked expression is the result of a dereference. 12801 bool IsDereference = false; 12802 bool NextIsDereference = false; 12803 12804 // Loop to process MemberExpr chains. 12805 while (true) { 12806 IsDereference = NextIsDereference; 12807 12808 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12810 NextIsDereference = ME->isArrow(); 12811 const ValueDecl *VD = ME->getMemberDecl(); 12812 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12813 // Mutable fields can be modified even if the class is const. 12814 if (Field->isMutable()) { 12815 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12816 break; 12817 } 12818 12819 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12820 if (!DiagnosticEmitted) { 12821 S.Diag(Loc, diag::err_typecheck_assign_const) 12822 << ExprRange << ConstMember << false /*static*/ << Field 12823 << Field->getType(); 12824 DiagnosticEmitted = true; 12825 } 12826 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12827 << ConstMember << false /*static*/ << Field << Field->getType() 12828 << Field->getSourceRange(); 12829 } 12830 E = ME->getBase(); 12831 continue; 12832 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12833 if (VDecl->getType().isConstQualified()) { 12834 if (!DiagnosticEmitted) { 12835 S.Diag(Loc, diag::err_typecheck_assign_const) 12836 << ExprRange << ConstMember << true /*static*/ << VDecl 12837 << VDecl->getType(); 12838 DiagnosticEmitted = true; 12839 } 12840 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12841 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12842 << VDecl->getSourceRange(); 12843 } 12844 // Static fields do not inherit constness from parents. 12845 break; 12846 } 12847 break; // End MemberExpr 12848 } else if (const ArraySubscriptExpr *ASE = 12849 dyn_cast<ArraySubscriptExpr>(E)) { 12850 E = ASE->getBase()->IgnoreParenImpCasts(); 12851 continue; 12852 } else if (const ExtVectorElementExpr *EVE = 12853 dyn_cast<ExtVectorElementExpr>(E)) { 12854 E = EVE->getBase()->IgnoreParenImpCasts(); 12855 continue; 12856 } 12857 break; 12858 } 12859 12860 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12861 // Function calls 12862 const FunctionDecl *FD = CE->getDirectCallee(); 12863 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12864 if (!DiagnosticEmitted) { 12865 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12866 << ConstFunction << FD; 12867 DiagnosticEmitted = true; 12868 } 12869 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12870 diag::note_typecheck_assign_const) 12871 << ConstFunction << FD << FD->getReturnType() 12872 << FD->getReturnTypeSourceRange(); 12873 } 12874 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12875 // Point to variable declaration. 12876 if (const ValueDecl *VD = DRE->getDecl()) { 12877 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12878 if (!DiagnosticEmitted) { 12879 S.Diag(Loc, diag::err_typecheck_assign_const) 12880 << ExprRange << ConstVariable << VD << VD->getType(); 12881 DiagnosticEmitted = true; 12882 } 12883 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12884 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12885 } 12886 } 12887 } else if (isa<CXXThisExpr>(E)) { 12888 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12889 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12890 if (MD->isConst()) { 12891 if (!DiagnosticEmitted) { 12892 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12893 << ConstMethod << MD; 12894 DiagnosticEmitted = true; 12895 } 12896 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12897 << ConstMethod << MD << MD->getSourceRange(); 12898 } 12899 } 12900 } 12901 } 12902 12903 if (DiagnosticEmitted) 12904 return; 12905 12906 // Can't determine a more specific message, so display the generic error. 12907 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12908 } 12909 12910 enum OriginalExprKind { 12911 OEK_Variable, 12912 OEK_Member, 12913 OEK_LValue 12914 }; 12915 12916 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12917 const RecordType *Ty, 12918 SourceLocation Loc, SourceRange Range, 12919 OriginalExprKind OEK, 12920 bool &DiagnosticEmitted) { 12921 std::vector<const RecordType *> RecordTypeList; 12922 RecordTypeList.push_back(Ty); 12923 unsigned NextToCheckIndex = 0; 12924 // We walk the record hierarchy breadth-first to ensure that we print 12925 // diagnostics in field nesting order. 12926 while (RecordTypeList.size() > NextToCheckIndex) { 12927 bool IsNested = NextToCheckIndex > 0; 12928 for (const FieldDecl *Field : 12929 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12930 // First, check every field for constness. 12931 QualType FieldTy = Field->getType(); 12932 if (FieldTy.isConstQualified()) { 12933 if (!DiagnosticEmitted) { 12934 S.Diag(Loc, diag::err_typecheck_assign_const) 12935 << Range << NestedConstMember << OEK << VD 12936 << IsNested << Field; 12937 DiagnosticEmitted = true; 12938 } 12939 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12940 << NestedConstMember << IsNested << Field 12941 << FieldTy << Field->getSourceRange(); 12942 } 12943 12944 // Then we append it to the list to check next in order. 12945 FieldTy = FieldTy.getCanonicalType(); 12946 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12947 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12948 RecordTypeList.push_back(FieldRecTy); 12949 } 12950 } 12951 ++NextToCheckIndex; 12952 } 12953 } 12954 12955 /// Emit an error for the case where a record we are trying to assign to has a 12956 /// const-qualified field somewhere in its hierarchy. 12957 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12958 SourceLocation Loc) { 12959 QualType Ty = E->getType(); 12960 assert(Ty->isRecordType() && "lvalue was not record?"); 12961 SourceRange Range = E->getSourceRange(); 12962 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12963 bool DiagEmitted = false; 12964 12965 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12966 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12967 Range, OEK_Member, DiagEmitted); 12968 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12969 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12970 Range, OEK_Variable, DiagEmitted); 12971 else 12972 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12973 Range, OEK_LValue, DiagEmitted); 12974 if (!DiagEmitted) 12975 DiagnoseConstAssignment(S, E, Loc); 12976 } 12977 12978 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12979 /// emit an error and return true. If so, return false. 12980 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12981 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12982 12983 S.CheckShadowingDeclModification(E, Loc); 12984 12985 SourceLocation OrigLoc = Loc; 12986 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12987 &Loc); 12988 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12989 IsLV = Expr::MLV_InvalidMessageExpression; 12990 if (IsLV == Expr::MLV_Valid) 12991 return false; 12992 12993 unsigned DiagID = 0; 12994 bool NeedType = false; 12995 switch (IsLV) { // C99 6.5.16p2 12996 case Expr::MLV_ConstQualified: 12997 // Use a specialized diagnostic when we're assigning to an object 12998 // from an enclosing function or block. 12999 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13000 if (NCCK == NCCK_Block) 13001 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13002 else 13003 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13004 break; 13005 } 13006 13007 // In ARC, use some specialized diagnostics for occasions where we 13008 // infer 'const'. These are always pseudo-strong variables. 13009 if (S.getLangOpts().ObjCAutoRefCount) { 13010 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13011 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13012 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13013 13014 // Use the normal diagnostic if it's pseudo-__strong but the 13015 // user actually wrote 'const'. 13016 if (var->isARCPseudoStrong() && 13017 (!var->getTypeSourceInfo() || 13018 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13019 // There are three pseudo-strong cases: 13020 // - self 13021 ObjCMethodDecl *method = S.getCurMethodDecl(); 13022 if (method && var == method->getSelfDecl()) { 13023 DiagID = method->isClassMethod() 13024 ? diag::err_typecheck_arc_assign_self_class_method 13025 : diag::err_typecheck_arc_assign_self; 13026 13027 // - Objective-C externally_retained attribute. 13028 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13029 isa<ParmVarDecl>(var)) { 13030 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13031 13032 // - fast enumeration variables 13033 } else { 13034 DiagID = diag::err_typecheck_arr_assign_enumeration; 13035 } 13036 13037 SourceRange Assign; 13038 if (Loc != OrigLoc) 13039 Assign = SourceRange(OrigLoc, OrigLoc); 13040 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13041 // We need to preserve the AST regardless, so migration tool 13042 // can do its job. 13043 return false; 13044 } 13045 } 13046 } 13047 13048 // If none of the special cases above are triggered, then this is a 13049 // simple const assignment. 13050 if (DiagID == 0) { 13051 DiagnoseConstAssignment(S, E, Loc); 13052 return true; 13053 } 13054 13055 break; 13056 case Expr::MLV_ConstAddrSpace: 13057 DiagnoseConstAssignment(S, E, Loc); 13058 return true; 13059 case Expr::MLV_ConstQualifiedField: 13060 DiagnoseRecursiveConstFields(S, E, Loc); 13061 return true; 13062 case Expr::MLV_ArrayType: 13063 case Expr::MLV_ArrayTemporary: 13064 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13065 NeedType = true; 13066 break; 13067 case Expr::MLV_NotObjectType: 13068 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13069 NeedType = true; 13070 break; 13071 case Expr::MLV_LValueCast: 13072 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13073 break; 13074 case Expr::MLV_Valid: 13075 llvm_unreachable("did not take early return for MLV_Valid"); 13076 case Expr::MLV_InvalidExpression: 13077 case Expr::MLV_MemberFunction: 13078 case Expr::MLV_ClassTemporary: 13079 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13080 break; 13081 case Expr::MLV_IncompleteType: 13082 case Expr::MLV_IncompleteVoidType: 13083 return S.RequireCompleteType(Loc, E->getType(), 13084 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13085 case Expr::MLV_DuplicateVectorComponents: 13086 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13087 break; 13088 case Expr::MLV_NoSetterProperty: 13089 llvm_unreachable("readonly properties should be processed differently"); 13090 case Expr::MLV_InvalidMessageExpression: 13091 DiagID = diag::err_readonly_message_assignment; 13092 break; 13093 case Expr::MLV_SubObjCPropertySetting: 13094 DiagID = diag::err_no_subobject_property_setting; 13095 break; 13096 } 13097 13098 SourceRange Assign; 13099 if (Loc != OrigLoc) 13100 Assign = SourceRange(OrigLoc, OrigLoc); 13101 if (NeedType) 13102 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13103 else 13104 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13105 return true; 13106 } 13107 13108 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13109 SourceLocation Loc, 13110 Sema &Sema) { 13111 if (Sema.inTemplateInstantiation()) 13112 return; 13113 if (Sema.isUnevaluatedContext()) 13114 return; 13115 if (Loc.isInvalid() || Loc.isMacroID()) 13116 return; 13117 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13118 return; 13119 13120 // C / C++ fields 13121 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13122 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13123 if (ML && MR) { 13124 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13125 return; 13126 const ValueDecl *LHSDecl = 13127 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13128 const ValueDecl *RHSDecl = 13129 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13130 if (LHSDecl != RHSDecl) 13131 return; 13132 if (LHSDecl->getType().isVolatileQualified()) 13133 return; 13134 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13135 if (RefTy->getPointeeType().isVolatileQualified()) 13136 return; 13137 13138 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13139 } 13140 13141 // Objective-C instance variables 13142 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13143 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13144 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13145 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13146 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13147 if (RL && RR && RL->getDecl() == RR->getDecl()) 13148 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13149 } 13150 } 13151 13152 // C99 6.5.16.1 13153 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13154 SourceLocation Loc, 13155 QualType CompoundType) { 13156 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13157 13158 // Verify that LHS is a modifiable lvalue, and emit error if not. 13159 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13160 return QualType(); 13161 13162 QualType LHSType = LHSExpr->getType(); 13163 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13164 CompoundType; 13165 // OpenCL v1.2 s6.1.1.1 p2: 13166 // The half data type can only be used to declare a pointer to a buffer that 13167 // contains half values 13168 if (getLangOpts().OpenCL && 13169 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13170 LHSType->isHalfType()) { 13171 Diag(Loc, diag::err_opencl_half_load_store) << 1 13172 << LHSType.getUnqualifiedType(); 13173 return QualType(); 13174 } 13175 13176 AssignConvertType ConvTy; 13177 if (CompoundType.isNull()) { 13178 Expr *RHSCheck = RHS.get(); 13179 13180 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13181 13182 QualType LHSTy(LHSType); 13183 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13184 if (RHS.isInvalid()) 13185 return QualType(); 13186 // Special case of NSObject attributes on c-style pointer types. 13187 if (ConvTy == IncompatiblePointer && 13188 ((Context.isObjCNSObjectType(LHSType) && 13189 RHSType->isObjCObjectPointerType()) || 13190 (Context.isObjCNSObjectType(RHSType) && 13191 LHSType->isObjCObjectPointerType()))) 13192 ConvTy = Compatible; 13193 13194 if (ConvTy == Compatible && 13195 LHSType->isObjCObjectType()) 13196 Diag(Loc, diag::err_objc_object_assignment) 13197 << LHSType; 13198 13199 // If the RHS is a unary plus or minus, check to see if they = and + are 13200 // right next to each other. If so, the user may have typo'd "x =+ 4" 13201 // instead of "x += 4". 13202 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13203 RHSCheck = ICE->getSubExpr(); 13204 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13205 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13206 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13207 // Only if the two operators are exactly adjacent. 13208 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13209 // And there is a space or other character before the subexpr of the 13210 // unary +/-. We don't want to warn on "x=-1". 13211 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13212 UO->getSubExpr()->getBeginLoc().isFileID()) { 13213 Diag(Loc, diag::warn_not_compound_assign) 13214 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13215 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13216 } 13217 } 13218 13219 if (ConvTy == Compatible) { 13220 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13221 // Warn about retain cycles where a block captures the LHS, but 13222 // not if the LHS is a simple variable into which the block is 13223 // being stored...unless that variable can be captured by reference! 13224 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13225 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13226 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13227 checkRetainCycles(LHSExpr, RHS.get()); 13228 } 13229 13230 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13231 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13232 // It is safe to assign a weak reference into a strong variable. 13233 // Although this code can still have problems: 13234 // id x = self.weakProp; 13235 // id y = self.weakProp; 13236 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13237 // paths through the function. This should be revisited if 13238 // -Wrepeated-use-of-weak is made flow-sensitive. 13239 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13240 // variable, which will be valid for the current autorelease scope. 13241 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13242 RHS.get()->getBeginLoc())) 13243 getCurFunction()->markSafeWeakUse(RHS.get()); 13244 13245 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13246 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13247 } 13248 } 13249 } else { 13250 // Compound assignment "x += y" 13251 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13252 } 13253 13254 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13255 RHS.get(), AA_Assigning)) 13256 return QualType(); 13257 13258 CheckForNullPointerDereference(*this, LHSExpr); 13259 13260 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13261 if (CompoundType.isNull()) { 13262 // C++2a [expr.ass]p5: 13263 // A simple-assignment whose left operand is of a volatile-qualified 13264 // type is deprecated unless the assignment is either a discarded-value 13265 // expression or an unevaluated operand 13266 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13267 } else { 13268 // C++2a [expr.ass]p6: 13269 // [Compound-assignment] expressions are deprecated if E1 has 13270 // volatile-qualified type 13271 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13272 } 13273 } 13274 13275 // C99 6.5.16p3: The type of an assignment expression is the type of the 13276 // left operand unless the left operand has qualified type, in which case 13277 // it is the unqualified version of the type of the left operand. 13278 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13279 // is converted to the type of the assignment expression (above). 13280 // C++ 5.17p1: the type of the assignment expression is that of its left 13281 // operand. 13282 return (getLangOpts().CPlusPlus 13283 ? LHSType : LHSType.getUnqualifiedType()); 13284 } 13285 13286 // Only ignore explicit casts to void. 13287 static bool IgnoreCommaOperand(const Expr *E) { 13288 E = E->IgnoreParens(); 13289 13290 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13291 if (CE->getCastKind() == CK_ToVoid) { 13292 return true; 13293 } 13294 13295 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13296 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13297 CE->getSubExpr()->getType()->isDependentType()) { 13298 return true; 13299 } 13300 } 13301 13302 return false; 13303 } 13304 13305 // Look for instances where it is likely the comma operator is confused with 13306 // another operator. There is an explicit list of acceptable expressions for 13307 // the left hand side of the comma operator, otherwise emit a warning. 13308 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13309 // No warnings in macros 13310 if (Loc.isMacroID()) 13311 return; 13312 13313 // Don't warn in template instantiations. 13314 if (inTemplateInstantiation()) 13315 return; 13316 13317 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13318 // instead, skip more than needed, then call back into here with the 13319 // CommaVisitor in SemaStmt.cpp. 13320 // The listed locations are the initialization and increment portions 13321 // of a for loop. The additional checks are on the condition of 13322 // if statements, do/while loops, and for loops. 13323 // Differences in scope flags for C89 mode requires the extra logic. 13324 const unsigned ForIncrementFlags = 13325 getLangOpts().C99 || getLangOpts().CPlusPlus 13326 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13327 : Scope::ContinueScope | Scope::BreakScope; 13328 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13329 const unsigned ScopeFlags = getCurScope()->getFlags(); 13330 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13331 (ScopeFlags & ForInitFlags) == ForInitFlags) 13332 return; 13333 13334 // If there are multiple comma operators used together, get the RHS of the 13335 // of the comma operator as the LHS. 13336 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13337 if (BO->getOpcode() != BO_Comma) 13338 break; 13339 LHS = BO->getRHS(); 13340 } 13341 13342 // Only allow some expressions on LHS to not warn. 13343 if (IgnoreCommaOperand(LHS)) 13344 return; 13345 13346 Diag(Loc, diag::warn_comma_operator); 13347 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13348 << LHS->getSourceRange() 13349 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13350 LangOpts.CPlusPlus ? "static_cast<void>(" 13351 : "(void)(") 13352 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13353 ")"); 13354 } 13355 13356 // C99 6.5.17 13357 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13358 SourceLocation Loc) { 13359 LHS = S.CheckPlaceholderExpr(LHS.get()); 13360 RHS = S.CheckPlaceholderExpr(RHS.get()); 13361 if (LHS.isInvalid() || RHS.isInvalid()) 13362 return QualType(); 13363 13364 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13365 // operands, but not unary promotions. 13366 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13367 13368 // So we treat the LHS as a ignored value, and in C++ we allow the 13369 // containing site to determine what should be done with the RHS. 13370 LHS = S.IgnoredValueConversions(LHS.get()); 13371 if (LHS.isInvalid()) 13372 return QualType(); 13373 13374 S.DiagnoseUnusedExprResult(LHS.get()); 13375 13376 if (!S.getLangOpts().CPlusPlus) { 13377 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13378 if (RHS.isInvalid()) 13379 return QualType(); 13380 if (!RHS.get()->getType()->isVoidType()) 13381 S.RequireCompleteType(Loc, RHS.get()->getType(), 13382 diag::err_incomplete_type); 13383 } 13384 13385 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13386 S.DiagnoseCommaOperator(LHS.get(), Loc); 13387 13388 return RHS.get()->getType(); 13389 } 13390 13391 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13392 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13393 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13394 ExprValueKind &VK, 13395 ExprObjectKind &OK, 13396 SourceLocation OpLoc, 13397 bool IsInc, bool IsPrefix) { 13398 if (Op->isTypeDependent()) 13399 return S.Context.DependentTy; 13400 13401 QualType ResType = Op->getType(); 13402 // Atomic types can be used for increment / decrement where the non-atomic 13403 // versions can, so ignore the _Atomic() specifier for the purpose of 13404 // checking. 13405 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13406 ResType = ResAtomicType->getValueType(); 13407 13408 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13409 13410 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13411 // Decrement of bool is not allowed. 13412 if (!IsInc) { 13413 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13414 return QualType(); 13415 } 13416 // Increment of bool sets it to true, but is deprecated. 13417 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13418 : diag::warn_increment_bool) 13419 << Op->getSourceRange(); 13420 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13421 // Error on enum increments and decrements in C++ mode 13422 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13423 return QualType(); 13424 } else if (ResType->isRealType()) { 13425 // OK! 13426 } else if (ResType->isPointerType()) { 13427 // C99 6.5.2.4p2, 6.5.6p2 13428 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13429 return QualType(); 13430 } else if (ResType->isObjCObjectPointerType()) { 13431 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13432 // Otherwise, we just need a complete type. 13433 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13434 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13435 return QualType(); 13436 } else if (ResType->isAnyComplexType()) { 13437 // C99 does not support ++/-- on complex types, we allow as an extension. 13438 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13439 << ResType << Op->getSourceRange(); 13440 } else if (ResType->isPlaceholderType()) { 13441 ExprResult PR = S.CheckPlaceholderExpr(Op); 13442 if (PR.isInvalid()) return QualType(); 13443 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13444 IsInc, IsPrefix); 13445 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13446 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13447 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13448 (ResType->castAs<VectorType>()->getVectorKind() != 13449 VectorType::AltiVecBool)) { 13450 // The z vector extensions allow ++ and -- for non-bool vectors. 13451 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13452 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13453 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13454 } else { 13455 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13456 << ResType << int(IsInc) << Op->getSourceRange(); 13457 return QualType(); 13458 } 13459 // At this point, we know we have a real, complex or pointer type. 13460 // Now make sure the operand is a modifiable lvalue. 13461 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13462 return QualType(); 13463 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13464 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13465 // An operand with volatile-qualified type is deprecated 13466 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13467 << IsInc << ResType; 13468 } 13469 // In C++, a prefix increment is the same type as the operand. Otherwise 13470 // (in C or with postfix), the increment is the unqualified type of the 13471 // operand. 13472 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13473 VK = VK_LValue; 13474 OK = Op->getObjectKind(); 13475 return ResType; 13476 } else { 13477 VK = VK_PRValue; 13478 return ResType.getUnqualifiedType(); 13479 } 13480 } 13481 13482 13483 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13484 /// This routine allows us to typecheck complex/recursive expressions 13485 /// where the declaration is needed for type checking. We only need to 13486 /// handle cases when the expression references a function designator 13487 /// or is an lvalue. Here are some examples: 13488 /// - &(x) => x 13489 /// - &*****f => f for f a function designator. 13490 /// - &s.xx => s 13491 /// - &s.zz[1].yy -> s, if zz is an array 13492 /// - *(x + 1) -> x, if x is an array 13493 /// - &"123"[2] -> 0 13494 /// - & __real__ x -> x 13495 /// 13496 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13497 /// members. 13498 static ValueDecl *getPrimaryDecl(Expr *E) { 13499 switch (E->getStmtClass()) { 13500 case Stmt::DeclRefExprClass: 13501 return cast<DeclRefExpr>(E)->getDecl(); 13502 case Stmt::MemberExprClass: 13503 // If this is an arrow operator, the address is an offset from 13504 // the base's value, so the object the base refers to is 13505 // irrelevant. 13506 if (cast<MemberExpr>(E)->isArrow()) 13507 return nullptr; 13508 // Otherwise, the expression refers to a part of the base 13509 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13510 case Stmt::ArraySubscriptExprClass: { 13511 // FIXME: This code shouldn't be necessary! We should catch the implicit 13512 // promotion of register arrays earlier. 13513 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13514 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13515 if (ICE->getSubExpr()->getType()->isArrayType()) 13516 return getPrimaryDecl(ICE->getSubExpr()); 13517 } 13518 return nullptr; 13519 } 13520 case Stmt::UnaryOperatorClass: { 13521 UnaryOperator *UO = cast<UnaryOperator>(E); 13522 13523 switch(UO->getOpcode()) { 13524 case UO_Real: 13525 case UO_Imag: 13526 case UO_Extension: 13527 return getPrimaryDecl(UO->getSubExpr()); 13528 default: 13529 return nullptr; 13530 } 13531 } 13532 case Stmt::ParenExprClass: 13533 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13534 case Stmt::ImplicitCastExprClass: 13535 // If the result of an implicit cast is an l-value, we care about 13536 // the sub-expression; otherwise, the result here doesn't matter. 13537 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13538 case Stmt::CXXUuidofExprClass: 13539 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13540 default: 13541 return nullptr; 13542 } 13543 } 13544 13545 namespace { 13546 enum { 13547 AO_Bit_Field = 0, 13548 AO_Vector_Element = 1, 13549 AO_Property_Expansion = 2, 13550 AO_Register_Variable = 3, 13551 AO_Matrix_Element = 4, 13552 AO_No_Error = 5 13553 }; 13554 } 13555 /// Diagnose invalid operand for address of operations. 13556 /// 13557 /// \param Type The type of operand which cannot have its address taken. 13558 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13559 Expr *E, unsigned Type) { 13560 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13561 } 13562 13563 /// CheckAddressOfOperand - The operand of & must be either a function 13564 /// designator or an lvalue designating an object. If it is an lvalue, the 13565 /// object cannot be declared with storage class register or be a bit field. 13566 /// Note: The usual conversions are *not* applied to the operand of the & 13567 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13568 /// In C++, the operand might be an overloaded function name, in which case 13569 /// we allow the '&' but retain the overloaded-function type. 13570 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13571 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13572 if (PTy->getKind() == BuiltinType::Overload) { 13573 Expr *E = OrigOp.get()->IgnoreParens(); 13574 if (!isa<OverloadExpr>(E)) { 13575 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13576 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13577 << OrigOp.get()->getSourceRange(); 13578 return QualType(); 13579 } 13580 13581 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13582 if (isa<UnresolvedMemberExpr>(Ovl)) 13583 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13584 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13585 << OrigOp.get()->getSourceRange(); 13586 return QualType(); 13587 } 13588 13589 return Context.OverloadTy; 13590 } 13591 13592 if (PTy->getKind() == BuiltinType::UnknownAny) 13593 return Context.UnknownAnyTy; 13594 13595 if (PTy->getKind() == BuiltinType::BoundMember) { 13596 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13597 << OrigOp.get()->getSourceRange(); 13598 return QualType(); 13599 } 13600 13601 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13602 if (OrigOp.isInvalid()) return QualType(); 13603 } 13604 13605 if (OrigOp.get()->isTypeDependent()) 13606 return Context.DependentTy; 13607 13608 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13609 13610 // Make sure to ignore parentheses in subsequent checks 13611 Expr *op = OrigOp.get()->IgnoreParens(); 13612 13613 // In OpenCL captures for blocks called as lambda functions 13614 // are located in the private address space. Blocks used in 13615 // enqueue_kernel can be located in a different address space 13616 // depending on a vendor implementation. Thus preventing 13617 // taking an address of the capture to avoid invalid AS casts. 13618 if (LangOpts.OpenCL) { 13619 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13620 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13621 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13622 return QualType(); 13623 } 13624 } 13625 13626 if (getLangOpts().C99) { 13627 // Implement C99-only parts of addressof rules. 13628 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13629 if (uOp->getOpcode() == UO_Deref) 13630 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13631 // (assuming the deref expression is valid). 13632 return uOp->getSubExpr()->getType(); 13633 } 13634 // Technically, there should be a check for array subscript 13635 // expressions here, but the result of one is always an lvalue anyway. 13636 } 13637 ValueDecl *dcl = getPrimaryDecl(op); 13638 13639 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13640 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13641 op->getBeginLoc())) 13642 return QualType(); 13643 13644 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13645 unsigned AddressOfError = AO_No_Error; 13646 13647 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13648 bool sfinae = (bool)isSFINAEContext(); 13649 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13650 : diag::ext_typecheck_addrof_temporary) 13651 << op->getType() << op->getSourceRange(); 13652 if (sfinae) 13653 return QualType(); 13654 // Materialize the temporary as an lvalue so that we can take its address. 13655 OrigOp = op = 13656 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13657 } else if (isa<ObjCSelectorExpr>(op)) { 13658 return Context.getPointerType(op->getType()); 13659 } else if (lval == Expr::LV_MemberFunction) { 13660 // If it's an instance method, make a member pointer. 13661 // The expression must have exactly the form &A::foo. 13662 13663 // If the underlying expression isn't a decl ref, give up. 13664 if (!isa<DeclRefExpr>(op)) { 13665 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13666 << OrigOp.get()->getSourceRange(); 13667 return QualType(); 13668 } 13669 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13670 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13671 13672 // The id-expression was parenthesized. 13673 if (OrigOp.get() != DRE) { 13674 Diag(OpLoc, diag::err_parens_pointer_member_function) 13675 << OrigOp.get()->getSourceRange(); 13676 13677 // The method was named without a qualifier. 13678 } else if (!DRE->getQualifier()) { 13679 if (MD->getParent()->getName().empty()) 13680 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13681 << op->getSourceRange(); 13682 else { 13683 SmallString<32> Str; 13684 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13685 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13686 << op->getSourceRange() 13687 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13688 } 13689 } 13690 13691 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13692 if (isa<CXXDestructorDecl>(MD)) 13693 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13694 13695 QualType MPTy = Context.getMemberPointerType( 13696 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13697 // Under the MS ABI, lock down the inheritance model now. 13698 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13699 (void)isCompleteType(OpLoc, MPTy); 13700 return MPTy; 13701 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13702 // C99 6.5.3.2p1 13703 // The operand must be either an l-value or a function designator 13704 if (!op->getType()->isFunctionType()) { 13705 // Use a special diagnostic for loads from property references. 13706 if (isa<PseudoObjectExpr>(op)) { 13707 AddressOfError = AO_Property_Expansion; 13708 } else { 13709 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13710 << op->getType() << op->getSourceRange(); 13711 return QualType(); 13712 } 13713 } 13714 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13715 // The operand cannot be a bit-field 13716 AddressOfError = AO_Bit_Field; 13717 } else if (op->getObjectKind() == OK_VectorComponent) { 13718 // The operand cannot be an element of a vector 13719 AddressOfError = AO_Vector_Element; 13720 } else if (op->getObjectKind() == OK_MatrixComponent) { 13721 // The operand cannot be an element of a matrix. 13722 AddressOfError = AO_Matrix_Element; 13723 } else if (dcl) { // C99 6.5.3.2p1 13724 // We have an lvalue with a decl. Make sure the decl is not declared 13725 // with the register storage-class specifier. 13726 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13727 // in C++ it is not error to take address of a register 13728 // variable (c++03 7.1.1P3) 13729 if (vd->getStorageClass() == SC_Register && 13730 !getLangOpts().CPlusPlus) { 13731 AddressOfError = AO_Register_Variable; 13732 } 13733 } else if (isa<MSPropertyDecl>(dcl)) { 13734 AddressOfError = AO_Property_Expansion; 13735 } else if (isa<FunctionTemplateDecl>(dcl)) { 13736 return Context.OverloadTy; 13737 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13738 // Okay: we can take the address of a field. 13739 // Could be a pointer to member, though, if there is an explicit 13740 // scope qualifier for the class. 13741 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13742 DeclContext *Ctx = dcl->getDeclContext(); 13743 if (Ctx && Ctx->isRecord()) { 13744 if (dcl->getType()->isReferenceType()) { 13745 Diag(OpLoc, 13746 diag::err_cannot_form_pointer_to_member_of_reference_type) 13747 << dcl->getDeclName() << dcl->getType(); 13748 return QualType(); 13749 } 13750 13751 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13752 Ctx = Ctx->getParent(); 13753 13754 QualType MPTy = Context.getMemberPointerType( 13755 op->getType(), 13756 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13757 // Under the MS ABI, lock down the inheritance model now. 13758 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13759 (void)isCompleteType(OpLoc, MPTy); 13760 return MPTy; 13761 } 13762 } 13763 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13764 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13765 llvm_unreachable("Unknown/unexpected decl type"); 13766 } 13767 13768 if (AddressOfError != AO_No_Error) { 13769 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13770 return QualType(); 13771 } 13772 13773 if (lval == Expr::LV_IncompleteVoidType) { 13774 // Taking the address of a void variable is technically illegal, but we 13775 // allow it in cases which are otherwise valid. 13776 // Example: "extern void x; void* y = &x;". 13777 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13778 } 13779 13780 // If the operand has type "type", the result has type "pointer to type". 13781 if (op->getType()->isObjCObjectType()) 13782 return Context.getObjCObjectPointerType(op->getType()); 13783 13784 CheckAddressOfPackedMember(op); 13785 13786 return Context.getPointerType(op->getType()); 13787 } 13788 13789 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13790 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13791 if (!DRE) 13792 return; 13793 const Decl *D = DRE->getDecl(); 13794 if (!D) 13795 return; 13796 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13797 if (!Param) 13798 return; 13799 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13800 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13801 return; 13802 if (FunctionScopeInfo *FD = S.getCurFunction()) 13803 if (!FD->ModifiedNonNullParams.count(Param)) 13804 FD->ModifiedNonNullParams.insert(Param); 13805 } 13806 13807 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13808 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13809 SourceLocation OpLoc) { 13810 if (Op->isTypeDependent()) 13811 return S.Context.DependentTy; 13812 13813 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13814 if (ConvResult.isInvalid()) 13815 return QualType(); 13816 Op = ConvResult.get(); 13817 QualType OpTy = Op->getType(); 13818 QualType Result; 13819 13820 if (isa<CXXReinterpretCastExpr>(Op)) { 13821 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13822 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13823 Op->getSourceRange()); 13824 } 13825 13826 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13827 { 13828 Result = PT->getPointeeType(); 13829 } 13830 else if (const ObjCObjectPointerType *OPT = 13831 OpTy->getAs<ObjCObjectPointerType>()) 13832 Result = OPT->getPointeeType(); 13833 else { 13834 ExprResult PR = S.CheckPlaceholderExpr(Op); 13835 if (PR.isInvalid()) return QualType(); 13836 if (PR.get() != Op) 13837 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13838 } 13839 13840 if (Result.isNull()) { 13841 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13842 << OpTy << Op->getSourceRange(); 13843 return QualType(); 13844 } 13845 13846 // Note that per both C89 and C99, indirection is always legal, even if Result 13847 // is an incomplete type or void. It would be possible to warn about 13848 // dereferencing a void pointer, but it's completely well-defined, and such a 13849 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13850 // for pointers to 'void' but is fine for any other pointer type: 13851 // 13852 // C++ [expr.unary.op]p1: 13853 // [...] the expression to which [the unary * operator] is applied shall 13854 // be a pointer to an object type, or a pointer to a function type 13855 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13856 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13857 << OpTy << Op->getSourceRange(); 13858 13859 // Dereferences are usually l-values... 13860 VK = VK_LValue; 13861 13862 // ...except that certain expressions are never l-values in C. 13863 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13864 VK = VK_PRValue; 13865 13866 return Result; 13867 } 13868 13869 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13870 BinaryOperatorKind Opc; 13871 switch (Kind) { 13872 default: llvm_unreachable("Unknown binop!"); 13873 case tok::periodstar: Opc = BO_PtrMemD; break; 13874 case tok::arrowstar: Opc = BO_PtrMemI; break; 13875 case tok::star: Opc = BO_Mul; break; 13876 case tok::slash: Opc = BO_Div; break; 13877 case tok::percent: Opc = BO_Rem; break; 13878 case tok::plus: Opc = BO_Add; break; 13879 case tok::minus: Opc = BO_Sub; break; 13880 case tok::lessless: Opc = BO_Shl; break; 13881 case tok::greatergreater: Opc = BO_Shr; break; 13882 case tok::lessequal: Opc = BO_LE; break; 13883 case tok::less: Opc = BO_LT; break; 13884 case tok::greaterequal: Opc = BO_GE; break; 13885 case tok::greater: Opc = BO_GT; break; 13886 case tok::exclaimequal: Opc = BO_NE; break; 13887 case tok::equalequal: Opc = BO_EQ; break; 13888 case tok::spaceship: Opc = BO_Cmp; break; 13889 case tok::amp: Opc = BO_And; break; 13890 case tok::caret: Opc = BO_Xor; break; 13891 case tok::pipe: Opc = BO_Or; break; 13892 case tok::ampamp: Opc = BO_LAnd; break; 13893 case tok::pipepipe: Opc = BO_LOr; break; 13894 case tok::equal: Opc = BO_Assign; break; 13895 case tok::starequal: Opc = BO_MulAssign; break; 13896 case tok::slashequal: Opc = BO_DivAssign; break; 13897 case tok::percentequal: Opc = BO_RemAssign; break; 13898 case tok::plusequal: Opc = BO_AddAssign; break; 13899 case tok::minusequal: Opc = BO_SubAssign; break; 13900 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13901 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13902 case tok::ampequal: Opc = BO_AndAssign; break; 13903 case tok::caretequal: Opc = BO_XorAssign; break; 13904 case tok::pipeequal: Opc = BO_OrAssign; break; 13905 case tok::comma: Opc = BO_Comma; break; 13906 } 13907 return Opc; 13908 } 13909 13910 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13911 tok::TokenKind Kind) { 13912 UnaryOperatorKind Opc; 13913 switch (Kind) { 13914 default: llvm_unreachable("Unknown unary op!"); 13915 case tok::plusplus: Opc = UO_PreInc; break; 13916 case tok::minusminus: Opc = UO_PreDec; break; 13917 case tok::amp: Opc = UO_AddrOf; break; 13918 case tok::star: Opc = UO_Deref; break; 13919 case tok::plus: Opc = UO_Plus; break; 13920 case tok::minus: Opc = UO_Minus; break; 13921 case tok::tilde: Opc = UO_Not; break; 13922 case tok::exclaim: Opc = UO_LNot; break; 13923 case tok::kw___real: Opc = UO_Real; break; 13924 case tok::kw___imag: Opc = UO_Imag; break; 13925 case tok::kw___extension__: Opc = UO_Extension; break; 13926 } 13927 return Opc; 13928 } 13929 13930 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13931 /// This warning suppressed in the event of macro expansions. 13932 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13933 SourceLocation OpLoc, bool IsBuiltin) { 13934 if (S.inTemplateInstantiation()) 13935 return; 13936 if (S.isUnevaluatedContext()) 13937 return; 13938 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13939 return; 13940 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13941 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13942 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13943 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13944 if (!LHSDeclRef || !RHSDeclRef || 13945 LHSDeclRef->getLocation().isMacroID() || 13946 RHSDeclRef->getLocation().isMacroID()) 13947 return; 13948 const ValueDecl *LHSDecl = 13949 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13950 const ValueDecl *RHSDecl = 13951 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13952 if (LHSDecl != RHSDecl) 13953 return; 13954 if (LHSDecl->getType().isVolatileQualified()) 13955 return; 13956 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13957 if (RefTy->getPointeeType().isVolatileQualified()) 13958 return; 13959 13960 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13961 : diag::warn_self_assignment_overloaded) 13962 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13963 << RHSExpr->getSourceRange(); 13964 } 13965 13966 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13967 /// is usually indicative of introspection within the Objective-C pointer. 13968 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13969 SourceLocation OpLoc) { 13970 if (!S.getLangOpts().ObjC) 13971 return; 13972 13973 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13974 const Expr *LHS = L.get(); 13975 const Expr *RHS = R.get(); 13976 13977 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13978 ObjCPointerExpr = LHS; 13979 OtherExpr = RHS; 13980 } 13981 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13982 ObjCPointerExpr = RHS; 13983 OtherExpr = LHS; 13984 } 13985 13986 // This warning is deliberately made very specific to reduce false 13987 // positives with logic that uses '&' for hashing. This logic mainly 13988 // looks for code trying to introspect into tagged pointers, which 13989 // code should generally never do. 13990 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13991 unsigned Diag = diag::warn_objc_pointer_masking; 13992 // Determine if we are introspecting the result of performSelectorXXX. 13993 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13994 // Special case messages to -performSelector and friends, which 13995 // can return non-pointer values boxed in a pointer value. 13996 // Some clients may wish to silence warnings in this subcase. 13997 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13998 Selector S = ME->getSelector(); 13999 StringRef SelArg0 = S.getNameForSlot(0); 14000 if (SelArg0.startswith("performSelector")) 14001 Diag = diag::warn_objc_pointer_masking_performSelector; 14002 } 14003 14004 S.Diag(OpLoc, Diag) 14005 << ObjCPointerExpr->getSourceRange(); 14006 } 14007 } 14008 14009 static NamedDecl *getDeclFromExpr(Expr *E) { 14010 if (!E) 14011 return nullptr; 14012 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14013 return DRE->getDecl(); 14014 if (auto *ME = dyn_cast<MemberExpr>(E)) 14015 return ME->getMemberDecl(); 14016 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14017 return IRE->getDecl(); 14018 return nullptr; 14019 } 14020 14021 // This helper function promotes a binary operator's operands (which are of a 14022 // half vector type) to a vector of floats and then truncates the result to 14023 // a vector of either half or short. 14024 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14025 BinaryOperatorKind Opc, QualType ResultTy, 14026 ExprValueKind VK, ExprObjectKind OK, 14027 bool IsCompAssign, SourceLocation OpLoc, 14028 FPOptionsOverride FPFeatures) { 14029 auto &Context = S.getASTContext(); 14030 assert((isVector(ResultTy, Context.HalfTy) || 14031 isVector(ResultTy, Context.ShortTy)) && 14032 "Result must be a vector of half or short"); 14033 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14034 isVector(RHS.get()->getType(), Context.HalfTy) && 14035 "both operands expected to be a half vector"); 14036 14037 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14038 QualType BinOpResTy = RHS.get()->getType(); 14039 14040 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14041 // change BinOpResTy to a vector of ints. 14042 if (isVector(ResultTy, Context.ShortTy)) 14043 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14044 14045 if (IsCompAssign) 14046 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14047 ResultTy, VK, OK, OpLoc, FPFeatures, 14048 BinOpResTy, BinOpResTy); 14049 14050 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14051 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14052 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14053 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14054 } 14055 14056 static std::pair<ExprResult, ExprResult> 14057 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14058 Expr *RHSExpr) { 14059 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14060 if (!S.Context.isDependenceAllowed()) { 14061 // C cannot handle TypoExpr nodes on either side of a binop because it 14062 // doesn't handle dependent types properly, so make sure any TypoExprs have 14063 // been dealt with before checking the operands. 14064 LHS = S.CorrectDelayedTyposInExpr(LHS); 14065 RHS = S.CorrectDelayedTyposInExpr( 14066 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14067 [Opc, LHS](Expr *E) { 14068 if (Opc != BO_Assign) 14069 return ExprResult(E); 14070 // Avoid correcting the RHS to the same Expr as the LHS. 14071 Decl *D = getDeclFromExpr(E); 14072 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14073 }); 14074 } 14075 return std::make_pair(LHS, RHS); 14076 } 14077 14078 /// Returns true if conversion between vectors of halfs and vectors of floats 14079 /// is needed. 14080 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14081 Expr *E0, Expr *E1 = nullptr) { 14082 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14083 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14084 return false; 14085 14086 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14087 QualType Ty = E->IgnoreImplicit()->getType(); 14088 14089 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14090 // to vectors of floats. Although the element type of the vectors is __fp16, 14091 // the vectors shouldn't be treated as storage-only types. See the 14092 // discussion here: https://reviews.llvm.org/rG825235c140e7 14093 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14094 if (VT->getVectorKind() == VectorType::NeonVector) 14095 return false; 14096 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14097 } 14098 return false; 14099 }; 14100 14101 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14102 } 14103 14104 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14105 /// operator @p Opc at location @c TokLoc. This routine only supports 14106 /// built-in operations; ActOnBinOp handles overloaded operators. 14107 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14108 BinaryOperatorKind Opc, 14109 Expr *LHSExpr, Expr *RHSExpr) { 14110 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14111 // The syntax only allows initializer lists on the RHS of assignment, 14112 // so we don't need to worry about accepting invalid code for 14113 // non-assignment operators. 14114 // C++11 5.17p9: 14115 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14116 // of x = {} is x = T(). 14117 InitializationKind Kind = InitializationKind::CreateDirectList( 14118 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14119 InitializedEntity Entity = 14120 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14121 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14122 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14123 if (Init.isInvalid()) 14124 return Init; 14125 RHSExpr = Init.get(); 14126 } 14127 14128 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14129 QualType ResultTy; // Result type of the binary operator. 14130 // The following two variables are used for compound assignment operators 14131 QualType CompLHSTy; // Type of LHS after promotions for computation 14132 QualType CompResultTy; // Type of computation result 14133 ExprValueKind VK = VK_PRValue; 14134 ExprObjectKind OK = OK_Ordinary; 14135 bool ConvertHalfVec = false; 14136 14137 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14138 if (!LHS.isUsable() || !RHS.isUsable()) 14139 return ExprError(); 14140 14141 if (getLangOpts().OpenCL) { 14142 QualType LHSTy = LHSExpr->getType(); 14143 QualType RHSTy = RHSExpr->getType(); 14144 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14145 // the ATOMIC_VAR_INIT macro. 14146 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14147 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14148 if (BO_Assign == Opc) 14149 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14150 else 14151 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14152 return ExprError(); 14153 } 14154 14155 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14156 // only with a builtin functions and therefore should be disallowed here. 14157 if (LHSTy->isImageType() || RHSTy->isImageType() || 14158 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14159 LHSTy->isPipeType() || RHSTy->isPipeType() || 14160 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14161 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14162 return ExprError(); 14163 } 14164 } 14165 14166 switch (Opc) { 14167 case BO_Assign: 14168 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14169 if (getLangOpts().CPlusPlus && 14170 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14171 VK = LHS.get()->getValueKind(); 14172 OK = LHS.get()->getObjectKind(); 14173 } 14174 if (!ResultTy.isNull()) { 14175 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14176 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14177 14178 // Avoid copying a block to the heap if the block is assigned to a local 14179 // auto variable that is declared in the same scope as the block. This 14180 // optimization is unsafe if the local variable is declared in an outer 14181 // scope. For example: 14182 // 14183 // BlockTy b; 14184 // { 14185 // b = ^{...}; 14186 // } 14187 // // It is unsafe to invoke the block here if it wasn't copied to the 14188 // // heap. 14189 // b(); 14190 14191 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14192 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14193 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14194 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14195 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14196 14197 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14198 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14199 NTCUC_Assignment, NTCUK_Copy); 14200 } 14201 RecordModifiableNonNullParam(*this, LHS.get()); 14202 break; 14203 case BO_PtrMemD: 14204 case BO_PtrMemI: 14205 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14206 Opc == BO_PtrMemI); 14207 break; 14208 case BO_Mul: 14209 case BO_Div: 14210 ConvertHalfVec = true; 14211 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14212 Opc == BO_Div); 14213 break; 14214 case BO_Rem: 14215 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14216 break; 14217 case BO_Add: 14218 ConvertHalfVec = true; 14219 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14220 break; 14221 case BO_Sub: 14222 ConvertHalfVec = true; 14223 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14224 break; 14225 case BO_Shl: 14226 case BO_Shr: 14227 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14228 break; 14229 case BO_LE: 14230 case BO_LT: 14231 case BO_GE: 14232 case BO_GT: 14233 ConvertHalfVec = true; 14234 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14235 break; 14236 case BO_EQ: 14237 case BO_NE: 14238 ConvertHalfVec = true; 14239 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14240 break; 14241 case BO_Cmp: 14242 ConvertHalfVec = true; 14243 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14244 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14245 break; 14246 case BO_And: 14247 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14248 LLVM_FALLTHROUGH; 14249 case BO_Xor: 14250 case BO_Or: 14251 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14252 break; 14253 case BO_LAnd: 14254 case BO_LOr: 14255 ConvertHalfVec = true; 14256 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14257 break; 14258 case BO_MulAssign: 14259 case BO_DivAssign: 14260 ConvertHalfVec = true; 14261 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14262 Opc == BO_DivAssign); 14263 CompLHSTy = CompResultTy; 14264 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14265 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14266 break; 14267 case BO_RemAssign: 14268 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14269 CompLHSTy = CompResultTy; 14270 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14271 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14272 break; 14273 case BO_AddAssign: 14274 ConvertHalfVec = true; 14275 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14276 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14277 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14278 break; 14279 case BO_SubAssign: 14280 ConvertHalfVec = true; 14281 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14282 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14283 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14284 break; 14285 case BO_ShlAssign: 14286 case BO_ShrAssign: 14287 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14288 CompLHSTy = CompResultTy; 14289 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14290 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14291 break; 14292 case BO_AndAssign: 14293 case BO_OrAssign: // fallthrough 14294 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14295 LLVM_FALLTHROUGH; 14296 case BO_XorAssign: 14297 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14298 CompLHSTy = CompResultTy; 14299 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14300 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14301 break; 14302 case BO_Comma: 14303 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14304 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14305 VK = RHS.get()->getValueKind(); 14306 OK = RHS.get()->getObjectKind(); 14307 } 14308 break; 14309 } 14310 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14311 return ExprError(); 14312 14313 // Some of the binary operations require promoting operands of half vector to 14314 // float vectors and truncating the result back to half vector. For now, we do 14315 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14316 // arm64). 14317 assert( 14318 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14319 isVector(LHS.get()->getType(), Context.HalfTy)) && 14320 "both sides are half vectors or neither sides are"); 14321 ConvertHalfVec = 14322 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14323 14324 // Check for array bounds violations for both sides of the BinaryOperator 14325 CheckArrayAccess(LHS.get()); 14326 CheckArrayAccess(RHS.get()); 14327 14328 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14329 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14330 &Context.Idents.get("object_setClass"), 14331 SourceLocation(), LookupOrdinaryName); 14332 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14333 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14334 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14335 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14336 "object_setClass(") 14337 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14338 ",") 14339 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14340 } 14341 else 14342 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14343 } 14344 else if (const ObjCIvarRefExpr *OIRE = 14345 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14346 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14347 14348 // Opc is not a compound assignment if CompResultTy is null. 14349 if (CompResultTy.isNull()) { 14350 if (ConvertHalfVec) 14351 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14352 OpLoc, CurFPFeatureOverrides()); 14353 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14354 VK, OK, OpLoc, CurFPFeatureOverrides()); 14355 } 14356 14357 // Handle compound assignments. 14358 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14359 OK_ObjCProperty) { 14360 VK = VK_LValue; 14361 OK = LHS.get()->getObjectKind(); 14362 } 14363 14364 // The LHS is not converted to the result type for fixed-point compound 14365 // assignment as the common type is computed on demand. Reset the CompLHSTy 14366 // to the LHS type we would have gotten after unary conversions. 14367 if (CompResultTy->isFixedPointType()) 14368 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14369 14370 if (ConvertHalfVec) 14371 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14372 OpLoc, CurFPFeatureOverrides()); 14373 14374 return CompoundAssignOperator::Create( 14375 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14376 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14377 } 14378 14379 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14380 /// operators are mixed in a way that suggests that the programmer forgot that 14381 /// comparison operators have higher precedence. The most typical example of 14382 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14383 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14384 SourceLocation OpLoc, Expr *LHSExpr, 14385 Expr *RHSExpr) { 14386 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14387 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14388 14389 // Check that one of the sides is a comparison operator and the other isn't. 14390 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14391 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14392 if (isLeftComp == isRightComp) 14393 return; 14394 14395 // Bitwise operations are sometimes used as eager logical ops. 14396 // Don't diagnose this. 14397 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14398 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14399 if (isLeftBitwise || isRightBitwise) 14400 return; 14401 14402 SourceRange DiagRange = isLeftComp 14403 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14404 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14405 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14406 SourceRange ParensRange = 14407 isLeftComp 14408 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14409 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14410 14411 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14412 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14413 SuggestParentheses(Self, OpLoc, 14414 Self.PDiag(diag::note_precedence_silence) << OpStr, 14415 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14416 SuggestParentheses(Self, OpLoc, 14417 Self.PDiag(diag::note_precedence_bitwise_first) 14418 << BinaryOperator::getOpcodeStr(Opc), 14419 ParensRange); 14420 } 14421 14422 /// It accepts a '&&' expr that is inside a '||' one. 14423 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14424 /// in parentheses. 14425 static void 14426 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14427 BinaryOperator *Bop) { 14428 assert(Bop->getOpcode() == BO_LAnd); 14429 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14430 << Bop->getSourceRange() << OpLoc; 14431 SuggestParentheses(Self, Bop->getOperatorLoc(), 14432 Self.PDiag(diag::note_precedence_silence) 14433 << Bop->getOpcodeStr(), 14434 Bop->getSourceRange()); 14435 } 14436 14437 /// Returns true if the given expression can be evaluated as a constant 14438 /// 'true'. 14439 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14440 bool Res; 14441 return !E->isValueDependent() && 14442 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14443 } 14444 14445 /// Returns true if the given expression can be evaluated as a constant 14446 /// 'false'. 14447 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14448 bool Res; 14449 return !E->isValueDependent() && 14450 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14451 } 14452 14453 /// Look for '&&' in the left hand of a '||' expr. 14454 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14455 Expr *LHSExpr, Expr *RHSExpr) { 14456 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14457 if (Bop->getOpcode() == BO_LAnd) { 14458 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14459 if (EvaluatesAsFalse(S, RHSExpr)) 14460 return; 14461 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14462 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14463 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14464 } else if (Bop->getOpcode() == BO_LOr) { 14465 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14466 // If it's "a || b && 1 || c" we didn't warn earlier for 14467 // "a || b && 1", but warn now. 14468 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14469 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14470 } 14471 } 14472 } 14473 } 14474 14475 /// Look for '&&' in the right hand of a '||' expr. 14476 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14477 Expr *LHSExpr, Expr *RHSExpr) { 14478 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14479 if (Bop->getOpcode() == BO_LAnd) { 14480 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14481 if (EvaluatesAsFalse(S, LHSExpr)) 14482 return; 14483 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14484 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14485 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14486 } 14487 } 14488 } 14489 14490 /// Look for bitwise op in the left or right hand of a bitwise op with 14491 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14492 /// the '&' expression in parentheses. 14493 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14494 SourceLocation OpLoc, Expr *SubExpr) { 14495 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14496 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14497 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14498 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14499 << Bop->getSourceRange() << OpLoc; 14500 SuggestParentheses(S, Bop->getOperatorLoc(), 14501 S.PDiag(diag::note_precedence_silence) 14502 << Bop->getOpcodeStr(), 14503 Bop->getSourceRange()); 14504 } 14505 } 14506 } 14507 14508 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14509 Expr *SubExpr, StringRef Shift) { 14510 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14511 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14512 StringRef Op = Bop->getOpcodeStr(); 14513 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14514 << Bop->getSourceRange() << OpLoc << Shift << Op; 14515 SuggestParentheses(S, Bop->getOperatorLoc(), 14516 S.PDiag(diag::note_precedence_silence) << Op, 14517 Bop->getSourceRange()); 14518 } 14519 } 14520 } 14521 14522 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14523 Expr *LHSExpr, Expr *RHSExpr) { 14524 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14525 if (!OCE) 14526 return; 14527 14528 FunctionDecl *FD = OCE->getDirectCallee(); 14529 if (!FD || !FD->isOverloadedOperator()) 14530 return; 14531 14532 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14533 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14534 return; 14535 14536 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14537 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14538 << (Kind == OO_LessLess); 14539 SuggestParentheses(S, OCE->getOperatorLoc(), 14540 S.PDiag(diag::note_precedence_silence) 14541 << (Kind == OO_LessLess ? "<<" : ">>"), 14542 OCE->getSourceRange()); 14543 SuggestParentheses( 14544 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14545 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14546 } 14547 14548 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14549 /// precedence. 14550 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14551 SourceLocation OpLoc, Expr *LHSExpr, 14552 Expr *RHSExpr){ 14553 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14554 if (BinaryOperator::isBitwiseOp(Opc)) 14555 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14556 14557 // Diagnose "arg1 & arg2 | arg3" 14558 if ((Opc == BO_Or || Opc == BO_Xor) && 14559 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14560 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14561 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14562 } 14563 14564 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14565 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14566 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14567 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14568 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14569 } 14570 14571 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14572 || Opc == BO_Shr) { 14573 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14574 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14575 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14576 } 14577 14578 // Warn on overloaded shift operators and comparisons, such as: 14579 // cout << 5 == 4; 14580 if (BinaryOperator::isComparisonOp(Opc)) 14581 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14582 } 14583 14584 // Binary Operators. 'Tok' is the token for the operator. 14585 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14586 tok::TokenKind Kind, 14587 Expr *LHSExpr, Expr *RHSExpr) { 14588 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14589 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14590 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14591 14592 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14593 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14594 14595 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14596 } 14597 14598 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14599 UnresolvedSetImpl &Functions) { 14600 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14601 if (OverOp != OO_None && OverOp != OO_Equal) 14602 LookupOverloadedOperatorName(OverOp, S, Functions); 14603 14604 // In C++20 onwards, we may have a second operator to look up. 14605 if (getLangOpts().CPlusPlus20) { 14606 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14607 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14608 } 14609 } 14610 14611 /// Build an overloaded binary operator expression in the given scope. 14612 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14613 BinaryOperatorKind Opc, 14614 Expr *LHS, Expr *RHS) { 14615 switch (Opc) { 14616 case BO_Assign: 14617 case BO_DivAssign: 14618 case BO_RemAssign: 14619 case BO_SubAssign: 14620 case BO_AndAssign: 14621 case BO_OrAssign: 14622 case BO_XorAssign: 14623 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14624 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14625 break; 14626 default: 14627 break; 14628 } 14629 14630 // Find all of the overloaded operators visible from this point. 14631 UnresolvedSet<16> Functions; 14632 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14633 14634 // Build the (potentially-overloaded, potentially-dependent) 14635 // binary operation. 14636 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14637 } 14638 14639 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14640 BinaryOperatorKind Opc, 14641 Expr *LHSExpr, Expr *RHSExpr) { 14642 ExprResult LHS, RHS; 14643 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14644 if (!LHS.isUsable() || !RHS.isUsable()) 14645 return ExprError(); 14646 LHSExpr = LHS.get(); 14647 RHSExpr = RHS.get(); 14648 14649 // We want to end up calling one of checkPseudoObjectAssignment 14650 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14651 // both expressions are overloadable or either is type-dependent), 14652 // or CreateBuiltinBinOp (in any other case). We also want to get 14653 // any placeholder types out of the way. 14654 14655 // Handle pseudo-objects in the LHS. 14656 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14657 // Assignments with a pseudo-object l-value need special analysis. 14658 if (pty->getKind() == BuiltinType::PseudoObject && 14659 BinaryOperator::isAssignmentOp(Opc)) 14660 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14661 14662 // Don't resolve overloads if the other type is overloadable. 14663 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14664 // We can't actually test that if we still have a placeholder, 14665 // though. Fortunately, none of the exceptions we see in that 14666 // code below are valid when the LHS is an overload set. Note 14667 // that an overload set can be dependently-typed, but it never 14668 // instantiates to having an overloadable type. 14669 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14670 if (resolvedRHS.isInvalid()) return ExprError(); 14671 RHSExpr = resolvedRHS.get(); 14672 14673 if (RHSExpr->isTypeDependent() || 14674 RHSExpr->getType()->isOverloadableType()) 14675 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14676 } 14677 14678 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14679 // template, diagnose the missing 'template' keyword instead of diagnosing 14680 // an invalid use of a bound member function. 14681 // 14682 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14683 // to C++1z [over.over]/1.4, but we already checked for that case above. 14684 if (Opc == BO_LT && inTemplateInstantiation() && 14685 (pty->getKind() == BuiltinType::BoundMember || 14686 pty->getKind() == BuiltinType::Overload)) { 14687 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14688 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14689 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14690 return isa<FunctionTemplateDecl>(ND); 14691 })) { 14692 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14693 : OE->getNameLoc(), 14694 diag::err_template_kw_missing) 14695 << OE->getName().getAsString() << ""; 14696 return ExprError(); 14697 } 14698 } 14699 14700 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14701 if (LHS.isInvalid()) return ExprError(); 14702 LHSExpr = LHS.get(); 14703 } 14704 14705 // Handle pseudo-objects in the RHS. 14706 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14707 // An overload in the RHS can potentially be resolved by the type 14708 // being assigned to. 14709 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14710 if (getLangOpts().CPlusPlus && 14711 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14712 LHSExpr->getType()->isOverloadableType())) 14713 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14714 14715 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14716 } 14717 14718 // Don't resolve overloads if the other type is overloadable. 14719 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14720 LHSExpr->getType()->isOverloadableType()) 14721 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14722 14723 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14724 if (!resolvedRHS.isUsable()) return ExprError(); 14725 RHSExpr = resolvedRHS.get(); 14726 } 14727 14728 if (getLangOpts().CPlusPlus) { 14729 // If either expression is type-dependent, always build an 14730 // overloaded op. 14731 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14732 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14733 14734 // Otherwise, build an overloaded op if either expression has an 14735 // overloadable type. 14736 if (LHSExpr->getType()->isOverloadableType() || 14737 RHSExpr->getType()->isOverloadableType()) 14738 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14739 } 14740 14741 if (getLangOpts().RecoveryAST && 14742 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14743 assert(!getLangOpts().CPlusPlus); 14744 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14745 "Should only occur in error-recovery path."); 14746 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14747 // C [6.15.16] p3: 14748 // An assignment expression has the value of the left operand after the 14749 // assignment, but is not an lvalue. 14750 return CompoundAssignOperator::Create( 14751 Context, LHSExpr, RHSExpr, Opc, 14752 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14753 OpLoc, CurFPFeatureOverrides()); 14754 QualType ResultType; 14755 switch (Opc) { 14756 case BO_Assign: 14757 ResultType = LHSExpr->getType().getUnqualifiedType(); 14758 break; 14759 case BO_LT: 14760 case BO_GT: 14761 case BO_LE: 14762 case BO_GE: 14763 case BO_EQ: 14764 case BO_NE: 14765 case BO_LAnd: 14766 case BO_LOr: 14767 // These operators have a fixed result type regardless of operands. 14768 ResultType = Context.IntTy; 14769 break; 14770 case BO_Comma: 14771 ResultType = RHSExpr->getType(); 14772 break; 14773 default: 14774 ResultType = Context.DependentTy; 14775 break; 14776 } 14777 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14778 VK_PRValue, OK_Ordinary, OpLoc, 14779 CurFPFeatureOverrides()); 14780 } 14781 14782 // Build a built-in binary operation. 14783 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14784 } 14785 14786 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14787 if (T.isNull() || T->isDependentType()) 14788 return false; 14789 14790 if (!T->isPromotableIntegerType()) 14791 return true; 14792 14793 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14794 } 14795 14796 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14797 UnaryOperatorKind Opc, 14798 Expr *InputExpr) { 14799 ExprResult Input = InputExpr; 14800 ExprValueKind VK = VK_PRValue; 14801 ExprObjectKind OK = OK_Ordinary; 14802 QualType resultType; 14803 bool CanOverflow = false; 14804 14805 bool ConvertHalfVec = false; 14806 if (getLangOpts().OpenCL) { 14807 QualType Ty = InputExpr->getType(); 14808 // The only legal unary operation for atomics is '&'. 14809 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14810 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14811 // only with a builtin functions and therefore should be disallowed here. 14812 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14813 || Ty->isBlockPointerType())) { 14814 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14815 << InputExpr->getType() 14816 << Input.get()->getSourceRange()); 14817 } 14818 } 14819 14820 switch (Opc) { 14821 case UO_PreInc: 14822 case UO_PreDec: 14823 case UO_PostInc: 14824 case UO_PostDec: 14825 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14826 OpLoc, 14827 Opc == UO_PreInc || 14828 Opc == UO_PostInc, 14829 Opc == UO_PreInc || 14830 Opc == UO_PreDec); 14831 CanOverflow = isOverflowingIntegerType(Context, resultType); 14832 break; 14833 case UO_AddrOf: 14834 resultType = CheckAddressOfOperand(Input, OpLoc); 14835 CheckAddressOfNoDeref(InputExpr); 14836 RecordModifiableNonNullParam(*this, InputExpr); 14837 break; 14838 case UO_Deref: { 14839 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14840 if (Input.isInvalid()) return ExprError(); 14841 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14842 break; 14843 } 14844 case UO_Plus: 14845 case UO_Minus: 14846 CanOverflow = Opc == UO_Minus && 14847 isOverflowingIntegerType(Context, Input.get()->getType()); 14848 Input = UsualUnaryConversions(Input.get()); 14849 if (Input.isInvalid()) return ExprError(); 14850 // Unary plus and minus require promoting an operand of half vector to a 14851 // float vector and truncating the result back to a half vector. For now, we 14852 // do this only when HalfArgsAndReturns is set (that is, when the target is 14853 // arm or arm64). 14854 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14855 14856 // If the operand is a half vector, promote it to a float vector. 14857 if (ConvertHalfVec) 14858 Input = convertVector(Input.get(), Context.FloatTy, *this); 14859 resultType = Input.get()->getType(); 14860 if (resultType->isDependentType()) 14861 break; 14862 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14863 break; 14864 else if (resultType->isVectorType() && 14865 // The z vector extensions don't allow + or - with bool vectors. 14866 (!Context.getLangOpts().ZVector || 14867 resultType->castAs<VectorType>()->getVectorKind() != 14868 VectorType::AltiVecBool)) 14869 break; 14870 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14871 Opc == UO_Plus && 14872 resultType->isPointerType()) 14873 break; 14874 14875 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14876 << resultType << Input.get()->getSourceRange()); 14877 14878 case UO_Not: // bitwise complement 14879 Input = UsualUnaryConversions(Input.get()); 14880 if (Input.isInvalid()) 14881 return ExprError(); 14882 resultType = Input.get()->getType(); 14883 if (resultType->isDependentType()) 14884 break; 14885 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14886 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14887 // C99 does not support '~' for complex conjugation. 14888 Diag(OpLoc, diag::ext_integer_complement_complex) 14889 << resultType << Input.get()->getSourceRange(); 14890 else if (resultType->hasIntegerRepresentation()) 14891 break; 14892 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14893 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14894 // on vector float types. 14895 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14896 if (!T->isIntegerType()) 14897 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14898 << resultType << Input.get()->getSourceRange()); 14899 } else { 14900 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14901 << resultType << Input.get()->getSourceRange()); 14902 } 14903 break; 14904 14905 case UO_LNot: // logical negation 14906 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14907 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14908 if (Input.isInvalid()) return ExprError(); 14909 resultType = Input.get()->getType(); 14910 14911 // Though we still have to promote half FP to float... 14912 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14913 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14914 resultType = Context.FloatTy; 14915 } 14916 14917 if (resultType->isDependentType()) 14918 break; 14919 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14920 // C99 6.5.3.3p1: ok, fallthrough; 14921 if (Context.getLangOpts().CPlusPlus) { 14922 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14923 // operand contextually converted to bool. 14924 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14925 ScalarTypeToBooleanCastKind(resultType)); 14926 } else if (Context.getLangOpts().OpenCL && 14927 Context.getLangOpts().OpenCLVersion < 120) { 14928 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14929 // operate on scalar float types. 14930 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14931 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14932 << resultType << Input.get()->getSourceRange()); 14933 } 14934 } else if (resultType->isExtVectorType()) { 14935 if (Context.getLangOpts().OpenCL && 14936 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14937 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14938 // operate on vector float types. 14939 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14940 if (!T->isIntegerType()) 14941 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14942 << resultType << Input.get()->getSourceRange()); 14943 } 14944 // Vector logical not returns the signed variant of the operand type. 14945 resultType = GetSignedVectorType(resultType); 14946 break; 14947 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14948 const VectorType *VTy = resultType->castAs<VectorType>(); 14949 if (VTy->getVectorKind() != VectorType::GenericVector) 14950 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14951 << resultType << Input.get()->getSourceRange()); 14952 14953 // Vector logical not returns the signed variant of the operand type. 14954 resultType = GetSignedVectorType(resultType); 14955 break; 14956 } else { 14957 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14958 << resultType << Input.get()->getSourceRange()); 14959 } 14960 14961 // LNot always has type int. C99 6.5.3.3p5. 14962 // In C++, it's bool. C++ 5.3.1p8 14963 resultType = Context.getLogicalOperationType(); 14964 break; 14965 case UO_Real: 14966 case UO_Imag: 14967 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14968 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14969 // complex l-values to ordinary l-values and all other values to r-values. 14970 if (Input.isInvalid()) return ExprError(); 14971 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14972 if (Input.get()->isGLValue() && 14973 Input.get()->getObjectKind() == OK_Ordinary) 14974 VK = Input.get()->getValueKind(); 14975 } else if (!getLangOpts().CPlusPlus) { 14976 // In C, a volatile scalar is read by __imag. In C++, it is not. 14977 Input = DefaultLvalueConversion(Input.get()); 14978 } 14979 break; 14980 case UO_Extension: 14981 resultType = Input.get()->getType(); 14982 VK = Input.get()->getValueKind(); 14983 OK = Input.get()->getObjectKind(); 14984 break; 14985 case UO_Coawait: 14986 // It's unnecessary to represent the pass-through operator co_await in the 14987 // AST; just return the input expression instead. 14988 assert(!Input.get()->getType()->isDependentType() && 14989 "the co_await expression must be non-dependant before " 14990 "building operator co_await"); 14991 return Input; 14992 } 14993 if (resultType.isNull() || Input.isInvalid()) 14994 return ExprError(); 14995 14996 // Check for array bounds violations in the operand of the UnaryOperator, 14997 // except for the '*' and '&' operators that have to be handled specially 14998 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14999 // that are explicitly defined as valid by the standard). 15000 if (Opc != UO_AddrOf && Opc != UO_Deref) 15001 CheckArrayAccess(Input.get()); 15002 15003 auto *UO = 15004 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15005 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15006 15007 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15008 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15009 !isUnevaluatedContext()) 15010 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15011 15012 // Convert the result back to a half vector. 15013 if (ConvertHalfVec) 15014 return convertVector(UO, Context.HalfTy, *this); 15015 return UO; 15016 } 15017 15018 /// Determine whether the given expression is a qualified member 15019 /// access expression, of a form that could be turned into a pointer to member 15020 /// with the address-of operator. 15021 bool Sema::isQualifiedMemberAccess(Expr *E) { 15022 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15023 if (!DRE->getQualifier()) 15024 return false; 15025 15026 ValueDecl *VD = DRE->getDecl(); 15027 if (!VD->isCXXClassMember()) 15028 return false; 15029 15030 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15031 return true; 15032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15033 return Method->isInstance(); 15034 15035 return false; 15036 } 15037 15038 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15039 if (!ULE->getQualifier()) 15040 return false; 15041 15042 for (NamedDecl *D : ULE->decls()) { 15043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15044 if (Method->isInstance()) 15045 return true; 15046 } else { 15047 // Overload set does not contain methods. 15048 break; 15049 } 15050 } 15051 15052 return false; 15053 } 15054 15055 return false; 15056 } 15057 15058 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15059 UnaryOperatorKind Opc, Expr *Input) { 15060 // First things first: handle placeholders so that the 15061 // overloaded-operator check considers the right type. 15062 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15063 // Increment and decrement of pseudo-object references. 15064 if (pty->getKind() == BuiltinType::PseudoObject && 15065 UnaryOperator::isIncrementDecrementOp(Opc)) 15066 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15067 15068 // extension is always a builtin operator. 15069 if (Opc == UO_Extension) 15070 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15071 15072 // & gets special logic for several kinds of placeholder. 15073 // The builtin code knows what to do. 15074 if (Opc == UO_AddrOf && 15075 (pty->getKind() == BuiltinType::Overload || 15076 pty->getKind() == BuiltinType::UnknownAny || 15077 pty->getKind() == BuiltinType::BoundMember)) 15078 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15079 15080 // Anything else needs to be handled now. 15081 ExprResult Result = CheckPlaceholderExpr(Input); 15082 if (Result.isInvalid()) return ExprError(); 15083 Input = Result.get(); 15084 } 15085 15086 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15087 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15088 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15089 // Find all of the overloaded operators visible from this point. 15090 UnresolvedSet<16> Functions; 15091 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15092 if (S && OverOp != OO_None) 15093 LookupOverloadedOperatorName(OverOp, S, Functions); 15094 15095 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15096 } 15097 15098 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15099 } 15100 15101 // Unary Operators. 'Tok' is the token for the operator. 15102 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15103 tok::TokenKind Op, Expr *Input) { 15104 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15105 } 15106 15107 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15108 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15109 LabelDecl *TheDecl) { 15110 TheDecl->markUsed(Context); 15111 // Create the AST node. The address of a label always has type 'void*'. 15112 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15113 Context.getPointerType(Context.VoidTy)); 15114 } 15115 15116 void Sema::ActOnStartStmtExpr() { 15117 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15118 } 15119 15120 void Sema::ActOnStmtExprError() { 15121 // Note that function is also called by TreeTransform when leaving a 15122 // StmtExpr scope without rebuilding anything. 15123 15124 DiscardCleanupsInEvaluationContext(); 15125 PopExpressionEvaluationContext(); 15126 } 15127 15128 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15129 SourceLocation RPLoc) { 15130 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15131 } 15132 15133 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15134 SourceLocation RPLoc, unsigned TemplateDepth) { 15135 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15136 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15137 15138 if (hasAnyUnrecoverableErrorsInThisFunction()) 15139 DiscardCleanupsInEvaluationContext(); 15140 assert(!Cleanup.exprNeedsCleanups() && 15141 "cleanups within StmtExpr not correctly bound!"); 15142 PopExpressionEvaluationContext(); 15143 15144 // FIXME: there are a variety of strange constraints to enforce here, for 15145 // example, it is not possible to goto into a stmt expression apparently. 15146 // More semantic analysis is needed. 15147 15148 // If there are sub-stmts in the compound stmt, take the type of the last one 15149 // as the type of the stmtexpr. 15150 QualType Ty = Context.VoidTy; 15151 bool StmtExprMayBindToTemp = false; 15152 if (!Compound->body_empty()) { 15153 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15154 if (const auto *LastStmt = 15155 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15156 if (const Expr *Value = LastStmt->getExprStmt()) { 15157 StmtExprMayBindToTemp = true; 15158 Ty = Value->getType(); 15159 } 15160 } 15161 } 15162 15163 // FIXME: Check that expression type is complete/non-abstract; statement 15164 // expressions are not lvalues. 15165 Expr *ResStmtExpr = 15166 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15167 if (StmtExprMayBindToTemp) 15168 return MaybeBindToTemporary(ResStmtExpr); 15169 return ResStmtExpr; 15170 } 15171 15172 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15173 if (ER.isInvalid()) 15174 return ExprError(); 15175 15176 // Do function/array conversion on the last expression, but not 15177 // lvalue-to-rvalue. However, initialize an unqualified type. 15178 ER = DefaultFunctionArrayConversion(ER.get()); 15179 if (ER.isInvalid()) 15180 return ExprError(); 15181 Expr *E = ER.get(); 15182 15183 if (E->isTypeDependent()) 15184 return E; 15185 15186 // In ARC, if the final expression ends in a consume, splice 15187 // the consume out and bind it later. In the alternate case 15188 // (when dealing with a retainable type), the result 15189 // initialization will create a produce. In both cases the 15190 // result will be +1, and we'll need to balance that out with 15191 // a bind. 15192 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15193 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15194 return Cast->getSubExpr(); 15195 15196 // FIXME: Provide a better location for the initialization. 15197 return PerformCopyInitialization( 15198 InitializedEntity::InitializeStmtExprResult( 15199 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15200 SourceLocation(), E); 15201 } 15202 15203 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15204 TypeSourceInfo *TInfo, 15205 ArrayRef<OffsetOfComponent> Components, 15206 SourceLocation RParenLoc) { 15207 QualType ArgTy = TInfo->getType(); 15208 bool Dependent = ArgTy->isDependentType(); 15209 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15210 15211 // We must have at least one component that refers to the type, and the first 15212 // one is known to be a field designator. Verify that the ArgTy represents 15213 // a struct/union/class. 15214 if (!Dependent && !ArgTy->isRecordType()) 15215 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15216 << ArgTy << TypeRange); 15217 15218 // Type must be complete per C99 7.17p3 because a declaring a variable 15219 // with an incomplete type would be ill-formed. 15220 if (!Dependent 15221 && RequireCompleteType(BuiltinLoc, ArgTy, 15222 diag::err_offsetof_incomplete_type, TypeRange)) 15223 return ExprError(); 15224 15225 bool DidWarnAboutNonPOD = false; 15226 QualType CurrentType = ArgTy; 15227 SmallVector<OffsetOfNode, 4> Comps; 15228 SmallVector<Expr*, 4> Exprs; 15229 for (const OffsetOfComponent &OC : Components) { 15230 if (OC.isBrackets) { 15231 // Offset of an array sub-field. TODO: Should we allow vector elements? 15232 if (!CurrentType->isDependentType()) { 15233 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15234 if(!AT) 15235 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15236 << CurrentType); 15237 CurrentType = AT->getElementType(); 15238 } else 15239 CurrentType = Context.DependentTy; 15240 15241 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15242 if (IdxRval.isInvalid()) 15243 return ExprError(); 15244 Expr *Idx = IdxRval.get(); 15245 15246 // The expression must be an integral expression. 15247 // FIXME: An integral constant expression? 15248 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15249 !Idx->getType()->isIntegerType()) 15250 return ExprError( 15251 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15252 << Idx->getSourceRange()); 15253 15254 // Record this array index. 15255 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15256 Exprs.push_back(Idx); 15257 continue; 15258 } 15259 15260 // Offset of a field. 15261 if (CurrentType->isDependentType()) { 15262 // We have the offset of a field, but we can't look into the dependent 15263 // type. Just record the identifier of the field. 15264 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15265 CurrentType = Context.DependentTy; 15266 continue; 15267 } 15268 15269 // We need to have a complete type to look into. 15270 if (RequireCompleteType(OC.LocStart, CurrentType, 15271 diag::err_offsetof_incomplete_type)) 15272 return ExprError(); 15273 15274 // Look for the designated field. 15275 const RecordType *RC = CurrentType->getAs<RecordType>(); 15276 if (!RC) 15277 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15278 << CurrentType); 15279 RecordDecl *RD = RC->getDecl(); 15280 15281 // C++ [lib.support.types]p5: 15282 // The macro offsetof accepts a restricted set of type arguments in this 15283 // International Standard. type shall be a POD structure or a POD union 15284 // (clause 9). 15285 // C++11 [support.types]p4: 15286 // If type is not a standard-layout class (Clause 9), the results are 15287 // undefined. 15288 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15289 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15290 unsigned DiagID = 15291 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15292 : diag::ext_offsetof_non_pod_type; 15293 15294 if (!IsSafe && !DidWarnAboutNonPOD && 15295 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15296 PDiag(DiagID) 15297 << SourceRange(Components[0].LocStart, OC.LocEnd) 15298 << CurrentType)) 15299 DidWarnAboutNonPOD = true; 15300 } 15301 15302 // Look for the field. 15303 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15304 LookupQualifiedName(R, RD); 15305 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15306 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15307 if (!MemberDecl) { 15308 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15309 MemberDecl = IndirectMemberDecl->getAnonField(); 15310 } 15311 15312 if (!MemberDecl) 15313 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15314 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15315 OC.LocEnd)); 15316 15317 // C99 7.17p3: 15318 // (If the specified member is a bit-field, the behavior is undefined.) 15319 // 15320 // We diagnose this as an error. 15321 if (MemberDecl->isBitField()) { 15322 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15323 << MemberDecl->getDeclName() 15324 << SourceRange(BuiltinLoc, RParenLoc); 15325 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15326 return ExprError(); 15327 } 15328 15329 RecordDecl *Parent = MemberDecl->getParent(); 15330 if (IndirectMemberDecl) 15331 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15332 15333 // If the member was found in a base class, introduce OffsetOfNodes for 15334 // the base class indirections. 15335 CXXBasePaths Paths; 15336 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15337 Paths)) { 15338 if (Paths.getDetectedVirtual()) { 15339 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15340 << MemberDecl->getDeclName() 15341 << SourceRange(BuiltinLoc, RParenLoc); 15342 return ExprError(); 15343 } 15344 15345 CXXBasePath &Path = Paths.front(); 15346 for (const CXXBasePathElement &B : Path) 15347 Comps.push_back(OffsetOfNode(B.Base)); 15348 } 15349 15350 if (IndirectMemberDecl) { 15351 for (auto *FI : IndirectMemberDecl->chain()) { 15352 assert(isa<FieldDecl>(FI)); 15353 Comps.push_back(OffsetOfNode(OC.LocStart, 15354 cast<FieldDecl>(FI), OC.LocEnd)); 15355 } 15356 } else 15357 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15358 15359 CurrentType = MemberDecl->getType().getNonReferenceType(); 15360 } 15361 15362 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15363 Comps, Exprs, RParenLoc); 15364 } 15365 15366 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15367 SourceLocation BuiltinLoc, 15368 SourceLocation TypeLoc, 15369 ParsedType ParsedArgTy, 15370 ArrayRef<OffsetOfComponent> Components, 15371 SourceLocation RParenLoc) { 15372 15373 TypeSourceInfo *ArgTInfo; 15374 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15375 if (ArgTy.isNull()) 15376 return ExprError(); 15377 15378 if (!ArgTInfo) 15379 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15380 15381 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15382 } 15383 15384 15385 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15386 Expr *CondExpr, 15387 Expr *LHSExpr, Expr *RHSExpr, 15388 SourceLocation RPLoc) { 15389 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15390 15391 ExprValueKind VK = VK_PRValue; 15392 ExprObjectKind OK = OK_Ordinary; 15393 QualType resType; 15394 bool CondIsTrue = false; 15395 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15396 resType = Context.DependentTy; 15397 } else { 15398 // The conditional expression is required to be a constant expression. 15399 llvm::APSInt condEval(32); 15400 ExprResult CondICE = VerifyIntegerConstantExpression( 15401 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15402 if (CondICE.isInvalid()) 15403 return ExprError(); 15404 CondExpr = CondICE.get(); 15405 CondIsTrue = condEval.getZExtValue(); 15406 15407 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15408 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15409 15410 resType = ActiveExpr->getType(); 15411 VK = ActiveExpr->getValueKind(); 15412 OK = ActiveExpr->getObjectKind(); 15413 } 15414 15415 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15416 resType, VK, OK, RPLoc, CondIsTrue); 15417 } 15418 15419 //===----------------------------------------------------------------------===// 15420 // Clang Extensions. 15421 //===----------------------------------------------------------------------===// 15422 15423 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15424 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15425 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15426 15427 if (LangOpts.CPlusPlus) { 15428 MangleNumberingContext *MCtx; 15429 Decl *ManglingContextDecl; 15430 std::tie(MCtx, ManglingContextDecl) = 15431 getCurrentMangleNumberContext(Block->getDeclContext()); 15432 if (MCtx) { 15433 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15434 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15435 } 15436 } 15437 15438 PushBlockScope(CurScope, Block); 15439 CurContext->addDecl(Block); 15440 if (CurScope) 15441 PushDeclContext(CurScope, Block); 15442 else 15443 CurContext = Block; 15444 15445 getCurBlock()->HasImplicitReturnType = true; 15446 15447 // Enter a new evaluation context to insulate the block from any 15448 // cleanups from the enclosing full-expression. 15449 PushExpressionEvaluationContext( 15450 ExpressionEvaluationContext::PotentiallyEvaluated); 15451 } 15452 15453 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15454 Scope *CurScope) { 15455 assert(ParamInfo.getIdentifier() == nullptr && 15456 "block-id should have no identifier!"); 15457 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15458 BlockScopeInfo *CurBlock = getCurBlock(); 15459 15460 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15461 QualType T = Sig->getType(); 15462 15463 // FIXME: We should allow unexpanded parameter packs here, but that would, 15464 // in turn, make the block expression contain unexpanded parameter packs. 15465 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15466 // Drop the parameters. 15467 FunctionProtoType::ExtProtoInfo EPI; 15468 EPI.HasTrailingReturn = false; 15469 EPI.TypeQuals.addConst(); 15470 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15471 Sig = Context.getTrivialTypeSourceInfo(T); 15472 } 15473 15474 // GetTypeForDeclarator always produces a function type for a block 15475 // literal signature. Furthermore, it is always a FunctionProtoType 15476 // unless the function was written with a typedef. 15477 assert(T->isFunctionType() && 15478 "GetTypeForDeclarator made a non-function block signature"); 15479 15480 // Look for an explicit signature in that function type. 15481 FunctionProtoTypeLoc ExplicitSignature; 15482 15483 if ((ExplicitSignature = Sig->getTypeLoc() 15484 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15485 15486 // Check whether that explicit signature was synthesized by 15487 // GetTypeForDeclarator. If so, don't save that as part of the 15488 // written signature. 15489 if (ExplicitSignature.getLocalRangeBegin() == 15490 ExplicitSignature.getLocalRangeEnd()) { 15491 // This would be much cheaper if we stored TypeLocs instead of 15492 // TypeSourceInfos. 15493 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15494 unsigned Size = Result.getFullDataSize(); 15495 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15496 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15497 15498 ExplicitSignature = FunctionProtoTypeLoc(); 15499 } 15500 } 15501 15502 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15503 CurBlock->FunctionType = T; 15504 15505 const auto *Fn = T->castAs<FunctionType>(); 15506 QualType RetTy = Fn->getReturnType(); 15507 bool isVariadic = 15508 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15509 15510 CurBlock->TheDecl->setIsVariadic(isVariadic); 15511 15512 // Context.DependentTy is used as a placeholder for a missing block 15513 // return type. TODO: what should we do with declarators like: 15514 // ^ * { ... } 15515 // If the answer is "apply template argument deduction".... 15516 if (RetTy != Context.DependentTy) { 15517 CurBlock->ReturnType = RetTy; 15518 CurBlock->TheDecl->setBlockMissingReturnType(false); 15519 CurBlock->HasImplicitReturnType = false; 15520 } 15521 15522 // Push block parameters from the declarator if we had them. 15523 SmallVector<ParmVarDecl*, 8> Params; 15524 if (ExplicitSignature) { 15525 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15526 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15527 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15528 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15529 // Diagnose this as an extension in C17 and earlier. 15530 if (!getLangOpts().C2x) 15531 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15532 } 15533 Params.push_back(Param); 15534 } 15535 15536 // Fake up parameter variables if we have a typedef, like 15537 // ^ fntype { ... } 15538 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15539 for (const auto &I : Fn->param_types()) { 15540 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15541 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15542 Params.push_back(Param); 15543 } 15544 } 15545 15546 // Set the parameters on the block decl. 15547 if (!Params.empty()) { 15548 CurBlock->TheDecl->setParams(Params); 15549 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15550 /*CheckParameterNames=*/false); 15551 } 15552 15553 // Finally we can process decl attributes. 15554 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15555 15556 // Put the parameter variables in scope. 15557 for (auto AI : CurBlock->TheDecl->parameters()) { 15558 AI->setOwningFunction(CurBlock->TheDecl); 15559 15560 // If this has an identifier, add it to the scope stack. 15561 if (AI->getIdentifier()) { 15562 CheckShadow(CurBlock->TheScope, AI); 15563 15564 PushOnScopeChains(AI, CurBlock->TheScope); 15565 } 15566 } 15567 } 15568 15569 /// ActOnBlockError - If there is an error parsing a block, this callback 15570 /// is invoked to pop the information about the block from the action impl. 15571 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15572 // Leave the expression-evaluation context. 15573 DiscardCleanupsInEvaluationContext(); 15574 PopExpressionEvaluationContext(); 15575 15576 // Pop off CurBlock, handle nested blocks. 15577 PopDeclContext(); 15578 PopFunctionScopeInfo(); 15579 } 15580 15581 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15582 /// literal was successfully completed. ^(int x){...} 15583 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15584 Stmt *Body, Scope *CurScope) { 15585 // If blocks are disabled, emit an error. 15586 if (!LangOpts.Blocks) 15587 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15588 15589 // Leave the expression-evaluation context. 15590 if (hasAnyUnrecoverableErrorsInThisFunction()) 15591 DiscardCleanupsInEvaluationContext(); 15592 assert(!Cleanup.exprNeedsCleanups() && 15593 "cleanups within block not correctly bound!"); 15594 PopExpressionEvaluationContext(); 15595 15596 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15597 BlockDecl *BD = BSI->TheDecl; 15598 15599 if (BSI->HasImplicitReturnType) 15600 deduceClosureReturnType(*BSI); 15601 15602 QualType RetTy = Context.VoidTy; 15603 if (!BSI->ReturnType.isNull()) 15604 RetTy = BSI->ReturnType; 15605 15606 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15607 QualType BlockTy; 15608 15609 // If the user wrote a function type in some form, try to use that. 15610 if (!BSI->FunctionType.isNull()) { 15611 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15612 15613 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15614 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15615 15616 // Turn protoless block types into nullary block types. 15617 if (isa<FunctionNoProtoType>(FTy)) { 15618 FunctionProtoType::ExtProtoInfo EPI; 15619 EPI.ExtInfo = Ext; 15620 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15621 15622 // Otherwise, if we don't need to change anything about the function type, 15623 // preserve its sugar structure. 15624 } else if (FTy->getReturnType() == RetTy && 15625 (!NoReturn || FTy->getNoReturnAttr())) { 15626 BlockTy = BSI->FunctionType; 15627 15628 // Otherwise, make the minimal modifications to the function type. 15629 } else { 15630 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15631 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15632 EPI.TypeQuals = Qualifiers(); 15633 EPI.ExtInfo = Ext; 15634 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15635 } 15636 15637 // If we don't have a function type, just build one from nothing. 15638 } else { 15639 FunctionProtoType::ExtProtoInfo EPI; 15640 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15641 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15642 } 15643 15644 DiagnoseUnusedParameters(BD->parameters()); 15645 BlockTy = Context.getBlockPointerType(BlockTy); 15646 15647 // If needed, diagnose invalid gotos and switches in the block. 15648 if (getCurFunction()->NeedsScopeChecking() && 15649 !PP.isCodeCompletionEnabled()) 15650 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15651 15652 BD->setBody(cast<CompoundStmt>(Body)); 15653 15654 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15655 DiagnoseUnguardedAvailabilityViolations(BD); 15656 15657 // Try to apply the named return value optimization. We have to check again 15658 // if we can do this, though, because blocks keep return statements around 15659 // to deduce an implicit return type. 15660 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15661 !BD->isDependentContext()) 15662 computeNRVO(Body, BSI); 15663 15664 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15665 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15666 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15667 NTCUK_Destruct|NTCUK_Copy); 15668 15669 PopDeclContext(); 15670 15671 // Set the captured variables on the block. 15672 SmallVector<BlockDecl::Capture, 4> Captures; 15673 for (Capture &Cap : BSI->Captures) { 15674 if (Cap.isInvalid() || Cap.isThisCapture()) 15675 continue; 15676 15677 VarDecl *Var = Cap.getVariable(); 15678 Expr *CopyExpr = nullptr; 15679 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15680 if (const RecordType *Record = 15681 Cap.getCaptureType()->getAs<RecordType>()) { 15682 // The capture logic needs the destructor, so make sure we mark it. 15683 // Usually this is unnecessary because most local variables have 15684 // their destructors marked at declaration time, but parameters are 15685 // an exception because it's technically only the call site that 15686 // actually requires the destructor. 15687 if (isa<ParmVarDecl>(Var)) 15688 FinalizeVarWithDestructor(Var, Record); 15689 15690 // Enter a separate potentially-evaluated context while building block 15691 // initializers to isolate their cleanups from those of the block 15692 // itself. 15693 // FIXME: Is this appropriate even when the block itself occurs in an 15694 // unevaluated operand? 15695 EnterExpressionEvaluationContext EvalContext( 15696 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15697 15698 SourceLocation Loc = Cap.getLocation(); 15699 15700 ExprResult Result = BuildDeclarationNameExpr( 15701 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15702 15703 // According to the blocks spec, the capture of a variable from 15704 // the stack requires a const copy constructor. This is not true 15705 // of the copy/move done to move a __block variable to the heap. 15706 if (!Result.isInvalid() && 15707 !Result.get()->getType().isConstQualified()) { 15708 Result = ImpCastExprToType(Result.get(), 15709 Result.get()->getType().withConst(), 15710 CK_NoOp, VK_LValue); 15711 } 15712 15713 if (!Result.isInvalid()) { 15714 Result = PerformCopyInitialization( 15715 InitializedEntity::InitializeBlock(Var->getLocation(), 15716 Cap.getCaptureType(), false), 15717 Loc, Result.get()); 15718 } 15719 15720 // Build a full-expression copy expression if initialization 15721 // succeeded and used a non-trivial constructor. Recover from 15722 // errors by pretending that the copy isn't necessary. 15723 if (!Result.isInvalid() && 15724 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15725 ->isTrivial()) { 15726 Result = MaybeCreateExprWithCleanups(Result); 15727 CopyExpr = Result.get(); 15728 } 15729 } 15730 } 15731 15732 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15733 CopyExpr); 15734 Captures.push_back(NewCap); 15735 } 15736 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15737 15738 // Pop the block scope now but keep it alive to the end of this function. 15739 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15740 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15741 15742 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15743 15744 // If the block isn't obviously global, i.e. it captures anything at 15745 // all, then we need to do a few things in the surrounding context: 15746 if (Result->getBlockDecl()->hasCaptures()) { 15747 // First, this expression has a new cleanup object. 15748 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15749 Cleanup.setExprNeedsCleanups(true); 15750 15751 // It also gets a branch-protected scope if any of the captured 15752 // variables needs destruction. 15753 for (const auto &CI : Result->getBlockDecl()->captures()) { 15754 const VarDecl *var = CI.getVariable(); 15755 if (var->getType().isDestructedType() != QualType::DK_none) { 15756 setFunctionHasBranchProtectedScope(); 15757 break; 15758 } 15759 } 15760 } 15761 15762 if (getCurFunction()) 15763 getCurFunction()->addBlock(BD); 15764 15765 return Result; 15766 } 15767 15768 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15769 SourceLocation RPLoc) { 15770 TypeSourceInfo *TInfo; 15771 GetTypeFromParser(Ty, &TInfo); 15772 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15773 } 15774 15775 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15776 Expr *E, TypeSourceInfo *TInfo, 15777 SourceLocation RPLoc) { 15778 Expr *OrigExpr = E; 15779 bool IsMS = false; 15780 15781 // CUDA device code does not support varargs. 15782 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15783 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15784 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15785 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15786 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15787 } 15788 } 15789 15790 // NVPTX does not support va_arg expression. 15791 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15792 Context.getTargetInfo().getTriple().isNVPTX()) 15793 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15794 15795 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15796 // as Microsoft ABI on an actual Microsoft platform, where 15797 // __builtin_ms_va_list and __builtin_va_list are the same.) 15798 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15799 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15800 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15801 if (Context.hasSameType(MSVaListType, E->getType())) { 15802 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15803 return ExprError(); 15804 IsMS = true; 15805 } 15806 } 15807 15808 // Get the va_list type 15809 QualType VaListType = Context.getBuiltinVaListType(); 15810 if (!IsMS) { 15811 if (VaListType->isArrayType()) { 15812 // Deal with implicit array decay; for example, on x86-64, 15813 // va_list is an array, but it's supposed to decay to 15814 // a pointer for va_arg. 15815 VaListType = Context.getArrayDecayedType(VaListType); 15816 // Make sure the input expression also decays appropriately. 15817 ExprResult Result = UsualUnaryConversions(E); 15818 if (Result.isInvalid()) 15819 return ExprError(); 15820 E = Result.get(); 15821 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15822 // If va_list is a record type and we are compiling in C++ mode, 15823 // check the argument using reference binding. 15824 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15825 Context, Context.getLValueReferenceType(VaListType), false); 15826 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15827 if (Init.isInvalid()) 15828 return ExprError(); 15829 E = Init.getAs<Expr>(); 15830 } else { 15831 // Otherwise, the va_list argument must be an l-value because 15832 // it is modified by va_arg. 15833 if (!E->isTypeDependent() && 15834 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15835 return ExprError(); 15836 } 15837 } 15838 15839 if (!IsMS && !E->isTypeDependent() && 15840 !Context.hasSameType(VaListType, E->getType())) 15841 return ExprError( 15842 Diag(E->getBeginLoc(), 15843 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15844 << OrigExpr->getType() << E->getSourceRange()); 15845 15846 if (!TInfo->getType()->isDependentType()) { 15847 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15848 diag::err_second_parameter_to_va_arg_incomplete, 15849 TInfo->getTypeLoc())) 15850 return ExprError(); 15851 15852 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15853 TInfo->getType(), 15854 diag::err_second_parameter_to_va_arg_abstract, 15855 TInfo->getTypeLoc())) 15856 return ExprError(); 15857 15858 if (!TInfo->getType().isPODType(Context)) { 15859 Diag(TInfo->getTypeLoc().getBeginLoc(), 15860 TInfo->getType()->isObjCLifetimeType() 15861 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15862 : diag::warn_second_parameter_to_va_arg_not_pod) 15863 << TInfo->getType() 15864 << TInfo->getTypeLoc().getSourceRange(); 15865 } 15866 15867 // Check for va_arg where arguments of the given type will be promoted 15868 // (i.e. this va_arg is guaranteed to have undefined behavior). 15869 QualType PromoteType; 15870 if (TInfo->getType()->isPromotableIntegerType()) { 15871 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15872 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15873 // and C2x 7.16.1.1p2 says, in part: 15874 // If type is not compatible with the type of the actual next argument 15875 // (as promoted according to the default argument promotions), the 15876 // behavior is undefined, except for the following cases: 15877 // - both types are pointers to qualified or unqualified versions of 15878 // compatible types; 15879 // - one type is a signed integer type, the other type is the 15880 // corresponding unsigned integer type, and the value is 15881 // representable in both types; 15882 // - one type is pointer to qualified or unqualified void and the 15883 // other is a pointer to a qualified or unqualified character type. 15884 // Given that type compatibility is the primary requirement (ignoring 15885 // qualifications), you would think we could call typesAreCompatible() 15886 // directly to test this. However, in C++, that checks for *same type*, 15887 // which causes false positives when passing an enumeration type to 15888 // va_arg. Instead, get the underlying type of the enumeration and pass 15889 // that. 15890 QualType UnderlyingType = TInfo->getType(); 15891 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15892 UnderlyingType = ET->getDecl()->getIntegerType(); 15893 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15894 /*CompareUnqualified*/ true)) 15895 PromoteType = QualType(); 15896 15897 // If the types are still not compatible, we need to test whether the 15898 // promoted type and the underlying type are the same except for 15899 // signedness. Ask the AST for the correctly corresponding type and see 15900 // if that's compatible. 15901 if (!PromoteType.isNull() && 15902 PromoteType->isUnsignedIntegerType() != 15903 UnderlyingType->isUnsignedIntegerType()) { 15904 UnderlyingType = 15905 UnderlyingType->isUnsignedIntegerType() 15906 ? Context.getCorrespondingSignedType(UnderlyingType) 15907 : Context.getCorrespondingUnsignedType(UnderlyingType); 15908 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15909 /*CompareUnqualified*/ true)) 15910 PromoteType = QualType(); 15911 } 15912 } 15913 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15914 PromoteType = Context.DoubleTy; 15915 if (!PromoteType.isNull()) 15916 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15917 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15918 << TInfo->getType() 15919 << PromoteType 15920 << TInfo->getTypeLoc().getSourceRange()); 15921 } 15922 15923 QualType T = TInfo->getType().getNonLValueExprType(Context); 15924 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15925 } 15926 15927 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15928 // The type of __null will be int or long, depending on the size of 15929 // pointers on the target. 15930 QualType Ty; 15931 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15932 if (pw == Context.getTargetInfo().getIntWidth()) 15933 Ty = Context.IntTy; 15934 else if (pw == Context.getTargetInfo().getLongWidth()) 15935 Ty = Context.LongTy; 15936 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15937 Ty = Context.LongLongTy; 15938 else { 15939 llvm_unreachable("I don't know size of pointer!"); 15940 } 15941 15942 return new (Context) GNUNullExpr(Ty, TokenLoc); 15943 } 15944 15945 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15946 SourceLocation BuiltinLoc, 15947 SourceLocation RPLoc) { 15948 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15949 } 15950 15951 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15952 SourceLocation BuiltinLoc, 15953 SourceLocation RPLoc, 15954 DeclContext *ParentContext) { 15955 return new (Context) 15956 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15957 } 15958 15959 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15960 bool Diagnose) { 15961 if (!getLangOpts().ObjC) 15962 return false; 15963 15964 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15965 if (!PT) 15966 return false; 15967 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15968 15969 // Ignore any parens, implicit casts (should only be 15970 // array-to-pointer decays), and not-so-opaque values. The last is 15971 // important for making this trigger for property assignments. 15972 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15973 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15974 if (OV->getSourceExpr()) 15975 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15976 15977 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15978 if (!PT->isObjCIdType() && 15979 !(ID && ID->getIdentifier()->isStr("NSString"))) 15980 return false; 15981 if (!SL->isAscii()) 15982 return false; 15983 15984 if (Diagnose) { 15985 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15986 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15987 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15988 } 15989 return true; 15990 } 15991 15992 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15993 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15994 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15995 !SrcExpr->isNullPointerConstant( 15996 getASTContext(), Expr::NPC_NeverValueDependent)) { 15997 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15998 return false; 15999 if (Diagnose) { 16000 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16001 << /*number*/1 16002 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16003 Expr *NumLit = 16004 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16005 if (NumLit) 16006 Exp = NumLit; 16007 } 16008 return true; 16009 } 16010 16011 return false; 16012 } 16013 16014 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16015 const Expr *SrcExpr) { 16016 if (!DstType->isFunctionPointerType() || 16017 !SrcExpr->getType()->isFunctionType()) 16018 return false; 16019 16020 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16021 if (!DRE) 16022 return false; 16023 16024 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16025 if (!FD) 16026 return false; 16027 16028 return !S.checkAddressOfFunctionIsAvailable(FD, 16029 /*Complain=*/true, 16030 SrcExpr->getBeginLoc()); 16031 } 16032 16033 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16034 SourceLocation Loc, 16035 QualType DstType, QualType SrcType, 16036 Expr *SrcExpr, AssignmentAction Action, 16037 bool *Complained) { 16038 if (Complained) 16039 *Complained = false; 16040 16041 // Decode the result (notice that AST's are still created for extensions). 16042 bool CheckInferredResultType = false; 16043 bool isInvalid = false; 16044 unsigned DiagKind = 0; 16045 ConversionFixItGenerator ConvHints; 16046 bool MayHaveConvFixit = false; 16047 bool MayHaveFunctionDiff = false; 16048 const ObjCInterfaceDecl *IFace = nullptr; 16049 const ObjCProtocolDecl *PDecl = nullptr; 16050 16051 switch (ConvTy) { 16052 case Compatible: 16053 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16054 return false; 16055 16056 case PointerToInt: 16057 if (getLangOpts().CPlusPlus) { 16058 DiagKind = diag::err_typecheck_convert_pointer_int; 16059 isInvalid = true; 16060 } else { 16061 DiagKind = diag::ext_typecheck_convert_pointer_int; 16062 } 16063 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16064 MayHaveConvFixit = true; 16065 break; 16066 case IntToPointer: 16067 if (getLangOpts().CPlusPlus) { 16068 DiagKind = diag::err_typecheck_convert_int_pointer; 16069 isInvalid = true; 16070 } else { 16071 DiagKind = diag::ext_typecheck_convert_int_pointer; 16072 } 16073 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16074 MayHaveConvFixit = true; 16075 break; 16076 case IncompatibleFunctionPointer: 16077 if (getLangOpts().CPlusPlus) { 16078 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16079 isInvalid = true; 16080 } else { 16081 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16082 } 16083 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16084 MayHaveConvFixit = true; 16085 break; 16086 case IncompatiblePointer: 16087 if (Action == AA_Passing_CFAudited) { 16088 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16089 } else if (getLangOpts().CPlusPlus) { 16090 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16091 isInvalid = true; 16092 } else { 16093 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16094 } 16095 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16096 SrcType->isObjCObjectPointerType(); 16097 if (!CheckInferredResultType) { 16098 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16099 } else if (CheckInferredResultType) { 16100 SrcType = SrcType.getUnqualifiedType(); 16101 DstType = DstType.getUnqualifiedType(); 16102 } 16103 MayHaveConvFixit = true; 16104 break; 16105 case IncompatiblePointerSign: 16106 if (getLangOpts().CPlusPlus) { 16107 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16108 isInvalid = true; 16109 } else { 16110 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16111 } 16112 break; 16113 case FunctionVoidPointer: 16114 if (getLangOpts().CPlusPlus) { 16115 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16116 isInvalid = true; 16117 } else { 16118 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16119 } 16120 break; 16121 case IncompatiblePointerDiscardsQualifiers: { 16122 // Perform array-to-pointer decay if necessary. 16123 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16124 16125 isInvalid = true; 16126 16127 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16128 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16129 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16130 DiagKind = diag::err_typecheck_incompatible_address_space; 16131 break; 16132 16133 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16134 DiagKind = diag::err_typecheck_incompatible_ownership; 16135 break; 16136 } 16137 16138 llvm_unreachable("unknown error case for discarding qualifiers!"); 16139 // fallthrough 16140 } 16141 case CompatiblePointerDiscardsQualifiers: 16142 // If the qualifiers lost were because we were applying the 16143 // (deprecated) C++ conversion from a string literal to a char* 16144 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16145 // Ideally, this check would be performed in 16146 // checkPointerTypesForAssignment. However, that would require a 16147 // bit of refactoring (so that the second argument is an 16148 // expression, rather than a type), which should be done as part 16149 // of a larger effort to fix checkPointerTypesForAssignment for 16150 // C++ semantics. 16151 if (getLangOpts().CPlusPlus && 16152 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16153 return false; 16154 if (getLangOpts().CPlusPlus) { 16155 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16156 isInvalid = true; 16157 } else { 16158 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16159 } 16160 16161 break; 16162 case IncompatibleNestedPointerQualifiers: 16163 if (getLangOpts().CPlusPlus) { 16164 isInvalid = true; 16165 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16166 } else { 16167 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16168 } 16169 break; 16170 case IncompatibleNestedPointerAddressSpaceMismatch: 16171 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16172 isInvalid = true; 16173 break; 16174 case IntToBlockPointer: 16175 DiagKind = diag::err_int_to_block_pointer; 16176 isInvalid = true; 16177 break; 16178 case IncompatibleBlockPointer: 16179 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16180 isInvalid = true; 16181 break; 16182 case IncompatibleObjCQualifiedId: { 16183 if (SrcType->isObjCQualifiedIdType()) { 16184 const ObjCObjectPointerType *srcOPT = 16185 SrcType->castAs<ObjCObjectPointerType>(); 16186 for (auto *srcProto : srcOPT->quals()) { 16187 PDecl = srcProto; 16188 break; 16189 } 16190 if (const ObjCInterfaceType *IFaceT = 16191 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16192 IFace = IFaceT->getDecl(); 16193 } 16194 else if (DstType->isObjCQualifiedIdType()) { 16195 const ObjCObjectPointerType *dstOPT = 16196 DstType->castAs<ObjCObjectPointerType>(); 16197 for (auto *dstProto : dstOPT->quals()) { 16198 PDecl = dstProto; 16199 break; 16200 } 16201 if (const ObjCInterfaceType *IFaceT = 16202 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16203 IFace = IFaceT->getDecl(); 16204 } 16205 if (getLangOpts().CPlusPlus) { 16206 DiagKind = diag::err_incompatible_qualified_id; 16207 isInvalid = true; 16208 } else { 16209 DiagKind = diag::warn_incompatible_qualified_id; 16210 } 16211 break; 16212 } 16213 case IncompatibleVectors: 16214 if (getLangOpts().CPlusPlus) { 16215 DiagKind = diag::err_incompatible_vectors; 16216 isInvalid = true; 16217 } else { 16218 DiagKind = diag::warn_incompatible_vectors; 16219 } 16220 break; 16221 case IncompatibleObjCWeakRef: 16222 DiagKind = diag::err_arc_weak_unavailable_assign; 16223 isInvalid = true; 16224 break; 16225 case Incompatible: 16226 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16227 if (Complained) 16228 *Complained = true; 16229 return true; 16230 } 16231 16232 DiagKind = diag::err_typecheck_convert_incompatible; 16233 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16234 MayHaveConvFixit = true; 16235 isInvalid = true; 16236 MayHaveFunctionDiff = true; 16237 break; 16238 } 16239 16240 QualType FirstType, SecondType; 16241 switch (Action) { 16242 case AA_Assigning: 16243 case AA_Initializing: 16244 // The destination type comes first. 16245 FirstType = DstType; 16246 SecondType = SrcType; 16247 break; 16248 16249 case AA_Returning: 16250 case AA_Passing: 16251 case AA_Passing_CFAudited: 16252 case AA_Converting: 16253 case AA_Sending: 16254 case AA_Casting: 16255 // The source type comes first. 16256 FirstType = SrcType; 16257 SecondType = DstType; 16258 break; 16259 } 16260 16261 PartialDiagnostic FDiag = PDiag(DiagKind); 16262 if (Action == AA_Passing_CFAudited) 16263 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16264 else 16265 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16266 16267 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16268 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16269 auto isPlainChar = [](const clang::Type *Type) { 16270 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16271 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16272 }; 16273 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16274 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16275 } 16276 16277 // If we can fix the conversion, suggest the FixIts. 16278 if (!ConvHints.isNull()) { 16279 for (FixItHint &H : ConvHints.Hints) 16280 FDiag << H; 16281 } 16282 16283 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16284 16285 if (MayHaveFunctionDiff) 16286 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16287 16288 Diag(Loc, FDiag); 16289 if ((DiagKind == diag::warn_incompatible_qualified_id || 16290 DiagKind == diag::err_incompatible_qualified_id) && 16291 PDecl && IFace && !IFace->hasDefinition()) 16292 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16293 << IFace << PDecl; 16294 16295 if (SecondType == Context.OverloadTy) 16296 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16297 FirstType, /*TakingAddress=*/true); 16298 16299 if (CheckInferredResultType) 16300 EmitRelatedResultTypeNote(SrcExpr); 16301 16302 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16303 EmitRelatedResultTypeNoteForReturn(DstType); 16304 16305 if (Complained) 16306 *Complained = true; 16307 return isInvalid; 16308 } 16309 16310 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16311 llvm::APSInt *Result, 16312 AllowFoldKind CanFold) { 16313 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16314 public: 16315 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16316 QualType T) override { 16317 return S.Diag(Loc, diag::err_ice_not_integral) 16318 << T << S.LangOpts.CPlusPlus; 16319 } 16320 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16321 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16322 } 16323 } Diagnoser; 16324 16325 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16326 } 16327 16328 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16329 llvm::APSInt *Result, 16330 unsigned DiagID, 16331 AllowFoldKind CanFold) { 16332 class IDDiagnoser : public VerifyICEDiagnoser { 16333 unsigned DiagID; 16334 16335 public: 16336 IDDiagnoser(unsigned DiagID) 16337 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16338 16339 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16340 return S.Diag(Loc, DiagID); 16341 } 16342 } Diagnoser(DiagID); 16343 16344 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16345 } 16346 16347 Sema::SemaDiagnosticBuilder 16348 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16349 QualType T) { 16350 return diagnoseNotICE(S, Loc); 16351 } 16352 16353 Sema::SemaDiagnosticBuilder 16354 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16355 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16356 } 16357 16358 ExprResult 16359 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16360 VerifyICEDiagnoser &Diagnoser, 16361 AllowFoldKind CanFold) { 16362 SourceLocation DiagLoc = E->getBeginLoc(); 16363 16364 if (getLangOpts().CPlusPlus11) { 16365 // C++11 [expr.const]p5: 16366 // If an expression of literal class type is used in a context where an 16367 // integral constant expression is required, then that class type shall 16368 // have a single non-explicit conversion function to an integral or 16369 // unscoped enumeration type 16370 ExprResult Converted; 16371 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16372 VerifyICEDiagnoser &BaseDiagnoser; 16373 public: 16374 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16375 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16376 BaseDiagnoser.Suppress, true), 16377 BaseDiagnoser(BaseDiagnoser) {} 16378 16379 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16380 QualType T) override { 16381 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16382 } 16383 16384 SemaDiagnosticBuilder diagnoseIncomplete( 16385 Sema &S, SourceLocation Loc, QualType T) override { 16386 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16387 } 16388 16389 SemaDiagnosticBuilder diagnoseExplicitConv( 16390 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16391 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16392 } 16393 16394 SemaDiagnosticBuilder noteExplicitConv( 16395 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16396 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16397 << ConvTy->isEnumeralType() << ConvTy; 16398 } 16399 16400 SemaDiagnosticBuilder diagnoseAmbiguous( 16401 Sema &S, SourceLocation Loc, QualType T) override { 16402 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16403 } 16404 16405 SemaDiagnosticBuilder noteAmbiguous( 16406 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16407 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16408 << ConvTy->isEnumeralType() << ConvTy; 16409 } 16410 16411 SemaDiagnosticBuilder diagnoseConversion( 16412 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16413 llvm_unreachable("conversion functions are permitted"); 16414 } 16415 } ConvertDiagnoser(Diagnoser); 16416 16417 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16418 ConvertDiagnoser); 16419 if (Converted.isInvalid()) 16420 return Converted; 16421 E = Converted.get(); 16422 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16423 return ExprError(); 16424 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16425 // An ICE must be of integral or unscoped enumeration type. 16426 if (!Diagnoser.Suppress) 16427 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16428 << E->getSourceRange(); 16429 return ExprError(); 16430 } 16431 16432 ExprResult RValueExpr = DefaultLvalueConversion(E); 16433 if (RValueExpr.isInvalid()) 16434 return ExprError(); 16435 16436 E = RValueExpr.get(); 16437 16438 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16439 // in the non-ICE case. 16440 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16441 if (Result) 16442 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16443 if (!isa<ConstantExpr>(E)) 16444 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16445 : ConstantExpr::Create(Context, E); 16446 return E; 16447 } 16448 16449 Expr::EvalResult EvalResult; 16450 SmallVector<PartialDiagnosticAt, 8> Notes; 16451 EvalResult.Diag = &Notes; 16452 16453 // Try to evaluate the expression, and produce diagnostics explaining why it's 16454 // not a constant expression as a side-effect. 16455 bool Folded = 16456 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16457 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16458 16459 if (!isa<ConstantExpr>(E)) 16460 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16461 16462 // In C++11, we can rely on diagnostics being produced for any expression 16463 // which is not a constant expression. If no diagnostics were produced, then 16464 // this is a constant expression. 16465 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16466 if (Result) 16467 *Result = EvalResult.Val.getInt(); 16468 return E; 16469 } 16470 16471 // If our only note is the usual "invalid subexpression" note, just point 16472 // the caret at its location rather than producing an essentially 16473 // redundant note. 16474 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16475 diag::note_invalid_subexpr_in_const_expr) { 16476 DiagLoc = Notes[0].first; 16477 Notes.clear(); 16478 } 16479 16480 if (!Folded || !CanFold) { 16481 if (!Diagnoser.Suppress) { 16482 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16483 for (const PartialDiagnosticAt &Note : Notes) 16484 Diag(Note.first, Note.second); 16485 } 16486 16487 return ExprError(); 16488 } 16489 16490 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16491 for (const PartialDiagnosticAt &Note : Notes) 16492 Diag(Note.first, Note.second); 16493 16494 if (Result) 16495 *Result = EvalResult.Val.getInt(); 16496 return E; 16497 } 16498 16499 namespace { 16500 // Handle the case where we conclude a expression which we speculatively 16501 // considered to be unevaluated is actually evaluated. 16502 class TransformToPE : public TreeTransform<TransformToPE> { 16503 typedef TreeTransform<TransformToPE> BaseTransform; 16504 16505 public: 16506 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16507 16508 // Make sure we redo semantic analysis 16509 bool AlwaysRebuild() { return true; } 16510 bool ReplacingOriginal() { return true; } 16511 16512 // We need to special-case DeclRefExprs referring to FieldDecls which 16513 // are not part of a member pointer formation; normal TreeTransforming 16514 // doesn't catch this case because of the way we represent them in the AST. 16515 // FIXME: This is a bit ugly; is it really the best way to handle this 16516 // case? 16517 // 16518 // Error on DeclRefExprs referring to FieldDecls. 16519 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16520 if (isa<FieldDecl>(E->getDecl()) && 16521 !SemaRef.isUnevaluatedContext()) 16522 return SemaRef.Diag(E->getLocation(), 16523 diag::err_invalid_non_static_member_use) 16524 << E->getDecl() << E->getSourceRange(); 16525 16526 return BaseTransform::TransformDeclRefExpr(E); 16527 } 16528 16529 // Exception: filter out member pointer formation 16530 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16531 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16532 return E; 16533 16534 return BaseTransform::TransformUnaryOperator(E); 16535 } 16536 16537 // The body of a lambda-expression is in a separate expression evaluation 16538 // context so never needs to be transformed. 16539 // FIXME: Ideally we wouldn't transform the closure type either, and would 16540 // just recreate the capture expressions and lambda expression. 16541 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16542 return SkipLambdaBody(E, Body); 16543 } 16544 }; 16545 } 16546 16547 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16548 assert(isUnevaluatedContext() && 16549 "Should only transform unevaluated expressions"); 16550 ExprEvalContexts.back().Context = 16551 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16552 if (isUnevaluatedContext()) 16553 return E; 16554 return TransformToPE(*this).TransformExpr(E); 16555 } 16556 16557 void 16558 Sema::PushExpressionEvaluationContext( 16559 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16560 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16561 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16562 LambdaContextDecl, ExprContext); 16563 Cleanup.reset(); 16564 if (!MaybeODRUseExprs.empty()) 16565 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16566 } 16567 16568 void 16569 Sema::PushExpressionEvaluationContext( 16570 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16571 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16572 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16573 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16574 } 16575 16576 namespace { 16577 16578 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16579 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16580 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16581 if (E->getOpcode() == UO_Deref) 16582 return CheckPossibleDeref(S, E->getSubExpr()); 16583 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16584 return CheckPossibleDeref(S, E->getBase()); 16585 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16586 return CheckPossibleDeref(S, E->getBase()); 16587 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16588 QualType Inner; 16589 QualType Ty = E->getType(); 16590 if (const auto *Ptr = Ty->getAs<PointerType>()) 16591 Inner = Ptr->getPointeeType(); 16592 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16593 Inner = Arr->getElementType(); 16594 else 16595 return nullptr; 16596 16597 if (Inner->hasAttr(attr::NoDeref)) 16598 return E; 16599 } 16600 return nullptr; 16601 } 16602 16603 } // namespace 16604 16605 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16606 for (const Expr *E : Rec.PossibleDerefs) { 16607 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16608 if (DeclRef) { 16609 const ValueDecl *Decl = DeclRef->getDecl(); 16610 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16611 << Decl->getName() << E->getSourceRange(); 16612 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16613 } else { 16614 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16615 << E->getSourceRange(); 16616 } 16617 } 16618 Rec.PossibleDerefs.clear(); 16619 } 16620 16621 /// Check whether E, which is either a discarded-value expression or an 16622 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16623 /// and if so, remove it from the list of volatile-qualified assignments that 16624 /// we are going to warn are deprecated. 16625 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16626 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16627 return; 16628 16629 // Note: ignoring parens here is not justified by the standard rules, but 16630 // ignoring parentheses seems like a more reasonable approach, and this only 16631 // drives a deprecation warning so doesn't affect conformance. 16632 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16633 if (BO->getOpcode() == BO_Assign) { 16634 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16635 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16636 LHSs.end()); 16637 } 16638 } 16639 } 16640 16641 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16642 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16643 !Decl->isConsteval() || isConstantEvaluated() || 16644 RebuildingImmediateInvocation) 16645 return E; 16646 16647 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16648 /// It's OK if this fails; we'll also remove this in 16649 /// HandleImmediateInvocations, but catching it here allows us to avoid 16650 /// walking the AST looking for it in simple cases. 16651 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16652 if (auto *DeclRef = 16653 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16654 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16655 16656 E = MaybeCreateExprWithCleanups(E); 16657 16658 ConstantExpr *Res = ConstantExpr::Create( 16659 getASTContext(), E.get(), 16660 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16661 getASTContext()), 16662 /*IsImmediateInvocation*/ true); 16663 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16664 return Res; 16665 } 16666 16667 static void EvaluateAndDiagnoseImmediateInvocation( 16668 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16669 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16670 Expr::EvalResult Eval; 16671 Eval.Diag = &Notes; 16672 ConstantExpr *CE = Candidate.getPointer(); 16673 bool Result = CE->EvaluateAsConstantExpr( 16674 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16675 if (!Result || !Notes.empty()) { 16676 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16677 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16678 InnerExpr = FunctionalCast->getSubExpr(); 16679 FunctionDecl *FD = nullptr; 16680 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16681 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16682 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16683 FD = Call->getConstructor(); 16684 else 16685 llvm_unreachable("unhandled decl kind"); 16686 assert(FD->isConsteval()); 16687 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16688 for (auto &Note : Notes) 16689 SemaRef.Diag(Note.first, Note.second); 16690 return; 16691 } 16692 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16693 } 16694 16695 static void RemoveNestedImmediateInvocation( 16696 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16697 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16698 struct ComplexRemove : TreeTransform<ComplexRemove> { 16699 using Base = TreeTransform<ComplexRemove>; 16700 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16701 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16702 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16703 CurrentII; 16704 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16705 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16706 SmallVector<Sema::ImmediateInvocationCandidate, 16707 4>::reverse_iterator Current) 16708 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16709 void RemoveImmediateInvocation(ConstantExpr* E) { 16710 auto It = std::find_if(CurrentII, IISet.rend(), 16711 [E](Sema::ImmediateInvocationCandidate Elem) { 16712 return Elem.getPointer() == E; 16713 }); 16714 assert(It != IISet.rend() && 16715 "ConstantExpr marked IsImmediateInvocation should " 16716 "be present"); 16717 It->setInt(1); // Mark as deleted 16718 } 16719 ExprResult TransformConstantExpr(ConstantExpr *E) { 16720 if (!E->isImmediateInvocation()) 16721 return Base::TransformConstantExpr(E); 16722 RemoveImmediateInvocation(E); 16723 return Base::TransformExpr(E->getSubExpr()); 16724 } 16725 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16726 /// we need to remove its DeclRefExpr from the DRSet. 16727 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16728 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16729 return Base::TransformCXXOperatorCallExpr(E); 16730 } 16731 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16732 /// here. 16733 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16734 if (!Init) 16735 return Init; 16736 /// ConstantExpr are the first layer of implicit node to be removed so if 16737 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16738 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16739 if (CE->isImmediateInvocation()) 16740 RemoveImmediateInvocation(CE); 16741 return Base::TransformInitializer(Init, NotCopyInit); 16742 } 16743 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16744 DRSet.erase(E); 16745 return E; 16746 } 16747 bool AlwaysRebuild() { return false; } 16748 bool ReplacingOriginal() { return true; } 16749 bool AllowSkippingCXXConstructExpr() { 16750 bool Res = AllowSkippingFirstCXXConstructExpr; 16751 AllowSkippingFirstCXXConstructExpr = true; 16752 return Res; 16753 } 16754 bool AllowSkippingFirstCXXConstructExpr = true; 16755 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16756 Rec.ImmediateInvocationCandidates, It); 16757 16758 /// CXXConstructExpr with a single argument are getting skipped by 16759 /// TreeTransform in some situtation because they could be implicit. This 16760 /// can only occur for the top-level CXXConstructExpr because it is used 16761 /// nowhere in the expression being transformed therefore will not be rebuilt. 16762 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16763 /// skipping the first CXXConstructExpr. 16764 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16765 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16766 16767 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16768 assert(Res.isUsable()); 16769 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16770 It->getPointer()->setSubExpr(Res.get()); 16771 } 16772 16773 static void 16774 HandleImmediateInvocations(Sema &SemaRef, 16775 Sema::ExpressionEvaluationContextRecord &Rec) { 16776 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16777 Rec.ReferenceToConsteval.size() == 0) || 16778 SemaRef.RebuildingImmediateInvocation) 16779 return; 16780 16781 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16782 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16783 /// need to remove ReferenceToConsteval in the immediate invocation. 16784 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16785 16786 /// Prevent sema calls during the tree transform from adding pointers that 16787 /// are already in the sets. 16788 llvm::SaveAndRestore<bool> DisableIITracking( 16789 SemaRef.RebuildingImmediateInvocation, true); 16790 16791 /// Prevent diagnostic during tree transfrom as they are duplicates 16792 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16793 16794 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16795 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16796 if (!It->getInt()) 16797 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16798 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16799 Rec.ReferenceToConsteval.size()) { 16800 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16801 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16802 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16803 bool VisitDeclRefExpr(DeclRefExpr *E) { 16804 DRSet.erase(E); 16805 return DRSet.size(); 16806 } 16807 } Visitor(Rec.ReferenceToConsteval); 16808 Visitor.TraverseStmt( 16809 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16810 } 16811 for (auto CE : Rec.ImmediateInvocationCandidates) 16812 if (!CE.getInt()) 16813 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16814 for (auto DR : Rec.ReferenceToConsteval) { 16815 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16816 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16817 << FD; 16818 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16819 } 16820 } 16821 16822 void Sema::PopExpressionEvaluationContext() { 16823 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16824 unsigned NumTypos = Rec.NumTypos; 16825 16826 if (!Rec.Lambdas.empty()) { 16827 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16828 if (!getLangOpts().CPlusPlus20 && 16829 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16830 Rec.isUnevaluated() || 16831 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16832 unsigned D; 16833 if (Rec.isUnevaluated()) { 16834 // C++11 [expr.prim.lambda]p2: 16835 // A lambda-expression shall not appear in an unevaluated operand 16836 // (Clause 5). 16837 D = diag::err_lambda_unevaluated_operand; 16838 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16839 // C++1y [expr.const]p2: 16840 // A conditional-expression e is a core constant expression unless the 16841 // evaluation of e, following the rules of the abstract machine, would 16842 // evaluate [...] a lambda-expression. 16843 D = diag::err_lambda_in_constant_expression; 16844 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16845 // C++17 [expr.prim.lamda]p2: 16846 // A lambda-expression shall not appear [...] in a template-argument. 16847 D = diag::err_lambda_in_invalid_context; 16848 } else 16849 llvm_unreachable("Couldn't infer lambda error message."); 16850 16851 for (const auto *L : Rec.Lambdas) 16852 Diag(L->getBeginLoc(), D); 16853 } 16854 } 16855 16856 WarnOnPendingNoDerefs(Rec); 16857 HandleImmediateInvocations(*this, Rec); 16858 16859 // Warn on any volatile-qualified simple-assignments that are not discarded- 16860 // value expressions nor unevaluated operands (those cases get removed from 16861 // this list by CheckUnusedVolatileAssignment). 16862 for (auto *BO : Rec.VolatileAssignmentLHSs) 16863 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16864 << BO->getType(); 16865 16866 // When are coming out of an unevaluated context, clear out any 16867 // temporaries that we may have created as part of the evaluation of 16868 // the expression in that context: they aren't relevant because they 16869 // will never be constructed. 16870 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16871 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16872 ExprCleanupObjects.end()); 16873 Cleanup = Rec.ParentCleanup; 16874 CleanupVarDeclMarking(); 16875 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16876 // Otherwise, merge the contexts together. 16877 } else { 16878 Cleanup.mergeFrom(Rec.ParentCleanup); 16879 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16880 Rec.SavedMaybeODRUseExprs.end()); 16881 } 16882 16883 // Pop the current expression evaluation context off the stack. 16884 ExprEvalContexts.pop_back(); 16885 16886 // The global expression evaluation context record is never popped. 16887 ExprEvalContexts.back().NumTypos += NumTypos; 16888 } 16889 16890 void Sema::DiscardCleanupsInEvaluationContext() { 16891 ExprCleanupObjects.erase( 16892 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16893 ExprCleanupObjects.end()); 16894 Cleanup.reset(); 16895 MaybeODRUseExprs.clear(); 16896 } 16897 16898 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16899 ExprResult Result = CheckPlaceholderExpr(E); 16900 if (Result.isInvalid()) 16901 return ExprError(); 16902 E = Result.get(); 16903 if (!E->getType()->isVariablyModifiedType()) 16904 return E; 16905 return TransformToPotentiallyEvaluated(E); 16906 } 16907 16908 /// Are we in a context that is potentially constant evaluated per C++20 16909 /// [expr.const]p12? 16910 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16911 /// C++2a [expr.const]p12: 16912 // An expression or conversion is potentially constant evaluated if it is 16913 switch (SemaRef.ExprEvalContexts.back().Context) { 16914 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16915 // -- a manifestly constant-evaluated expression, 16916 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16917 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16918 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16919 // -- a potentially-evaluated expression, 16920 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16921 // -- an immediate subexpression of a braced-init-list, 16922 16923 // -- [FIXME] an expression of the form & cast-expression that occurs 16924 // within a templated entity 16925 // -- a subexpression of one of the above that is not a subexpression of 16926 // a nested unevaluated operand. 16927 return true; 16928 16929 case Sema::ExpressionEvaluationContext::Unevaluated: 16930 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16931 // Expressions in this context are never evaluated. 16932 return false; 16933 } 16934 llvm_unreachable("Invalid context"); 16935 } 16936 16937 /// Return true if this function has a calling convention that requires mangling 16938 /// in the size of the parameter pack. 16939 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16940 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16941 // we don't need parameter type sizes. 16942 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16943 if (!TT.isOSWindows() || !TT.isX86()) 16944 return false; 16945 16946 // If this is C++ and this isn't an extern "C" function, parameters do not 16947 // need to be complete. In this case, C++ mangling will apply, which doesn't 16948 // use the size of the parameters. 16949 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16950 return false; 16951 16952 // Stdcall, fastcall, and vectorcall need this special treatment. 16953 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16954 switch (CC) { 16955 case CC_X86StdCall: 16956 case CC_X86FastCall: 16957 case CC_X86VectorCall: 16958 return true; 16959 default: 16960 break; 16961 } 16962 return false; 16963 } 16964 16965 /// Require that all of the parameter types of function be complete. Normally, 16966 /// parameter types are only required to be complete when a function is called 16967 /// or defined, but to mangle functions with certain calling conventions, the 16968 /// mangler needs to know the size of the parameter list. In this situation, 16969 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16970 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16971 /// result in a linker error. Clang doesn't implement this behavior, and instead 16972 /// attempts to error at compile time. 16973 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16974 SourceLocation Loc) { 16975 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16976 FunctionDecl *FD; 16977 ParmVarDecl *Param; 16978 16979 public: 16980 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16981 : FD(FD), Param(Param) {} 16982 16983 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16984 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16985 StringRef CCName; 16986 switch (CC) { 16987 case CC_X86StdCall: 16988 CCName = "stdcall"; 16989 break; 16990 case CC_X86FastCall: 16991 CCName = "fastcall"; 16992 break; 16993 case CC_X86VectorCall: 16994 CCName = "vectorcall"; 16995 break; 16996 default: 16997 llvm_unreachable("CC does not need mangling"); 16998 } 16999 17000 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17001 << Param->getDeclName() << FD->getDeclName() << CCName; 17002 } 17003 }; 17004 17005 for (ParmVarDecl *Param : FD->parameters()) { 17006 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17007 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17008 } 17009 } 17010 17011 namespace { 17012 enum class OdrUseContext { 17013 /// Declarations in this context are not odr-used. 17014 None, 17015 /// Declarations in this context are formally odr-used, but this is a 17016 /// dependent context. 17017 Dependent, 17018 /// Declarations in this context are odr-used but not actually used (yet). 17019 FormallyOdrUsed, 17020 /// Declarations in this context are used. 17021 Used 17022 }; 17023 } 17024 17025 /// Are we within a context in which references to resolved functions or to 17026 /// variables result in odr-use? 17027 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17028 OdrUseContext Result; 17029 17030 switch (SemaRef.ExprEvalContexts.back().Context) { 17031 case Sema::ExpressionEvaluationContext::Unevaluated: 17032 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17033 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17034 return OdrUseContext::None; 17035 17036 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17037 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17038 Result = OdrUseContext::Used; 17039 break; 17040 17041 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17042 Result = OdrUseContext::FormallyOdrUsed; 17043 break; 17044 17045 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17046 // A default argument formally results in odr-use, but doesn't actually 17047 // result in a use in any real sense until it itself is used. 17048 Result = OdrUseContext::FormallyOdrUsed; 17049 break; 17050 } 17051 17052 if (SemaRef.CurContext->isDependentContext()) 17053 return OdrUseContext::Dependent; 17054 17055 return Result; 17056 } 17057 17058 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17059 if (!Func->isConstexpr()) 17060 return false; 17061 17062 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17063 return true; 17064 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17065 return CCD && CCD->getInheritedConstructor(); 17066 } 17067 17068 /// Mark a function referenced, and check whether it is odr-used 17069 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17070 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17071 bool MightBeOdrUse) { 17072 assert(Func && "No function?"); 17073 17074 Func->setReferenced(); 17075 17076 // Recursive functions aren't really used until they're used from some other 17077 // context. 17078 bool IsRecursiveCall = CurContext == Func; 17079 17080 // C++11 [basic.def.odr]p3: 17081 // A function whose name appears as a potentially-evaluated expression is 17082 // odr-used if it is the unique lookup result or the selected member of a 17083 // set of overloaded functions [...]. 17084 // 17085 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17086 // can just check that here. 17087 OdrUseContext OdrUse = 17088 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17089 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17090 OdrUse = OdrUseContext::FormallyOdrUsed; 17091 17092 // Trivial default constructors and destructors are never actually used. 17093 // FIXME: What about other special members? 17094 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17095 OdrUse == OdrUseContext::Used) { 17096 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17097 if (Constructor->isDefaultConstructor()) 17098 OdrUse = OdrUseContext::FormallyOdrUsed; 17099 if (isa<CXXDestructorDecl>(Func)) 17100 OdrUse = OdrUseContext::FormallyOdrUsed; 17101 } 17102 17103 // C++20 [expr.const]p12: 17104 // A function [...] is needed for constant evaluation if it is [...] a 17105 // constexpr function that is named by an expression that is potentially 17106 // constant evaluated 17107 bool NeededForConstantEvaluation = 17108 isPotentiallyConstantEvaluatedContext(*this) && 17109 isImplicitlyDefinableConstexprFunction(Func); 17110 17111 // Determine whether we require a function definition to exist, per 17112 // C++11 [temp.inst]p3: 17113 // Unless a function template specialization has been explicitly 17114 // instantiated or explicitly specialized, the function template 17115 // specialization is implicitly instantiated when the specialization is 17116 // referenced in a context that requires a function definition to exist. 17117 // C++20 [temp.inst]p7: 17118 // The existence of a definition of a [...] function is considered to 17119 // affect the semantics of the program if the [...] function is needed for 17120 // constant evaluation by an expression 17121 // C++20 [basic.def.odr]p10: 17122 // Every program shall contain exactly one definition of every non-inline 17123 // function or variable that is odr-used in that program outside of a 17124 // discarded statement 17125 // C++20 [special]p1: 17126 // The implementation will implicitly define [defaulted special members] 17127 // if they are odr-used or needed for constant evaluation. 17128 // 17129 // Note that we skip the implicit instantiation of templates that are only 17130 // used in unused default arguments or by recursive calls to themselves. 17131 // This is formally non-conforming, but seems reasonable in practice. 17132 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17133 NeededForConstantEvaluation); 17134 17135 // C++14 [temp.expl.spec]p6: 17136 // If a template [...] is explicitly specialized then that specialization 17137 // shall be declared before the first use of that specialization that would 17138 // cause an implicit instantiation to take place, in every translation unit 17139 // in which such a use occurs 17140 if (NeedDefinition && 17141 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17142 Func->getMemberSpecializationInfo())) 17143 checkSpecializationVisibility(Loc, Func); 17144 17145 if (getLangOpts().CUDA) 17146 CheckCUDACall(Loc, Func); 17147 17148 if (getLangOpts().SYCLIsDevice) 17149 checkSYCLDeviceFunction(Loc, Func); 17150 17151 // If we need a definition, try to create one. 17152 if (NeedDefinition && !Func->getBody()) { 17153 runWithSufficientStackSpace(Loc, [&] { 17154 if (CXXConstructorDecl *Constructor = 17155 dyn_cast<CXXConstructorDecl>(Func)) { 17156 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17157 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17158 if (Constructor->isDefaultConstructor()) { 17159 if (Constructor->isTrivial() && 17160 !Constructor->hasAttr<DLLExportAttr>()) 17161 return; 17162 DefineImplicitDefaultConstructor(Loc, Constructor); 17163 } else if (Constructor->isCopyConstructor()) { 17164 DefineImplicitCopyConstructor(Loc, Constructor); 17165 } else if (Constructor->isMoveConstructor()) { 17166 DefineImplicitMoveConstructor(Loc, Constructor); 17167 } 17168 } else if (Constructor->getInheritedConstructor()) { 17169 DefineInheritingConstructor(Loc, Constructor); 17170 } 17171 } else if (CXXDestructorDecl *Destructor = 17172 dyn_cast<CXXDestructorDecl>(Func)) { 17173 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17174 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17175 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17176 return; 17177 DefineImplicitDestructor(Loc, Destructor); 17178 } 17179 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17180 MarkVTableUsed(Loc, Destructor->getParent()); 17181 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17182 if (MethodDecl->isOverloadedOperator() && 17183 MethodDecl->getOverloadedOperator() == OO_Equal) { 17184 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17185 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17186 if (MethodDecl->isCopyAssignmentOperator()) 17187 DefineImplicitCopyAssignment(Loc, MethodDecl); 17188 else if (MethodDecl->isMoveAssignmentOperator()) 17189 DefineImplicitMoveAssignment(Loc, MethodDecl); 17190 } 17191 } else if (isa<CXXConversionDecl>(MethodDecl) && 17192 MethodDecl->getParent()->isLambda()) { 17193 CXXConversionDecl *Conversion = 17194 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17195 if (Conversion->isLambdaToBlockPointerConversion()) 17196 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17197 else 17198 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17199 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17200 MarkVTableUsed(Loc, MethodDecl->getParent()); 17201 } 17202 17203 if (Func->isDefaulted() && !Func->isDeleted()) { 17204 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17205 if (DCK != DefaultedComparisonKind::None) 17206 DefineDefaultedComparison(Loc, Func, DCK); 17207 } 17208 17209 // Implicit instantiation of function templates and member functions of 17210 // class templates. 17211 if (Func->isImplicitlyInstantiable()) { 17212 TemplateSpecializationKind TSK = 17213 Func->getTemplateSpecializationKindForInstantiation(); 17214 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17215 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17216 if (FirstInstantiation) { 17217 PointOfInstantiation = Loc; 17218 if (auto *MSI = Func->getMemberSpecializationInfo()) 17219 MSI->setPointOfInstantiation(Loc); 17220 // FIXME: Notify listener. 17221 else 17222 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17223 } else if (TSK != TSK_ImplicitInstantiation) { 17224 // Use the point of use as the point of instantiation, instead of the 17225 // point of explicit instantiation (which we track as the actual point 17226 // of instantiation). This gives better backtraces in diagnostics. 17227 PointOfInstantiation = Loc; 17228 } 17229 17230 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17231 Func->isConstexpr()) { 17232 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17233 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17234 CodeSynthesisContexts.size()) 17235 PendingLocalImplicitInstantiations.push_back( 17236 std::make_pair(Func, PointOfInstantiation)); 17237 else if (Func->isConstexpr()) 17238 // Do not defer instantiations of constexpr functions, to avoid the 17239 // expression evaluator needing to call back into Sema if it sees a 17240 // call to such a function. 17241 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17242 else { 17243 Func->setInstantiationIsPending(true); 17244 PendingInstantiations.push_back( 17245 std::make_pair(Func, PointOfInstantiation)); 17246 // Notify the consumer that a function was implicitly instantiated. 17247 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17248 } 17249 } 17250 } else { 17251 // Walk redefinitions, as some of them may be instantiable. 17252 for (auto i : Func->redecls()) { 17253 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17254 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17255 } 17256 } 17257 }); 17258 } 17259 17260 // C++14 [except.spec]p17: 17261 // An exception-specification is considered to be needed when: 17262 // - the function is odr-used or, if it appears in an unevaluated operand, 17263 // would be odr-used if the expression were potentially-evaluated; 17264 // 17265 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17266 // function is a pure virtual function we're calling, and in that case the 17267 // function was selected by overload resolution and we need to resolve its 17268 // exception specification for a different reason. 17269 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17270 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17271 ResolveExceptionSpec(Loc, FPT); 17272 17273 // If this is the first "real" use, act on that. 17274 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17275 // Keep track of used but undefined functions. 17276 if (!Func->isDefined()) { 17277 if (mightHaveNonExternalLinkage(Func)) 17278 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17279 else if (Func->getMostRecentDecl()->isInlined() && 17280 !LangOpts.GNUInline && 17281 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17282 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17283 else if (isExternalWithNoLinkageType(Func)) 17284 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17285 } 17286 17287 // Some x86 Windows calling conventions mangle the size of the parameter 17288 // pack into the name. Computing the size of the parameters requires the 17289 // parameter types to be complete. Check that now. 17290 if (funcHasParameterSizeMangling(*this, Func)) 17291 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17292 17293 // In the MS C++ ABI, the compiler emits destructor variants where they are 17294 // used. If the destructor is used here but defined elsewhere, mark the 17295 // virtual base destructors referenced. If those virtual base destructors 17296 // are inline, this will ensure they are defined when emitting the complete 17297 // destructor variant. This checking may be redundant if the destructor is 17298 // provided later in this TU. 17299 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17300 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17301 CXXRecordDecl *Parent = Dtor->getParent(); 17302 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17303 CheckCompleteDestructorVariant(Loc, Dtor); 17304 } 17305 } 17306 17307 Func->markUsed(Context); 17308 } 17309 } 17310 17311 /// Directly mark a variable odr-used. Given a choice, prefer to use 17312 /// MarkVariableReferenced since it does additional checks and then 17313 /// calls MarkVarDeclODRUsed. 17314 /// If the variable must be captured: 17315 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17316 /// - else capture it in the DeclContext that maps to the 17317 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17318 static void 17319 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17320 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17321 // Keep track of used but undefined variables. 17322 // FIXME: We shouldn't suppress this warning for static data members. 17323 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17324 (!Var->isExternallyVisible() || Var->isInline() || 17325 SemaRef.isExternalWithNoLinkageType(Var)) && 17326 !(Var->isStaticDataMember() && Var->hasInit())) { 17327 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17328 if (old.isInvalid()) 17329 old = Loc; 17330 } 17331 QualType CaptureType, DeclRefType; 17332 if (SemaRef.LangOpts.OpenMP) 17333 SemaRef.tryCaptureOpenMPLambdas(Var); 17334 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17335 /*EllipsisLoc*/ SourceLocation(), 17336 /*BuildAndDiagnose*/ true, 17337 CaptureType, DeclRefType, 17338 FunctionScopeIndexToStopAt); 17339 17340 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17341 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17342 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17343 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17344 if (VarTarget == Sema::CVT_Host && 17345 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17346 UserTarget == Sema::CFT_Global)) { 17347 // Diagnose ODR-use of host global variables in device functions. 17348 // Reference of device global variables in host functions is allowed 17349 // through shadow variables therefore it is not diagnosed. 17350 if (SemaRef.LangOpts.CUDAIsDevice) { 17351 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17352 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17353 SemaRef.targetDiag(Var->getLocation(), 17354 Var->getType().isConstQualified() 17355 ? diag::note_cuda_const_var_unpromoted 17356 : diag::note_cuda_host_var); 17357 } 17358 } else if (VarTarget == Sema::CVT_Device && 17359 (UserTarget == Sema::CFT_Host || 17360 UserTarget == Sema::CFT_HostDevice) && 17361 !Var->hasExternalStorage()) { 17362 // Record a CUDA/HIP device side variable if it is ODR-used 17363 // by host code. This is done conservatively, when the variable is 17364 // referenced in any of the following contexts: 17365 // - a non-function context 17366 // - a host function 17367 // - a host device function 17368 // This makes the ODR-use of the device side variable by host code to 17369 // be visible in the device compilation for the compiler to be able to 17370 // emit template variables instantiated by host code only and to 17371 // externalize the static device side variable ODR-used by host code. 17372 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17373 } 17374 } 17375 17376 Var->markUsed(SemaRef.Context); 17377 } 17378 17379 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17380 SourceLocation Loc, 17381 unsigned CapturingScopeIndex) { 17382 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17383 } 17384 17385 static void 17386 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17387 ValueDecl *var, DeclContext *DC) { 17388 DeclContext *VarDC = var->getDeclContext(); 17389 17390 // If the parameter still belongs to the translation unit, then 17391 // we're actually just using one parameter in the declaration of 17392 // the next. 17393 if (isa<ParmVarDecl>(var) && 17394 isa<TranslationUnitDecl>(VarDC)) 17395 return; 17396 17397 // For C code, don't diagnose about capture if we're not actually in code 17398 // right now; it's impossible to write a non-constant expression outside of 17399 // function context, so we'll get other (more useful) diagnostics later. 17400 // 17401 // For C++, things get a bit more nasty... it would be nice to suppress this 17402 // diagnostic for certain cases like using a local variable in an array bound 17403 // for a member of a local class, but the correct predicate is not obvious. 17404 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17405 return; 17406 17407 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17408 unsigned ContextKind = 3; // unknown 17409 if (isa<CXXMethodDecl>(VarDC) && 17410 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17411 ContextKind = 2; 17412 } else if (isa<FunctionDecl>(VarDC)) { 17413 ContextKind = 0; 17414 } else if (isa<BlockDecl>(VarDC)) { 17415 ContextKind = 1; 17416 } 17417 17418 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17419 << var << ValueKind << ContextKind << VarDC; 17420 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17421 << var; 17422 17423 // FIXME: Add additional diagnostic info about class etc. which prevents 17424 // capture. 17425 } 17426 17427 17428 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17429 bool &SubCapturesAreNested, 17430 QualType &CaptureType, 17431 QualType &DeclRefType) { 17432 // Check whether we've already captured it. 17433 if (CSI->CaptureMap.count(Var)) { 17434 // If we found a capture, any subcaptures are nested. 17435 SubCapturesAreNested = true; 17436 17437 // Retrieve the capture type for this variable. 17438 CaptureType = CSI->getCapture(Var).getCaptureType(); 17439 17440 // Compute the type of an expression that refers to this variable. 17441 DeclRefType = CaptureType.getNonReferenceType(); 17442 17443 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17444 // are mutable in the sense that user can change their value - they are 17445 // private instances of the captured declarations. 17446 const Capture &Cap = CSI->getCapture(Var); 17447 if (Cap.isCopyCapture() && 17448 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17449 !(isa<CapturedRegionScopeInfo>(CSI) && 17450 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17451 DeclRefType.addConst(); 17452 return true; 17453 } 17454 return false; 17455 } 17456 17457 // Only block literals, captured statements, and lambda expressions can 17458 // capture; other scopes don't work. 17459 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17460 SourceLocation Loc, 17461 const bool Diagnose, Sema &S) { 17462 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17463 return getLambdaAwareParentOfDeclContext(DC); 17464 else if (Var->hasLocalStorage()) { 17465 if (Diagnose) 17466 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17467 } 17468 return nullptr; 17469 } 17470 17471 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17472 // certain types of variables (unnamed, variably modified types etc.) 17473 // so check for eligibility. 17474 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17475 SourceLocation Loc, 17476 const bool Diagnose, Sema &S) { 17477 17478 bool IsBlock = isa<BlockScopeInfo>(CSI); 17479 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17480 17481 // Lambdas are not allowed to capture unnamed variables 17482 // (e.g. anonymous unions). 17483 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17484 // assuming that's the intent. 17485 if (IsLambda && !Var->getDeclName()) { 17486 if (Diagnose) { 17487 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17488 S.Diag(Var->getLocation(), diag::note_declared_at); 17489 } 17490 return false; 17491 } 17492 17493 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17494 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17495 if (Diagnose) { 17496 S.Diag(Loc, diag::err_ref_vm_type); 17497 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17498 } 17499 return false; 17500 } 17501 // Prohibit structs with flexible array members too. 17502 // We cannot capture what is in the tail end of the struct. 17503 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17504 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17505 if (Diagnose) { 17506 if (IsBlock) 17507 S.Diag(Loc, diag::err_ref_flexarray_type); 17508 else 17509 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17510 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17511 } 17512 return false; 17513 } 17514 } 17515 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17516 // Lambdas and captured statements are not allowed to capture __block 17517 // variables; they don't support the expected semantics. 17518 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17519 if (Diagnose) { 17520 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17521 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17522 } 17523 return false; 17524 } 17525 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17526 if (S.getLangOpts().OpenCL && IsBlock && 17527 Var->getType()->isBlockPointerType()) { 17528 if (Diagnose) 17529 S.Diag(Loc, diag::err_opencl_block_ref_block); 17530 return false; 17531 } 17532 17533 return true; 17534 } 17535 17536 // Returns true if the capture by block was successful. 17537 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17538 SourceLocation Loc, 17539 const bool BuildAndDiagnose, 17540 QualType &CaptureType, 17541 QualType &DeclRefType, 17542 const bool Nested, 17543 Sema &S, bool Invalid) { 17544 bool ByRef = false; 17545 17546 // Blocks are not allowed to capture arrays, excepting OpenCL. 17547 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17548 // (decayed to pointers). 17549 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17550 if (BuildAndDiagnose) { 17551 S.Diag(Loc, diag::err_ref_array_type); 17552 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17553 Invalid = true; 17554 } else { 17555 return false; 17556 } 17557 } 17558 17559 // Forbid the block-capture of autoreleasing variables. 17560 if (!Invalid && 17561 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17562 if (BuildAndDiagnose) { 17563 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17564 << /*block*/ 0; 17565 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17566 Invalid = true; 17567 } else { 17568 return false; 17569 } 17570 } 17571 17572 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17573 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17574 QualType PointeeTy = PT->getPointeeType(); 17575 17576 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17577 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17578 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17579 if (BuildAndDiagnose) { 17580 SourceLocation VarLoc = Var->getLocation(); 17581 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17582 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17583 } 17584 } 17585 } 17586 17587 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17588 if (HasBlocksAttr || CaptureType->isReferenceType() || 17589 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17590 // Block capture by reference does not change the capture or 17591 // declaration reference types. 17592 ByRef = true; 17593 } else { 17594 // Block capture by copy introduces 'const'. 17595 CaptureType = CaptureType.getNonReferenceType().withConst(); 17596 DeclRefType = CaptureType; 17597 } 17598 17599 // Actually capture the variable. 17600 if (BuildAndDiagnose) 17601 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17602 CaptureType, Invalid); 17603 17604 return !Invalid; 17605 } 17606 17607 17608 /// Capture the given variable in the captured region. 17609 static bool captureInCapturedRegion( 17610 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17611 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17612 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17613 bool IsTopScope, Sema &S, bool Invalid) { 17614 // By default, capture variables by reference. 17615 bool ByRef = true; 17616 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17617 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17618 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17619 // Using an LValue reference type is consistent with Lambdas (see below). 17620 if (S.isOpenMPCapturedDecl(Var)) { 17621 bool HasConst = DeclRefType.isConstQualified(); 17622 DeclRefType = DeclRefType.getUnqualifiedType(); 17623 // Don't lose diagnostics about assignments to const. 17624 if (HasConst) 17625 DeclRefType.addConst(); 17626 } 17627 // Do not capture firstprivates in tasks. 17628 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17629 OMPC_unknown) 17630 return true; 17631 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17632 RSI->OpenMPCaptureLevel); 17633 } 17634 17635 if (ByRef) 17636 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17637 else 17638 CaptureType = DeclRefType; 17639 17640 // Actually capture the variable. 17641 if (BuildAndDiagnose) 17642 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17643 Loc, SourceLocation(), CaptureType, Invalid); 17644 17645 return !Invalid; 17646 } 17647 17648 /// Capture the given variable in the lambda. 17649 static bool captureInLambda(LambdaScopeInfo *LSI, 17650 VarDecl *Var, 17651 SourceLocation Loc, 17652 const bool BuildAndDiagnose, 17653 QualType &CaptureType, 17654 QualType &DeclRefType, 17655 const bool RefersToCapturedVariable, 17656 const Sema::TryCaptureKind Kind, 17657 SourceLocation EllipsisLoc, 17658 const bool IsTopScope, 17659 Sema &S, bool Invalid) { 17660 // Determine whether we are capturing by reference or by value. 17661 bool ByRef = false; 17662 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17663 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17664 } else { 17665 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17666 } 17667 17668 // Compute the type of the field that will capture this variable. 17669 if (ByRef) { 17670 // C++11 [expr.prim.lambda]p15: 17671 // An entity is captured by reference if it is implicitly or 17672 // explicitly captured but not captured by copy. It is 17673 // unspecified whether additional unnamed non-static data 17674 // members are declared in the closure type for entities 17675 // captured by reference. 17676 // 17677 // FIXME: It is not clear whether we want to build an lvalue reference 17678 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17679 // to do the former, while EDG does the latter. Core issue 1249 will 17680 // clarify, but for now we follow GCC because it's a more permissive and 17681 // easily defensible position. 17682 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17683 } else { 17684 // C++11 [expr.prim.lambda]p14: 17685 // For each entity captured by copy, an unnamed non-static 17686 // data member is declared in the closure type. The 17687 // declaration order of these members is unspecified. The type 17688 // of such a data member is the type of the corresponding 17689 // captured entity if the entity is not a reference to an 17690 // object, or the referenced type otherwise. [Note: If the 17691 // captured entity is a reference to a function, the 17692 // corresponding data member is also a reference to a 17693 // function. - end note ] 17694 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17695 if (!RefType->getPointeeType()->isFunctionType()) 17696 CaptureType = RefType->getPointeeType(); 17697 } 17698 17699 // Forbid the lambda copy-capture of autoreleasing variables. 17700 if (!Invalid && 17701 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17702 if (BuildAndDiagnose) { 17703 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17704 S.Diag(Var->getLocation(), diag::note_previous_decl) 17705 << Var->getDeclName(); 17706 Invalid = true; 17707 } else { 17708 return false; 17709 } 17710 } 17711 17712 // Make sure that by-copy captures are of a complete and non-abstract type. 17713 if (!Invalid && BuildAndDiagnose) { 17714 if (!CaptureType->isDependentType() && 17715 S.RequireCompleteSizedType( 17716 Loc, CaptureType, 17717 diag::err_capture_of_incomplete_or_sizeless_type, 17718 Var->getDeclName())) 17719 Invalid = true; 17720 else if (S.RequireNonAbstractType(Loc, CaptureType, 17721 diag::err_capture_of_abstract_type)) 17722 Invalid = true; 17723 } 17724 } 17725 17726 // Compute the type of a reference to this captured variable. 17727 if (ByRef) 17728 DeclRefType = CaptureType.getNonReferenceType(); 17729 else { 17730 // C++ [expr.prim.lambda]p5: 17731 // The closure type for a lambda-expression has a public inline 17732 // function call operator [...]. This function call operator is 17733 // declared const (9.3.1) if and only if the lambda-expression's 17734 // parameter-declaration-clause is not followed by mutable. 17735 DeclRefType = CaptureType.getNonReferenceType(); 17736 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17737 DeclRefType.addConst(); 17738 } 17739 17740 // Add the capture. 17741 if (BuildAndDiagnose) 17742 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17743 Loc, EllipsisLoc, CaptureType, Invalid); 17744 17745 return !Invalid; 17746 } 17747 17748 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17749 // Offer a Copy fix even if the type is dependent. 17750 if (Var->getType()->isDependentType()) 17751 return true; 17752 QualType T = Var->getType().getNonReferenceType(); 17753 if (T.isTriviallyCopyableType(Context)) 17754 return true; 17755 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17756 17757 if (!(RD = RD->getDefinition())) 17758 return false; 17759 if (RD->hasSimpleCopyConstructor()) 17760 return true; 17761 if (RD->hasUserDeclaredCopyConstructor()) 17762 for (CXXConstructorDecl *Ctor : RD->ctors()) 17763 if (Ctor->isCopyConstructor()) 17764 return !Ctor->isDeleted(); 17765 } 17766 return false; 17767 } 17768 17769 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17770 /// default capture. Fixes may be omitted if they aren't allowed by the 17771 /// standard, for example we can't emit a default copy capture fix-it if we 17772 /// already explicitly copy capture capture another variable. 17773 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17774 VarDecl *Var) { 17775 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17776 // Don't offer Capture by copy of default capture by copy fixes if Var is 17777 // known not to be copy constructible. 17778 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17779 17780 SmallString<32> FixBuffer; 17781 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17782 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17783 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17784 if (ShouldOfferCopyFix) { 17785 // Offer fixes to insert an explicit capture for the variable. 17786 // [] -> [VarName] 17787 // [OtherCapture] -> [OtherCapture, VarName] 17788 FixBuffer.assign({Separator, Var->getName()}); 17789 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17790 << Var << /*value*/ 0 17791 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17792 } 17793 // As above but capture by reference. 17794 FixBuffer.assign({Separator, "&", Var->getName()}); 17795 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17796 << Var << /*reference*/ 1 17797 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17798 } 17799 17800 // Only try to offer default capture if there are no captures excluding this 17801 // and init captures. 17802 // [this]: OK. 17803 // [X = Y]: OK. 17804 // [&A, &B]: Don't offer. 17805 // [A, B]: Don't offer. 17806 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17807 return !C.isThisCapture() && !C.isInitCapture(); 17808 })) 17809 return; 17810 17811 // The default capture specifiers, '=' or '&', must appear first in the 17812 // capture body. 17813 SourceLocation DefaultInsertLoc = 17814 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17815 17816 if (ShouldOfferCopyFix) { 17817 bool CanDefaultCopyCapture = true; 17818 // [=, *this] OK since c++17 17819 // [=, this] OK since c++20 17820 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17821 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17822 ? LSI->getCXXThisCapture().isCopyCapture() 17823 : false; 17824 // We can't use default capture by copy if any captures already specified 17825 // capture by copy. 17826 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17827 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17828 })) { 17829 FixBuffer.assign({"=", Separator}); 17830 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17831 << /*value*/ 0 17832 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17833 } 17834 } 17835 17836 // We can't use default capture by reference if any captures already specified 17837 // capture by reference. 17838 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17839 return !C.isInitCapture() && C.isReferenceCapture() && 17840 !C.isThisCapture(); 17841 })) { 17842 FixBuffer.assign({"&", Separator}); 17843 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17844 << /*reference*/ 1 17845 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17846 } 17847 } 17848 17849 bool Sema::tryCaptureVariable( 17850 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17851 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17852 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17853 // An init-capture is notionally from the context surrounding its 17854 // declaration, but its parent DC is the lambda class. 17855 DeclContext *VarDC = Var->getDeclContext(); 17856 if (Var->isInitCapture()) 17857 VarDC = VarDC->getParent(); 17858 17859 DeclContext *DC = CurContext; 17860 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17861 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17862 // We need to sync up the Declaration Context with the 17863 // FunctionScopeIndexToStopAt 17864 if (FunctionScopeIndexToStopAt) { 17865 unsigned FSIndex = FunctionScopes.size() - 1; 17866 while (FSIndex != MaxFunctionScopesIndex) { 17867 DC = getLambdaAwareParentOfDeclContext(DC); 17868 --FSIndex; 17869 } 17870 } 17871 17872 17873 // If the variable is declared in the current context, there is no need to 17874 // capture it. 17875 if (VarDC == DC) return true; 17876 17877 // Capture global variables if it is required to use private copy of this 17878 // variable. 17879 bool IsGlobal = !Var->hasLocalStorage(); 17880 if (IsGlobal && 17881 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17882 MaxFunctionScopesIndex))) 17883 return true; 17884 Var = Var->getCanonicalDecl(); 17885 17886 // Walk up the stack to determine whether we can capture the variable, 17887 // performing the "simple" checks that don't depend on type. We stop when 17888 // we've either hit the declared scope of the variable or find an existing 17889 // capture of that variable. We start from the innermost capturing-entity 17890 // (the DC) and ensure that all intervening capturing-entities 17891 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17892 // declcontext can either capture the variable or have already captured 17893 // the variable. 17894 CaptureType = Var->getType(); 17895 DeclRefType = CaptureType.getNonReferenceType(); 17896 bool Nested = false; 17897 bool Explicit = (Kind != TryCapture_Implicit); 17898 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17899 do { 17900 // Only block literals, captured statements, and lambda expressions can 17901 // capture; other scopes don't work. 17902 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17903 ExprLoc, 17904 BuildAndDiagnose, 17905 *this); 17906 // We need to check for the parent *first* because, if we *have* 17907 // private-captured a global variable, we need to recursively capture it in 17908 // intermediate blocks, lambdas, etc. 17909 if (!ParentDC) { 17910 if (IsGlobal) { 17911 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17912 break; 17913 } 17914 return true; 17915 } 17916 17917 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17918 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17919 17920 17921 // Check whether we've already captured it. 17922 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17923 DeclRefType)) { 17924 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17925 break; 17926 } 17927 // If we are instantiating a generic lambda call operator body, 17928 // we do not want to capture new variables. What was captured 17929 // during either a lambdas transformation or initial parsing 17930 // should be used. 17931 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17932 if (BuildAndDiagnose) { 17933 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17934 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17935 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17936 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17937 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17938 buildLambdaCaptureFixit(*this, LSI, Var); 17939 } else 17940 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17941 } 17942 return true; 17943 } 17944 17945 // Try to capture variable-length arrays types. 17946 if (Var->getType()->isVariablyModifiedType()) { 17947 // We're going to walk down into the type and look for VLA 17948 // expressions. 17949 QualType QTy = Var->getType(); 17950 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17951 QTy = PVD->getOriginalType(); 17952 captureVariablyModifiedType(Context, QTy, CSI); 17953 } 17954 17955 if (getLangOpts().OpenMP) { 17956 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17957 // OpenMP private variables should not be captured in outer scope, so 17958 // just break here. Similarly, global variables that are captured in a 17959 // target region should not be captured outside the scope of the region. 17960 if (RSI->CapRegionKind == CR_OpenMP) { 17961 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17962 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17963 // If the variable is private (i.e. not captured) and has variably 17964 // modified type, we still need to capture the type for correct 17965 // codegen in all regions, associated with the construct. Currently, 17966 // it is captured in the innermost captured region only. 17967 if (IsOpenMPPrivateDecl != OMPC_unknown && 17968 Var->getType()->isVariablyModifiedType()) { 17969 QualType QTy = Var->getType(); 17970 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17971 QTy = PVD->getOriginalType(); 17972 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17973 I < E; ++I) { 17974 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17975 FunctionScopes[FunctionScopesIndex - I]); 17976 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17977 "Wrong number of captured regions associated with the " 17978 "OpenMP construct."); 17979 captureVariablyModifiedType(Context, QTy, OuterRSI); 17980 } 17981 } 17982 bool IsTargetCap = 17983 IsOpenMPPrivateDecl != OMPC_private && 17984 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17985 RSI->OpenMPCaptureLevel); 17986 // Do not capture global if it is not privatized in outer regions. 17987 bool IsGlobalCap = 17988 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17989 RSI->OpenMPCaptureLevel); 17990 17991 // When we detect target captures we are looking from inside the 17992 // target region, therefore we need to propagate the capture from the 17993 // enclosing region. Therefore, the capture is not initially nested. 17994 if (IsTargetCap) 17995 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17996 17997 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17998 (IsGlobal && !IsGlobalCap)) { 17999 Nested = !IsTargetCap; 18000 bool HasConst = DeclRefType.isConstQualified(); 18001 DeclRefType = DeclRefType.getUnqualifiedType(); 18002 // Don't lose diagnostics about assignments to const. 18003 if (HasConst) 18004 DeclRefType.addConst(); 18005 CaptureType = Context.getLValueReferenceType(DeclRefType); 18006 break; 18007 } 18008 } 18009 } 18010 } 18011 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18012 // No capture-default, and this is not an explicit capture 18013 // so cannot capture this variable. 18014 if (BuildAndDiagnose) { 18015 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18016 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18017 auto *LSI = cast<LambdaScopeInfo>(CSI); 18018 if (LSI->Lambda) { 18019 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18020 buildLambdaCaptureFixit(*this, LSI, Var); 18021 } 18022 // FIXME: If we error out because an outer lambda can not implicitly 18023 // capture a variable that an inner lambda explicitly captures, we 18024 // should have the inner lambda do the explicit capture - because 18025 // it makes for cleaner diagnostics later. This would purely be done 18026 // so that the diagnostic does not misleadingly claim that a variable 18027 // can not be captured by a lambda implicitly even though it is captured 18028 // explicitly. Suggestion: 18029 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18030 // at the function head 18031 // - cache the StartingDeclContext - this must be a lambda 18032 // - captureInLambda in the innermost lambda the variable. 18033 } 18034 return true; 18035 } 18036 18037 FunctionScopesIndex--; 18038 DC = ParentDC; 18039 Explicit = false; 18040 } while (!VarDC->Equals(DC)); 18041 18042 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18043 // computing the type of the capture at each step, checking type-specific 18044 // requirements, and adding captures if requested. 18045 // If the variable had already been captured previously, we start capturing 18046 // at the lambda nested within that one. 18047 bool Invalid = false; 18048 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18049 ++I) { 18050 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18051 18052 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18053 // certain types of variables (unnamed, variably modified types etc.) 18054 // so check for eligibility. 18055 if (!Invalid) 18056 Invalid = 18057 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18058 18059 // After encountering an error, if we're actually supposed to capture, keep 18060 // capturing in nested contexts to suppress any follow-on diagnostics. 18061 if (Invalid && !BuildAndDiagnose) 18062 return true; 18063 18064 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18065 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18066 DeclRefType, Nested, *this, Invalid); 18067 Nested = true; 18068 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18069 Invalid = !captureInCapturedRegion( 18070 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18071 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18072 Nested = true; 18073 } else { 18074 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18075 Invalid = 18076 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18077 DeclRefType, Nested, Kind, EllipsisLoc, 18078 /*IsTopScope*/ I == N - 1, *this, Invalid); 18079 Nested = true; 18080 } 18081 18082 if (Invalid && !BuildAndDiagnose) 18083 return true; 18084 } 18085 return Invalid; 18086 } 18087 18088 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18089 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18090 QualType CaptureType; 18091 QualType DeclRefType; 18092 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18093 /*BuildAndDiagnose=*/true, CaptureType, 18094 DeclRefType, nullptr); 18095 } 18096 18097 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18098 QualType CaptureType; 18099 QualType DeclRefType; 18100 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18101 /*BuildAndDiagnose=*/false, CaptureType, 18102 DeclRefType, nullptr); 18103 } 18104 18105 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18106 QualType CaptureType; 18107 QualType DeclRefType; 18108 18109 // Determine whether we can capture this variable. 18110 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18111 /*BuildAndDiagnose=*/false, CaptureType, 18112 DeclRefType, nullptr)) 18113 return QualType(); 18114 18115 return DeclRefType; 18116 } 18117 18118 namespace { 18119 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18120 // The produced TemplateArgumentListInfo* points to data stored within this 18121 // object, so should only be used in contexts where the pointer will not be 18122 // used after the CopiedTemplateArgs object is destroyed. 18123 class CopiedTemplateArgs { 18124 bool HasArgs; 18125 TemplateArgumentListInfo TemplateArgStorage; 18126 public: 18127 template<typename RefExpr> 18128 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18129 if (HasArgs) 18130 E->copyTemplateArgumentsInto(TemplateArgStorage); 18131 } 18132 operator TemplateArgumentListInfo*() 18133 #ifdef __has_cpp_attribute 18134 #if __has_cpp_attribute(clang::lifetimebound) 18135 [[clang::lifetimebound]] 18136 #endif 18137 #endif 18138 { 18139 return HasArgs ? &TemplateArgStorage : nullptr; 18140 } 18141 }; 18142 } 18143 18144 /// Walk the set of potential results of an expression and mark them all as 18145 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18146 /// 18147 /// \return A new expression if we found any potential results, ExprEmpty() if 18148 /// not, and ExprError() if we diagnosed an error. 18149 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18150 NonOdrUseReason NOUR) { 18151 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18152 // an object that satisfies the requirements for appearing in a 18153 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18154 // is immediately applied." This function handles the lvalue-to-rvalue 18155 // conversion part. 18156 // 18157 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18158 // transform it into the relevant kind of non-odr-use node and rebuild the 18159 // tree of nodes leading to it. 18160 // 18161 // This is a mini-TreeTransform that only transforms a restricted subset of 18162 // nodes (and only certain operands of them). 18163 18164 // Rebuild a subexpression. 18165 auto Rebuild = [&](Expr *Sub) { 18166 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18167 }; 18168 18169 // Check whether a potential result satisfies the requirements of NOUR. 18170 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18171 // Any entity other than a VarDecl is always odr-used whenever it's named 18172 // in a potentially-evaluated expression. 18173 auto *VD = dyn_cast<VarDecl>(D); 18174 if (!VD) 18175 return true; 18176 18177 // C++2a [basic.def.odr]p4: 18178 // A variable x whose name appears as a potentially-evalauted expression 18179 // e is odr-used by e unless 18180 // -- x is a reference that is usable in constant expressions, or 18181 // -- x is a variable of non-reference type that is usable in constant 18182 // expressions and has no mutable subobjects, and e is an element of 18183 // the set of potential results of an expression of 18184 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18185 // conversion is applied, or 18186 // -- x is a variable of non-reference type, and e is an element of the 18187 // set of potential results of a discarded-value expression to which 18188 // the lvalue-to-rvalue conversion is not applied 18189 // 18190 // We check the first bullet and the "potentially-evaluated" condition in 18191 // BuildDeclRefExpr. We check the type requirements in the second bullet 18192 // in CheckLValueToRValueConversionOperand below. 18193 switch (NOUR) { 18194 case NOUR_None: 18195 case NOUR_Unevaluated: 18196 llvm_unreachable("unexpected non-odr-use-reason"); 18197 18198 case NOUR_Constant: 18199 // Constant references were handled when they were built. 18200 if (VD->getType()->isReferenceType()) 18201 return true; 18202 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18203 if (RD->hasMutableFields()) 18204 return true; 18205 if (!VD->isUsableInConstantExpressions(S.Context)) 18206 return true; 18207 break; 18208 18209 case NOUR_Discarded: 18210 if (VD->getType()->isReferenceType()) 18211 return true; 18212 break; 18213 } 18214 return false; 18215 }; 18216 18217 // Mark that this expression does not constitute an odr-use. 18218 auto MarkNotOdrUsed = [&] { 18219 S.MaybeODRUseExprs.remove(E); 18220 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18221 LSI->markVariableExprAsNonODRUsed(E); 18222 }; 18223 18224 // C++2a [basic.def.odr]p2: 18225 // The set of potential results of an expression e is defined as follows: 18226 switch (E->getStmtClass()) { 18227 // -- If e is an id-expression, ... 18228 case Expr::DeclRefExprClass: { 18229 auto *DRE = cast<DeclRefExpr>(E); 18230 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18231 break; 18232 18233 // Rebuild as a non-odr-use DeclRefExpr. 18234 MarkNotOdrUsed(); 18235 return DeclRefExpr::Create( 18236 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18237 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18238 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18239 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18240 } 18241 18242 case Expr::FunctionParmPackExprClass: { 18243 auto *FPPE = cast<FunctionParmPackExpr>(E); 18244 // If any of the declarations in the pack is odr-used, then the expression 18245 // as a whole constitutes an odr-use. 18246 for (VarDecl *D : *FPPE) 18247 if (IsPotentialResultOdrUsed(D)) 18248 return ExprEmpty(); 18249 18250 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18251 // nothing cares about whether we marked this as an odr-use, but it might 18252 // be useful for non-compiler tools. 18253 MarkNotOdrUsed(); 18254 break; 18255 } 18256 18257 // -- If e is a subscripting operation with an array operand... 18258 case Expr::ArraySubscriptExprClass: { 18259 auto *ASE = cast<ArraySubscriptExpr>(E); 18260 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18261 if (!OldBase->getType()->isArrayType()) 18262 break; 18263 ExprResult Base = Rebuild(OldBase); 18264 if (!Base.isUsable()) 18265 return Base; 18266 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18267 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18268 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18269 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18270 ASE->getRBracketLoc()); 18271 } 18272 18273 case Expr::MemberExprClass: { 18274 auto *ME = cast<MemberExpr>(E); 18275 // -- If e is a class member access expression [...] naming a non-static 18276 // data member... 18277 if (isa<FieldDecl>(ME->getMemberDecl())) { 18278 ExprResult Base = Rebuild(ME->getBase()); 18279 if (!Base.isUsable()) 18280 return Base; 18281 return MemberExpr::Create( 18282 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18283 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18284 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18285 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18286 ME->getObjectKind(), ME->isNonOdrUse()); 18287 } 18288 18289 if (ME->getMemberDecl()->isCXXInstanceMember()) 18290 break; 18291 18292 // -- If e is a class member access expression naming a static data member, 18293 // ... 18294 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18295 break; 18296 18297 // Rebuild as a non-odr-use MemberExpr. 18298 MarkNotOdrUsed(); 18299 return MemberExpr::Create( 18300 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18301 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18302 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18303 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18304 } 18305 18306 case Expr::BinaryOperatorClass: { 18307 auto *BO = cast<BinaryOperator>(E); 18308 Expr *LHS = BO->getLHS(); 18309 Expr *RHS = BO->getRHS(); 18310 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18311 if (BO->getOpcode() == BO_PtrMemD) { 18312 ExprResult Sub = Rebuild(LHS); 18313 if (!Sub.isUsable()) 18314 return Sub; 18315 LHS = Sub.get(); 18316 // -- If e is a comma expression, ... 18317 } else if (BO->getOpcode() == BO_Comma) { 18318 ExprResult Sub = Rebuild(RHS); 18319 if (!Sub.isUsable()) 18320 return Sub; 18321 RHS = Sub.get(); 18322 } else { 18323 break; 18324 } 18325 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18326 LHS, RHS); 18327 } 18328 18329 // -- If e has the form (e1)... 18330 case Expr::ParenExprClass: { 18331 auto *PE = cast<ParenExpr>(E); 18332 ExprResult Sub = Rebuild(PE->getSubExpr()); 18333 if (!Sub.isUsable()) 18334 return Sub; 18335 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18336 } 18337 18338 // -- If e is a glvalue conditional expression, ... 18339 // We don't apply this to a binary conditional operator. FIXME: Should we? 18340 case Expr::ConditionalOperatorClass: { 18341 auto *CO = cast<ConditionalOperator>(E); 18342 ExprResult LHS = Rebuild(CO->getLHS()); 18343 if (LHS.isInvalid()) 18344 return ExprError(); 18345 ExprResult RHS = Rebuild(CO->getRHS()); 18346 if (RHS.isInvalid()) 18347 return ExprError(); 18348 if (!LHS.isUsable() && !RHS.isUsable()) 18349 return ExprEmpty(); 18350 if (!LHS.isUsable()) 18351 LHS = CO->getLHS(); 18352 if (!RHS.isUsable()) 18353 RHS = CO->getRHS(); 18354 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18355 CO->getCond(), LHS.get(), RHS.get()); 18356 } 18357 18358 // [Clang extension] 18359 // -- If e has the form __extension__ e1... 18360 case Expr::UnaryOperatorClass: { 18361 auto *UO = cast<UnaryOperator>(E); 18362 if (UO->getOpcode() != UO_Extension) 18363 break; 18364 ExprResult Sub = Rebuild(UO->getSubExpr()); 18365 if (!Sub.isUsable()) 18366 return Sub; 18367 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18368 Sub.get()); 18369 } 18370 18371 // [Clang extension] 18372 // -- If e has the form _Generic(...), the set of potential results is the 18373 // union of the sets of potential results of the associated expressions. 18374 case Expr::GenericSelectionExprClass: { 18375 auto *GSE = cast<GenericSelectionExpr>(E); 18376 18377 SmallVector<Expr *, 4> AssocExprs; 18378 bool AnyChanged = false; 18379 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18380 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18381 if (AssocExpr.isInvalid()) 18382 return ExprError(); 18383 if (AssocExpr.isUsable()) { 18384 AssocExprs.push_back(AssocExpr.get()); 18385 AnyChanged = true; 18386 } else { 18387 AssocExprs.push_back(OrigAssocExpr); 18388 } 18389 } 18390 18391 return AnyChanged ? S.CreateGenericSelectionExpr( 18392 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18393 GSE->getRParenLoc(), GSE->getControllingExpr(), 18394 GSE->getAssocTypeSourceInfos(), AssocExprs) 18395 : ExprEmpty(); 18396 } 18397 18398 // [Clang extension] 18399 // -- If e has the form __builtin_choose_expr(...), the set of potential 18400 // results is the union of the sets of potential results of the 18401 // second and third subexpressions. 18402 case Expr::ChooseExprClass: { 18403 auto *CE = cast<ChooseExpr>(E); 18404 18405 ExprResult LHS = Rebuild(CE->getLHS()); 18406 if (LHS.isInvalid()) 18407 return ExprError(); 18408 18409 ExprResult RHS = Rebuild(CE->getLHS()); 18410 if (RHS.isInvalid()) 18411 return ExprError(); 18412 18413 if (!LHS.get() && !RHS.get()) 18414 return ExprEmpty(); 18415 if (!LHS.isUsable()) 18416 LHS = CE->getLHS(); 18417 if (!RHS.isUsable()) 18418 RHS = CE->getRHS(); 18419 18420 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18421 RHS.get(), CE->getRParenLoc()); 18422 } 18423 18424 // Step through non-syntactic nodes. 18425 case Expr::ConstantExprClass: { 18426 auto *CE = cast<ConstantExpr>(E); 18427 ExprResult Sub = Rebuild(CE->getSubExpr()); 18428 if (!Sub.isUsable()) 18429 return Sub; 18430 return ConstantExpr::Create(S.Context, Sub.get()); 18431 } 18432 18433 // We could mostly rely on the recursive rebuilding to rebuild implicit 18434 // casts, but not at the top level, so rebuild them here. 18435 case Expr::ImplicitCastExprClass: { 18436 auto *ICE = cast<ImplicitCastExpr>(E); 18437 // Only step through the narrow set of cast kinds we expect to encounter. 18438 // Anything else suggests we've left the region in which potential results 18439 // can be found. 18440 switch (ICE->getCastKind()) { 18441 case CK_NoOp: 18442 case CK_DerivedToBase: 18443 case CK_UncheckedDerivedToBase: { 18444 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18445 if (!Sub.isUsable()) 18446 return Sub; 18447 CXXCastPath Path(ICE->path()); 18448 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18449 ICE->getValueKind(), &Path); 18450 } 18451 18452 default: 18453 break; 18454 } 18455 break; 18456 } 18457 18458 default: 18459 break; 18460 } 18461 18462 // Can't traverse through this node. Nothing to do. 18463 return ExprEmpty(); 18464 } 18465 18466 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18467 // Check whether the operand is or contains an object of non-trivial C union 18468 // type. 18469 if (E->getType().isVolatileQualified() && 18470 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18471 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18472 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18473 Sema::NTCUC_LValueToRValueVolatile, 18474 NTCUK_Destruct|NTCUK_Copy); 18475 18476 // C++2a [basic.def.odr]p4: 18477 // [...] an expression of non-volatile-qualified non-class type to which 18478 // the lvalue-to-rvalue conversion is applied [...] 18479 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18480 return E; 18481 18482 ExprResult Result = 18483 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18484 if (Result.isInvalid()) 18485 return ExprError(); 18486 return Result.get() ? Result : E; 18487 } 18488 18489 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18490 Res = CorrectDelayedTyposInExpr(Res); 18491 18492 if (!Res.isUsable()) 18493 return Res; 18494 18495 // If a constant-expression is a reference to a variable where we delay 18496 // deciding whether it is an odr-use, just assume we will apply the 18497 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18498 // (a non-type template argument), we have special handling anyway. 18499 return CheckLValueToRValueConversionOperand(Res.get()); 18500 } 18501 18502 void Sema::CleanupVarDeclMarking() { 18503 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18504 // call. 18505 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18506 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18507 18508 for (Expr *E : LocalMaybeODRUseExprs) { 18509 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18510 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18511 DRE->getLocation(), *this); 18512 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18513 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18514 *this); 18515 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18516 for (VarDecl *VD : *FP) 18517 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18518 } else { 18519 llvm_unreachable("Unexpected expression"); 18520 } 18521 } 18522 18523 assert(MaybeODRUseExprs.empty() && 18524 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18525 } 18526 18527 static void DoMarkVarDeclReferenced( 18528 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18529 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18530 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18531 isa<FunctionParmPackExpr>(E)) && 18532 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18533 Var->setReferenced(); 18534 18535 if (Var->isInvalidDecl()) 18536 return; 18537 18538 auto *MSI = Var->getMemberSpecializationInfo(); 18539 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18540 : Var->getTemplateSpecializationKind(); 18541 18542 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18543 bool UsableInConstantExpr = 18544 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18545 18546 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18547 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18548 } 18549 18550 // C++20 [expr.const]p12: 18551 // A variable [...] is needed for constant evaluation if it is [...] a 18552 // variable whose name appears as a potentially constant evaluated 18553 // expression that is either a contexpr variable or is of non-volatile 18554 // const-qualified integral type or of reference type 18555 bool NeededForConstantEvaluation = 18556 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18557 18558 bool NeedDefinition = 18559 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18560 18561 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18562 "Can't instantiate a partial template specialization."); 18563 18564 // If this might be a member specialization of a static data member, check 18565 // the specialization is visible. We already did the checks for variable 18566 // template specializations when we created them. 18567 if (NeedDefinition && TSK != TSK_Undeclared && 18568 !isa<VarTemplateSpecializationDecl>(Var)) 18569 SemaRef.checkSpecializationVisibility(Loc, Var); 18570 18571 // Perform implicit instantiation of static data members, static data member 18572 // templates of class templates, and variable template specializations. Delay 18573 // instantiations of variable templates, except for those that could be used 18574 // in a constant expression. 18575 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18576 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18577 // instantiation declaration if a variable is usable in a constant 18578 // expression (among other cases). 18579 bool TryInstantiating = 18580 TSK == TSK_ImplicitInstantiation || 18581 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18582 18583 if (TryInstantiating) { 18584 SourceLocation PointOfInstantiation = 18585 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18586 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18587 if (FirstInstantiation) { 18588 PointOfInstantiation = Loc; 18589 if (MSI) 18590 MSI->setPointOfInstantiation(PointOfInstantiation); 18591 // FIXME: Notify listener. 18592 else 18593 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18594 } 18595 18596 if (UsableInConstantExpr) { 18597 // Do not defer instantiations of variables that could be used in a 18598 // constant expression. 18599 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18600 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18601 }); 18602 18603 // Re-set the member to trigger a recomputation of the dependence bits 18604 // for the expression. 18605 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18606 DRE->setDecl(DRE->getDecl()); 18607 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18608 ME->setMemberDecl(ME->getMemberDecl()); 18609 } else if (FirstInstantiation || 18610 isa<VarTemplateSpecializationDecl>(Var)) { 18611 // FIXME: For a specialization of a variable template, we don't 18612 // distinguish between "declaration and type implicitly instantiated" 18613 // and "implicit instantiation of definition requested", so we have 18614 // no direct way to avoid enqueueing the pending instantiation 18615 // multiple times. 18616 SemaRef.PendingInstantiations 18617 .push_back(std::make_pair(Var, PointOfInstantiation)); 18618 } 18619 } 18620 } 18621 18622 // C++2a [basic.def.odr]p4: 18623 // A variable x whose name appears as a potentially-evaluated expression e 18624 // is odr-used by e unless 18625 // -- x is a reference that is usable in constant expressions 18626 // -- x is a variable of non-reference type that is usable in constant 18627 // expressions and has no mutable subobjects [FIXME], and e is an 18628 // element of the set of potential results of an expression of 18629 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18630 // conversion is applied 18631 // -- x is a variable of non-reference type, and e is an element of the set 18632 // of potential results of a discarded-value expression to which the 18633 // lvalue-to-rvalue conversion is not applied [FIXME] 18634 // 18635 // We check the first part of the second bullet here, and 18636 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18637 // FIXME: To get the third bullet right, we need to delay this even for 18638 // variables that are not usable in constant expressions. 18639 18640 // If we already know this isn't an odr-use, there's nothing more to do. 18641 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18642 if (DRE->isNonOdrUse()) 18643 return; 18644 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18645 if (ME->isNonOdrUse()) 18646 return; 18647 18648 switch (OdrUse) { 18649 case OdrUseContext::None: 18650 assert((!E || isa<FunctionParmPackExpr>(E)) && 18651 "missing non-odr-use marking for unevaluated decl ref"); 18652 break; 18653 18654 case OdrUseContext::FormallyOdrUsed: 18655 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18656 // behavior. 18657 break; 18658 18659 case OdrUseContext::Used: 18660 // If we might later find that this expression isn't actually an odr-use, 18661 // delay the marking. 18662 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18663 SemaRef.MaybeODRUseExprs.insert(E); 18664 else 18665 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18666 break; 18667 18668 case OdrUseContext::Dependent: 18669 // If this is a dependent context, we don't need to mark variables as 18670 // odr-used, but we may still need to track them for lambda capture. 18671 // FIXME: Do we also need to do this inside dependent typeid expressions 18672 // (which are modeled as unevaluated at this point)? 18673 const bool RefersToEnclosingScope = 18674 (SemaRef.CurContext != Var->getDeclContext() && 18675 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18676 if (RefersToEnclosingScope) { 18677 LambdaScopeInfo *const LSI = 18678 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18679 if (LSI && (!LSI->CallOperator || 18680 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18681 // If a variable could potentially be odr-used, defer marking it so 18682 // until we finish analyzing the full expression for any 18683 // lvalue-to-rvalue 18684 // or discarded value conversions that would obviate odr-use. 18685 // Add it to the list of potential captures that will be analyzed 18686 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18687 // unless the variable is a reference that was initialized by a constant 18688 // expression (this will never need to be captured or odr-used). 18689 // 18690 // FIXME: We can simplify this a lot after implementing P0588R1. 18691 assert(E && "Capture variable should be used in an expression."); 18692 if (!Var->getType()->isReferenceType() || 18693 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18694 LSI->addPotentialCapture(E->IgnoreParens()); 18695 } 18696 } 18697 break; 18698 } 18699 } 18700 18701 /// Mark a variable referenced, and check whether it is odr-used 18702 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18703 /// used directly for normal expressions referring to VarDecl. 18704 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18705 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18706 } 18707 18708 static void 18709 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18710 bool MightBeOdrUse, 18711 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18712 if (SemaRef.isInOpenMPDeclareTargetContext()) 18713 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18714 18715 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18716 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18717 return; 18718 } 18719 18720 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18721 18722 // If this is a call to a method via a cast, also mark the method in the 18723 // derived class used in case codegen can devirtualize the call. 18724 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18725 if (!ME) 18726 return; 18727 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18728 if (!MD) 18729 return; 18730 // Only attempt to devirtualize if this is truly a virtual call. 18731 bool IsVirtualCall = MD->isVirtual() && 18732 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18733 if (!IsVirtualCall) 18734 return; 18735 18736 // If it's possible to devirtualize the call, mark the called function 18737 // referenced. 18738 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18739 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18740 if (DM) 18741 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18742 } 18743 18744 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18745 /// 18746 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18747 /// handled with care if the DeclRefExpr is not newly-created. 18748 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18749 // TODO: update this with DR# once a defect report is filed. 18750 // C++11 defect. The address of a pure member should not be an ODR use, even 18751 // if it's a qualified reference. 18752 bool OdrUse = true; 18753 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18754 if (Method->isVirtual() && 18755 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18756 OdrUse = false; 18757 18758 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18759 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18760 FD->isConsteval() && !RebuildingImmediateInvocation) 18761 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18762 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18763 RefsMinusAssignments); 18764 } 18765 18766 /// Perform reference-marking and odr-use handling for a MemberExpr. 18767 void Sema::MarkMemberReferenced(MemberExpr *E) { 18768 // C++11 [basic.def.odr]p2: 18769 // A non-overloaded function whose name appears as a potentially-evaluated 18770 // expression or a member of a set of candidate functions, if selected by 18771 // overload resolution when referred to from a potentially-evaluated 18772 // expression, is odr-used, unless it is a pure virtual function and its 18773 // name is not explicitly qualified. 18774 bool MightBeOdrUse = true; 18775 if (E->performsVirtualDispatch(getLangOpts())) { 18776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18777 if (Method->isPure()) 18778 MightBeOdrUse = false; 18779 } 18780 SourceLocation Loc = 18781 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18782 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18783 RefsMinusAssignments); 18784 } 18785 18786 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18787 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18788 for (VarDecl *VD : *E) 18789 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18790 RefsMinusAssignments); 18791 } 18792 18793 /// Perform marking for a reference to an arbitrary declaration. It 18794 /// marks the declaration referenced, and performs odr-use checking for 18795 /// functions and variables. This method should not be used when building a 18796 /// normal expression which refers to a variable. 18797 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18798 bool MightBeOdrUse) { 18799 if (MightBeOdrUse) { 18800 if (auto *VD = dyn_cast<VarDecl>(D)) { 18801 MarkVariableReferenced(Loc, VD); 18802 return; 18803 } 18804 } 18805 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18806 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18807 return; 18808 } 18809 D->setReferenced(); 18810 } 18811 18812 namespace { 18813 // Mark all of the declarations used by a type as referenced. 18814 // FIXME: Not fully implemented yet! We need to have a better understanding 18815 // of when we're entering a context we should not recurse into. 18816 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18817 // TreeTransforms rebuilding the type in a new context. Rather than 18818 // duplicating the TreeTransform logic, we should consider reusing it here. 18819 // Currently that causes problems when rebuilding LambdaExprs. 18820 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18821 Sema &S; 18822 SourceLocation Loc; 18823 18824 public: 18825 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18826 18827 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18828 18829 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18830 }; 18831 } 18832 18833 bool MarkReferencedDecls::TraverseTemplateArgument( 18834 const TemplateArgument &Arg) { 18835 { 18836 // A non-type template argument is a constant-evaluated context. 18837 EnterExpressionEvaluationContext Evaluated( 18838 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18839 if (Arg.getKind() == TemplateArgument::Declaration) { 18840 if (Decl *D = Arg.getAsDecl()) 18841 S.MarkAnyDeclReferenced(Loc, D, true); 18842 } else if (Arg.getKind() == TemplateArgument::Expression) { 18843 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18844 } 18845 } 18846 18847 return Inherited::TraverseTemplateArgument(Arg); 18848 } 18849 18850 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18851 MarkReferencedDecls Marker(*this, Loc); 18852 Marker.TraverseType(T); 18853 } 18854 18855 namespace { 18856 /// Helper class that marks all of the declarations referenced by 18857 /// potentially-evaluated subexpressions as "referenced". 18858 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18859 public: 18860 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18861 bool SkipLocalVariables; 18862 18863 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18864 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18865 18866 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18867 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18868 } 18869 18870 void VisitDeclRefExpr(DeclRefExpr *E) { 18871 // If we were asked not to visit local variables, don't. 18872 if (SkipLocalVariables) { 18873 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18874 if (VD->hasLocalStorage()) 18875 return; 18876 } 18877 18878 // FIXME: This can trigger the instantiation of the initializer of a 18879 // variable, which can cause the expression to become value-dependent 18880 // or error-dependent. Do we need to propagate the new dependence bits? 18881 S.MarkDeclRefReferenced(E); 18882 } 18883 18884 void VisitMemberExpr(MemberExpr *E) { 18885 S.MarkMemberReferenced(E); 18886 Visit(E->getBase()); 18887 } 18888 }; 18889 } // namespace 18890 18891 /// Mark any declarations that appear within this expression or any 18892 /// potentially-evaluated subexpressions as "referenced". 18893 /// 18894 /// \param SkipLocalVariables If true, don't mark local variables as 18895 /// 'referenced'. 18896 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18897 bool SkipLocalVariables) { 18898 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18899 } 18900 18901 /// Emit a diagnostic that describes an effect on the run-time behavior 18902 /// of the program being compiled. 18903 /// 18904 /// This routine emits the given diagnostic when the code currently being 18905 /// type-checked is "potentially evaluated", meaning that there is a 18906 /// possibility that the code will actually be executable. Code in sizeof() 18907 /// expressions, code used only during overload resolution, etc., are not 18908 /// potentially evaluated. This routine will suppress such diagnostics or, 18909 /// in the absolutely nutty case of potentially potentially evaluated 18910 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18911 /// later. 18912 /// 18913 /// This routine should be used for all diagnostics that describe the run-time 18914 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18915 /// Failure to do so will likely result in spurious diagnostics or failures 18916 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18917 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18918 const PartialDiagnostic &PD) { 18919 switch (ExprEvalContexts.back().Context) { 18920 case ExpressionEvaluationContext::Unevaluated: 18921 case ExpressionEvaluationContext::UnevaluatedList: 18922 case ExpressionEvaluationContext::UnevaluatedAbstract: 18923 case ExpressionEvaluationContext::DiscardedStatement: 18924 // The argument will never be evaluated, so don't complain. 18925 break; 18926 18927 case ExpressionEvaluationContext::ConstantEvaluated: 18928 // Relevant diagnostics should be produced by constant evaluation. 18929 break; 18930 18931 case ExpressionEvaluationContext::PotentiallyEvaluated: 18932 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18933 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18934 FunctionScopes.back()->PossiblyUnreachableDiags. 18935 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18936 return true; 18937 } 18938 18939 // The initializer of a constexpr variable or of the first declaration of a 18940 // static data member is not syntactically a constant evaluated constant, 18941 // but nonetheless is always required to be a constant expression, so we 18942 // can skip diagnosing. 18943 // FIXME: Using the mangling context here is a hack. 18944 if (auto *VD = dyn_cast_or_null<VarDecl>( 18945 ExprEvalContexts.back().ManglingContextDecl)) { 18946 if (VD->isConstexpr() || 18947 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18948 break; 18949 // FIXME: For any other kind of variable, we should build a CFG for its 18950 // initializer and check whether the context in question is reachable. 18951 } 18952 18953 Diag(Loc, PD); 18954 return true; 18955 } 18956 18957 return false; 18958 } 18959 18960 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18961 const PartialDiagnostic &PD) { 18962 return DiagRuntimeBehavior( 18963 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18964 } 18965 18966 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18967 CallExpr *CE, FunctionDecl *FD) { 18968 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18969 return false; 18970 18971 // If we're inside a decltype's expression, don't check for a valid return 18972 // type or construct temporaries until we know whether this is the last call. 18973 if (ExprEvalContexts.back().ExprContext == 18974 ExpressionEvaluationContextRecord::EK_Decltype) { 18975 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18976 return false; 18977 } 18978 18979 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18980 FunctionDecl *FD; 18981 CallExpr *CE; 18982 18983 public: 18984 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18985 : FD(FD), CE(CE) { } 18986 18987 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18988 if (!FD) { 18989 S.Diag(Loc, diag::err_call_incomplete_return) 18990 << T << CE->getSourceRange(); 18991 return; 18992 } 18993 18994 S.Diag(Loc, diag::err_call_function_incomplete_return) 18995 << CE->getSourceRange() << FD << T; 18996 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18997 << FD->getDeclName(); 18998 } 18999 } Diagnoser(FD, CE); 19000 19001 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19002 return true; 19003 19004 return false; 19005 } 19006 19007 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19008 // will prevent this condition from triggering, which is what we want. 19009 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19010 SourceLocation Loc; 19011 19012 unsigned diagnostic = diag::warn_condition_is_assignment; 19013 bool IsOrAssign = false; 19014 19015 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19016 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19017 return; 19018 19019 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19020 19021 // Greylist some idioms by putting them into a warning subcategory. 19022 if (ObjCMessageExpr *ME 19023 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19024 Selector Sel = ME->getSelector(); 19025 19026 // self = [<foo> init...] 19027 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19028 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19029 19030 // <foo> = [<bar> nextObject] 19031 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19032 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19033 } 19034 19035 Loc = Op->getOperatorLoc(); 19036 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19037 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19038 return; 19039 19040 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19041 Loc = Op->getOperatorLoc(); 19042 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19043 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19044 else { 19045 // Not an assignment. 19046 return; 19047 } 19048 19049 Diag(Loc, diagnostic) << E->getSourceRange(); 19050 19051 SourceLocation Open = E->getBeginLoc(); 19052 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19053 Diag(Loc, diag::note_condition_assign_silence) 19054 << FixItHint::CreateInsertion(Open, "(") 19055 << FixItHint::CreateInsertion(Close, ")"); 19056 19057 if (IsOrAssign) 19058 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19059 << FixItHint::CreateReplacement(Loc, "!="); 19060 else 19061 Diag(Loc, diag::note_condition_assign_to_comparison) 19062 << FixItHint::CreateReplacement(Loc, "=="); 19063 } 19064 19065 /// Redundant parentheses over an equality comparison can indicate 19066 /// that the user intended an assignment used as condition. 19067 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19068 // Don't warn if the parens came from a macro. 19069 SourceLocation parenLoc = ParenE->getBeginLoc(); 19070 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19071 return; 19072 // Don't warn for dependent expressions. 19073 if (ParenE->isTypeDependent()) 19074 return; 19075 19076 Expr *E = ParenE->IgnoreParens(); 19077 19078 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19079 if (opE->getOpcode() == BO_EQ && 19080 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19081 == Expr::MLV_Valid) { 19082 SourceLocation Loc = opE->getOperatorLoc(); 19083 19084 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19085 SourceRange ParenERange = ParenE->getSourceRange(); 19086 Diag(Loc, diag::note_equality_comparison_silence) 19087 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19088 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19089 Diag(Loc, diag::note_equality_comparison_to_assign) 19090 << FixItHint::CreateReplacement(Loc, "="); 19091 } 19092 } 19093 19094 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19095 bool IsConstexpr) { 19096 DiagnoseAssignmentAsCondition(E); 19097 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19098 DiagnoseEqualityWithExtraParens(parenE); 19099 19100 ExprResult result = CheckPlaceholderExpr(E); 19101 if (result.isInvalid()) return ExprError(); 19102 E = result.get(); 19103 19104 if (!E->isTypeDependent()) { 19105 if (getLangOpts().CPlusPlus) 19106 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19107 19108 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19109 if (ERes.isInvalid()) 19110 return ExprError(); 19111 E = ERes.get(); 19112 19113 QualType T = E->getType(); 19114 if (!T->isScalarType()) { // C99 6.8.4.1p1 19115 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19116 << T << E->getSourceRange(); 19117 return ExprError(); 19118 } 19119 CheckBoolLikeConversion(E, Loc); 19120 } 19121 19122 return E; 19123 } 19124 19125 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19126 Expr *SubExpr, ConditionKind CK) { 19127 // Empty conditions are valid in for-statements. 19128 if (!SubExpr) 19129 return ConditionResult(); 19130 19131 ExprResult Cond; 19132 switch (CK) { 19133 case ConditionKind::Boolean: 19134 Cond = CheckBooleanCondition(Loc, SubExpr); 19135 break; 19136 19137 case ConditionKind::ConstexprIf: 19138 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19139 break; 19140 19141 case ConditionKind::Switch: 19142 Cond = CheckSwitchCondition(Loc, SubExpr); 19143 break; 19144 } 19145 if (Cond.isInvalid()) { 19146 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19147 {SubExpr}); 19148 if (!Cond.get()) 19149 return ConditionError(); 19150 } 19151 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19152 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19153 if (!FullExpr.get()) 19154 return ConditionError(); 19155 19156 return ConditionResult(*this, nullptr, FullExpr, 19157 CK == ConditionKind::ConstexprIf); 19158 } 19159 19160 namespace { 19161 /// A visitor for rebuilding a call to an __unknown_any expression 19162 /// to have an appropriate type. 19163 struct RebuildUnknownAnyFunction 19164 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19165 19166 Sema &S; 19167 19168 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19169 19170 ExprResult VisitStmt(Stmt *S) { 19171 llvm_unreachable("unexpected statement!"); 19172 } 19173 19174 ExprResult VisitExpr(Expr *E) { 19175 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19176 << E->getSourceRange(); 19177 return ExprError(); 19178 } 19179 19180 /// Rebuild an expression which simply semantically wraps another 19181 /// expression which it shares the type and value kind of. 19182 template <class T> ExprResult rebuildSugarExpr(T *E) { 19183 ExprResult SubResult = Visit(E->getSubExpr()); 19184 if (SubResult.isInvalid()) return ExprError(); 19185 19186 Expr *SubExpr = SubResult.get(); 19187 E->setSubExpr(SubExpr); 19188 E->setType(SubExpr->getType()); 19189 E->setValueKind(SubExpr->getValueKind()); 19190 assert(E->getObjectKind() == OK_Ordinary); 19191 return E; 19192 } 19193 19194 ExprResult VisitParenExpr(ParenExpr *E) { 19195 return rebuildSugarExpr(E); 19196 } 19197 19198 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19199 return rebuildSugarExpr(E); 19200 } 19201 19202 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19203 ExprResult SubResult = Visit(E->getSubExpr()); 19204 if (SubResult.isInvalid()) return ExprError(); 19205 19206 Expr *SubExpr = SubResult.get(); 19207 E->setSubExpr(SubExpr); 19208 E->setType(S.Context.getPointerType(SubExpr->getType())); 19209 assert(E->isPRValue()); 19210 assert(E->getObjectKind() == OK_Ordinary); 19211 return E; 19212 } 19213 19214 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19215 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19216 19217 E->setType(VD->getType()); 19218 19219 assert(E->isPRValue()); 19220 if (S.getLangOpts().CPlusPlus && 19221 !(isa<CXXMethodDecl>(VD) && 19222 cast<CXXMethodDecl>(VD)->isInstance())) 19223 E->setValueKind(VK_LValue); 19224 19225 return E; 19226 } 19227 19228 ExprResult VisitMemberExpr(MemberExpr *E) { 19229 return resolveDecl(E, E->getMemberDecl()); 19230 } 19231 19232 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19233 return resolveDecl(E, E->getDecl()); 19234 } 19235 }; 19236 } 19237 19238 /// Given a function expression of unknown-any type, try to rebuild it 19239 /// to have a function type. 19240 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19241 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19242 if (Result.isInvalid()) return ExprError(); 19243 return S.DefaultFunctionArrayConversion(Result.get()); 19244 } 19245 19246 namespace { 19247 /// A visitor for rebuilding an expression of type __unknown_anytype 19248 /// into one which resolves the type directly on the referring 19249 /// expression. Strict preservation of the original source 19250 /// structure is not a goal. 19251 struct RebuildUnknownAnyExpr 19252 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19253 19254 Sema &S; 19255 19256 /// The current destination type. 19257 QualType DestType; 19258 19259 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19260 : S(S), DestType(CastType) {} 19261 19262 ExprResult VisitStmt(Stmt *S) { 19263 llvm_unreachable("unexpected statement!"); 19264 } 19265 19266 ExprResult VisitExpr(Expr *E) { 19267 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19268 << E->getSourceRange(); 19269 return ExprError(); 19270 } 19271 19272 ExprResult VisitCallExpr(CallExpr *E); 19273 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19274 19275 /// Rebuild an expression which simply semantically wraps another 19276 /// expression which it shares the type and value kind of. 19277 template <class T> ExprResult rebuildSugarExpr(T *E) { 19278 ExprResult SubResult = Visit(E->getSubExpr()); 19279 if (SubResult.isInvalid()) return ExprError(); 19280 Expr *SubExpr = SubResult.get(); 19281 E->setSubExpr(SubExpr); 19282 E->setType(SubExpr->getType()); 19283 E->setValueKind(SubExpr->getValueKind()); 19284 assert(E->getObjectKind() == OK_Ordinary); 19285 return E; 19286 } 19287 19288 ExprResult VisitParenExpr(ParenExpr *E) { 19289 return rebuildSugarExpr(E); 19290 } 19291 19292 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19293 return rebuildSugarExpr(E); 19294 } 19295 19296 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19297 const PointerType *Ptr = DestType->getAs<PointerType>(); 19298 if (!Ptr) { 19299 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19300 << E->getSourceRange(); 19301 return ExprError(); 19302 } 19303 19304 if (isa<CallExpr>(E->getSubExpr())) { 19305 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19306 << E->getSourceRange(); 19307 return ExprError(); 19308 } 19309 19310 assert(E->isPRValue()); 19311 assert(E->getObjectKind() == OK_Ordinary); 19312 E->setType(DestType); 19313 19314 // Build the sub-expression as if it were an object of the pointee type. 19315 DestType = Ptr->getPointeeType(); 19316 ExprResult SubResult = Visit(E->getSubExpr()); 19317 if (SubResult.isInvalid()) return ExprError(); 19318 E->setSubExpr(SubResult.get()); 19319 return E; 19320 } 19321 19322 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19323 19324 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19325 19326 ExprResult VisitMemberExpr(MemberExpr *E) { 19327 return resolveDecl(E, E->getMemberDecl()); 19328 } 19329 19330 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19331 return resolveDecl(E, E->getDecl()); 19332 } 19333 }; 19334 } 19335 19336 /// Rebuilds a call expression which yielded __unknown_anytype. 19337 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19338 Expr *CalleeExpr = E->getCallee(); 19339 19340 enum FnKind { 19341 FK_MemberFunction, 19342 FK_FunctionPointer, 19343 FK_BlockPointer 19344 }; 19345 19346 FnKind Kind; 19347 QualType CalleeType = CalleeExpr->getType(); 19348 if (CalleeType == S.Context.BoundMemberTy) { 19349 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19350 Kind = FK_MemberFunction; 19351 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19352 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19353 CalleeType = Ptr->getPointeeType(); 19354 Kind = FK_FunctionPointer; 19355 } else { 19356 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19357 Kind = FK_BlockPointer; 19358 } 19359 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19360 19361 // Verify that this is a legal result type of a function. 19362 if (DestType->isArrayType() || DestType->isFunctionType()) { 19363 unsigned diagID = diag::err_func_returning_array_function; 19364 if (Kind == FK_BlockPointer) 19365 diagID = diag::err_block_returning_array_function; 19366 19367 S.Diag(E->getExprLoc(), diagID) 19368 << DestType->isFunctionType() << DestType; 19369 return ExprError(); 19370 } 19371 19372 // Otherwise, go ahead and set DestType as the call's result. 19373 E->setType(DestType.getNonLValueExprType(S.Context)); 19374 E->setValueKind(Expr::getValueKindForType(DestType)); 19375 assert(E->getObjectKind() == OK_Ordinary); 19376 19377 // Rebuild the function type, replacing the result type with DestType. 19378 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19379 if (Proto) { 19380 // __unknown_anytype(...) is a special case used by the debugger when 19381 // it has no idea what a function's signature is. 19382 // 19383 // We want to build this call essentially under the K&R 19384 // unprototyped rules, but making a FunctionNoProtoType in C++ 19385 // would foul up all sorts of assumptions. However, we cannot 19386 // simply pass all arguments as variadic arguments, nor can we 19387 // portably just call the function under a non-variadic type; see 19388 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19389 // However, it turns out that in practice it is generally safe to 19390 // call a function declared as "A foo(B,C,D);" under the prototype 19391 // "A foo(B,C,D,...);". The only known exception is with the 19392 // Windows ABI, where any variadic function is implicitly cdecl 19393 // regardless of its normal CC. Therefore we change the parameter 19394 // types to match the types of the arguments. 19395 // 19396 // This is a hack, but it is far superior to moving the 19397 // corresponding target-specific code from IR-gen to Sema/AST. 19398 19399 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19400 SmallVector<QualType, 8> ArgTypes; 19401 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19402 ArgTypes.reserve(E->getNumArgs()); 19403 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19404 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19405 } 19406 ParamTypes = ArgTypes; 19407 } 19408 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19409 Proto->getExtProtoInfo()); 19410 } else { 19411 DestType = S.Context.getFunctionNoProtoType(DestType, 19412 FnType->getExtInfo()); 19413 } 19414 19415 // Rebuild the appropriate pointer-to-function type. 19416 switch (Kind) { 19417 case FK_MemberFunction: 19418 // Nothing to do. 19419 break; 19420 19421 case FK_FunctionPointer: 19422 DestType = S.Context.getPointerType(DestType); 19423 break; 19424 19425 case FK_BlockPointer: 19426 DestType = S.Context.getBlockPointerType(DestType); 19427 break; 19428 } 19429 19430 // Finally, we can recurse. 19431 ExprResult CalleeResult = Visit(CalleeExpr); 19432 if (!CalleeResult.isUsable()) return ExprError(); 19433 E->setCallee(CalleeResult.get()); 19434 19435 // Bind a temporary if necessary. 19436 return S.MaybeBindToTemporary(E); 19437 } 19438 19439 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19440 // Verify that this is a legal result type of a call. 19441 if (DestType->isArrayType() || DestType->isFunctionType()) { 19442 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19443 << DestType->isFunctionType() << DestType; 19444 return ExprError(); 19445 } 19446 19447 // Rewrite the method result type if available. 19448 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19449 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19450 Method->setReturnType(DestType); 19451 } 19452 19453 // Change the type of the message. 19454 E->setType(DestType.getNonReferenceType()); 19455 E->setValueKind(Expr::getValueKindForType(DestType)); 19456 19457 return S.MaybeBindToTemporary(E); 19458 } 19459 19460 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19461 // The only case we should ever see here is a function-to-pointer decay. 19462 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19463 assert(E->isPRValue()); 19464 assert(E->getObjectKind() == OK_Ordinary); 19465 19466 E->setType(DestType); 19467 19468 // Rebuild the sub-expression as the pointee (function) type. 19469 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19470 19471 ExprResult Result = Visit(E->getSubExpr()); 19472 if (!Result.isUsable()) return ExprError(); 19473 19474 E->setSubExpr(Result.get()); 19475 return E; 19476 } else if (E->getCastKind() == CK_LValueToRValue) { 19477 assert(E->isPRValue()); 19478 assert(E->getObjectKind() == OK_Ordinary); 19479 19480 assert(isa<BlockPointerType>(E->getType())); 19481 19482 E->setType(DestType); 19483 19484 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19485 DestType = S.Context.getLValueReferenceType(DestType); 19486 19487 ExprResult Result = Visit(E->getSubExpr()); 19488 if (!Result.isUsable()) return ExprError(); 19489 19490 E->setSubExpr(Result.get()); 19491 return E; 19492 } else { 19493 llvm_unreachable("Unhandled cast type!"); 19494 } 19495 } 19496 19497 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19498 ExprValueKind ValueKind = VK_LValue; 19499 QualType Type = DestType; 19500 19501 // We know how to make this work for certain kinds of decls: 19502 19503 // - functions 19504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19505 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19506 DestType = Ptr->getPointeeType(); 19507 ExprResult Result = resolveDecl(E, VD); 19508 if (Result.isInvalid()) return ExprError(); 19509 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19510 VK_PRValue); 19511 } 19512 19513 if (!Type->isFunctionType()) { 19514 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19515 << VD << E->getSourceRange(); 19516 return ExprError(); 19517 } 19518 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19519 // We must match the FunctionDecl's type to the hack introduced in 19520 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19521 // type. See the lengthy commentary in that routine. 19522 QualType FDT = FD->getType(); 19523 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19524 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19525 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19526 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19527 SourceLocation Loc = FD->getLocation(); 19528 FunctionDecl *NewFD = FunctionDecl::Create( 19529 S.Context, FD->getDeclContext(), Loc, Loc, 19530 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19531 SC_None, S.getCurFPFeatures().isFPConstrained(), 19532 false /*isInlineSpecified*/, FD->hasPrototype(), 19533 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19534 19535 if (FD->getQualifier()) 19536 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19537 19538 SmallVector<ParmVarDecl*, 16> Params; 19539 for (const auto &AI : FT->param_types()) { 19540 ParmVarDecl *Param = 19541 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19542 Param->setScopeInfo(0, Params.size()); 19543 Params.push_back(Param); 19544 } 19545 NewFD->setParams(Params); 19546 DRE->setDecl(NewFD); 19547 VD = DRE->getDecl(); 19548 } 19549 } 19550 19551 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19552 if (MD->isInstance()) { 19553 ValueKind = VK_PRValue; 19554 Type = S.Context.BoundMemberTy; 19555 } 19556 19557 // Function references aren't l-values in C. 19558 if (!S.getLangOpts().CPlusPlus) 19559 ValueKind = VK_PRValue; 19560 19561 // - variables 19562 } else if (isa<VarDecl>(VD)) { 19563 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19564 Type = RefTy->getPointeeType(); 19565 } else if (Type->isFunctionType()) { 19566 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19567 << VD << E->getSourceRange(); 19568 return ExprError(); 19569 } 19570 19571 // - nothing else 19572 } else { 19573 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19574 << VD << E->getSourceRange(); 19575 return ExprError(); 19576 } 19577 19578 // Modifying the declaration like this is friendly to IR-gen but 19579 // also really dangerous. 19580 VD->setType(DestType); 19581 E->setType(Type); 19582 E->setValueKind(ValueKind); 19583 return E; 19584 } 19585 19586 /// Check a cast of an unknown-any type. We intentionally only 19587 /// trigger this for C-style casts. 19588 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19589 Expr *CastExpr, CastKind &CastKind, 19590 ExprValueKind &VK, CXXCastPath &Path) { 19591 // The type we're casting to must be either void or complete. 19592 if (!CastType->isVoidType() && 19593 RequireCompleteType(TypeRange.getBegin(), CastType, 19594 diag::err_typecheck_cast_to_incomplete)) 19595 return ExprError(); 19596 19597 // Rewrite the casted expression from scratch. 19598 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19599 if (!result.isUsable()) return ExprError(); 19600 19601 CastExpr = result.get(); 19602 VK = CastExpr->getValueKind(); 19603 CastKind = CK_NoOp; 19604 19605 return CastExpr; 19606 } 19607 19608 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19609 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19610 } 19611 19612 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19613 Expr *arg, QualType ¶mType) { 19614 // If the syntactic form of the argument is not an explicit cast of 19615 // any sort, just do default argument promotion. 19616 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19617 if (!castArg) { 19618 ExprResult result = DefaultArgumentPromotion(arg); 19619 if (result.isInvalid()) return ExprError(); 19620 paramType = result.get()->getType(); 19621 return result; 19622 } 19623 19624 // Otherwise, use the type that was written in the explicit cast. 19625 assert(!arg->hasPlaceholderType()); 19626 paramType = castArg->getTypeAsWritten(); 19627 19628 // Copy-initialize a parameter of that type. 19629 InitializedEntity entity = 19630 InitializedEntity::InitializeParameter(Context, paramType, 19631 /*consumed*/ false); 19632 return PerformCopyInitialization(entity, callLoc, arg); 19633 } 19634 19635 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19636 Expr *orig = E; 19637 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19638 while (true) { 19639 E = E->IgnoreParenImpCasts(); 19640 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19641 E = call->getCallee(); 19642 diagID = diag::err_uncasted_call_of_unknown_any; 19643 } else { 19644 break; 19645 } 19646 } 19647 19648 SourceLocation loc; 19649 NamedDecl *d; 19650 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19651 loc = ref->getLocation(); 19652 d = ref->getDecl(); 19653 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19654 loc = mem->getMemberLoc(); 19655 d = mem->getMemberDecl(); 19656 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19657 diagID = diag::err_uncasted_call_of_unknown_any; 19658 loc = msg->getSelectorStartLoc(); 19659 d = msg->getMethodDecl(); 19660 if (!d) { 19661 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19662 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19663 << orig->getSourceRange(); 19664 return ExprError(); 19665 } 19666 } else { 19667 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19668 << E->getSourceRange(); 19669 return ExprError(); 19670 } 19671 19672 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19673 19674 // Never recoverable. 19675 return ExprError(); 19676 } 19677 19678 /// Check for operands with placeholder types and complain if found. 19679 /// Returns ExprError() if there was an error and no recovery was possible. 19680 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19681 if (!Context.isDependenceAllowed()) { 19682 // C cannot handle TypoExpr nodes on either side of a binop because it 19683 // doesn't handle dependent types properly, so make sure any TypoExprs have 19684 // been dealt with before checking the operands. 19685 ExprResult Result = CorrectDelayedTyposInExpr(E); 19686 if (!Result.isUsable()) return ExprError(); 19687 E = Result.get(); 19688 } 19689 19690 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19691 if (!placeholderType) return E; 19692 19693 switch (placeholderType->getKind()) { 19694 19695 // Overloaded expressions. 19696 case BuiltinType::Overload: { 19697 // Try to resolve a single function template specialization. 19698 // This is obligatory. 19699 ExprResult Result = E; 19700 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19701 return Result; 19702 19703 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19704 // leaves Result unchanged on failure. 19705 Result = E; 19706 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19707 return Result; 19708 19709 // If that failed, try to recover with a call. 19710 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19711 /*complain*/ true); 19712 return Result; 19713 } 19714 19715 // Bound member functions. 19716 case BuiltinType::BoundMember: { 19717 ExprResult result = E; 19718 const Expr *BME = E->IgnoreParens(); 19719 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19720 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19721 if (isa<CXXPseudoDestructorExpr>(BME)) { 19722 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19723 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19724 if (ME->getMemberNameInfo().getName().getNameKind() == 19725 DeclarationName::CXXDestructorName) 19726 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19727 } 19728 tryToRecoverWithCall(result, PD, 19729 /*complain*/ true); 19730 return result; 19731 } 19732 19733 // ARC unbridged casts. 19734 case BuiltinType::ARCUnbridgedCast: { 19735 Expr *realCast = stripARCUnbridgedCast(E); 19736 diagnoseARCUnbridgedCast(realCast); 19737 return realCast; 19738 } 19739 19740 // Expressions of unknown type. 19741 case BuiltinType::UnknownAny: 19742 return diagnoseUnknownAnyExpr(*this, E); 19743 19744 // Pseudo-objects. 19745 case BuiltinType::PseudoObject: 19746 return checkPseudoObjectRValue(E); 19747 19748 case BuiltinType::BuiltinFn: { 19749 // Accept __noop without parens by implicitly converting it to a call expr. 19750 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19751 if (DRE) { 19752 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19753 if (FD->getBuiltinID() == Builtin::BI__noop) { 19754 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19755 CK_BuiltinFnToFnPtr) 19756 .get(); 19757 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19758 VK_PRValue, SourceLocation(), 19759 FPOptionsOverride()); 19760 } 19761 } 19762 19763 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19764 return ExprError(); 19765 } 19766 19767 case BuiltinType::IncompleteMatrixIdx: 19768 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19769 ->getRowIdx() 19770 ->getBeginLoc(), 19771 diag::err_matrix_incomplete_index); 19772 return ExprError(); 19773 19774 // Expressions of unknown type. 19775 case BuiltinType::OMPArraySection: 19776 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19777 return ExprError(); 19778 19779 // Expressions of unknown type. 19780 case BuiltinType::OMPArrayShaping: 19781 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19782 19783 case BuiltinType::OMPIterator: 19784 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19785 19786 // Everything else should be impossible. 19787 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19788 case BuiltinType::Id: 19789 #include "clang/Basic/OpenCLImageTypes.def" 19790 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19791 case BuiltinType::Id: 19792 #include "clang/Basic/OpenCLExtensionTypes.def" 19793 #define SVE_TYPE(Name, Id, SingletonId) \ 19794 case BuiltinType::Id: 19795 #include "clang/Basic/AArch64SVEACLETypes.def" 19796 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19797 case BuiltinType::Id: 19798 #include "clang/Basic/PPCTypes.def" 19799 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19800 #include "clang/Basic/RISCVVTypes.def" 19801 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19802 #define PLACEHOLDER_TYPE(Id, SingletonId) 19803 #include "clang/AST/BuiltinTypes.def" 19804 break; 19805 } 19806 19807 llvm_unreachable("invalid placeholder type!"); 19808 } 19809 19810 bool Sema::CheckCaseExpression(Expr *E) { 19811 if (E->isTypeDependent()) 19812 return true; 19813 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19814 return E->getType()->isIntegralOrEnumerationType(); 19815 return false; 19816 } 19817 19818 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19819 ExprResult 19820 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19821 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19822 "Unknown Objective-C Boolean value!"); 19823 QualType BoolT = Context.ObjCBuiltinBoolTy; 19824 if (!Context.getBOOLDecl()) { 19825 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19826 Sema::LookupOrdinaryName); 19827 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19828 NamedDecl *ND = Result.getFoundDecl(); 19829 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19830 Context.setBOOLDecl(TD); 19831 } 19832 } 19833 if (Context.getBOOLDecl()) 19834 BoolT = Context.getBOOLType(); 19835 return new (Context) 19836 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19837 } 19838 19839 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19840 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19841 SourceLocation RParen) { 19842 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19843 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19844 return Spec.getPlatform() == Platform; 19845 }); 19846 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19847 // for "maccatalyst" if "maccatalyst" is not specified. 19848 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19849 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19850 return Spec.getPlatform() == "ios"; 19851 }); 19852 } 19853 if (Spec == AvailSpecs.end()) 19854 return None; 19855 return Spec->getVersion(); 19856 }; 19857 19858 VersionTuple Version; 19859 if (auto MaybeVersion = 19860 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19861 Version = *MaybeVersion; 19862 19863 // The use of `@available` in the enclosing context should be analyzed to 19864 // warn when it's used inappropriately (i.e. not if(@available)). 19865 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19866 Context->HasPotentialAvailabilityViolations = true; 19867 19868 return new (Context) 19869 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19870 } 19871 19872 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19873 ArrayRef<Expr *> SubExprs, QualType T) { 19874 if (!Context.getLangOpts().RecoveryAST) 19875 return ExprError(); 19876 19877 if (isSFINAEContext()) 19878 return ExprError(); 19879 19880 if (T.isNull() || T->isUndeducedType() || 19881 !Context.getLangOpts().RecoveryASTType) 19882 // We don't know the concrete type, fallback to dependent type. 19883 T = Context.DependentTy; 19884 19885 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19886 } 19887