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 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay).get(); 531 } 532 return E; 533 } 534 535 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 536 // Check to see if we are dereferencing a null pointer. If so, 537 // and if not volatile-qualified, this is undefined behavior that the 538 // optimizer will delete, so warn about it. People sometimes try to use this 539 // to get a deterministic trap and are surprised by clang's behavior. This 540 // only handles the pattern "*null", which is a very syntactic check. 541 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 542 if (UO && UO->getOpcode() == UO_Deref && 543 UO->getSubExpr()->getType()->isPointerType()) { 544 const LangAS AS = 545 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 546 if ((!isTargetAddressSpace(AS) || 547 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 548 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 549 S.Context, Expr::NPC_ValueDependentIsNotNull) && 550 !UO->getType().isVolatileQualified()) { 551 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 552 S.PDiag(diag::warn_indirection_through_null) 553 << UO->getSubExpr()->getSourceRange()); 554 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 555 S.PDiag(diag::note_indirection_through_null)); 556 } 557 } 558 } 559 560 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 561 SourceLocation AssignLoc, 562 const Expr* RHS) { 563 const ObjCIvarDecl *IV = OIRE->getDecl(); 564 if (!IV) 565 return; 566 567 DeclarationName MemberName = IV->getDeclName(); 568 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 569 if (!Member || !Member->isStr("isa")) 570 return; 571 572 const Expr *Base = OIRE->getBase(); 573 QualType BaseType = Base->getType(); 574 if (OIRE->isArrow()) 575 BaseType = BaseType->getPointeeType(); 576 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 577 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 578 ObjCInterfaceDecl *ClassDeclared = nullptr; 579 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 580 if (!ClassDeclared->getSuperClass() 581 && (*ClassDeclared->ivar_begin()) == IV) { 582 if (RHS) { 583 NamedDecl *ObjectSetClass = 584 S.LookupSingleName(S.TUScope, 585 &S.Context.Idents.get("object_setClass"), 586 SourceLocation(), S.LookupOrdinaryName); 587 if (ObjectSetClass) { 588 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 589 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 590 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 591 "object_setClass(") 592 << FixItHint::CreateReplacement( 593 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 594 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 595 } 596 else 597 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 598 } else { 599 NamedDecl *ObjectGetClass = 600 S.LookupSingleName(S.TUScope, 601 &S.Context.Idents.get("object_getClass"), 602 SourceLocation(), S.LookupOrdinaryName); 603 if (ObjectGetClass) 604 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 605 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 606 "object_getClass(") 607 << FixItHint::CreateReplacement( 608 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 609 else 610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 611 } 612 S.Diag(IV->getLocation(), diag::note_ivar_decl); 613 } 614 } 615 } 616 617 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 618 // Handle any placeholder expressions which made it here. 619 if (E->getType()->isPlaceholderType()) { 620 ExprResult result = CheckPlaceholderExpr(E); 621 if (result.isInvalid()) return ExprError(); 622 E = result.get(); 623 } 624 625 // C++ [conv.lval]p1: 626 // A glvalue of a non-function, non-array type T can be 627 // converted to a prvalue. 628 if (!E->isGLValue()) return E; 629 630 QualType T = E->getType(); 631 assert(!T.isNull() && "r-value conversion on typeless expression?"); 632 633 // lvalue-to-rvalue conversion cannot be applied to function or array types. 634 if (T->isFunctionType() || T->isArrayType()) 635 return E; 636 637 // We don't want to throw lvalue-to-rvalue casts on top of 638 // expressions of certain types in C++. 639 if (getLangOpts().CPlusPlus && 640 (E->getType() == Context.OverloadTy || 641 T->isDependentType() || 642 T->isRecordType())) 643 return E; 644 645 // The C standard is actually really unclear on this point, and 646 // DR106 tells us what the result should be but not why. It's 647 // generally best to say that void types just doesn't undergo 648 // lvalue-to-rvalue at all. Note that expressions of unqualified 649 // 'void' type are never l-values, but qualified void can be. 650 if (T->isVoidType()) 651 return E; 652 653 // OpenCL usually rejects direct accesses to values of 'half' type. 654 if (getLangOpts().OpenCL && 655 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 656 T->isHalfType()) { 657 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 658 << 0 << T; 659 return ExprError(); 660 } 661 662 CheckForNullPointerDereference(*this, E); 663 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 664 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 665 &Context.Idents.get("object_getClass"), 666 SourceLocation(), LookupOrdinaryName); 667 if (ObjectGetClass) 668 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 669 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 670 << FixItHint::CreateReplacement( 671 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 672 else 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 674 } 675 else if (const ObjCIvarRefExpr *OIRE = 676 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 677 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 678 679 // C++ [conv.lval]p1: 680 // [...] If T is a non-class type, the type of the prvalue is the 681 // cv-unqualified version of T. Otherwise, the type of the 682 // rvalue is T. 683 // 684 // C99 6.3.2.1p2: 685 // If the lvalue has qualified type, the value has the unqualified 686 // version of the type of the lvalue; otherwise, the value has the 687 // type of the lvalue. 688 if (T.hasQualifiers()) 689 T = T.getUnqualifiedType(); 690 691 // Under the MS ABI, lock down the inheritance model now. 692 if (T->isMemberPointerType() && 693 Context.getTargetInfo().getCXXABI().isMicrosoft()) 694 (void)isCompleteType(E->getExprLoc(), T); 695 696 ExprResult Res = CheckLValueToRValueConversionOperand(E); 697 if (Res.isInvalid()) 698 return Res; 699 E = Res.get(); 700 701 // Loading a __weak object implicitly retains the value, so we need a cleanup to 702 // balance that. 703 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 704 Cleanup.setExprNeedsCleanups(true); 705 706 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 707 Cleanup.setExprNeedsCleanups(true); 708 709 // C++ [conv.lval]p3: 710 // If T is cv std::nullptr_t, the result is a null pointer constant. 711 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 712 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 713 CurFPFeatureOverrides()); 714 715 // C11 6.3.2.1p2: 716 // ... if the lvalue has atomic type, the value has the non-atomic version 717 // of the type of the lvalue ... 718 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 719 T = Atomic->getValueType().getUnqualifiedType(); 720 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 721 nullptr, VK_PRValue, FPOptionsOverride()); 722 } 723 724 return Res; 725 } 726 727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 728 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 729 if (Res.isInvalid()) 730 return ExprError(); 731 Res = DefaultLvalueConversion(Res.get()); 732 if (Res.isInvalid()) 733 return ExprError(); 734 return Res; 735 } 736 737 /// CallExprUnaryConversions - a special case of an unary conversion 738 /// performed on a function designator of a call expression. 739 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 740 QualType Ty = E->getType(); 741 ExprResult Res = E; 742 // Only do implicit cast for a function type, but not for a pointer 743 // to function type. 744 if (Ty->isFunctionType()) { 745 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 746 CK_FunctionToPointerDecay); 747 if (Res.isInvalid()) 748 return ExprError(); 749 } 750 Res = DefaultLvalueConversion(Res.get()); 751 if (Res.isInvalid()) 752 return ExprError(); 753 return Res.get(); 754 } 755 756 /// UsualUnaryConversions - Performs various conversions that are common to most 757 /// operators (C99 6.3). The conversions of array and function types are 758 /// sometimes suppressed. For example, the array->pointer conversion doesn't 759 /// apply if the array is an argument to the sizeof or address (&) operators. 760 /// In these instances, this routine should *not* be called. 761 ExprResult Sema::UsualUnaryConversions(Expr *E) { 762 // First, convert to an r-value. 763 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 764 if (Res.isInvalid()) 765 return ExprError(); 766 E = Res.get(); 767 768 QualType Ty = E->getType(); 769 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 770 771 // Half FP have to be promoted to float unless it is natively supported 772 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 773 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 774 775 // Try to perform integral promotions if the object has a theoretically 776 // promotable type. 777 if (Ty->isIntegralOrUnscopedEnumerationType()) { 778 // C99 6.3.1.1p2: 779 // 780 // The following may be used in an expression wherever an int or 781 // unsigned int may be used: 782 // - an object or expression with an integer type whose integer 783 // conversion rank is less than or equal to the rank of int 784 // and unsigned int. 785 // - A bit-field of type _Bool, int, signed int, or unsigned int. 786 // 787 // If an int can represent all values of the original type, the 788 // value is converted to an int; otherwise, it is converted to an 789 // unsigned int. These are called the integer promotions. All 790 // other types are unchanged by the integer promotions. 791 792 QualType PTy = Context.isPromotableBitField(E); 793 if (!PTy.isNull()) { 794 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 795 return E; 796 } 797 if (Ty->isPromotableIntegerType()) { 798 QualType PT = Context.getPromotedIntegerType(Ty); 799 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 800 return E; 801 } 802 } 803 return E; 804 } 805 806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 807 /// do not have a prototype. Arguments that have type float or __fp16 808 /// are promoted to double. All other argument types are converted by 809 /// UsualUnaryConversions(). 810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 811 QualType Ty = E->getType(); 812 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 813 814 ExprResult Res = UsualUnaryConversions(E); 815 if (Res.isInvalid()) 816 return ExprError(); 817 E = Res.get(); 818 819 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 820 // promote to double. 821 // Note that default argument promotion applies only to float (and 822 // half/fp16); it does not apply to _Float16. 823 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 824 if (BTy && (BTy->getKind() == BuiltinType::Half || 825 BTy->getKind() == BuiltinType::Float)) { 826 if (getLangOpts().OpenCL && 827 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 828 if (BTy->getKind() == BuiltinType::Half) { 829 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 830 } 831 } else { 832 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 833 } 834 } 835 if (BTy && 836 getLangOpts().getExtendIntArgs() == 837 LangOptions::ExtendArgsKind::ExtendTo64 && 838 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 839 Context.getTypeSizeInChars(BTy) < 840 Context.getTypeSizeInChars(Context.LongLongTy)) { 841 E = (Ty->isUnsignedIntegerType()) 842 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 843 .get() 844 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 845 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 846 "Unexpected typesize for LongLongTy"); 847 } 848 849 // C++ performs lvalue-to-rvalue conversion as a default argument 850 // promotion, even on class types, but note: 851 // C++11 [conv.lval]p2: 852 // When an lvalue-to-rvalue conversion occurs in an unevaluated 853 // operand or a subexpression thereof the value contained in the 854 // referenced object is not accessed. Otherwise, if the glvalue 855 // has a class type, the conversion copy-initializes a temporary 856 // of type T from the glvalue and the result of the conversion 857 // is a prvalue for the temporary. 858 // FIXME: add some way to gate this entire thing for correctness in 859 // potentially potentially evaluated contexts. 860 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 861 ExprResult Temp = PerformCopyInitialization( 862 InitializedEntity::InitializeTemporary(E->getType()), 863 E->getExprLoc(), E); 864 if (Temp.isInvalid()) 865 return ExprError(); 866 E = Temp.get(); 867 } 868 869 return E; 870 } 871 872 /// Determine the degree of POD-ness for an expression. 873 /// Incomplete types are considered POD, since this check can be performed 874 /// when we're in an unevaluated context. 875 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 876 if (Ty->isIncompleteType()) { 877 // C++11 [expr.call]p7: 878 // After these conversions, if the argument does not have arithmetic, 879 // enumeration, pointer, pointer to member, or class type, the program 880 // is ill-formed. 881 // 882 // Since we've already performed array-to-pointer and function-to-pointer 883 // decay, the only such type in C++ is cv void. This also handles 884 // initializer lists as variadic arguments. 885 if (Ty->isVoidType()) 886 return VAK_Invalid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 return VAK_Valid; 891 } 892 893 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 894 return VAK_Invalid; 895 896 if (Ty.isCXX98PODType(Context)) 897 return VAK_Valid; 898 899 // C++11 [expr.call]p7: 900 // Passing a potentially-evaluated argument of class type (Clause 9) 901 // having a non-trivial copy constructor, a non-trivial move constructor, 902 // or a non-trivial destructor, with no corresponding parameter, 903 // is conditionally-supported with implementation-defined semantics. 904 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 905 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 906 if (!Record->hasNonTrivialCopyConstructor() && 907 !Record->hasNonTrivialMoveConstructor() && 908 !Record->hasNonTrivialDestructor()) 909 return VAK_ValidInCXX11; 910 911 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 912 return VAK_Valid; 913 914 if (Ty->isObjCObjectType()) 915 return VAK_Invalid; 916 917 if (getLangOpts().MSVCCompat) 918 return VAK_MSVCUndefined; 919 920 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 921 // permitted to reject them. We should consider doing so. 922 return VAK_Undefined; 923 } 924 925 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 926 // Don't allow one to pass an Objective-C interface to a vararg. 927 const QualType &Ty = E->getType(); 928 VarArgKind VAK = isValidVarArgType(Ty); 929 930 // Complain about passing non-POD types through varargs. 931 switch (VAK) { 932 case VAK_ValidInCXX11: 933 DiagRuntimeBehavior( 934 E->getBeginLoc(), nullptr, 935 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 936 LLVM_FALLTHROUGH; 937 case VAK_Valid: 938 if (Ty->isRecordType()) { 939 // This is unlikely to be what the user intended. If the class has a 940 // 'c_str' member function, the user probably meant to call that. 941 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 942 PDiag(diag::warn_pass_class_arg_to_vararg) 943 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 944 } 945 break; 946 947 case VAK_Undefined: 948 case VAK_MSVCUndefined: 949 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 950 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 951 << getLangOpts().CPlusPlus11 << Ty << CT); 952 break; 953 954 case VAK_Invalid: 955 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 956 Diag(E->getBeginLoc(), 957 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 958 << Ty << CT; 959 else if (Ty->isObjCObjectType()) 960 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 961 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 962 << Ty << CT); 963 else 964 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 965 << isa<InitListExpr>(E) << Ty << CT; 966 break; 967 } 968 } 969 970 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 971 /// will create a trap if the resulting type is not a POD type. 972 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 973 FunctionDecl *FDecl) { 974 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 975 // Strip the unbridged-cast placeholder expression off, if applicable. 976 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 977 (CT == VariadicMethod || 978 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 979 E = stripARCUnbridgedCast(E); 980 981 // Otherwise, do normal placeholder checking. 982 } else { 983 ExprResult ExprRes = CheckPlaceholderExpr(E); 984 if (ExprRes.isInvalid()) 985 return ExprError(); 986 E = ExprRes.get(); 987 } 988 } 989 990 ExprResult ExprRes = DefaultArgumentPromotion(E); 991 if (ExprRes.isInvalid()) 992 return ExprError(); 993 994 // Copy blocks to the heap. 995 if (ExprRes.get()->getType()->isBlockPointerType()) 996 maybeExtendBlockObject(ExprRes); 997 998 E = ExprRes.get(); 999 1000 // Diagnostics regarding non-POD argument types are 1001 // emitted along with format string checking in Sema::CheckFunctionCall(). 1002 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1003 // Turn this into a trap. 1004 CXXScopeSpec SS; 1005 SourceLocation TemplateKWLoc; 1006 UnqualifiedId Name; 1007 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1008 E->getBeginLoc()); 1009 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1010 /*HasTrailingLParen=*/true, 1011 /*IsAddressOfOperand=*/false); 1012 if (TrapFn.isInvalid()) 1013 return ExprError(); 1014 1015 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1016 None, E->getEndLoc()); 1017 if (Call.isInvalid()) 1018 return ExprError(); 1019 1020 ExprResult Comma = 1021 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1022 if (Comma.isInvalid()) 1023 return ExprError(); 1024 return Comma.get(); 1025 } 1026 1027 if (!getLangOpts().CPlusPlus && 1028 RequireCompleteType(E->getExprLoc(), E->getType(), 1029 diag::err_call_incomplete_argument)) 1030 return ExprError(); 1031 1032 return E; 1033 } 1034 1035 /// Converts an integer to complex float type. Helper function of 1036 /// UsualArithmeticConversions() 1037 /// 1038 /// \return false if the integer expression is an integer type and is 1039 /// successfully converted to the complex type. 1040 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1041 ExprResult &ComplexExpr, 1042 QualType IntTy, 1043 QualType ComplexTy, 1044 bool SkipCast) { 1045 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1046 if (SkipCast) return false; 1047 if (IntTy->isIntegerType()) { 1048 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1049 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1050 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1051 CK_FloatingRealToComplex); 1052 } else { 1053 assert(IntTy->isComplexIntegerType()); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1055 CK_IntegralComplexToFloatingComplex); 1056 } 1057 return false; 1058 } 1059 1060 /// Handle arithmetic conversion with complex types. Helper function of 1061 /// UsualArithmeticConversions() 1062 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1063 ExprResult &RHS, QualType LHSType, 1064 QualType RHSType, 1065 bool IsCompAssign) { 1066 // if we have an integer operand, the result is the complex type. 1067 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1068 /*skipCast*/false)) 1069 return LHSType; 1070 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1071 /*skipCast*/IsCompAssign)) 1072 return RHSType; 1073 1074 // This handles complex/complex, complex/float, or float/complex. 1075 // When both operands are complex, the shorter operand is converted to the 1076 // type of the longer, and that is the type of the result. This corresponds 1077 // to what is done when combining two real floating-point operands. 1078 // The fun begins when size promotion occur across type domains. 1079 // From H&S 6.3.4: When one operand is complex and the other is a real 1080 // floating-point type, the less precise type is converted, within it's 1081 // real or complex domain, to the precision of the other type. For example, 1082 // when combining a "long double" with a "double _Complex", the 1083 // "double _Complex" is promoted to "long double _Complex". 1084 1085 // Compute the rank of the two types, regardless of whether they are complex. 1086 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1087 1088 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1089 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1090 QualType LHSElementType = 1091 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1092 QualType RHSElementType = 1093 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1094 1095 QualType ResultType = S.Context.getComplexType(LHSElementType); 1096 if (Order < 0) { 1097 // Promote the precision of the LHS if not an assignment. 1098 ResultType = S.Context.getComplexType(RHSElementType); 1099 if (!IsCompAssign) { 1100 if (LHSComplexType) 1101 LHS = 1102 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1103 else 1104 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1105 } 1106 } else if (Order > 0) { 1107 // Promote the precision of the RHS. 1108 if (RHSComplexType) 1109 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1110 else 1111 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1112 } 1113 return ResultType; 1114 } 1115 1116 /// Handle arithmetic conversion from integer to float. Helper function 1117 /// of UsualArithmeticConversions() 1118 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1119 ExprResult &IntExpr, 1120 QualType FloatTy, QualType IntTy, 1121 bool ConvertFloat, bool ConvertInt) { 1122 if (IntTy->isIntegerType()) { 1123 if (ConvertInt) 1124 // Convert intExpr to the lhs floating point type. 1125 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1126 CK_IntegralToFloating); 1127 return FloatTy; 1128 } 1129 1130 // Convert both sides to the appropriate complex float. 1131 assert(IntTy->isComplexIntegerType()); 1132 QualType result = S.Context.getComplexType(FloatTy); 1133 1134 // _Complex int -> _Complex float 1135 if (ConvertInt) 1136 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1137 CK_IntegralComplexToFloatingComplex); 1138 1139 // float -> _Complex float 1140 if (ConvertFloat) 1141 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1142 CK_FloatingRealToComplex); 1143 1144 return result; 1145 } 1146 1147 /// Handle arithmethic conversion with floating point types. Helper 1148 /// function of UsualArithmeticConversions() 1149 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1150 ExprResult &RHS, QualType LHSType, 1151 QualType RHSType, bool IsCompAssign) { 1152 bool LHSFloat = LHSType->isRealFloatingType(); 1153 bool RHSFloat = RHSType->isRealFloatingType(); 1154 1155 // N1169 4.1.4: If one of the operands has a floating type and the other 1156 // operand has a fixed-point type, the fixed-point operand 1157 // is converted to the floating type [...] 1158 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1159 if (LHSFloat) 1160 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1161 else if (!IsCompAssign) 1162 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1163 return LHSFloat ? LHSType : RHSType; 1164 } 1165 1166 // If we have two real floating types, convert the smaller operand 1167 // to the bigger result. 1168 if (LHSFloat && RHSFloat) { 1169 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1170 if (order > 0) { 1171 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1172 return LHSType; 1173 } 1174 1175 assert(order < 0 && "illegal float comparison"); 1176 if (!IsCompAssign) 1177 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1178 return RHSType; 1179 } 1180 1181 if (LHSFloat) { 1182 // Half FP has to be promoted to float unless it is natively supported 1183 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1184 LHSType = S.Context.FloatTy; 1185 1186 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1187 /*ConvertFloat=*/!IsCompAssign, 1188 /*ConvertInt=*/ true); 1189 } 1190 assert(RHSFloat); 1191 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1192 /*ConvertFloat=*/ true, 1193 /*ConvertInt=*/!IsCompAssign); 1194 } 1195 1196 /// Diagnose attempts to convert between __float128 and long double if 1197 /// there is no support for such conversion. Helper function of 1198 /// UsualArithmeticConversions(). 1199 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1200 QualType RHSType) { 1201 /* No issue converting if at least one of the types is not a floating point 1202 type or the two types have the same rank. 1203 */ 1204 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1205 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1206 return false; 1207 1208 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1209 "The remaining types must be floating point types."); 1210 1211 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1212 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1213 1214 QualType LHSElemType = LHSComplex ? 1215 LHSComplex->getElementType() : LHSType; 1216 QualType RHSElemType = RHSComplex ? 1217 RHSComplex->getElementType() : RHSType; 1218 1219 // No issue if the two types have the same representation 1220 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1221 &S.Context.getFloatTypeSemantics(RHSElemType)) 1222 return false; 1223 1224 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1225 RHSElemType == S.Context.LongDoubleTy); 1226 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1227 RHSElemType == S.Context.Float128Ty); 1228 1229 // We've handled the situation where __float128 and long double have the same 1230 // representation. We allow all conversions for all possible long double types 1231 // except PPC's double double. 1232 return Float128AndLongDouble && 1233 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1234 &llvm::APFloat::PPCDoubleDouble()); 1235 } 1236 1237 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1238 1239 namespace { 1240 /// These helper callbacks are placed in an anonymous namespace to 1241 /// permit their use as function template parameters. 1242 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1243 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1244 } 1245 1246 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1247 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1248 CK_IntegralComplexCast); 1249 } 1250 } 1251 1252 /// Handle integer arithmetic conversions. Helper function of 1253 /// UsualArithmeticConversions() 1254 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1255 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1256 ExprResult &RHS, QualType LHSType, 1257 QualType RHSType, bool IsCompAssign) { 1258 // The rules for this case are in C99 6.3.1.8 1259 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1260 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1261 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1262 if (LHSSigned == RHSSigned) { 1263 // Same signedness; use the higher-ranked type 1264 if (order >= 0) { 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 (order != (LHSSigned ? 1 : -1)) { 1271 // The unsigned type has greater than or equal rank to the 1272 // signed type, so use the unsigned type 1273 if (RHSSigned) { 1274 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1275 return LHSType; 1276 } else if (!IsCompAssign) 1277 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1278 return RHSType; 1279 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1280 // The two types are different widths; if we are here, that 1281 // means the signed type is larger than the unsigned type, so 1282 // use the signed type. 1283 if (LHSSigned) { 1284 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1285 return LHSType; 1286 } else if (!IsCompAssign) 1287 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1288 return RHSType; 1289 } else { 1290 // The signed type is higher-ranked than the unsigned type, 1291 // but isn't actually any bigger (like unsigned int and long 1292 // on most 32-bit systems). Use the unsigned type corresponding 1293 // to the signed type. 1294 QualType result = 1295 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1296 RHS = (*doRHSCast)(S, RHS.get(), result); 1297 if (!IsCompAssign) 1298 LHS = (*doLHSCast)(S, LHS.get(), result); 1299 return result; 1300 } 1301 } 1302 1303 /// Handle conversions with GCC complex int extension. Helper function 1304 /// of UsualArithmeticConversions() 1305 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1306 ExprResult &RHS, QualType LHSType, 1307 QualType RHSType, 1308 bool IsCompAssign) { 1309 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1310 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1311 1312 if (LHSComplexInt && RHSComplexInt) { 1313 QualType LHSEltType = LHSComplexInt->getElementType(); 1314 QualType RHSEltType = RHSComplexInt->getElementType(); 1315 QualType ScalarType = 1316 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1317 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1318 1319 return S.Context.getComplexType(ScalarType); 1320 } 1321 1322 if (LHSComplexInt) { 1323 QualType LHSEltType = LHSComplexInt->getElementType(); 1324 QualType ScalarType = 1325 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1326 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1327 QualType ComplexType = S.Context.getComplexType(ScalarType); 1328 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1329 CK_IntegralRealToComplex); 1330 1331 return ComplexType; 1332 } 1333 1334 assert(RHSComplexInt); 1335 1336 QualType RHSEltType = RHSComplexInt->getElementType(); 1337 QualType ScalarType = 1338 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1339 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1340 QualType ComplexType = S.Context.getComplexType(ScalarType); 1341 1342 if (!IsCompAssign) 1343 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1344 CK_IntegralRealToComplex); 1345 return ComplexType; 1346 } 1347 1348 /// Return the rank of a given fixed point or integer type. The value itself 1349 /// doesn't matter, but the values must be increasing with proper increasing 1350 /// rank as described in N1169 4.1.1. 1351 static unsigned GetFixedPointRank(QualType Ty) { 1352 const auto *BTy = Ty->getAs<BuiltinType>(); 1353 assert(BTy && "Expected a builtin type."); 1354 1355 switch (BTy->getKind()) { 1356 case BuiltinType::ShortFract: 1357 case BuiltinType::UShortFract: 1358 case BuiltinType::SatShortFract: 1359 case BuiltinType::SatUShortFract: 1360 return 1; 1361 case BuiltinType::Fract: 1362 case BuiltinType::UFract: 1363 case BuiltinType::SatFract: 1364 case BuiltinType::SatUFract: 1365 return 2; 1366 case BuiltinType::LongFract: 1367 case BuiltinType::ULongFract: 1368 case BuiltinType::SatLongFract: 1369 case BuiltinType::SatULongFract: 1370 return 3; 1371 case BuiltinType::ShortAccum: 1372 case BuiltinType::UShortAccum: 1373 case BuiltinType::SatShortAccum: 1374 case BuiltinType::SatUShortAccum: 1375 return 4; 1376 case BuiltinType::Accum: 1377 case BuiltinType::UAccum: 1378 case BuiltinType::SatAccum: 1379 case BuiltinType::SatUAccum: 1380 return 5; 1381 case BuiltinType::LongAccum: 1382 case BuiltinType::ULongAccum: 1383 case BuiltinType::SatLongAccum: 1384 case BuiltinType::SatULongAccum: 1385 return 6; 1386 default: 1387 if (BTy->isInteger()) 1388 return 0; 1389 llvm_unreachable("Unexpected fixed point or integer type"); 1390 } 1391 } 1392 1393 /// handleFixedPointConversion - Fixed point operations between fixed 1394 /// point types and integers or other fixed point types do not fall under 1395 /// usual arithmetic conversion since these conversions could result in loss 1396 /// of precsision (N1169 4.1.4). These operations should be calculated with 1397 /// the full precision of their result type (N1169 4.1.6.2.1). 1398 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1399 QualType RHSTy) { 1400 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1401 "Expected at least one of the operands to be a fixed point type"); 1402 assert((LHSTy->isFixedPointOrIntegerType() || 1403 RHSTy->isFixedPointOrIntegerType()) && 1404 "Special fixed point arithmetic operation conversions are only " 1405 "applied to ints or other fixed point types"); 1406 1407 // If one operand has signed fixed-point type and the other operand has 1408 // unsigned fixed-point type, then the unsigned fixed-point operand is 1409 // converted to its corresponding signed fixed-point type and the resulting 1410 // type is the type of the converted operand. 1411 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1412 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1413 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1414 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1415 1416 // The result type is the type with the highest rank, whereby a fixed-point 1417 // conversion rank is always greater than an integer conversion rank; if the 1418 // type of either of the operands is a saturating fixedpoint type, the result 1419 // type shall be the saturating fixed-point type corresponding to the type 1420 // with the highest rank; the resulting value is converted (taking into 1421 // account rounding and overflow) to the precision of the resulting type. 1422 // Same ranks between signed and unsigned types are resolved earlier, so both 1423 // types are either signed or both unsigned at this point. 1424 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1425 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1426 1427 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1428 1429 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1430 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1431 1432 return ResultTy; 1433 } 1434 1435 /// Check that the usual arithmetic conversions can be performed on this pair of 1436 /// expressions that might be of enumeration type. 1437 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1438 SourceLocation Loc, 1439 Sema::ArithConvKind ACK) { 1440 // C++2a [expr.arith.conv]p1: 1441 // If one operand is of enumeration type and the other operand is of a 1442 // different enumeration type or a floating-point type, this behavior is 1443 // deprecated ([depr.arith.conv.enum]). 1444 // 1445 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1446 // Eventually we will presumably reject these cases (in C++23 onwards?). 1447 QualType L = LHS->getType(), R = RHS->getType(); 1448 bool LEnum = L->isUnscopedEnumerationType(), 1449 REnum = R->isUnscopedEnumerationType(); 1450 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1451 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1452 (REnum && L->isFloatingType())) { 1453 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1454 ? diag::warn_arith_conv_enum_float_cxx20 1455 : diag::warn_arith_conv_enum_float) 1456 << LHS->getSourceRange() << RHS->getSourceRange() 1457 << (int)ACK << LEnum << L << R; 1458 } else if (!IsCompAssign && LEnum && REnum && 1459 !S.Context.hasSameUnqualifiedType(L, R)) { 1460 unsigned DiagID; 1461 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1462 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1463 // If either enumeration type is unnamed, it's less likely that the 1464 // user cares about this, but this situation is still deprecated in 1465 // C++2a. Use a different warning group. 1466 DiagID = S.getLangOpts().CPlusPlus20 1467 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1468 : diag::warn_arith_conv_mixed_anon_enum_types; 1469 } else if (ACK == Sema::ACK_Conditional) { 1470 // Conditional expressions are separated out because they have 1471 // historically had a different warning flag. 1472 DiagID = S.getLangOpts().CPlusPlus20 1473 ? diag::warn_conditional_mixed_enum_types_cxx20 1474 : diag::warn_conditional_mixed_enum_types; 1475 } else if (ACK == Sema::ACK_Comparison) { 1476 // Comparison expressions are separated out because they have 1477 // historically had a different warning flag. 1478 DiagID = S.getLangOpts().CPlusPlus20 1479 ? diag::warn_comparison_mixed_enum_types_cxx20 1480 : diag::warn_comparison_mixed_enum_types; 1481 } else { 1482 DiagID = S.getLangOpts().CPlusPlus20 1483 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1484 : diag::warn_arith_conv_mixed_enum_types; 1485 } 1486 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1487 << (int)ACK << L << R; 1488 } 1489 } 1490 1491 /// UsualArithmeticConversions - Performs various conversions that are common to 1492 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1493 /// routine returns the first non-arithmetic type found. The client is 1494 /// responsible for emitting appropriate error diagnostics. 1495 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1496 SourceLocation Loc, 1497 ArithConvKind ACK) { 1498 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1499 1500 if (ACK != ACK_CompAssign) { 1501 LHS = UsualUnaryConversions(LHS.get()); 1502 if (LHS.isInvalid()) 1503 return QualType(); 1504 } 1505 1506 RHS = UsualUnaryConversions(RHS.get()); 1507 if (RHS.isInvalid()) 1508 return QualType(); 1509 1510 // For conversion purposes, we ignore any qualifiers. 1511 // For example, "const float" and "float" are equivalent. 1512 QualType LHSType = 1513 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1514 QualType RHSType = 1515 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1516 1517 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1518 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1519 LHSType = AtomicLHS->getValueType(); 1520 1521 // If both types are identical, no conversion is needed. 1522 if (LHSType == RHSType) 1523 return LHSType; 1524 1525 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1526 // The caller can deal with this (e.g. pointer + int). 1527 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1528 return QualType(); 1529 1530 // Apply unary and bitfield promotions to the LHS's type. 1531 QualType LHSUnpromotedType = LHSType; 1532 if (LHSType->isPromotableIntegerType()) 1533 LHSType = Context.getPromotedIntegerType(LHSType); 1534 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1535 if (!LHSBitfieldPromoteTy.isNull()) 1536 LHSType = LHSBitfieldPromoteTy; 1537 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1538 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1539 1540 // If both types are identical, no conversion is needed. 1541 if (LHSType == RHSType) 1542 return LHSType; 1543 1544 // ExtInt types aren't subject to conversions between them or normal integers, 1545 // so this fails. 1546 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1547 return QualType(); 1548 1549 // At this point, we have two different arithmetic types. 1550 1551 // Diagnose attempts to convert between __float128 and long double where 1552 // such conversions currently can't be handled. 1553 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1554 return QualType(); 1555 1556 // Handle complex types first (C99 6.3.1.8p1). 1557 if (LHSType->isComplexType() || RHSType->isComplexType()) 1558 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1559 ACK == ACK_CompAssign); 1560 1561 // Now handle "real" floating types (i.e. float, double, long double). 1562 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1563 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1564 ACK == ACK_CompAssign); 1565 1566 // Handle GCC complex int extension. 1567 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1568 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1569 ACK == ACK_CompAssign); 1570 1571 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1572 return handleFixedPointConversion(*this, LHSType, RHSType); 1573 1574 // Finally, we have two differing integer types. 1575 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1576 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1577 } 1578 1579 //===----------------------------------------------------------------------===// 1580 // Semantic Analysis for various Expression Types 1581 //===----------------------------------------------------------------------===// 1582 1583 1584 ExprResult 1585 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1586 SourceLocation DefaultLoc, 1587 SourceLocation RParenLoc, 1588 Expr *ControllingExpr, 1589 ArrayRef<ParsedType> ArgTypes, 1590 ArrayRef<Expr *> ArgExprs) { 1591 unsigned NumAssocs = ArgTypes.size(); 1592 assert(NumAssocs == ArgExprs.size()); 1593 1594 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1595 for (unsigned i = 0; i < NumAssocs; ++i) { 1596 if (ArgTypes[i]) 1597 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1598 else 1599 Types[i] = nullptr; 1600 } 1601 1602 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1603 ControllingExpr, 1604 llvm::makeArrayRef(Types, NumAssocs), 1605 ArgExprs); 1606 delete [] Types; 1607 return ER; 1608 } 1609 1610 ExprResult 1611 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1612 SourceLocation DefaultLoc, 1613 SourceLocation RParenLoc, 1614 Expr *ControllingExpr, 1615 ArrayRef<TypeSourceInfo *> Types, 1616 ArrayRef<Expr *> Exprs) { 1617 unsigned NumAssocs = Types.size(); 1618 assert(NumAssocs == Exprs.size()); 1619 1620 // Decay and strip qualifiers for the controlling expression type, and handle 1621 // placeholder type replacement. See committee discussion from WG14 DR423. 1622 { 1623 EnterExpressionEvaluationContext Unevaluated( 1624 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1625 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1626 if (R.isInvalid()) 1627 return ExprError(); 1628 ControllingExpr = R.get(); 1629 } 1630 1631 // The controlling expression is an unevaluated operand, so side effects are 1632 // likely unintended. 1633 if (!inTemplateInstantiation() && 1634 ControllingExpr->HasSideEffects(Context, false)) 1635 Diag(ControllingExpr->getExprLoc(), 1636 diag::warn_side_effects_unevaluated_context); 1637 1638 bool TypeErrorFound = false, 1639 IsResultDependent = ControllingExpr->isTypeDependent(), 1640 ContainsUnexpandedParameterPack 1641 = ControllingExpr->containsUnexpandedParameterPack(); 1642 1643 for (unsigned i = 0; i < NumAssocs; ++i) { 1644 if (Exprs[i]->containsUnexpandedParameterPack()) 1645 ContainsUnexpandedParameterPack = true; 1646 1647 if (Types[i]) { 1648 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1649 ContainsUnexpandedParameterPack = true; 1650 1651 if (Types[i]->getType()->isDependentType()) { 1652 IsResultDependent = true; 1653 } else { 1654 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1655 // complete object type other than a variably modified type." 1656 unsigned D = 0; 1657 if (Types[i]->getType()->isIncompleteType()) 1658 D = diag::err_assoc_type_incomplete; 1659 else if (!Types[i]->getType()->isObjectType()) 1660 D = diag::err_assoc_type_nonobject; 1661 else if (Types[i]->getType()->isVariablyModifiedType()) 1662 D = diag::err_assoc_type_variably_modified; 1663 1664 if (D != 0) { 1665 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1666 << Types[i]->getTypeLoc().getSourceRange() 1667 << Types[i]->getType(); 1668 TypeErrorFound = true; 1669 } 1670 1671 // C11 6.5.1.1p2 "No two generic associations in the same generic 1672 // selection shall specify compatible types." 1673 for (unsigned j = i+1; j < NumAssocs; ++j) 1674 if (Types[j] && !Types[j]->getType()->isDependentType() && 1675 Context.typesAreCompatible(Types[i]->getType(), 1676 Types[j]->getType())) { 1677 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1678 diag::err_assoc_compatible_types) 1679 << Types[j]->getTypeLoc().getSourceRange() 1680 << Types[j]->getType() 1681 << Types[i]->getType(); 1682 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1683 diag::note_compat_assoc) 1684 << Types[i]->getTypeLoc().getSourceRange() 1685 << Types[i]->getType(); 1686 TypeErrorFound = true; 1687 } 1688 } 1689 } 1690 } 1691 if (TypeErrorFound) 1692 return ExprError(); 1693 1694 // If we determined that the generic selection is result-dependent, don't 1695 // try to compute the result expression. 1696 if (IsResultDependent) 1697 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1698 Exprs, DefaultLoc, RParenLoc, 1699 ContainsUnexpandedParameterPack); 1700 1701 SmallVector<unsigned, 1> CompatIndices; 1702 unsigned DefaultIndex = -1U; 1703 for (unsigned i = 0; i < NumAssocs; ++i) { 1704 if (!Types[i]) 1705 DefaultIndex = i; 1706 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1707 Types[i]->getType())) 1708 CompatIndices.push_back(i); 1709 } 1710 1711 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1712 // type compatible with at most one of the types named in its generic 1713 // association list." 1714 if (CompatIndices.size() > 1) { 1715 // We strip parens here because the controlling expression is typically 1716 // parenthesized in macro definitions. 1717 ControllingExpr = ControllingExpr->IgnoreParens(); 1718 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1719 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1720 << (unsigned)CompatIndices.size(); 1721 for (unsigned I : CompatIndices) { 1722 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1723 diag::note_compat_assoc) 1724 << Types[I]->getTypeLoc().getSourceRange() 1725 << Types[I]->getType(); 1726 } 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1731 // its controlling expression shall have type compatible with exactly one of 1732 // the types named in its generic association list." 1733 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1734 // We strip parens here because the controlling expression is typically 1735 // parenthesized in macro definitions. 1736 ControllingExpr = ControllingExpr->IgnoreParens(); 1737 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1738 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1739 return ExprError(); 1740 } 1741 1742 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1743 // type name that is compatible with the type of the controlling expression, 1744 // then the result expression of the generic selection is the expression 1745 // in that generic association. Otherwise, the result expression of the 1746 // generic selection is the expression in the default generic association." 1747 unsigned ResultIndex = 1748 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1749 1750 return GenericSelectionExpr::Create( 1751 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1752 ContainsUnexpandedParameterPack, ResultIndex); 1753 } 1754 1755 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1756 /// location of the token and the offset of the ud-suffix within it. 1757 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1758 unsigned Offset) { 1759 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1760 S.getLangOpts()); 1761 } 1762 1763 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1764 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1765 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1766 IdentifierInfo *UDSuffix, 1767 SourceLocation UDSuffixLoc, 1768 ArrayRef<Expr*> Args, 1769 SourceLocation LitEndLoc) { 1770 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1771 1772 QualType ArgTy[2]; 1773 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1774 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1775 if (ArgTy[ArgIdx]->isArrayType()) 1776 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1777 } 1778 1779 DeclarationName OpName = 1780 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1781 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1782 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1783 1784 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1785 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1786 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1787 /*AllowStringTemplatePack*/ false, 1788 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1789 return ExprError(); 1790 1791 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1792 } 1793 1794 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1795 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1796 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1797 /// multiple tokens. However, the common case is that StringToks points to one 1798 /// string. 1799 /// 1800 ExprResult 1801 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1802 assert(!StringToks.empty() && "Must have at least one string!"); 1803 1804 StringLiteralParser Literal(StringToks, PP); 1805 if (Literal.hadError) 1806 return ExprError(); 1807 1808 SmallVector<SourceLocation, 4> StringTokLocs; 1809 for (const Token &Tok : StringToks) 1810 StringTokLocs.push_back(Tok.getLocation()); 1811 1812 QualType CharTy = Context.CharTy; 1813 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1814 if (Literal.isWide()) { 1815 CharTy = Context.getWideCharType(); 1816 Kind = StringLiteral::Wide; 1817 } else if (Literal.isUTF8()) { 1818 if (getLangOpts().Char8) 1819 CharTy = Context.Char8Ty; 1820 Kind = StringLiteral::UTF8; 1821 } else if (Literal.isUTF16()) { 1822 CharTy = Context.Char16Ty; 1823 Kind = StringLiteral::UTF16; 1824 } else if (Literal.isUTF32()) { 1825 CharTy = Context.Char32Ty; 1826 Kind = StringLiteral::UTF32; 1827 } else if (Literal.isPascal()) { 1828 CharTy = Context.UnsignedCharTy; 1829 } 1830 1831 // Warn on initializing an array of char from a u8 string literal; this 1832 // becomes ill-formed in C++2a. 1833 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1834 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1835 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1836 1837 // Create removals for all 'u8' prefixes in the string literal(s). This 1838 // ensures C++2a compatibility (but may change the program behavior when 1839 // built by non-Clang compilers for which the execution character set is 1840 // not always UTF-8). 1841 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1842 SourceLocation RemovalDiagLoc; 1843 for (const Token &Tok : StringToks) { 1844 if (Tok.getKind() == tok::utf8_string_literal) { 1845 if (RemovalDiagLoc.isInvalid()) 1846 RemovalDiagLoc = Tok.getLocation(); 1847 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1848 Tok.getLocation(), 1849 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1850 getSourceManager(), getLangOpts()))); 1851 } 1852 } 1853 Diag(RemovalDiagLoc, RemovalDiag); 1854 } 1855 1856 QualType StrTy = 1857 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1858 1859 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1860 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1861 Kind, Literal.Pascal, StrTy, 1862 &StringTokLocs[0], 1863 StringTokLocs.size()); 1864 if (Literal.getUDSuffix().empty()) 1865 return Lit; 1866 1867 // We're building a user-defined literal. 1868 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1869 SourceLocation UDSuffixLoc = 1870 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1871 Literal.getUDSuffixOffset()); 1872 1873 // Make sure we're allowed user-defined literals here. 1874 if (!UDLScope) 1875 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1876 1877 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1878 // operator "" X (str, len) 1879 QualType SizeType = Context.getSizeType(); 1880 1881 DeclarationName OpName = 1882 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1883 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1884 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1885 1886 QualType ArgTy[] = { 1887 Context.getArrayDecayedType(StrTy), SizeType 1888 }; 1889 1890 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1891 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1892 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1893 /*AllowStringTemplatePack*/ true, 1894 /*DiagnoseMissing*/ true, Lit)) { 1895 1896 case LOLR_Cooked: { 1897 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1898 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1899 StringTokLocs[0]); 1900 Expr *Args[] = { Lit, LenArg }; 1901 1902 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1903 } 1904 1905 case LOLR_Template: { 1906 TemplateArgumentListInfo ExplicitArgs; 1907 TemplateArgument Arg(Lit); 1908 TemplateArgumentLocInfo ArgInfo(Lit); 1909 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1910 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1911 &ExplicitArgs); 1912 } 1913 1914 case LOLR_StringTemplatePack: { 1915 TemplateArgumentListInfo ExplicitArgs; 1916 1917 unsigned CharBits = Context.getIntWidth(CharTy); 1918 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1919 llvm::APSInt Value(CharBits, CharIsUnsigned); 1920 1921 TemplateArgument TypeArg(CharTy); 1922 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1923 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1924 1925 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1926 Value = Lit->getCodeUnit(I); 1927 TemplateArgument Arg(Context, Value, CharTy); 1928 TemplateArgumentLocInfo ArgInfo; 1929 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1930 } 1931 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1932 &ExplicitArgs); 1933 } 1934 case LOLR_Raw: 1935 case LOLR_ErrorNoDiagnostic: 1936 llvm_unreachable("unexpected literal operator lookup result"); 1937 case LOLR_Error: 1938 return ExprError(); 1939 } 1940 llvm_unreachable("unexpected literal operator lookup result"); 1941 } 1942 1943 DeclRefExpr * 1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1945 SourceLocation Loc, 1946 const CXXScopeSpec *SS) { 1947 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1948 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1949 } 1950 1951 DeclRefExpr * 1952 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1953 const DeclarationNameInfo &NameInfo, 1954 const CXXScopeSpec *SS, NamedDecl *FoundD, 1955 SourceLocation TemplateKWLoc, 1956 const TemplateArgumentListInfo *TemplateArgs) { 1957 NestedNameSpecifierLoc NNS = 1958 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1959 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1960 TemplateArgs); 1961 } 1962 1963 // CUDA/HIP: Check whether a captured reference variable is referencing a 1964 // host variable in a device or host device lambda. 1965 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1966 VarDecl *VD) { 1967 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1968 return false; 1969 assert(VD->getType()->isReferenceType()); 1970 1971 // Check whether the reference variable is referencing a host variable. 1972 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1973 if (!DRE) 1974 return false; 1975 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1976 if (!Referee || !Referee->hasGlobalStorage() || 1977 Referee->hasAttr<CUDADeviceAttr>()) 1978 return false; 1979 1980 // Check whether the current function is a device or host device lambda. 1981 // Check whether the reference variable is a capture by getDeclContext() 1982 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1983 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1984 if (MD && MD->getParent()->isLambda() && 1985 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1986 VD->getDeclContext() != MD) 1987 return true; 1988 1989 return false; 1990 } 1991 1992 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1993 // A declaration named in an unevaluated operand never constitutes an odr-use. 1994 if (isUnevaluatedContext()) 1995 return NOUR_Unevaluated; 1996 1997 // C++2a [basic.def.odr]p4: 1998 // A variable x whose name appears as a potentially-evaluated expression e 1999 // is odr-used by e unless [...] x is a reference that is usable in 2000 // constant expressions. 2001 // CUDA/HIP: 2002 // If a reference variable referencing a host variable is captured in a 2003 // device or host device lambda, the value of the referee must be copied 2004 // to the capture and the reference variable must be treated as odr-use 2005 // since the value of the referee is not known at compile time and must 2006 // be loaded from the captured. 2007 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2008 if (VD->getType()->isReferenceType() && 2009 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2010 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2011 VD->isUsableInConstantExpressions(Context)) 2012 return NOUR_Constant; 2013 } 2014 2015 // All remaining non-variable cases constitute an odr-use. For variables, we 2016 // need to wait and see how the expression is used. 2017 return NOUR_None; 2018 } 2019 2020 /// BuildDeclRefExpr - Build an expression that references a 2021 /// declaration that does not require a closure capture. 2022 DeclRefExpr * 2023 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2024 const DeclarationNameInfo &NameInfo, 2025 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2026 SourceLocation TemplateKWLoc, 2027 const TemplateArgumentListInfo *TemplateArgs) { 2028 bool RefersToCapturedVariable = 2029 isa<VarDecl>(D) && 2030 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2031 2032 DeclRefExpr *E = DeclRefExpr::Create( 2033 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2034 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2035 MarkDeclRefReferenced(E); 2036 2037 // C++ [except.spec]p17: 2038 // An exception-specification is considered to be needed when: 2039 // - in an expression, the function is the unique lookup result or 2040 // the selected member of a set of overloaded functions. 2041 // 2042 // We delay doing this until after we've built the function reference and 2043 // marked it as used so that: 2044 // a) if the function is defaulted, we get errors from defining it before / 2045 // instead of errors from computing its exception specification, and 2046 // b) if the function is a defaulted comparison, we can use the body we 2047 // build when defining it as input to the exception specification 2048 // computation rather than computing a new body. 2049 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2050 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2051 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2052 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2053 } 2054 } 2055 2056 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2057 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2058 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2059 getCurFunction()->recordUseOfWeak(E); 2060 2061 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2062 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2063 FD = IFD->getAnonField(); 2064 if (FD) { 2065 UnusedPrivateFields.remove(FD); 2066 // Just in case we're building an illegal pointer-to-member. 2067 if (FD->isBitField()) 2068 E->setObjectKind(OK_BitField); 2069 } 2070 2071 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2072 // designates a bit-field. 2073 if (auto *BD = dyn_cast<BindingDecl>(D)) 2074 if (auto *BE = BD->getBinding()) 2075 E->setObjectKind(BE->getObjectKind()); 2076 2077 return E; 2078 } 2079 2080 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2081 /// possibly a list of template arguments. 2082 /// 2083 /// If this produces template arguments, it is permitted to call 2084 /// DecomposeTemplateName. 2085 /// 2086 /// This actually loses a lot of source location information for 2087 /// non-standard name kinds; we should consider preserving that in 2088 /// some way. 2089 void 2090 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2091 TemplateArgumentListInfo &Buffer, 2092 DeclarationNameInfo &NameInfo, 2093 const TemplateArgumentListInfo *&TemplateArgs) { 2094 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2095 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2096 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2097 2098 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2099 Id.TemplateId->NumArgs); 2100 translateTemplateArguments(TemplateArgsPtr, Buffer); 2101 2102 TemplateName TName = Id.TemplateId->Template.get(); 2103 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2104 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2105 TemplateArgs = &Buffer; 2106 } else { 2107 NameInfo = GetNameFromUnqualifiedId(Id); 2108 TemplateArgs = nullptr; 2109 } 2110 } 2111 2112 static void emitEmptyLookupTypoDiagnostic( 2113 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2114 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2115 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2116 DeclContext *Ctx = 2117 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2118 if (!TC) { 2119 // Emit a special diagnostic for failed member lookups. 2120 // FIXME: computing the declaration context might fail here (?) 2121 if (Ctx) 2122 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2123 << SS.getRange(); 2124 else 2125 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2126 return; 2127 } 2128 2129 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2130 bool DroppedSpecifier = 2131 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2132 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2133 ? diag::note_implicit_param_decl 2134 : diag::note_previous_decl; 2135 if (!Ctx) 2136 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2137 SemaRef.PDiag(NoteID)); 2138 else 2139 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2140 << Typo << Ctx << DroppedSpecifier 2141 << SS.getRange(), 2142 SemaRef.PDiag(NoteID)); 2143 } 2144 2145 /// Diagnose a lookup that found results in an enclosing class during error 2146 /// recovery. This usually indicates that the results were found in a dependent 2147 /// base class that could not be searched as part of a template definition. 2148 /// Always issues a diagnostic (though this may be only a warning in MS 2149 /// compatibility mode). 2150 /// 2151 /// Return \c true if the error is unrecoverable, or \c false if the caller 2152 /// should attempt to recover using these lookup results. 2153 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2154 // During a default argument instantiation the CurContext points 2155 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2156 // function parameter list, hence add an explicit check. 2157 bool isDefaultArgument = 2158 !CodeSynthesisContexts.empty() && 2159 CodeSynthesisContexts.back().Kind == 2160 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2161 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2162 bool isInstance = CurMethod && CurMethod->isInstance() && 2163 R.getNamingClass() == CurMethod->getParent() && 2164 !isDefaultArgument; 2165 2166 // There are two ways we can find a class-scope declaration during template 2167 // instantiation that we did not find in the template definition: if it is a 2168 // member of a dependent base class, or if it is declared after the point of 2169 // use in the same class. Distinguish these by comparing the class in which 2170 // the member was found to the naming class of the lookup. 2171 unsigned DiagID = diag::err_found_in_dependent_base; 2172 unsigned NoteID = diag::note_member_declared_at; 2173 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2174 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2175 : diag::err_found_later_in_class; 2176 } else if (getLangOpts().MSVCCompat) { 2177 DiagID = diag::ext_found_in_dependent_base; 2178 NoteID = diag::note_dependent_member_use; 2179 } 2180 2181 if (isInstance) { 2182 // Give a code modification hint to insert 'this->'. 2183 Diag(R.getNameLoc(), DiagID) 2184 << R.getLookupName() 2185 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2186 CheckCXXThisCapture(R.getNameLoc()); 2187 } else { 2188 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2189 // they're not shadowed). 2190 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2191 } 2192 2193 for (NamedDecl *D : R) 2194 Diag(D->getLocation(), NoteID); 2195 2196 // Return true if we are inside a default argument instantiation 2197 // and the found name refers to an instance member function, otherwise 2198 // the caller will try to create an implicit member call and this is wrong 2199 // for default arguments. 2200 // 2201 // FIXME: Is this special case necessary? We could allow the caller to 2202 // diagnose this. 2203 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2204 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2205 return true; 2206 } 2207 2208 // Tell the callee to try to recover. 2209 return false; 2210 } 2211 2212 /// Diagnose an empty lookup. 2213 /// 2214 /// \return false if new lookup candidates were found 2215 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2216 CorrectionCandidateCallback &CCC, 2217 TemplateArgumentListInfo *ExplicitTemplateArgs, 2218 ArrayRef<Expr *> Args, TypoExpr **Out) { 2219 DeclarationName Name = R.getLookupName(); 2220 2221 unsigned diagnostic = diag::err_undeclared_var_use; 2222 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2223 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2224 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2225 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2226 diagnostic = diag::err_undeclared_use; 2227 diagnostic_suggest = diag::err_undeclared_use_suggest; 2228 } 2229 2230 // If the original lookup was an unqualified lookup, fake an 2231 // unqualified lookup. This is useful when (for example) the 2232 // original lookup would not have found something because it was a 2233 // dependent name. 2234 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2235 while (DC) { 2236 if (isa<CXXRecordDecl>(DC)) { 2237 LookupQualifiedName(R, DC); 2238 2239 if (!R.empty()) { 2240 // Don't give errors about ambiguities in this lookup. 2241 R.suppressDiagnostics(); 2242 2243 // If there's a best viable function among the results, only mention 2244 // that one in the notes. 2245 OverloadCandidateSet Candidates(R.getNameLoc(), 2246 OverloadCandidateSet::CSK_Normal); 2247 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2248 OverloadCandidateSet::iterator Best; 2249 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2250 OR_Success) { 2251 R.clear(); 2252 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2253 R.resolveKind(); 2254 } 2255 2256 return DiagnoseDependentMemberLookup(R); 2257 } 2258 2259 R.clear(); 2260 } 2261 2262 DC = DC->getLookupParent(); 2263 } 2264 2265 // We didn't find anything, so try to correct for a typo. 2266 TypoCorrection Corrected; 2267 if (S && Out) { 2268 SourceLocation TypoLoc = R.getNameLoc(); 2269 assert(!ExplicitTemplateArgs && 2270 "Diagnosing an empty lookup with explicit template args!"); 2271 *Out = CorrectTypoDelayed( 2272 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2273 [=](const TypoCorrection &TC) { 2274 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2275 diagnostic, diagnostic_suggest); 2276 }, 2277 nullptr, CTK_ErrorRecovery); 2278 if (*Out) 2279 return true; 2280 } else if (S && 2281 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2282 S, &SS, CCC, CTK_ErrorRecovery))) { 2283 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2284 bool DroppedSpecifier = 2285 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2286 R.setLookupName(Corrected.getCorrection()); 2287 2288 bool AcceptableWithRecovery = false; 2289 bool AcceptableWithoutRecovery = false; 2290 NamedDecl *ND = Corrected.getFoundDecl(); 2291 if (ND) { 2292 if (Corrected.isOverloaded()) { 2293 OverloadCandidateSet OCS(R.getNameLoc(), 2294 OverloadCandidateSet::CSK_Normal); 2295 OverloadCandidateSet::iterator Best; 2296 for (NamedDecl *CD : Corrected) { 2297 if (FunctionTemplateDecl *FTD = 2298 dyn_cast<FunctionTemplateDecl>(CD)) 2299 AddTemplateOverloadCandidate( 2300 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2301 Args, OCS); 2302 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2303 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2304 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2305 Args, OCS); 2306 } 2307 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2308 case OR_Success: 2309 ND = Best->FoundDecl; 2310 Corrected.setCorrectionDecl(ND); 2311 break; 2312 default: 2313 // FIXME: Arbitrarily pick the first declaration for the note. 2314 Corrected.setCorrectionDecl(ND); 2315 break; 2316 } 2317 } 2318 R.addDecl(ND); 2319 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2320 CXXRecordDecl *Record = nullptr; 2321 if (Corrected.getCorrectionSpecifier()) { 2322 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2323 Record = Ty->getAsCXXRecordDecl(); 2324 } 2325 if (!Record) 2326 Record = cast<CXXRecordDecl>( 2327 ND->getDeclContext()->getRedeclContext()); 2328 R.setNamingClass(Record); 2329 } 2330 2331 auto *UnderlyingND = ND->getUnderlyingDecl(); 2332 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2333 isa<FunctionTemplateDecl>(UnderlyingND); 2334 // FIXME: If we ended up with a typo for a type name or 2335 // Objective-C class name, we're in trouble because the parser 2336 // is in the wrong place to recover. Suggest the typo 2337 // correction, but don't make it a fix-it since we're not going 2338 // to recover well anyway. 2339 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2340 getAsTypeTemplateDecl(UnderlyingND) || 2341 isa<ObjCInterfaceDecl>(UnderlyingND); 2342 } else { 2343 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2344 // because we aren't able to recover. 2345 AcceptableWithoutRecovery = true; 2346 } 2347 2348 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2349 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2350 ? diag::note_implicit_param_decl 2351 : diag::note_previous_decl; 2352 if (SS.isEmpty()) 2353 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2354 PDiag(NoteID), AcceptableWithRecovery); 2355 else 2356 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2357 << Name << computeDeclContext(SS, false) 2358 << DroppedSpecifier << SS.getRange(), 2359 PDiag(NoteID), AcceptableWithRecovery); 2360 2361 // Tell the callee whether to try to recover. 2362 return !AcceptableWithRecovery; 2363 } 2364 } 2365 R.clear(); 2366 2367 // Emit a special diagnostic for failed member lookups. 2368 // FIXME: computing the declaration context might fail here (?) 2369 if (!SS.isEmpty()) { 2370 Diag(R.getNameLoc(), diag::err_no_member) 2371 << Name << computeDeclContext(SS, false) 2372 << SS.getRange(); 2373 return true; 2374 } 2375 2376 // Give up, we can't recover. 2377 Diag(R.getNameLoc(), diagnostic) << Name; 2378 return true; 2379 } 2380 2381 /// In Microsoft mode, if we are inside a template class whose parent class has 2382 /// dependent base classes, and we can't resolve an unqualified identifier, then 2383 /// assume the identifier is a member of a dependent base class. We can only 2384 /// recover successfully in static methods, instance methods, and other contexts 2385 /// where 'this' is available. This doesn't precisely match MSVC's 2386 /// instantiation model, but it's close enough. 2387 static Expr * 2388 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2389 DeclarationNameInfo &NameInfo, 2390 SourceLocation TemplateKWLoc, 2391 const TemplateArgumentListInfo *TemplateArgs) { 2392 // Only try to recover from lookup into dependent bases in static methods or 2393 // contexts where 'this' is available. 2394 QualType ThisType = S.getCurrentThisType(); 2395 const CXXRecordDecl *RD = nullptr; 2396 if (!ThisType.isNull()) 2397 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2398 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2399 RD = MD->getParent(); 2400 if (!RD || !RD->hasAnyDependentBases()) 2401 return nullptr; 2402 2403 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2404 // is available, suggest inserting 'this->' as a fixit. 2405 SourceLocation Loc = NameInfo.getLoc(); 2406 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2407 DB << NameInfo.getName() << RD; 2408 2409 if (!ThisType.isNull()) { 2410 DB << FixItHint::CreateInsertion(Loc, "this->"); 2411 return CXXDependentScopeMemberExpr::Create( 2412 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2413 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2414 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2415 } 2416 2417 // Synthesize a fake NNS that points to the derived class. This will 2418 // perform name lookup during template instantiation. 2419 CXXScopeSpec SS; 2420 auto *NNS = 2421 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2422 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2423 return DependentScopeDeclRefExpr::Create( 2424 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2425 TemplateArgs); 2426 } 2427 2428 ExprResult 2429 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2430 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2431 bool HasTrailingLParen, bool IsAddressOfOperand, 2432 CorrectionCandidateCallback *CCC, 2433 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2434 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2435 "cannot be direct & operand and have a trailing lparen"); 2436 if (SS.isInvalid()) 2437 return ExprError(); 2438 2439 TemplateArgumentListInfo TemplateArgsBuffer; 2440 2441 // Decompose the UnqualifiedId into the following data. 2442 DeclarationNameInfo NameInfo; 2443 const TemplateArgumentListInfo *TemplateArgs; 2444 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2445 2446 DeclarationName Name = NameInfo.getName(); 2447 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2448 SourceLocation NameLoc = NameInfo.getLoc(); 2449 2450 if (II && II->isEditorPlaceholder()) { 2451 // FIXME: When typed placeholders are supported we can create a typed 2452 // placeholder expression node. 2453 return ExprError(); 2454 } 2455 2456 // C++ [temp.dep.expr]p3: 2457 // An id-expression is type-dependent if it contains: 2458 // -- an identifier that was declared with a dependent type, 2459 // (note: handled after lookup) 2460 // -- a template-id that is dependent, 2461 // (note: handled in BuildTemplateIdExpr) 2462 // -- a conversion-function-id that specifies a dependent type, 2463 // -- a nested-name-specifier that contains a class-name that 2464 // names a dependent type. 2465 // Determine whether this is a member of an unknown specialization; 2466 // we need to handle these differently. 2467 bool DependentID = false; 2468 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2469 Name.getCXXNameType()->isDependentType()) { 2470 DependentID = true; 2471 } else if (SS.isSet()) { 2472 if (DeclContext *DC = computeDeclContext(SS, false)) { 2473 if (RequireCompleteDeclContext(SS, DC)) 2474 return ExprError(); 2475 } else { 2476 DependentID = true; 2477 } 2478 } 2479 2480 if (DependentID) 2481 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2482 IsAddressOfOperand, TemplateArgs); 2483 2484 // Perform the required lookup. 2485 LookupResult R(*this, NameInfo, 2486 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2487 ? LookupObjCImplicitSelfParam 2488 : LookupOrdinaryName); 2489 if (TemplateKWLoc.isValid() || TemplateArgs) { 2490 // Lookup the template name again to correctly establish the context in 2491 // which it was found. This is really unfortunate as we already did the 2492 // lookup to determine that it was a template name in the first place. If 2493 // this becomes a performance hit, we can work harder to preserve those 2494 // results until we get here but it's likely not worth it. 2495 bool MemberOfUnknownSpecialization; 2496 AssumedTemplateKind AssumedTemplate; 2497 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2498 MemberOfUnknownSpecialization, TemplateKWLoc, 2499 &AssumedTemplate)) 2500 return ExprError(); 2501 2502 if (MemberOfUnknownSpecialization || 2503 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2504 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2505 IsAddressOfOperand, TemplateArgs); 2506 } else { 2507 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2508 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2509 2510 // If the result might be in a dependent base class, this is a dependent 2511 // id-expression. 2512 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2513 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2514 IsAddressOfOperand, TemplateArgs); 2515 2516 // If this reference is in an Objective-C method, then we need to do 2517 // some special Objective-C lookup, too. 2518 if (IvarLookupFollowUp) { 2519 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2520 if (E.isInvalid()) 2521 return ExprError(); 2522 2523 if (Expr *Ex = E.getAs<Expr>()) 2524 return Ex; 2525 } 2526 } 2527 2528 if (R.isAmbiguous()) 2529 return ExprError(); 2530 2531 // This could be an implicitly declared function reference (legal in C90, 2532 // extension in C99, forbidden in C++). 2533 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2534 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2535 if (D) R.addDecl(D); 2536 } 2537 2538 // Determine whether this name might be a candidate for 2539 // argument-dependent lookup. 2540 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2541 2542 if (R.empty() && !ADL) { 2543 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2544 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2545 TemplateKWLoc, TemplateArgs)) 2546 return E; 2547 } 2548 2549 // Don't diagnose an empty lookup for inline assembly. 2550 if (IsInlineAsmIdentifier) 2551 return ExprError(); 2552 2553 // If this name wasn't predeclared and if this is not a function 2554 // call, diagnose the problem. 2555 TypoExpr *TE = nullptr; 2556 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2557 : nullptr); 2558 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2559 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2560 "Typo correction callback misconfigured"); 2561 if (CCC) { 2562 // Make sure the callback knows what the typo being diagnosed is. 2563 CCC->setTypoName(II); 2564 if (SS.isValid()) 2565 CCC->setTypoNNS(SS.getScopeRep()); 2566 } 2567 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2568 // a template name, but we happen to have always already looked up the name 2569 // before we get here if it must be a template name. 2570 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2571 None, &TE)) { 2572 if (TE && KeywordReplacement) { 2573 auto &State = getTypoExprState(TE); 2574 auto BestTC = State.Consumer->getNextCorrection(); 2575 if (BestTC.isKeyword()) { 2576 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2577 if (State.DiagHandler) 2578 State.DiagHandler(BestTC); 2579 KeywordReplacement->startToken(); 2580 KeywordReplacement->setKind(II->getTokenID()); 2581 KeywordReplacement->setIdentifierInfo(II); 2582 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2583 // Clean up the state associated with the TypoExpr, since it has 2584 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2585 clearDelayedTypo(TE); 2586 // Signal that a correction to a keyword was performed by returning a 2587 // valid-but-null ExprResult. 2588 return (Expr*)nullptr; 2589 } 2590 State.Consumer->resetCorrectionStream(); 2591 } 2592 return TE ? TE : ExprError(); 2593 } 2594 2595 assert(!R.empty() && 2596 "DiagnoseEmptyLookup returned false but added no results"); 2597 2598 // If we found an Objective-C instance variable, let 2599 // LookupInObjCMethod build the appropriate expression to 2600 // reference the ivar. 2601 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2602 R.clear(); 2603 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2604 // In a hopelessly buggy code, Objective-C instance variable 2605 // lookup fails and no expression will be built to reference it. 2606 if (!E.isInvalid() && !E.get()) 2607 return ExprError(); 2608 return E; 2609 } 2610 } 2611 2612 // This is guaranteed from this point on. 2613 assert(!R.empty() || ADL); 2614 2615 // Check whether this might be a C++ implicit instance member access. 2616 // C++ [class.mfct.non-static]p3: 2617 // When an id-expression that is not part of a class member access 2618 // syntax and not used to form a pointer to member is used in the 2619 // body of a non-static member function of class X, if name lookup 2620 // resolves the name in the id-expression to a non-static non-type 2621 // member of some class C, the id-expression is transformed into a 2622 // class member access expression using (*this) as the 2623 // postfix-expression to the left of the . operator. 2624 // 2625 // But we don't actually need to do this for '&' operands if R 2626 // resolved to a function or overloaded function set, because the 2627 // expression is ill-formed if it actually works out to be a 2628 // non-static member function: 2629 // 2630 // C++ [expr.ref]p4: 2631 // Otherwise, if E1.E2 refers to a non-static member function. . . 2632 // [t]he expression can be used only as the left-hand operand of a 2633 // member function call. 2634 // 2635 // There are other safeguards against such uses, but it's important 2636 // to get this right here so that we don't end up making a 2637 // spuriously dependent expression if we're inside a dependent 2638 // instance method. 2639 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2640 bool MightBeImplicitMember; 2641 if (!IsAddressOfOperand) 2642 MightBeImplicitMember = true; 2643 else if (!SS.isEmpty()) 2644 MightBeImplicitMember = false; 2645 else if (R.isOverloadedResult()) 2646 MightBeImplicitMember = false; 2647 else if (R.isUnresolvableResult()) 2648 MightBeImplicitMember = true; 2649 else 2650 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2651 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2652 isa<MSPropertyDecl>(R.getFoundDecl()); 2653 2654 if (MightBeImplicitMember) 2655 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2656 R, TemplateArgs, S); 2657 } 2658 2659 if (TemplateArgs || TemplateKWLoc.isValid()) { 2660 2661 // In C++1y, if this is a variable template id, then check it 2662 // in BuildTemplateIdExpr(). 2663 // The single lookup result must be a variable template declaration. 2664 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2665 Id.TemplateId->Kind == TNK_Var_template) { 2666 assert(R.getAsSingle<VarTemplateDecl>() && 2667 "There should only be one declaration found."); 2668 } 2669 2670 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2671 } 2672 2673 return BuildDeclarationNameExpr(SS, R, ADL); 2674 } 2675 2676 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2677 /// declaration name, generally during template instantiation. 2678 /// There's a large number of things which don't need to be done along 2679 /// this path. 2680 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2681 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2682 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2683 DeclContext *DC = computeDeclContext(SS, false); 2684 if (!DC) 2685 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2686 NameInfo, /*TemplateArgs=*/nullptr); 2687 2688 if (RequireCompleteDeclContext(SS, DC)) 2689 return ExprError(); 2690 2691 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2692 LookupQualifiedName(R, DC); 2693 2694 if (R.isAmbiguous()) 2695 return ExprError(); 2696 2697 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2698 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2699 NameInfo, /*TemplateArgs=*/nullptr); 2700 2701 if (R.empty()) { 2702 // Don't diagnose problems with invalid record decl, the secondary no_member 2703 // diagnostic during template instantiation is likely bogus, e.g. if a class 2704 // is invalid because it's derived from an invalid base class, then missing 2705 // members were likely supposed to be inherited. 2706 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2707 if (CD->isInvalidDecl()) 2708 return ExprError(); 2709 Diag(NameInfo.getLoc(), diag::err_no_member) 2710 << NameInfo.getName() << DC << SS.getRange(); 2711 return ExprError(); 2712 } 2713 2714 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2715 // Diagnose a missing typename if this resolved unambiguously to a type in 2716 // a dependent context. If we can recover with a type, downgrade this to 2717 // a warning in Microsoft compatibility mode. 2718 unsigned DiagID = diag::err_typename_missing; 2719 if (RecoveryTSI && getLangOpts().MSVCCompat) 2720 DiagID = diag::ext_typename_missing; 2721 SourceLocation Loc = SS.getBeginLoc(); 2722 auto D = Diag(Loc, DiagID); 2723 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2724 << SourceRange(Loc, NameInfo.getEndLoc()); 2725 2726 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2727 // context. 2728 if (!RecoveryTSI) 2729 return ExprError(); 2730 2731 // Only issue the fixit if we're prepared to recover. 2732 D << FixItHint::CreateInsertion(Loc, "typename "); 2733 2734 // Recover by pretending this was an elaborated type. 2735 QualType Ty = Context.getTypeDeclType(TD); 2736 TypeLocBuilder TLB; 2737 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2738 2739 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2740 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2741 QTL.setElaboratedKeywordLoc(SourceLocation()); 2742 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2743 2744 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2745 2746 return ExprEmpty(); 2747 } 2748 2749 // Defend against this resolving to an implicit member access. We usually 2750 // won't get here if this might be a legitimate a class member (we end up in 2751 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2752 // a pointer-to-member or in an unevaluated context in C++11. 2753 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2754 return BuildPossibleImplicitMemberExpr(SS, 2755 /*TemplateKWLoc=*/SourceLocation(), 2756 R, /*TemplateArgs=*/nullptr, S); 2757 2758 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2759 } 2760 2761 /// The parser has read a name in, and Sema has detected that we're currently 2762 /// inside an ObjC method. Perform some additional checks and determine if we 2763 /// should form a reference to an ivar. 2764 /// 2765 /// Ideally, most of this would be done by lookup, but there's 2766 /// actually quite a lot of extra work involved. 2767 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2768 IdentifierInfo *II) { 2769 SourceLocation Loc = Lookup.getNameLoc(); 2770 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2771 2772 // Check for error condition which is already reported. 2773 if (!CurMethod) 2774 return DeclResult(true); 2775 2776 // There are two cases to handle here. 1) scoped lookup could have failed, 2777 // in which case we should look for an ivar. 2) scoped lookup could have 2778 // found a decl, but that decl is outside the current instance method (i.e. 2779 // a global variable). In these two cases, we do a lookup for an ivar with 2780 // this name, if the lookup sucedes, we replace it our current decl. 2781 2782 // If we're in a class method, we don't normally want to look for 2783 // ivars. But if we don't find anything else, and there's an 2784 // ivar, that's an error. 2785 bool IsClassMethod = CurMethod->isClassMethod(); 2786 2787 bool LookForIvars; 2788 if (Lookup.empty()) 2789 LookForIvars = true; 2790 else if (IsClassMethod) 2791 LookForIvars = false; 2792 else 2793 LookForIvars = (Lookup.isSingleResult() && 2794 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2795 ObjCInterfaceDecl *IFace = nullptr; 2796 if (LookForIvars) { 2797 IFace = CurMethod->getClassInterface(); 2798 ObjCInterfaceDecl *ClassDeclared; 2799 ObjCIvarDecl *IV = nullptr; 2800 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2801 // Diagnose using an ivar in a class method. 2802 if (IsClassMethod) { 2803 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2804 return DeclResult(true); 2805 } 2806 2807 // Diagnose the use of an ivar outside of the declaring class. 2808 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2809 !declaresSameEntity(ClassDeclared, IFace) && 2810 !getLangOpts().DebuggerSupport) 2811 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2812 2813 // Success. 2814 return IV; 2815 } 2816 } else if (CurMethod->isInstanceMethod()) { 2817 // We should warn if a local variable hides an ivar. 2818 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2819 ObjCInterfaceDecl *ClassDeclared; 2820 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2821 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2822 declaresSameEntity(IFace, ClassDeclared)) 2823 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2824 } 2825 } 2826 } else if (Lookup.isSingleResult() && 2827 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2828 // If accessing a stand-alone ivar in a class method, this is an error. 2829 if (const ObjCIvarDecl *IV = 2830 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2831 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2832 return DeclResult(true); 2833 } 2834 } 2835 2836 // Didn't encounter an error, didn't find an ivar. 2837 return DeclResult(false); 2838 } 2839 2840 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2841 ObjCIvarDecl *IV) { 2842 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2843 assert(CurMethod && CurMethod->isInstanceMethod() && 2844 "should not reference ivar from this context"); 2845 2846 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2847 assert(IFace && "should not reference ivar from this context"); 2848 2849 // If we're referencing an invalid decl, just return this as a silent 2850 // error node. The error diagnostic was already emitted on the decl. 2851 if (IV->isInvalidDecl()) 2852 return ExprError(); 2853 2854 // Check if referencing a field with __attribute__((deprecated)). 2855 if (DiagnoseUseOfDecl(IV, Loc)) 2856 return ExprError(); 2857 2858 // FIXME: This should use a new expr for a direct reference, don't 2859 // turn this into Self->ivar, just return a BareIVarExpr or something. 2860 IdentifierInfo &II = Context.Idents.get("self"); 2861 UnqualifiedId SelfName; 2862 SelfName.setImplicitSelfParam(&II); 2863 CXXScopeSpec SelfScopeSpec; 2864 SourceLocation TemplateKWLoc; 2865 ExprResult SelfExpr = 2866 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2867 /*HasTrailingLParen=*/false, 2868 /*IsAddressOfOperand=*/false); 2869 if (SelfExpr.isInvalid()) 2870 return ExprError(); 2871 2872 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2873 if (SelfExpr.isInvalid()) 2874 return ExprError(); 2875 2876 MarkAnyDeclReferenced(Loc, IV, true); 2877 2878 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2879 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2880 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2881 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2882 2883 ObjCIvarRefExpr *Result = new (Context) 2884 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2885 IV->getLocation(), SelfExpr.get(), true, true); 2886 2887 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2888 if (!isUnevaluatedContext() && 2889 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2890 getCurFunction()->recordUseOfWeak(Result); 2891 } 2892 if (getLangOpts().ObjCAutoRefCount) 2893 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2894 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2895 2896 return Result; 2897 } 2898 2899 /// The parser has read a name in, and Sema has detected that we're currently 2900 /// inside an ObjC method. Perform some additional checks and determine if we 2901 /// should form a reference to an ivar. If so, build an expression referencing 2902 /// that ivar. 2903 ExprResult 2904 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2905 IdentifierInfo *II, bool AllowBuiltinCreation) { 2906 // FIXME: Integrate this lookup step into LookupParsedName. 2907 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2908 if (Ivar.isInvalid()) 2909 return ExprError(); 2910 if (Ivar.isUsable()) 2911 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2912 cast<ObjCIvarDecl>(Ivar.get())); 2913 2914 if (Lookup.empty() && II && AllowBuiltinCreation) 2915 LookupBuiltin(Lookup); 2916 2917 // Sentinel value saying that we didn't do anything special. 2918 return ExprResult(false); 2919 } 2920 2921 /// Cast a base object to a member's actual type. 2922 /// 2923 /// There are two relevant checks: 2924 /// 2925 /// C++ [class.access.base]p7: 2926 /// 2927 /// If a class member access operator [...] is used to access a non-static 2928 /// data member or non-static member function, the reference is ill-formed if 2929 /// the left operand [...] cannot be implicitly converted to a pointer to the 2930 /// naming class of the right operand. 2931 /// 2932 /// C++ [expr.ref]p7: 2933 /// 2934 /// If E2 is a non-static data member or a non-static member function, the 2935 /// program is ill-formed if the class of which E2 is directly a member is an 2936 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2937 /// 2938 /// Note that the latter check does not consider access; the access of the 2939 /// "real" base class is checked as appropriate when checking the access of the 2940 /// member name. 2941 ExprResult 2942 Sema::PerformObjectMemberConversion(Expr *From, 2943 NestedNameSpecifier *Qualifier, 2944 NamedDecl *FoundDecl, 2945 NamedDecl *Member) { 2946 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2947 if (!RD) 2948 return From; 2949 2950 QualType DestRecordType; 2951 QualType DestType; 2952 QualType FromRecordType; 2953 QualType FromType = From->getType(); 2954 bool PointerConversions = false; 2955 if (isa<FieldDecl>(Member)) { 2956 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2957 auto FromPtrType = FromType->getAs<PointerType>(); 2958 DestRecordType = Context.getAddrSpaceQualType( 2959 DestRecordType, FromPtrType 2960 ? FromType->getPointeeType().getAddressSpace() 2961 : FromType.getAddressSpace()); 2962 2963 if (FromPtrType) { 2964 DestType = Context.getPointerType(DestRecordType); 2965 FromRecordType = FromPtrType->getPointeeType(); 2966 PointerConversions = true; 2967 } else { 2968 DestType = DestRecordType; 2969 FromRecordType = FromType; 2970 } 2971 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2972 if (Method->isStatic()) 2973 return From; 2974 2975 DestType = Method->getThisType(); 2976 DestRecordType = DestType->getPointeeType(); 2977 2978 if (FromType->getAs<PointerType>()) { 2979 FromRecordType = FromType->getPointeeType(); 2980 PointerConversions = true; 2981 } else { 2982 FromRecordType = FromType; 2983 DestType = DestRecordType; 2984 } 2985 2986 LangAS FromAS = FromRecordType.getAddressSpace(); 2987 LangAS DestAS = DestRecordType.getAddressSpace(); 2988 if (FromAS != DestAS) { 2989 QualType FromRecordTypeWithoutAS = 2990 Context.removeAddrSpaceQualType(FromRecordType); 2991 QualType FromTypeWithDestAS = 2992 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2993 if (PointerConversions) 2994 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2995 From = ImpCastExprToType(From, FromTypeWithDestAS, 2996 CK_AddressSpaceConversion, From->getValueKind()) 2997 .get(); 2998 } 2999 } else { 3000 // No conversion necessary. 3001 return From; 3002 } 3003 3004 if (DestType->isDependentType() || FromType->isDependentType()) 3005 return From; 3006 3007 // If the unqualified types are the same, no conversion is necessary. 3008 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3009 return From; 3010 3011 SourceRange FromRange = From->getSourceRange(); 3012 SourceLocation FromLoc = FromRange.getBegin(); 3013 3014 ExprValueKind VK = From->getValueKind(); 3015 3016 // C++ [class.member.lookup]p8: 3017 // [...] Ambiguities can often be resolved by qualifying a name with its 3018 // class name. 3019 // 3020 // If the member was a qualified name and the qualified referred to a 3021 // specific base subobject type, we'll cast to that intermediate type 3022 // first and then to the object in which the member is declared. That allows 3023 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3024 // 3025 // class Base { public: int x; }; 3026 // class Derived1 : public Base { }; 3027 // class Derived2 : public Base { }; 3028 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3029 // 3030 // void VeryDerived::f() { 3031 // x = 17; // error: ambiguous base subobjects 3032 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3033 // } 3034 if (Qualifier && Qualifier->getAsType()) { 3035 QualType QType = QualType(Qualifier->getAsType(), 0); 3036 assert(QType->isRecordType() && "lookup done with non-record type"); 3037 3038 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3039 3040 // In C++98, the qualifier type doesn't actually have to be a base 3041 // type of the object type, in which case we just ignore it. 3042 // Otherwise build the appropriate casts. 3043 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3044 CXXCastPath BasePath; 3045 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3046 FromLoc, FromRange, &BasePath)) 3047 return ExprError(); 3048 3049 if (PointerConversions) 3050 QType = Context.getPointerType(QType); 3051 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3052 VK, &BasePath).get(); 3053 3054 FromType = QType; 3055 FromRecordType = QRecordType; 3056 3057 // If the qualifier type was the same as the destination type, 3058 // we're done. 3059 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3060 return From; 3061 } 3062 } 3063 3064 CXXCastPath BasePath; 3065 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3066 FromLoc, FromRange, &BasePath, 3067 /*IgnoreAccess=*/true)) 3068 return ExprError(); 3069 3070 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3071 VK, &BasePath); 3072 } 3073 3074 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3075 const LookupResult &R, 3076 bool HasTrailingLParen) { 3077 // Only when used directly as the postfix-expression of a call. 3078 if (!HasTrailingLParen) 3079 return false; 3080 3081 // Never if a scope specifier was provided. 3082 if (SS.isSet()) 3083 return false; 3084 3085 // Only in C++ or ObjC++. 3086 if (!getLangOpts().CPlusPlus) 3087 return false; 3088 3089 // Turn off ADL when we find certain kinds of declarations during 3090 // normal lookup: 3091 for (NamedDecl *D : R) { 3092 // C++0x [basic.lookup.argdep]p3: 3093 // -- a declaration of a class member 3094 // Since using decls preserve this property, we check this on the 3095 // original decl. 3096 if (D->isCXXClassMember()) 3097 return false; 3098 3099 // C++0x [basic.lookup.argdep]p3: 3100 // -- a block-scope function declaration that is not a 3101 // using-declaration 3102 // NOTE: we also trigger this for function templates (in fact, we 3103 // don't check the decl type at all, since all other decl types 3104 // turn off ADL anyway). 3105 if (isa<UsingShadowDecl>(D)) 3106 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3107 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3108 return false; 3109 3110 // C++0x [basic.lookup.argdep]p3: 3111 // -- a declaration that is neither a function or a function 3112 // template 3113 // And also for builtin functions. 3114 if (isa<FunctionDecl>(D)) { 3115 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3116 3117 // But also builtin functions. 3118 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3119 return false; 3120 } else if (!isa<FunctionTemplateDecl>(D)) 3121 return false; 3122 } 3123 3124 return true; 3125 } 3126 3127 3128 /// Diagnoses obvious problems with the use of the given declaration 3129 /// as an expression. This is only actually called for lookups that 3130 /// were not overloaded, and it doesn't promise that the declaration 3131 /// will in fact be used. 3132 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3133 if (D->isInvalidDecl()) 3134 return true; 3135 3136 if (isa<TypedefNameDecl>(D)) { 3137 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3138 return true; 3139 } 3140 3141 if (isa<ObjCInterfaceDecl>(D)) { 3142 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3143 return true; 3144 } 3145 3146 if (isa<NamespaceDecl>(D)) { 3147 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3148 return true; 3149 } 3150 3151 return false; 3152 } 3153 3154 // Certain multiversion types should be treated as overloaded even when there is 3155 // only one result. 3156 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3157 assert(R.isSingleResult() && "Expected only a single result"); 3158 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3159 return FD && 3160 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3161 } 3162 3163 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3164 LookupResult &R, bool NeedsADL, 3165 bool AcceptInvalidDecl) { 3166 // If this is a single, fully-resolved result and we don't need ADL, 3167 // just build an ordinary singleton decl ref. 3168 if (!NeedsADL && R.isSingleResult() && 3169 !R.getAsSingle<FunctionTemplateDecl>() && 3170 !ShouldLookupResultBeMultiVersionOverload(R)) 3171 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3172 R.getRepresentativeDecl(), nullptr, 3173 AcceptInvalidDecl); 3174 3175 // We only need to check the declaration if there's exactly one 3176 // result, because in the overloaded case the results can only be 3177 // functions and function templates. 3178 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3179 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3180 return ExprError(); 3181 3182 // Otherwise, just build an unresolved lookup expression. Suppress 3183 // any lookup-related diagnostics; we'll hash these out later, when 3184 // we've picked a target. 3185 R.suppressDiagnostics(); 3186 3187 UnresolvedLookupExpr *ULE 3188 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3189 SS.getWithLocInContext(Context), 3190 R.getLookupNameInfo(), 3191 NeedsADL, R.isOverloadedResult(), 3192 R.begin(), R.end()); 3193 3194 return ULE; 3195 } 3196 3197 static void 3198 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3199 ValueDecl *var, DeclContext *DC); 3200 3201 /// Complete semantic analysis for a reference to the given declaration. 3202 ExprResult Sema::BuildDeclarationNameExpr( 3203 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3204 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3205 bool AcceptInvalidDecl) { 3206 assert(D && "Cannot refer to a NULL declaration"); 3207 assert(!isa<FunctionTemplateDecl>(D) && 3208 "Cannot refer unambiguously to a function template"); 3209 3210 SourceLocation Loc = NameInfo.getLoc(); 3211 if (CheckDeclInExpr(*this, Loc, D)) 3212 return ExprError(); 3213 3214 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3215 // Specifically diagnose references to class templates that are missing 3216 // a template argument list. 3217 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3218 return ExprError(); 3219 } 3220 3221 // Make sure that we're referring to a value. 3222 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3223 Diag(Loc, diag::err_ref_non_value) 3224 << D << SS.getRange(); 3225 Diag(D->getLocation(), diag::note_declared_at); 3226 return ExprError(); 3227 } 3228 3229 // Check whether this declaration can be used. Note that we suppress 3230 // this check when we're going to perform argument-dependent lookup 3231 // on this function name, because this might not be the function 3232 // that overload resolution actually selects. 3233 if (DiagnoseUseOfDecl(D, Loc)) 3234 return ExprError(); 3235 3236 auto *VD = cast<ValueDecl>(D); 3237 3238 // Only create DeclRefExpr's for valid Decl's. 3239 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3240 return ExprError(); 3241 3242 // Handle members of anonymous structs and unions. If we got here, 3243 // and the reference is to a class member indirect field, then this 3244 // must be the subject of a pointer-to-member expression. 3245 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3246 if (!indirectField->isCXXClassMember()) 3247 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3248 indirectField); 3249 3250 { 3251 QualType type = VD->getType(); 3252 if (type.isNull()) 3253 return ExprError(); 3254 ExprValueKind valueKind = VK_PRValue; 3255 3256 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3257 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3258 // is expanded by some outer '...' in the context of the use. 3259 type = type.getNonPackExpansionType(); 3260 3261 switch (D->getKind()) { 3262 // Ignore all the non-ValueDecl kinds. 3263 #define ABSTRACT_DECL(kind) 3264 #define VALUE(type, base) 3265 #define DECL(type, base) \ 3266 case Decl::type: 3267 #include "clang/AST/DeclNodes.inc" 3268 llvm_unreachable("invalid value decl kind"); 3269 3270 // These shouldn't make it here. 3271 case Decl::ObjCAtDefsField: 3272 llvm_unreachable("forming non-member reference to ivar?"); 3273 3274 // Enum constants are always r-values and never references. 3275 // Unresolved using declarations are dependent. 3276 case Decl::EnumConstant: 3277 case Decl::UnresolvedUsingValue: 3278 case Decl::OMPDeclareReduction: 3279 case Decl::OMPDeclareMapper: 3280 valueKind = VK_PRValue; 3281 break; 3282 3283 // Fields and indirect fields that got here must be for 3284 // pointer-to-member expressions; we just call them l-values for 3285 // internal consistency, because this subexpression doesn't really 3286 // exist in the high-level semantics. 3287 case Decl::Field: 3288 case Decl::IndirectField: 3289 case Decl::ObjCIvar: 3290 assert(getLangOpts().CPlusPlus && 3291 "building reference to field in C?"); 3292 3293 // These can't have reference type in well-formed programs, but 3294 // for internal consistency we do this anyway. 3295 type = type.getNonReferenceType(); 3296 valueKind = VK_LValue; 3297 break; 3298 3299 // Non-type template parameters are either l-values or r-values 3300 // depending on the type. 3301 case Decl::NonTypeTemplateParm: { 3302 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3303 type = reftype->getPointeeType(); 3304 valueKind = VK_LValue; // even if the parameter is an r-value reference 3305 break; 3306 } 3307 3308 // [expr.prim.id.unqual]p2: 3309 // If the entity is a template parameter object for a template 3310 // parameter of type T, the type of the expression is const T. 3311 // [...] The expression is an lvalue if the entity is a [...] template 3312 // parameter object. 3313 if (type->isRecordType()) { 3314 type = type.getUnqualifiedType().withConst(); 3315 valueKind = VK_LValue; 3316 break; 3317 } 3318 3319 // For non-references, we need to strip qualifiers just in case 3320 // the template parameter was declared as 'const int' or whatever. 3321 valueKind = VK_PRValue; 3322 type = type.getUnqualifiedType(); 3323 break; 3324 } 3325 3326 case Decl::Var: 3327 case Decl::VarTemplateSpecialization: 3328 case Decl::VarTemplatePartialSpecialization: 3329 case Decl::Decomposition: 3330 case Decl::OMPCapturedExpr: 3331 // In C, "extern void blah;" is valid and is an r-value. 3332 if (!getLangOpts().CPlusPlus && 3333 !type.hasQualifiers() && 3334 type->isVoidType()) { 3335 valueKind = VK_PRValue; 3336 break; 3337 } 3338 LLVM_FALLTHROUGH; 3339 3340 case Decl::ImplicitParam: 3341 case Decl::ParmVar: { 3342 // These are always l-values. 3343 valueKind = VK_LValue; 3344 type = type.getNonReferenceType(); 3345 3346 // FIXME: Does the addition of const really only apply in 3347 // potentially-evaluated contexts? Since the variable isn't actually 3348 // captured in an unevaluated context, it seems that the answer is no. 3349 if (!isUnevaluatedContext()) { 3350 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3351 if (!CapturedType.isNull()) 3352 type = CapturedType; 3353 } 3354 3355 break; 3356 } 3357 3358 case Decl::Binding: { 3359 // These are always lvalues. 3360 valueKind = VK_LValue; 3361 type = type.getNonReferenceType(); 3362 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3363 // decides how that's supposed to work. 3364 auto *BD = cast<BindingDecl>(VD); 3365 if (BD->getDeclContext() != CurContext) { 3366 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3367 if (DD && DD->hasLocalStorage()) 3368 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3369 } 3370 break; 3371 } 3372 3373 case Decl::Function: { 3374 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3375 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3376 type = Context.BuiltinFnTy; 3377 valueKind = VK_PRValue; 3378 break; 3379 } 3380 } 3381 3382 const FunctionType *fty = type->castAs<FunctionType>(); 3383 3384 // If we're referring to a function with an __unknown_anytype 3385 // result type, make the entire expression __unknown_anytype. 3386 if (fty->getReturnType() == Context.UnknownAnyTy) { 3387 type = Context.UnknownAnyTy; 3388 valueKind = VK_PRValue; 3389 break; 3390 } 3391 3392 // Functions are l-values in C++. 3393 if (getLangOpts().CPlusPlus) { 3394 valueKind = VK_LValue; 3395 break; 3396 } 3397 3398 // C99 DR 316 says that, if a function type comes from a 3399 // function definition (without a prototype), that type is only 3400 // used for checking compatibility. Therefore, when referencing 3401 // the function, we pretend that we don't have the full function 3402 // type. 3403 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3404 isa<FunctionProtoType>(fty)) 3405 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3406 fty->getExtInfo()); 3407 3408 // Functions are r-values in C. 3409 valueKind = VK_PRValue; 3410 break; 3411 } 3412 3413 case Decl::CXXDeductionGuide: 3414 llvm_unreachable("building reference to deduction guide"); 3415 3416 case Decl::MSProperty: 3417 case Decl::MSGuid: 3418 case Decl::TemplateParamObject: 3419 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3420 // capture in OpenMP, or duplicated between host and device? 3421 valueKind = VK_LValue; 3422 break; 3423 3424 case Decl::CXXMethod: 3425 // If we're referring to a method with an __unknown_anytype 3426 // result type, make the entire expression __unknown_anytype. 3427 // This should only be possible with a type written directly. 3428 if (const FunctionProtoType *proto 3429 = dyn_cast<FunctionProtoType>(VD->getType())) 3430 if (proto->getReturnType() == Context.UnknownAnyTy) { 3431 type = Context.UnknownAnyTy; 3432 valueKind = VK_PRValue; 3433 break; 3434 } 3435 3436 // C++ methods are l-values if static, r-values if non-static. 3437 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3438 valueKind = VK_LValue; 3439 break; 3440 } 3441 LLVM_FALLTHROUGH; 3442 3443 case Decl::CXXConversion: 3444 case Decl::CXXDestructor: 3445 case Decl::CXXConstructor: 3446 valueKind = VK_PRValue; 3447 break; 3448 } 3449 3450 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3451 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3452 TemplateArgs); 3453 } 3454 } 3455 3456 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3457 SmallString<32> &Target) { 3458 Target.resize(CharByteWidth * (Source.size() + 1)); 3459 char *ResultPtr = &Target[0]; 3460 const llvm::UTF8 *ErrorPtr; 3461 bool success = 3462 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3463 (void)success; 3464 assert(success); 3465 Target.resize(ResultPtr - &Target[0]); 3466 } 3467 3468 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3469 PredefinedExpr::IdentKind IK) { 3470 // Pick the current block, lambda, captured statement or function. 3471 Decl *currentDecl = nullptr; 3472 if (const BlockScopeInfo *BSI = getCurBlock()) 3473 currentDecl = BSI->TheDecl; 3474 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3475 currentDecl = LSI->CallOperator; 3476 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3477 currentDecl = CSI->TheCapturedDecl; 3478 else 3479 currentDecl = getCurFunctionOrMethodDecl(); 3480 3481 if (!currentDecl) { 3482 Diag(Loc, diag::ext_predef_outside_function); 3483 currentDecl = Context.getTranslationUnitDecl(); 3484 } 3485 3486 QualType ResTy; 3487 StringLiteral *SL = nullptr; 3488 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3489 ResTy = Context.DependentTy; 3490 else { 3491 // Pre-defined identifiers are of type char[x], where x is the length of 3492 // the string. 3493 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3494 unsigned Length = Str.length(); 3495 3496 llvm::APInt LengthI(32, Length + 1); 3497 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3498 ResTy = 3499 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3500 SmallString<32> RawChars; 3501 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3502 Str, RawChars); 3503 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3504 ArrayType::Normal, 3505 /*IndexTypeQuals*/ 0); 3506 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3507 /*Pascal*/ false, ResTy, Loc); 3508 } else { 3509 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3510 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3511 ArrayType::Normal, 3512 /*IndexTypeQuals*/ 0); 3513 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3514 /*Pascal*/ false, ResTy, Loc); 3515 } 3516 } 3517 3518 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3519 } 3520 3521 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3522 SourceLocation LParen, 3523 SourceLocation RParen, 3524 TypeSourceInfo *TSI) { 3525 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3526 } 3527 3528 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3529 SourceLocation LParen, 3530 SourceLocation RParen, 3531 ParsedType ParsedTy) { 3532 TypeSourceInfo *TSI = nullptr; 3533 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3534 3535 if (Ty.isNull()) 3536 return ExprError(); 3537 if (!TSI) 3538 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3539 3540 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3541 } 3542 3543 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3544 PredefinedExpr::IdentKind IK; 3545 3546 switch (Kind) { 3547 default: llvm_unreachable("Unknown simple primary expr!"); 3548 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3549 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3550 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3551 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3552 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3553 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3554 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3555 } 3556 3557 return BuildPredefinedExpr(Loc, IK); 3558 } 3559 3560 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3561 SmallString<16> CharBuffer; 3562 bool Invalid = false; 3563 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3564 if (Invalid) 3565 return ExprError(); 3566 3567 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3568 PP, Tok.getKind()); 3569 if (Literal.hadError()) 3570 return ExprError(); 3571 3572 QualType Ty; 3573 if (Literal.isWide()) 3574 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3575 else if (Literal.isUTF8() && getLangOpts().Char8) 3576 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3577 else if (Literal.isUTF16()) 3578 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3579 else if (Literal.isUTF32()) 3580 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3581 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3582 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3583 else 3584 Ty = Context.CharTy; // 'x' -> char in C++ 3585 3586 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3587 if (Literal.isWide()) 3588 Kind = CharacterLiteral::Wide; 3589 else if (Literal.isUTF16()) 3590 Kind = CharacterLiteral::UTF16; 3591 else if (Literal.isUTF32()) 3592 Kind = CharacterLiteral::UTF32; 3593 else if (Literal.isUTF8()) 3594 Kind = CharacterLiteral::UTF8; 3595 3596 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3597 Tok.getLocation()); 3598 3599 if (Literal.getUDSuffix().empty()) 3600 return Lit; 3601 3602 // We're building a user-defined literal. 3603 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3604 SourceLocation UDSuffixLoc = 3605 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3606 3607 // Make sure we're allowed user-defined literals here. 3608 if (!UDLScope) 3609 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3610 3611 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3612 // operator "" X (ch) 3613 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3614 Lit, Tok.getLocation()); 3615 } 3616 3617 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3618 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3619 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3620 Context.IntTy, Loc); 3621 } 3622 3623 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3624 QualType Ty, SourceLocation Loc) { 3625 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3626 3627 using llvm::APFloat; 3628 APFloat Val(Format); 3629 3630 APFloat::opStatus result = Literal.GetFloatValue(Val); 3631 3632 // Overflow is always an error, but underflow is only an error if 3633 // we underflowed to zero (APFloat reports denormals as underflow). 3634 if ((result & APFloat::opOverflow) || 3635 ((result & APFloat::opUnderflow) && Val.isZero())) { 3636 unsigned diagnostic; 3637 SmallString<20> buffer; 3638 if (result & APFloat::opOverflow) { 3639 diagnostic = diag::warn_float_overflow; 3640 APFloat::getLargest(Format).toString(buffer); 3641 } else { 3642 diagnostic = diag::warn_float_underflow; 3643 APFloat::getSmallest(Format).toString(buffer); 3644 } 3645 3646 S.Diag(Loc, diagnostic) 3647 << Ty 3648 << StringRef(buffer.data(), buffer.size()); 3649 } 3650 3651 bool isExact = (result == APFloat::opOK); 3652 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3653 } 3654 3655 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3656 assert(E && "Invalid expression"); 3657 3658 if (E->isValueDependent()) 3659 return false; 3660 3661 QualType QT = E->getType(); 3662 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3663 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3664 return true; 3665 } 3666 3667 llvm::APSInt ValueAPS; 3668 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3669 3670 if (R.isInvalid()) 3671 return true; 3672 3673 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3674 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3675 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3676 << toString(ValueAPS, 10) << ValueIsPositive; 3677 return true; 3678 } 3679 3680 return false; 3681 } 3682 3683 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3684 // Fast path for a single digit (which is quite common). A single digit 3685 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3686 if (Tok.getLength() == 1) { 3687 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3688 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3689 } 3690 3691 SmallString<128> SpellingBuffer; 3692 // NumericLiteralParser wants to overread by one character. Add padding to 3693 // the buffer in case the token is copied to the buffer. If getSpelling() 3694 // returns a StringRef to the memory buffer, it should have a null char at 3695 // the EOF, so it is also safe. 3696 SpellingBuffer.resize(Tok.getLength() + 1); 3697 3698 // Get the spelling of the token, which eliminates trigraphs, etc. 3699 bool Invalid = false; 3700 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3701 if (Invalid) 3702 return ExprError(); 3703 3704 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3705 PP.getSourceManager(), PP.getLangOpts(), 3706 PP.getTargetInfo(), PP.getDiagnostics()); 3707 if (Literal.hadError) 3708 return ExprError(); 3709 3710 if (Literal.hasUDSuffix()) { 3711 // We're building a user-defined literal. 3712 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3713 SourceLocation UDSuffixLoc = 3714 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3715 3716 // Make sure we're allowed user-defined literals here. 3717 if (!UDLScope) 3718 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3719 3720 QualType CookedTy; 3721 if (Literal.isFloatingLiteral()) { 3722 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3723 // long double, the literal is treated as a call of the form 3724 // operator "" X (f L) 3725 CookedTy = Context.LongDoubleTy; 3726 } else { 3727 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3728 // unsigned long long, the literal is treated as a call of the form 3729 // operator "" X (n ULL) 3730 CookedTy = Context.UnsignedLongLongTy; 3731 } 3732 3733 DeclarationName OpName = 3734 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3735 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3736 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3737 3738 SourceLocation TokLoc = Tok.getLocation(); 3739 3740 // Perform literal operator lookup to determine if we're building a raw 3741 // literal or a cooked one. 3742 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3743 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3744 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3745 /*AllowStringTemplatePack*/ false, 3746 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3747 case LOLR_ErrorNoDiagnostic: 3748 // Lookup failure for imaginary constants isn't fatal, there's still the 3749 // GNU extension producing _Complex types. 3750 break; 3751 case LOLR_Error: 3752 return ExprError(); 3753 case LOLR_Cooked: { 3754 Expr *Lit; 3755 if (Literal.isFloatingLiteral()) { 3756 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3757 } else { 3758 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3759 if (Literal.GetIntegerValue(ResultVal)) 3760 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3761 << /* Unsigned */ 1; 3762 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3763 Tok.getLocation()); 3764 } 3765 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3766 } 3767 3768 case LOLR_Raw: { 3769 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3770 // literal is treated as a call of the form 3771 // operator "" X ("n") 3772 unsigned Length = Literal.getUDSuffixOffset(); 3773 QualType StrTy = Context.getConstantArrayType( 3774 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3775 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3776 Expr *Lit = StringLiteral::Create( 3777 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3778 /*Pascal*/false, StrTy, &TokLoc, 1); 3779 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3780 } 3781 3782 case LOLR_Template: { 3783 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3784 // template), L is treated as a call fo the form 3785 // operator "" X <'c1', 'c2', ... 'ck'>() 3786 // where n is the source character sequence c1 c2 ... ck. 3787 TemplateArgumentListInfo ExplicitArgs; 3788 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3789 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3790 llvm::APSInt Value(CharBits, CharIsUnsigned); 3791 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3792 Value = TokSpelling[I]; 3793 TemplateArgument Arg(Context, Value, Context.CharTy); 3794 TemplateArgumentLocInfo ArgInfo; 3795 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3796 } 3797 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3798 &ExplicitArgs); 3799 } 3800 case LOLR_StringTemplatePack: 3801 llvm_unreachable("unexpected literal operator lookup result"); 3802 } 3803 } 3804 3805 Expr *Res; 3806 3807 if (Literal.isFixedPointLiteral()) { 3808 QualType Ty; 3809 3810 if (Literal.isAccum) { 3811 if (Literal.isHalf) { 3812 Ty = Context.ShortAccumTy; 3813 } else if (Literal.isLong) { 3814 Ty = Context.LongAccumTy; 3815 } else { 3816 Ty = Context.AccumTy; 3817 } 3818 } else if (Literal.isFract) { 3819 if (Literal.isHalf) { 3820 Ty = Context.ShortFractTy; 3821 } else if (Literal.isLong) { 3822 Ty = Context.LongFractTy; 3823 } else { 3824 Ty = Context.FractTy; 3825 } 3826 } 3827 3828 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3829 3830 bool isSigned = !Literal.isUnsigned; 3831 unsigned scale = Context.getFixedPointScale(Ty); 3832 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3833 3834 llvm::APInt Val(bit_width, 0, isSigned); 3835 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3836 bool ValIsZero = Val.isNullValue() && !Overflowed; 3837 3838 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3839 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3840 // Clause 6.4.4 - The value of a constant shall be in the range of 3841 // representable values for its type, with exception for constants of a 3842 // fract type with a value of exactly 1; such a constant shall denote 3843 // the maximal value for the type. 3844 --Val; 3845 else if (Val.ugt(MaxVal) || Overflowed) 3846 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3847 3848 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3849 Tok.getLocation(), scale); 3850 } else if (Literal.isFloatingLiteral()) { 3851 QualType Ty; 3852 if (Literal.isHalf){ 3853 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3854 Ty = Context.HalfTy; 3855 else { 3856 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3857 return ExprError(); 3858 } 3859 } else if (Literal.isFloat) 3860 Ty = Context.FloatTy; 3861 else if (Literal.isLong) 3862 Ty = Context.LongDoubleTy; 3863 else if (Literal.isFloat16) 3864 Ty = Context.Float16Ty; 3865 else if (Literal.isFloat128) 3866 Ty = Context.Float128Ty; 3867 else 3868 Ty = Context.DoubleTy; 3869 3870 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3871 3872 if (Ty == Context.DoubleTy) { 3873 if (getLangOpts().SinglePrecisionConstants) { 3874 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3875 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3876 } 3877 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3878 "cl_khr_fp64", getLangOpts())) { 3879 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3880 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3881 << (getLangOpts().OpenCLVersion >= 300); 3882 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3883 } 3884 } 3885 } else if (!Literal.isIntegerLiteral()) { 3886 return ExprError(); 3887 } else { 3888 QualType Ty; 3889 3890 // 'long long' is a C99 or C++11 feature. 3891 if (!getLangOpts().C99 && Literal.isLongLong) { 3892 if (getLangOpts().CPlusPlus) 3893 Diag(Tok.getLocation(), 3894 getLangOpts().CPlusPlus11 ? 3895 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3896 else 3897 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3898 } 3899 3900 // 'z/uz' literals are a C++2b feature. 3901 if (Literal.isSizeT) 3902 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3903 ? getLangOpts().CPlusPlus2b 3904 ? diag::warn_cxx20_compat_size_t_suffix 3905 : diag::ext_cxx2b_size_t_suffix 3906 : diag::err_cxx2b_size_t_suffix); 3907 3908 // Get the value in the widest-possible width. 3909 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3910 llvm::APInt ResultVal(MaxWidth, 0); 3911 3912 if (Literal.GetIntegerValue(ResultVal)) { 3913 // If this value didn't fit into uintmax_t, error and force to ull. 3914 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3915 << /* Unsigned */ 1; 3916 Ty = Context.UnsignedLongLongTy; 3917 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3918 "long long is not intmax_t?"); 3919 } else { 3920 // If this value fits into a ULL, try to figure out what else it fits into 3921 // according to the rules of C99 6.4.4.1p5. 3922 3923 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3924 // be an unsigned int. 3925 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3926 3927 // Check from smallest to largest, picking the smallest type we can. 3928 unsigned Width = 0; 3929 3930 // Microsoft specific integer suffixes are explicitly sized. 3931 if (Literal.MicrosoftInteger) { 3932 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3933 Width = 8; 3934 Ty = Context.CharTy; 3935 } else { 3936 Width = Literal.MicrosoftInteger; 3937 Ty = Context.getIntTypeForBitwidth(Width, 3938 /*Signed=*/!Literal.isUnsigned); 3939 } 3940 } 3941 3942 // Check C++2b size_t literals. 3943 if (Literal.isSizeT) { 3944 assert(!Literal.MicrosoftInteger && 3945 "size_t literals can't be Microsoft literals"); 3946 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3947 Context.getTargetInfo().getSizeType()); 3948 3949 // Does it fit in size_t? 3950 if (ResultVal.isIntN(SizeTSize)) { 3951 // Does it fit in ssize_t? 3952 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3953 Ty = Context.getSignedSizeType(); 3954 else if (AllowUnsigned) 3955 Ty = Context.getSizeType(); 3956 Width = SizeTSize; 3957 } 3958 } 3959 3960 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3961 !Literal.isSizeT) { 3962 // Are int/unsigned possibilities? 3963 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3964 3965 // Does it fit in a unsigned int? 3966 if (ResultVal.isIntN(IntSize)) { 3967 // Does it fit in a signed int? 3968 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3969 Ty = Context.IntTy; 3970 else if (AllowUnsigned) 3971 Ty = Context.UnsignedIntTy; 3972 Width = IntSize; 3973 } 3974 } 3975 3976 // Are long/unsigned long possibilities? 3977 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3978 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3979 3980 // Does it fit in a unsigned long? 3981 if (ResultVal.isIntN(LongSize)) { 3982 // Does it fit in a signed long? 3983 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3984 Ty = Context.LongTy; 3985 else if (AllowUnsigned) 3986 Ty = Context.UnsignedLongTy; 3987 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3988 // is compatible. 3989 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3990 const unsigned LongLongSize = 3991 Context.getTargetInfo().getLongLongWidth(); 3992 Diag(Tok.getLocation(), 3993 getLangOpts().CPlusPlus 3994 ? Literal.isLong 3995 ? diag::warn_old_implicitly_unsigned_long_cxx 3996 : /*C++98 UB*/ diag:: 3997 ext_old_implicitly_unsigned_long_cxx 3998 : diag::warn_old_implicitly_unsigned_long) 3999 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4000 : /*will be ill-formed*/ 1); 4001 Ty = Context.UnsignedLongTy; 4002 } 4003 Width = LongSize; 4004 } 4005 } 4006 4007 // Check long long if needed. 4008 if (Ty.isNull() && !Literal.isSizeT) { 4009 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4010 4011 // Does it fit in a unsigned long long? 4012 if (ResultVal.isIntN(LongLongSize)) { 4013 // Does it fit in a signed long long? 4014 // To be compatible with MSVC, hex integer literals ending with the 4015 // LL or i64 suffix are always signed in Microsoft mode. 4016 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4017 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4018 Ty = Context.LongLongTy; 4019 else if (AllowUnsigned) 4020 Ty = Context.UnsignedLongLongTy; 4021 Width = LongLongSize; 4022 } 4023 } 4024 4025 // If we still couldn't decide a type, we either have 'size_t' literal 4026 // that is out of range, or a decimal literal that does not fit in a 4027 // signed long long and has no U suffix. 4028 if (Ty.isNull()) { 4029 if (Literal.isSizeT) 4030 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4031 << Literal.isUnsigned; 4032 else 4033 Diag(Tok.getLocation(), 4034 diag::ext_integer_literal_too_large_for_signed); 4035 Ty = Context.UnsignedLongLongTy; 4036 Width = Context.getTargetInfo().getLongLongWidth(); 4037 } 4038 4039 if (ResultVal.getBitWidth() != Width) 4040 ResultVal = ResultVal.trunc(Width); 4041 } 4042 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4043 } 4044 4045 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4046 if (Literal.isImaginary) { 4047 Res = new (Context) ImaginaryLiteral(Res, 4048 Context.getComplexType(Res->getType())); 4049 4050 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4051 } 4052 return Res; 4053 } 4054 4055 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4056 assert(E && "ActOnParenExpr() missing expr"); 4057 return new (Context) ParenExpr(L, R, E); 4058 } 4059 4060 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4061 SourceLocation Loc, 4062 SourceRange ArgRange) { 4063 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4064 // scalar or vector data type argument..." 4065 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4066 // type (C99 6.2.5p18) or void. 4067 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4068 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4069 << T << ArgRange; 4070 return true; 4071 } 4072 4073 assert((T->isVoidType() || !T->isIncompleteType()) && 4074 "Scalar types should always be complete"); 4075 return false; 4076 } 4077 4078 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4079 SourceLocation Loc, 4080 SourceRange ArgRange, 4081 UnaryExprOrTypeTrait TraitKind) { 4082 // Invalid types must be hard errors for SFINAE in C++. 4083 if (S.LangOpts.CPlusPlus) 4084 return true; 4085 4086 // C99 6.5.3.4p1: 4087 if (T->isFunctionType() && 4088 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4089 TraitKind == UETT_PreferredAlignOf)) { 4090 // sizeof(function)/alignof(function) is allowed as an extension. 4091 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4092 << getTraitSpelling(TraitKind) << ArgRange; 4093 return false; 4094 } 4095 4096 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4097 // this is an error (OpenCL v1.1 s6.3.k) 4098 if (T->isVoidType()) { 4099 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4100 : diag::ext_sizeof_alignof_void_type; 4101 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4102 return false; 4103 } 4104 4105 return true; 4106 } 4107 4108 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4109 SourceLocation Loc, 4110 SourceRange ArgRange, 4111 UnaryExprOrTypeTrait TraitKind) { 4112 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4113 // runtime doesn't allow it. 4114 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4115 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4116 << T << (TraitKind == UETT_SizeOf) 4117 << ArgRange; 4118 return true; 4119 } 4120 4121 return false; 4122 } 4123 4124 /// Check whether E is a pointer from a decayed array type (the decayed 4125 /// pointer type is equal to T) and emit a warning if it is. 4126 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4127 Expr *E) { 4128 // Don't warn if the operation changed the type. 4129 if (T != E->getType()) 4130 return; 4131 4132 // Now look for array decays. 4133 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4134 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4135 return; 4136 4137 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4138 << ICE->getType() 4139 << ICE->getSubExpr()->getType(); 4140 } 4141 4142 /// Check the constraints on expression operands to unary type expression 4143 /// and type traits. 4144 /// 4145 /// Completes any types necessary and validates the constraints on the operand 4146 /// expression. The logic mostly mirrors the type-based overload, but may modify 4147 /// the expression as it completes the type for that expression through template 4148 /// instantiation, etc. 4149 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4150 UnaryExprOrTypeTrait ExprKind) { 4151 QualType ExprTy = E->getType(); 4152 assert(!ExprTy->isReferenceType()); 4153 4154 bool IsUnevaluatedOperand = 4155 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4156 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4157 if (IsUnevaluatedOperand) { 4158 ExprResult Result = CheckUnevaluatedOperand(E); 4159 if (Result.isInvalid()) 4160 return true; 4161 E = Result.get(); 4162 } 4163 4164 // The operand for sizeof and alignof is in an unevaluated expression context, 4165 // so side effects could result in unintended consequences. 4166 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4167 // used to build SFINAE gadgets. 4168 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4169 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4170 !E->isInstantiationDependent() && 4171 E->HasSideEffects(Context, false)) 4172 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4173 4174 if (ExprKind == UETT_VecStep) 4175 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4176 E->getSourceRange()); 4177 4178 // Explicitly list some types as extensions. 4179 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4180 E->getSourceRange(), ExprKind)) 4181 return false; 4182 4183 // 'alignof' applied to an expression only requires the base element type of 4184 // the expression to be complete. 'sizeof' requires the expression's type to 4185 // be complete (and will attempt to complete it if it's an array of unknown 4186 // bound). 4187 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4188 if (RequireCompleteSizedType( 4189 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4190 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4191 getTraitSpelling(ExprKind), E->getSourceRange())) 4192 return true; 4193 } else { 4194 if (RequireCompleteSizedExprType( 4195 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4196 getTraitSpelling(ExprKind), E->getSourceRange())) 4197 return true; 4198 } 4199 4200 // Completing the expression's type may have changed it. 4201 ExprTy = E->getType(); 4202 assert(!ExprTy->isReferenceType()); 4203 4204 if (ExprTy->isFunctionType()) { 4205 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4206 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4207 return true; 4208 } 4209 4210 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4211 E->getSourceRange(), ExprKind)) 4212 return true; 4213 4214 if (ExprKind == UETT_SizeOf) { 4215 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4216 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4217 QualType OType = PVD->getOriginalType(); 4218 QualType Type = PVD->getType(); 4219 if (Type->isPointerType() && OType->isArrayType()) { 4220 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4221 << Type << OType; 4222 Diag(PVD->getLocation(), diag::note_declared_at); 4223 } 4224 } 4225 } 4226 4227 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4228 // decays into a pointer and returns an unintended result. This is most 4229 // likely a typo for "sizeof(array) op x". 4230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4231 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4232 BO->getLHS()); 4233 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4234 BO->getRHS()); 4235 } 4236 } 4237 4238 return false; 4239 } 4240 4241 /// Check the constraints on operands to unary expression and type 4242 /// traits. 4243 /// 4244 /// This will complete any types necessary, and validate the various constraints 4245 /// on those operands. 4246 /// 4247 /// The UsualUnaryConversions() function is *not* called by this routine. 4248 /// C99 6.3.2.1p[2-4] all state: 4249 /// Except when it is the operand of the sizeof operator ... 4250 /// 4251 /// C++ [expr.sizeof]p4 4252 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4253 /// standard conversions are not applied to the operand of sizeof. 4254 /// 4255 /// This policy is followed for all of the unary trait expressions. 4256 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4257 SourceLocation OpLoc, 4258 SourceRange ExprRange, 4259 UnaryExprOrTypeTrait ExprKind) { 4260 if (ExprType->isDependentType()) 4261 return false; 4262 4263 // C++ [expr.sizeof]p2: 4264 // When applied to a reference or a reference type, the result 4265 // is the size of the referenced type. 4266 // C++11 [expr.alignof]p3: 4267 // When alignof is applied to a reference type, the result 4268 // shall be the alignment of the referenced type. 4269 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4270 ExprType = Ref->getPointeeType(); 4271 4272 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4273 // When alignof or _Alignof is applied to an array type, the result 4274 // is the alignment of the element type. 4275 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4276 ExprKind == UETT_OpenMPRequiredSimdAlign) 4277 ExprType = Context.getBaseElementType(ExprType); 4278 4279 if (ExprKind == UETT_VecStep) 4280 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4281 4282 // Explicitly list some types as extensions. 4283 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4284 ExprKind)) 4285 return false; 4286 4287 if (RequireCompleteSizedType( 4288 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4289 getTraitSpelling(ExprKind), ExprRange)) 4290 return true; 4291 4292 if (ExprType->isFunctionType()) { 4293 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4294 << getTraitSpelling(ExprKind) << ExprRange; 4295 return true; 4296 } 4297 4298 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4299 ExprKind)) 4300 return true; 4301 4302 return false; 4303 } 4304 4305 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4306 // Cannot know anything else if the expression is dependent. 4307 if (E->isTypeDependent()) 4308 return false; 4309 4310 if (E->getObjectKind() == OK_BitField) { 4311 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4312 << 1 << E->getSourceRange(); 4313 return true; 4314 } 4315 4316 ValueDecl *D = nullptr; 4317 Expr *Inner = E->IgnoreParens(); 4318 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4319 D = DRE->getDecl(); 4320 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4321 D = ME->getMemberDecl(); 4322 } 4323 4324 // If it's a field, require the containing struct to have a 4325 // complete definition so that we can compute the layout. 4326 // 4327 // This can happen in C++11 onwards, either by naming the member 4328 // in a way that is not transformed into a member access expression 4329 // (in an unevaluated operand, for instance), or by naming the member 4330 // in a trailing-return-type. 4331 // 4332 // For the record, since __alignof__ on expressions is a GCC 4333 // extension, GCC seems to permit this but always gives the 4334 // nonsensical answer 0. 4335 // 4336 // We don't really need the layout here --- we could instead just 4337 // directly check for all the appropriate alignment-lowing 4338 // attributes --- but that would require duplicating a lot of 4339 // logic that just isn't worth duplicating for such a marginal 4340 // use-case. 4341 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4342 // Fast path this check, since we at least know the record has a 4343 // definition if we can find a member of it. 4344 if (!FD->getParent()->isCompleteDefinition()) { 4345 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4346 << E->getSourceRange(); 4347 return true; 4348 } 4349 4350 // Otherwise, if it's a field, and the field doesn't have 4351 // reference type, then it must have a complete type (or be a 4352 // flexible array member, which we explicitly want to 4353 // white-list anyway), which makes the following checks trivial. 4354 if (!FD->getType()->isReferenceType()) 4355 return false; 4356 } 4357 4358 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4359 } 4360 4361 bool Sema::CheckVecStepExpr(Expr *E) { 4362 E = E->IgnoreParens(); 4363 4364 // Cannot know anything else if the expression is dependent. 4365 if (E->isTypeDependent()) 4366 return false; 4367 4368 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4369 } 4370 4371 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4372 CapturingScopeInfo *CSI) { 4373 assert(T->isVariablyModifiedType()); 4374 assert(CSI != nullptr); 4375 4376 // We're going to walk down into the type and look for VLA expressions. 4377 do { 4378 const Type *Ty = T.getTypePtr(); 4379 switch (Ty->getTypeClass()) { 4380 #define TYPE(Class, Base) 4381 #define ABSTRACT_TYPE(Class, Base) 4382 #define NON_CANONICAL_TYPE(Class, Base) 4383 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4384 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4385 #include "clang/AST/TypeNodes.inc" 4386 T = QualType(); 4387 break; 4388 // These types are never variably-modified. 4389 case Type::Builtin: 4390 case Type::Complex: 4391 case Type::Vector: 4392 case Type::ExtVector: 4393 case Type::ConstantMatrix: 4394 case Type::Record: 4395 case Type::Enum: 4396 case Type::Elaborated: 4397 case Type::TemplateSpecialization: 4398 case Type::ObjCObject: 4399 case Type::ObjCInterface: 4400 case Type::ObjCObjectPointer: 4401 case Type::ObjCTypeParam: 4402 case Type::Pipe: 4403 case Type::ExtInt: 4404 llvm_unreachable("type class is never variably-modified!"); 4405 case Type::Adjusted: 4406 T = cast<AdjustedType>(Ty)->getOriginalType(); 4407 break; 4408 case Type::Decayed: 4409 T = cast<DecayedType>(Ty)->getPointeeType(); 4410 break; 4411 case Type::Pointer: 4412 T = cast<PointerType>(Ty)->getPointeeType(); 4413 break; 4414 case Type::BlockPointer: 4415 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4416 break; 4417 case Type::LValueReference: 4418 case Type::RValueReference: 4419 T = cast<ReferenceType>(Ty)->getPointeeType(); 4420 break; 4421 case Type::MemberPointer: 4422 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4423 break; 4424 case Type::ConstantArray: 4425 case Type::IncompleteArray: 4426 // Losing element qualification here is fine. 4427 T = cast<ArrayType>(Ty)->getElementType(); 4428 break; 4429 case Type::VariableArray: { 4430 // Losing element qualification here is fine. 4431 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4432 4433 // Unknown size indication requires no size computation. 4434 // Otherwise, evaluate and record it. 4435 auto Size = VAT->getSizeExpr(); 4436 if (Size && !CSI->isVLATypeCaptured(VAT) && 4437 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4438 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4439 4440 T = VAT->getElementType(); 4441 break; 4442 } 4443 case Type::FunctionProto: 4444 case Type::FunctionNoProto: 4445 T = cast<FunctionType>(Ty)->getReturnType(); 4446 break; 4447 case Type::Paren: 4448 case Type::TypeOf: 4449 case Type::UnaryTransform: 4450 case Type::Attributed: 4451 case Type::SubstTemplateTypeParm: 4452 case Type::MacroQualified: 4453 // Keep walking after single level desugaring. 4454 T = T.getSingleStepDesugaredType(Context); 4455 break; 4456 case Type::Typedef: 4457 T = cast<TypedefType>(Ty)->desugar(); 4458 break; 4459 case Type::Decltype: 4460 T = cast<DecltypeType>(Ty)->desugar(); 4461 break; 4462 case Type::Auto: 4463 case Type::DeducedTemplateSpecialization: 4464 T = cast<DeducedType>(Ty)->getDeducedType(); 4465 break; 4466 case Type::TypeOfExpr: 4467 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4468 break; 4469 case Type::Atomic: 4470 T = cast<AtomicType>(Ty)->getValueType(); 4471 break; 4472 } 4473 } while (!T.isNull() && T->isVariablyModifiedType()); 4474 } 4475 4476 /// Build a sizeof or alignof expression given a type operand. 4477 ExprResult 4478 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4479 SourceLocation OpLoc, 4480 UnaryExprOrTypeTrait ExprKind, 4481 SourceRange R) { 4482 if (!TInfo) 4483 return ExprError(); 4484 4485 QualType T = TInfo->getType(); 4486 4487 if (!T->isDependentType() && 4488 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4489 return ExprError(); 4490 4491 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4492 if (auto *TT = T->getAs<TypedefType>()) { 4493 for (auto I = FunctionScopes.rbegin(), 4494 E = std::prev(FunctionScopes.rend()); 4495 I != E; ++I) { 4496 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4497 if (CSI == nullptr) 4498 break; 4499 DeclContext *DC = nullptr; 4500 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4501 DC = LSI->CallOperator; 4502 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4503 DC = CRSI->TheCapturedDecl; 4504 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4505 DC = BSI->TheDecl; 4506 if (DC) { 4507 if (DC->containsDecl(TT->getDecl())) 4508 break; 4509 captureVariablyModifiedType(Context, T, CSI); 4510 } 4511 } 4512 } 4513 } 4514 4515 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4516 return new (Context) UnaryExprOrTypeTraitExpr( 4517 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4518 } 4519 4520 /// Build a sizeof or alignof expression given an expression 4521 /// operand. 4522 ExprResult 4523 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4524 UnaryExprOrTypeTrait ExprKind) { 4525 ExprResult PE = CheckPlaceholderExpr(E); 4526 if (PE.isInvalid()) 4527 return ExprError(); 4528 4529 E = PE.get(); 4530 4531 // Verify that the operand is valid. 4532 bool isInvalid = false; 4533 if (E->isTypeDependent()) { 4534 // Delay type-checking for type-dependent expressions. 4535 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4536 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4537 } else if (ExprKind == UETT_VecStep) { 4538 isInvalid = CheckVecStepExpr(E); 4539 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4540 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4541 isInvalid = true; 4542 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4543 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4544 isInvalid = true; 4545 } else { 4546 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4547 } 4548 4549 if (isInvalid) 4550 return ExprError(); 4551 4552 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4553 PE = TransformToPotentiallyEvaluated(E); 4554 if (PE.isInvalid()) return ExprError(); 4555 E = PE.get(); 4556 } 4557 4558 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4559 return new (Context) UnaryExprOrTypeTraitExpr( 4560 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4561 } 4562 4563 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4564 /// expr and the same for @c alignof and @c __alignof 4565 /// Note that the ArgRange is invalid if isType is false. 4566 ExprResult 4567 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4568 UnaryExprOrTypeTrait ExprKind, bool IsType, 4569 void *TyOrEx, SourceRange ArgRange) { 4570 // If error parsing type, ignore. 4571 if (!TyOrEx) return ExprError(); 4572 4573 if (IsType) { 4574 TypeSourceInfo *TInfo; 4575 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4576 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4577 } 4578 4579 Expr *ArgEx = (Expr *)TyOrEx; 4580 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4581 return Result; 4582 } 4583 4584 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4585 bool IsReal) { 4586 if (V.get()->isTypeDependent()) 4587 return S.Context.DependentTy; 4588 4589 // _Real and _Imag are only l-values for normal l-values. 4590 if (V.get()->getObjectKind() != OK_Ordinary) { 4591 V = S.DefaultLvalueConversion(V.get()); 4592 if (V.isInvalid()) 4593 return QualType(); 4594 } 4595 4596 // These operators return the element type of a complex type. 4597 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4598 return CT->getElementType(); 4599 4600 // Otherwise they pass through real integer and floating point types here. 4601 if (V.get()->getType()->isArithmeticType()) 4602 return V.get()->getType(); 4603 4604 // Test for placeholders. 4605 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4606 if (PR.isInvalid()) return QualType(); 4607 if (PR.get() != V.get()) { 4608 V = PR; 4609 return CheckRealImagOperand(S, V, Loc, IsReal); 4610 } 4611 4612 // Reject anything else. 4613 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4614 << (IsReal ? "__real" : "__imag"); 4615 return QualType(); 4616 } 4617 4618 4619 4620 ExprResult 4621 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4622 tok::TokenKind Kind, Expr *Input) { 4623 UnaryOperatorKind Opc; 4624 switch (Kind) { 4625 default: llvm_unreachable("Unknown unary op!"); 4626 case tok::plusplus: Opc = UO_PostInc; break; 4627 case tok::minusminus: Opc = UO_PostDec; break; 4628 } 4629 4630 // Since this might is a postfix expression, get rid of ParenListExprs. 4631 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4632 if (Result.isInvalid()) return ExprError(); 4633 Input = Result.get(); 4634 4635 return BuildUnaryOp(S, OpLoc, Opc, Input); 4636 } 4637 4638 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4639 /// 4640 /// \return true on error 4641 static bool checkArithmeticOnObjCPointer(Sema &S, 4642 SourceLocation opLoc, 4643 Expr *op) { 4644 assert(op->getType()->isObjCObjectPointerType()); 4645 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4646 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4647 return false; 4648 4649 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4650 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4651 << op->getSourceRange(); 4652 return true; 4653 } 4654 4655 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4656 auto *BaseNoParens = Base->IgnoreParens(); 4657 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4658 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4659 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4660 } 4661 4662 ExprResult 4663 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4664 Expr *idx, SourceLocation rbLoc) { 4665 if (base && !base->getType().isNull() && 4666 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4667 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4668 SourceLocation(), /*Length*/ nullptr, 4669 /*Stride=*/nullptr, rbLoc); 4670 4671 // Since this might be a postfix expression, get rid of ParenListExprs. 4672 if (isa<ParenListExpr>(base)) { 4673 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4674 if (result.isInvalid()) return ExprError(); 4675 base = result.get(); 4676 } 4677 4678 // Check if base and idx form a MatrixSubscriptExpr. 4679 // 4680 // Helper to check for comma expressions, which are not allowed as indices for 4681 // matrix subscript expressions. 4682 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4683 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4684 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4685 << SourceRange(base->getBeginLoc(), rbLoc); 4686 return true; 4687 } 4688 return false; 4689 }; 4690 // The matrix subscript operator ([][])is considered a single operator. 4691 // Separating the index expressions by parenthesis is not allowed. 4692 if (base->getType()->isSpecificPlaceholderType( 4693 BuiltinType::IncompleteMatrixIdx) && 4694 !isa<MatrixSubscriptExpr>(base)) { 4695 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4696 << SourceRange(base->getBeginLoc(), rbLoc); 4697 return ExprError(); 4698 } 4699 // If the base is a MatrixSubscriptExpr, try to create a new 4700 // MatrixSubscriptExpr. 4701 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4702 if (matSubscriptE) { 4703 if (CheckAndReportCommaError(idx)) 4704 return ExprError(); 4705 4706 assert(matSubscriptE->isIncomplete() && 4707 "base has to be an incomplete matrix subscript"); 4708 return CreateBuiltinMatrixSubscriptExpr( 4709 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4710 } 4711 4712 // Handle any non-overload placeholder types in the base and index 4713 // expressions. We can't handle overloads here because the other 4714 // operand might be an overloadable type, in which case the overload 4715 // resolution for the operator overload should get the first crack 4716 // at the overload. 4717 bool IsMSPropertySubscript = false; 4718 if (base->getType()->isNonOverloadPlaceholderType()) { 4719 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4720 if (!IsMSPropertySubscript) { 4721 ExprResult result = CheckPlaceholderExpr(base); 4722 if (result.isInvalid()) 4723 return ExprError(); 4724 base = result.get(); 4725 } 4726 } 4727 4728 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4729 if (base->getType()->isMatrixType()) { 4730 if (CheckAndReportCommaError(idx)) 4731 return ExprError(); 4732 4733 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4734 } 4735 4736 // A comma-expression as the index is deprecated in C++2a onwards. 4737 if (getLangOpts().CPlusPlus20 && 4738 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4739 (isa<CXXOperatorCallExpr>(idx) && 4740 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4741 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4742 << SourceRange(base->getBeginLoc(), rbLoc); 4743 } 4744 4745 if (idx->getType()->isNonOverloadPlaceholderType()) { 4746 ExprResult result = CheckPlaceholderExpr(idx); 4747 if (result.isInvalid()) return ExprError(); 4748 idx = result.get(); 4749 } 4750 4751 // Build an unanalyzed expression if either operand is type-dependent. 4752 if (getLangOpts().CPlusPlus && 4753 (base->isTypeDependent() || idx->isTypeDependent())) { 4754 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4755 VK_LValue, OK_Ordinary, rbLoc); 4756 } 4757 4758 // MSDN, property (C++) 4759 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4760 // This attribute can also be used in the declaration of an empty array in a 4761 // class or structure definition. For example: 4762 // __declspec(property(get=GetX, put=PutX)) int x[]; 4763 // The above statement indicates that x[] can be used with one or more array 4764 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4765 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4766 if (IsMSPropertySubscript) { 4767 // Build MS property subscript expression if base is MS property reference 4768 // or MS property subscript. 4769 return new (Context) MSPropertySubscriptExpr( 4770 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4771 } 4772 4773 // Use C++ overloaded-operator rules if either operand has record 4774 // type. The spec says to do this if either type is *overloadable*, 4775 // but enum types can't declare subscript operators or conversion 4776 // operators, so there's nothing interesting for overload resolution 4777 // to do if there aren't any record types involved. 4778 // 4779 // ObjC pointers have their own subscripting logic that is not tied 4780 // to overload resolution and so should not take this path. 4781 if (getLangOpts().CPlusPlus && 4782 (base->getType()->isRecordType() || 4783 (!base->getType()->isObjCObjectPointerType() && 4784 idx->getType()->isRecordType()))) { 4785 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4786 } 4787 4788 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4789 4790 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4791 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4792 4793 return Res; 4794 } 4795 4796 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4797 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4798 InitializationKind Kind = 4799 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4800 InitializationSequence InitSeq(*this, Entity, Kind, E); 4801 return InitSeq.Perform(*this, Entity, Kind, E); 4802 } 4803 4804 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4805 Expr *ColumnIdx, 4806 SourceLocation RBLoc) { 4807 ExprResult BaseR = CheckPlaceholderExpr(Base); 4808 if (BaseR.isInvalid()) 4809 return BaseR; 4810 Base = BaseR.get(); 4811 4812 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4813 if (RowR.isInvalid()) 4814 return RowR; 4815 RowIdx = RowR.get(); 4816 4817 if (!ColumnIdx) 4818 return new (Context) MatrixSubscriptExpr( 4819 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4820 4821 // Build an unanalyzed expression if any of the operands is type-dependent. 4822 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4823 ColumnIdx->isTypeDependent()) 4824 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4825 Context.DependentTy, RBLoc); 4826 4827 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4828 if (ColumnR.isInvalid()) 4829 return ColumnR; 4830 ColumnIdx = ColumnR.get(); 4831 4832 // Check that IndexExpr is an integer expression. If it is a constant 4833 // expression, check that it is less than Dim (= the number of elements in the 4834 // corresponding dimension). 4835 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4836 bool IsColumnIdx) -> Expr * { 4837 if (!IndexExpr->getType()->isIntegerType() && 4838 !IndexExpr->isTypeDependent()) { 4839 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4840 << IsColumnIdx; 4841 return nullptr; 4842 } 4843 4844 if (Optional<llvm::APSInt> Idx = 4845 IndexExpr->getIntegerConstantExpr(Context)) { 4846 if ((*Idx < 0 || *Idx >= Dim)) { 4847 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4848 << IsColumnIdx << Dim; 4849 return nullptr; 4850 } 4851 } 4852 4853 ExprResult ConvExpr = 4854 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4855 assert(!ConvExpr.isInvalid() && 4856 "should be able to convert any integer type to size type"); 4857 return ConvExpr.get(); 4858 }; 4859 4860 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4861 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4862 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4863 if (!RowIdx || !ColumnIdx) 4864 return ExprError(); 4865 4866 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4867 MTy->getElementType(), RBLoc); 4868 } 4869 4870 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4871 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4872 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4873 4874 // For expressions like `&(*s).b`, the base is recorded and what should be 4875 // checked. 4876 const MemberExpr *Member = nullptr; 4877 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4878 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4879 4880 LastRecord.PossibleDerefs.erase(StrippedExpr); 4881 } 4882 4883 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4884 if (isUnevaluatedContext()) 4885 return; 4886 4887 QualType ResultTy = E->getType(); 4888 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4889 4890 // Bail if the element is an array since it is not memory access. 4891 if (isa<ArrayType>(ResultTy)) 4892 return; 4893 4894 if (ResultTy->hasAttr(attr::NoDeref)) { 4895 LastRecord.PossibleDerefs.insert(E); 4896 return; 4897 } 4898 4899 // Check if the base type is a pointer to a member access of a struct 4900 // marked with noderef. 4901 const Expr *Base = E->getBase(); 4902 QualType BaseTy = Base->getType(); 4903 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4904 // Not a pointer access 4905 return; 4906 4907 const MemberExpr *Member = nullptr; 4908 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4909 Member->isArrow()) 4910 Base = Member->getBase(); 4911 4912 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4913 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4914 LastRecord.PossibleDerefs.insert(E); 4915 } 4916 } 4917 4918 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4919 Expr *LowerBound, 4920 SourceLocation ColonLocFirst, 4921 SourceLocation ColonLocSecond, 4922 Expr *Length, Expr *Stride, 4923 SourceLocation RBLoc) { 4924 if (Base->getType()->isPlaceholderType() && 4925 !Base->getType()->isSpecificPlaceholderType( 4926 BuiltinType::OMPArraySection)) { 4927 ExprResult Result = CheckPlaceholderExpr(Base); 4928 if (Result.isInvalid()) 4929 return ExprError(); 4930 Base = Result.get(); 4931 } 4932 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4933 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4934 if (Result.isInvalid()) 4935 return ExprError(); 4936 Result = DefaultLvalueConversion(Result.get()); 4937 if (Result.isInvalid()) 4938 return ExprError(); 4939 LowerBound = Result.get(); 4940 } 4941 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4942 ExprResult Result = CheckPlaceholderExpr(Length); 4943 if (Result.isInvalid()) 4944 return ExprError(); 4945 Result = DefaultLvalueConversion(Result.get()); 4946 if (Result.isInvalid()) 4947 return ExprError(); 4948 Length = Result.get(); 4949 } 4950 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4951 ExprResult Result = CheckPlaceholderExpr(Stride); 4952 if (Result.isInvalid()) 4953 return ExprError(); 4954 Result = DefaultLvalueConversion(Result.get()); 4955 if (Result.isInvalid()) 4956 return ExprError(); 4957 Stride = Result.get(); 4958 } 4959 4960 // Build an unanalyzed expression if either operand is type-dependent. 4961 if (Base->isTypeDependent() || 4962 (LowerBound && 4963 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4964 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4965 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4966 return new (Context) OMPArraySectionExpr( 4967 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4968 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4969 } 4970 4971 // Perform default conversions. 4972 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4973 QualType ResultTy; 4974 if (OriginalTy->isAnyPointerType()) { 4975 ResultTy = OriginalTy->getPointeeType(); 4976 } else if (OriginalTy->isArrayType()) { 4977 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4978 } else { 4979 return ExprError( 4980 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4981 << Base->getSourceRange()); 4982 } 4983 // C99 6.5.2.1p1 4984 if (LowerBound) { 4985 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4986 LowerBound); 4987 if (Res.isInvalid()) 4988 return ExprError(Diag(LowerBound->getExprLoc(), 4989 diag::err_omp_typecheck_section_not_integer) 4990 << 0 << LowerBound->getSourceRange()); 4991 LowerBound = Res.get(); 4992 4993 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4994 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4995 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4996 << 0 << LowerBound->getSourceRange(); 4997 } 4998 if (Length) { 4999 auto Res = 5000 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5001 if (Res.isInvalid()) 5002 return ExprError(Diag(Length->getExprLoc(), 5003 diag::err_omp_typecheck_section_not_integer) 5004 << 1 << Length->getSourceRange()); 5005 Length = Res.get(); 5006 5007 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5008 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5009 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5010 << 1 << Length->getSourceRange(); 5011 } 5012 if (Stride) { 5013 ExprResult Res = 5014 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5015 if (Res.isInvalid()) 5016 return ExprError(Diag(Stride->getExprLoc(), 5017 diag::err_omp_typecheck_section_not_integer) 5018 << 1 << Stride->getSourceRange()); 5019 Stride = Res.get(); 5020 5021 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5022 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5023 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5024 << 1 << Stride->getSourceRange(); 5025 } 5026 5027 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5028 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5029 // type. Note that functions are not objects, and that (in C99 parlance) 5030 // incomplete types are not object types. 5031 if (ResultTy->isFunctionType()) { 5032 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5033 << ResultTy << Base->getSourceRange(); 5034 return ExprError(); 5035 } 5036 5037 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5038 diag::err_omp_section_incomplete_type, Base)) 5039 return ExprError(); 5040 5041 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5042 Expr::EvalResult Result; 5043 if (LowerBound->EvaluateAsInt(Result, Context)) { 5044 // OpenMP 5.0, [2.1.5 Array Sections] 5045 // The array section must be a subset of the original array. 5046 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5047 if (LowerBoundValue.isNegative()) { 5048 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5049 << LowerBound->getSourceRange(); 5050 return ExprError(); 5051 } 5052 } 5053 } 5054 5055 if (Length) { 5056 Expr::EvalResult Result; 5057 if (Length->EvaluateAsInt(Result, Context)) { 5058 // OpenMP 5.0, [2.1.5 Array Sections] 5059 // The length must evaluate to non-negative integers. 5060 llvm::APSInt LengthValue = Result.Val.getInt(); 5061 if (LengthValue.isNegative()) { 5062 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5063 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5064 << Length->getSourceRange(); 5065 return ExprError(); 5066 } 5067 } 5068 } else if (ColonLocFirst.isValid() && 5069 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5070 !OriginalTy->isVariableArrayType()))) { 5071 // OpenMP 5.0, [2.1.5 Array Sections] 5072 // When the size of the array dimension is not known, the length must be 5073 // specified explicitly. 5074 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5075 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5076 return ExprError(); 5077 } 5078 5079 if (Stride) { 5080 Expr::EvalResult Result; 5081 if (Stride->EvaluateAsInt(Result, Context)) { 5082 // OpenMP 5.0, [2.1.5 Array Sections] 5083 // The stride must evaluate to a positive integer. 5084 llvm::APSInt StrideValue = Result.Val.getInt(); 5085 if (!StrideValue.isStrictlyPositive()) { 5086 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5087 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5088 << Stride->getSourceRange(); 5089 return ExprError(); 5090 } 5091 } 5092 } 5093 5094 if (!Base->getType()->isSpecificPlaceholderType( 5095 BuiltinType::OMPArraySection)) { 5096 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5097 if (Result.isInvalid()) 5098 return ExprError(); 5099 Base = Result.get(); 5100 } 5101 return new (Context) OMPArraySectionExpr( 5102 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5103 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5104 } 5105 5106 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5107 SourceLocation RParenLoc, 5108 ArrayRef<Expr *> Dims, 5109 ArrayRef<SourceRange> Brackets) { 5110 if (Base->getType()->isPlaceholderType()) { 5111 ExprResult Result = CheckPlaceholderExpr(Base); 5112 if (Result.isInvalid()) 5113 return ExprError(); 5114 Result = DefaultLvalueConversion(Result.get()); 5115 if (Result.isInvalid()) 5116 return ExprError(); 5117 Base = Result.get(); 5118 } 5119 QualType BaseTy = Base->getType(); 5120 // Delay analysis of the types/expressions if instantiation/specialization is 5121 // required. 5122 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5123 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5124 LParenLoc, RParenLoc, Dims, Brackets); 5125 if (!BaseTy->isPointerType() || 5126 (!Base->isTypeDependent() && 5127 BaseTy->getPointeeType()->isIncompleteType())) 5128 return ExprError(Diag(Base->getExprLoc(), 5129 diag::err_omp_non_pointer_type_array_shaping_base) 5130 << Base->getSourceRange()); 5131 5132 SmallVector<Expr *, 4> NewDims; 5133 bool ErrorFound = false; 5134 for (Expr *Dim : Dims) { 5135 if (Dim->getType()->isPlaceholderType()) { 5136 ExprResult Result = CheckPlaceholderExpr(Dim); 5137 if (Result.isInvalid()) { 5138 ErrorFound = true; 5139 continue; 5140 } 5141 Result = DefaultLvalueConversion(Result.get()); 5142 if (Result.isInvalid()) { 5143 ErrorFound = true; 5144 continue; 5145 } 5146 Dim = Result.get(); 5147 } 5148 if (!Dim->isTypeDependent()) { 5149 ExprResult Result = 5150 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5151 if (Result.isInvalid()) { 5152 ErrorFound = true; 5153 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5154 << Dim->getSourceRange(); 5155 continue; 5156 } 5157 Dim = Result.get(); 5158 Expr::EvalResult EvResult; 5159 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5160 // OpenMP 5.0, [2.1.4 Array Shaping] 5161 // Each si is an integral type expression that must evaluate to a 5162 // positive integer. 5163 llvm::APSInt Value = EvResult.Val.getInt(); 5164 if (!Value.isStrictlyPositive()) { 5165 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5166 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5167 << Dim->getSourceRange(); 5168 ErrorFound = true; 5169 continue; 5170 } 5171 } 5172 } 5173 NewDims.push_back(Dim); 5174 } 5175 if (ErrorFound) 5176 return ExprError(); 5177 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5178 LParenLoc, RParenLoc, NewDims, Brackets); 5179 } 5180 5181 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5182 SourceLocation LLoc, SourceLocation RLoc, 5183 ArrayRef<OMPIteratorData> Data) { 5184 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5185 bool IsCorrect = true; 5186 for (const OMPIteratorData &D : Data) { 5187 TypeSourceInfo *TInfo = nullptr; 5188 SourceLocation StartLoc; 5189 QualType DeclTy; 5190 if (!D.Type.getAsOpaquePtr()) { 5191 // OpenMP 5.0, 2.1.6 Iterators 5192 // In an iterator-specifier, if the iterator-type is not specified then 5193 // the type of that iterator is of int type. 5194 DeclTy = Context.IntTy; 5195 StartLoc = D.DeclIdentLoc; 5196 } else { 5197 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5198 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5199 } 5200 5201 bool IsDeclTyDependent = DeclTy->isDependentType() || 5202 DeclTy->containsUnexpandedParameterPack() || 5203 DeclTy->isInstantiationDependentType(); 5204 if (!IsDeclTyDependent) { 5205 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5206 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5207 // The iterator-type must be an integral or pointer type. 5208 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5209 << DeclTy; 5210 IsCorrect = false; 5211 continue; 5212 } 5213 if (DeclTy.isConstant(Context)) { 5214 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5215 // The iterator-type must not be const qualified. 5216 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5217 << DeclTy; 5218 IsCorrect = false; 5219 continue; 5220 } 5221 } 5222 5223 // Iterator declaration. 5224 assert(D.DeclIdent && "Identifier expected."); 5225 // Always try to create iterator declarator to avoid extra error messages 5226 // about unknown declarations use. 5227 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5228 D.DeclIdent, DeclTy, TInfo, SC_None); 5229 VD->setImplicit(); 5230 if (S) { 5231 // Check for conflicting previous declaration. 5232 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5233 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5234 ForVisibleRedeclaration); 5235 Previous.suppressDiagnostics(); 5236 LookupName(Previous, S); 5237 5238 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5239 /*AllowInlineNamespace=*/false); 5240 if (!Previous.empty()) { 5241 NamedDecl *Old = Previous.getRepresentativeDecl(); 5242 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5243 Diag(Old->getLocation(), diag::note_previous_definition); 5244 } else { 5245 PushOnScopeChains(VD, S); 5246 } 5247 } else { 5248 CurContext->addDecl(VD); 5249 } 5250 Expr *Begin = D.Range.Begin; 5251 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5252 ExprResult BeginRes = 5253 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5254 Begin = BeginRes.get(); 5255 } 5256 Expr *End = D.Range.End; 5257 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5258 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5259 End = EndRes.get(); 5260 } 5261 Expr *Step = D.Range.Step; 5262 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5263 if (!Step->getType()->isIntegralType(Context)) { 5264 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5265 << Step << Step->getSourceRange(); 5266 IsCorrect = false; 5267 continue; 5268 } 5269 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5270 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5271 // If the step expression of a range-specification equals zero, the 5272 // behavior is unspecified. 5273 if (Result && Result->isNullValue()) { 5274 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5275 << Step << Step->getSourceRange(); 5276 IsCorrect = false; 5277 continue; 5278 } 5279 } 5280 if (!Begin || !End || !IsCorrect) { 5281 IsCorrect = false; 5282 continue; 5283 } 5284 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5285 IDElem.IteratorDecl = VD; 5286 IDElem.AssignmentLoc = D.AssignLoc; 5287 IDElem.Range.Begin = Begin; 5288 IDElem.Range.End = End; 5289 IDElem.Range.Step = Step; 5290 IDElem.ColonLoc = D.ColonLoc; 5291 IDElem.SecondColonLoc = D.SecColonLoc; 5292 } 5293 if (!IsCorrect) { 5294 // Invalidate all created iterator declarations if error is found. 5295 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5296 if (Decl *ID = D.IteratorDecl) 5297 ID->setInvalidDecl(); 5298 } 5299 return ExprError(); 5300 } 5301 SmallVector<OMPIteratorHelperData, 4> Helpers; 5302 if (!CurContext->isDependentContext()) { 5303 // Build number of ityeration for each iteration range. 5304 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5305 // ((Begini-Stepi-1-Endi) / -Stepi); 5306 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5307 // (Endi - Begini) 5308 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5309 D.Range.Begin); 5310 if(!Res.isUsable()) { 5311 IsCorrect = false; 5312 continue; 5313 } 5314 ExprResult St, St1; 5315 if (D.Range.Step) { 5316 St = D.Range.Step; 5317 // (Endi - Begini) + Stepi 5318 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5319 if (!Res.isUsable()) { 5320 IsCorrect = false; 5321 continue; 5322 } 5323 // (Endi - Begini) + Stepi - 1 5324 Res = 5325 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5326 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5327 if (!Res.isUsable()) { 5328 IsCorrect = false; 5329 continue; 5330 } 5331 // ((Endi - Begini) + Stepi - 1) / Stepi 5332 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5333 if (!Res.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5338 // (Begini - Endi) 5339 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5340 D.Range.Begin, D.Range.End); 5341 if (!Res1.isUsable()) { 5342 IsCorrect = false; 5343 continue; 5344 } 5345 // (Begini - Endi) - Stepi 5346 Res1 = 5347 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5348 if (!Res1.isUsable()) { 5349 IsCorrect = false; 5350 continue; 5351 } 5352 // (Begini - Endi) - Stepi - 1 5353 Res1 = 5354 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5355 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5356 if (!Res1.isUsable()) { 5357 IsCorrect = false; 5358 continue; 5359 } 5360 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5361 Res1 = 5362 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5363 if (!Res1.isUsable()) { 5364 IsCorrect = false; 5365 continue; 5366 } 5367 // Stepi > 0. 5368 ExprResult CmpRes = 5369 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5370 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5371 if (!CmpRes.isUsable()) { 5372 IsCorrect = false; 5373 continue; 5374 } 5375 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5376 Res.get(), Res1.get()); 5377 if (!Res.isUsable()) { 5378 IsCorrect = false; 5379 continue; 5380 } 5381 } 5382 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5383 if (!Res.isUsable()) { 5384 IsCorrect = false; 5385 continue; 5386 } 5387 5388 // Build counter update. 5389 // Build counter. 5390 auto *CounterVD = 5391 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5392 D.IteratorDecl->getBeginLoc(), nullptr, 5393 Res.get()->getType(), nullptr, SC_None); 5394 CounterVD->setImplicit(); 5395 ExprResult RefRes = 5396 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5397 D.IteratorDecl->getBeginLoc()); 5398 // Build counter update. 5399 // I = Begini + counter * Stepi; 5400 ExprResult UpdateRes; 5401 if (D.Range.Step) { 5402 UpdateRes = CreateBuiltinBinOp( 5403 D.AssignmentLoc, BO_Mul, 5404 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5405 } else { 5406 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5407 } 5408 if (!UpdateRes.isUsable()) { 5409 IsCorrect = false; 5410 continue; 5411 } 5412 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5413 UpdateRes.get()); 5414 if (!UpdateRes.isUsable()) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 ExprResult VDRes = 5419 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5420 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5421 D.IteratorDecl->getBeginLoc()); 5422 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5423 UpdateRes.get()); 5424 if (!UpdateRes.isUsable()) { 5425 IsCorrect = false; 5426 continue; 5427 } 5428 UpdateRes = 5429 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5430 if (!UpdateRes.isUsable()) { 5431 IsCorrect = false; 5432 continue; 5433 } 5434 ExprResult CounterUpdateRes = 5435 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5436 if (!CounterUpdateRes.isUsable()) { 5437 IsCorrect = false; 5438 continue; 5439 } 5440 CounterUpdateRes = 5441 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5442 if (!CounterUpdateRes.isUsable()) { 5443 IsCorrect = false; 5444 continue; 5445 } 5446 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5447 HD.CounterVD = CounterVD; 5448 HD.Upper = Res.get(); 5449 HD.Update = UpdateRes.get(); 5450 HD.CounterUpdate = CounterUpdateRes.get(); 5451 } 5452 } else { 5453 Helpers.assign(ID.size(), {}); 5454 } 5455 if (!IsCorrect) { 5456 // Invalidate all created iterator declarations if error is found. 5457 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5458 if (Decl *ID = D.IteratorDecl) 5459 ID->setInvalidDecl(); 5460 } 5461 return ExprError(); 5462 } 5463 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5464 LLoc, RLoc, ID, Helpers); 5465 } 5466 5467 ExprResult 5468 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5469 Expr *Idx, SourceLocation RLoc) { 5470 Expr *LHSExp = Base; 5471 Expr *RHSExp = Idx; 5472 5473 ExprValueKind VK = VK_LValue; 5474 ExprObjectKind OK = OK_Ordinary; 5475 5476 // Per C++ core issue 1213, the result is an xvalue if either operand is 5477 // a non-lvalue array, and an lvalue otherwise. 5478 if (getLangOpts().CPlusPlus11) { 5479 for (auto *Op : {LHSExp, RHSExp}) { 5480 Op = Op->IgnoreImplicit(); 5481 if (Op->getType()->isArrayType() && !Op->isLValue()) 5482 VK = VK_XValue; 5483 } 5484 } 5485 5486 // Perform default conversions. 5487 if (!LHSExp->getType()->getAs<VectorType>()) { 5488 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5489 if (Result.isInvalid()) 5490 return ExprError(); 5491 LHSExp = Result.get(); 5492 } 5493 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5494 if (Result.isInvalid()) 5495 return ExprError(); 5496 RHSExp = Result.get(); 5497 5498 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5499 5500 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5501 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5502 // in the subscript position. As a result, we need to derive the array base 5503 // and index from the expression types. 5504 Expr *BaseExpr, *IndexExpr; 5505 QualType ResultType; 5506 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5507 BaseExpr = LHSExp; 5508 IndexExpr = RHSExp; 5509 ResultType = Context.DependentTy; 5510 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5511 BaseExpr = LHSExp; 5512 IndexExpr = RHSExp; 5513 ResultType = PTy->getPointeeType(); 5514 } else if (const ObjCObjectPointerType *PTy = 5515 LHSTy->getAs<ObjCObjectPointerType>()) { 5516 BaseExpr = LHSExp; 5517 IndexExpr = RHSExp; 5518 5519 // Use custom logic if this should be the pseudo-object subscript 5520 // expression. 5521 if (!LangOpts.isSubscriptPointerArithmetic()) 5522 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5523 nullptr); 5524 5525 ResultType = PTy->getPointeeType(); 5526 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5527 // Handle the uncommon case of "123[Ptr]". 5528 BaseExpr = RHSExp; 5529 IndexExpr = LHSExp; 5530 ResultType = PTy->getPointeeType(); 5531 } else if (const ObjCObjectPointerType *PTy = 5532 RHSTy->getAs<ObjCObjectPointerType>()) { 5533 // Handle the uncommon case of "123[Ptr]". 5534 BaseExpr = RHSExp; 5535 IndexExpr = LHSExp; 5536 ResultType = PTy->getPointeeType(); 5537 if (!LangOpts.isSubscriptPointerArithmetic()) { 5538 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5539 << ResultType << BaseExpr->getSourceRange(); 5540 return ExprError(); 5541 } 5542 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5543 BaseExpr = LHSExp; // vectors: V[123] 5544 IndexExpr = RHSExp; 5545 // We apply C++ DR1213 to vector subscripting too. 5546 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_PRValue) { 5547 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5548 if (Materialized.isInvalid()) 5549 return ExprError(); 5550 LHSExp = Materialized.get(); 5551 } 5552 VK = LHSExp->getValueKind(); 5553 if (VK != VK_PRValue) 5554 OK = OK_VectorComponent; 5555 5556 ResultType = VTy->getElementType(); 5557 QualType BaseType = BaseExpr->getType(); 5558 Qualifiers BaseQuals = BaseType.getQualifiers(); 5559 Qualifiers MemberQuals = ResultType.getQualifiers(); 5560 Qualifiers Combined = BaseQuals + MemberQuals; 5561 if (Combined != MemberQuals) 5562 ResultType = Context.getQualifiedType(ResultType, Combined); 5563 } else if (LHSTy->isArrayType()) { 5564 // If we see an array that wasn't promoted by 5565 // DefaultFunctionArrayLvalueConversion, it must be an array that 5566 // wasn't promoted because of the C90 rule that doesn't 5567 // allow promoting non-lvalue arrays. Warn, then 5568 // force the promotion here. 5569 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5570 << LHSExp->getSourceRange(); 5571 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5572 CK_ArrayToPointerDecay).get(); 5573 LHSTy = LHSExp->getType(); 5574 5575 BaseExpr = LHSExp; 5576 IndexExpr = RHSExp; 5577 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5578 } else if (RHSTy->isArrayType()) { 5579 // Same as previous, except for 123[f().a] case 5580 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5581 << RHSExp->getSourceRange(); 5582 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5583 CK_ArrayToPointerDecay).get(); 5584 RHSTy = RHSExp->getType(); 5585 5586 BaseExpr = RHSExp; 5587 IndexExpr = LHSExp; 5588 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5589 } else { 5590 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5591 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5592 } 5593 // C99 6.5.2.1p1 5594 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5595 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5596 << IndexExpr->getSourceRange()); 5597 5598 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5599 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5600 && !IndexExpr->isTypeDependent()) 5601 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5602 5603 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5604 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5605 // type. Note that Functions are not objects, and that (in C99 parlance) 5606 // incomplete types are not object types. 5607 if (ResultType->isFunctionType()) { 5608 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5609 << ResultType << BaseExpr->getSourceRange(); 5610 return ExprError(); 5611 } 5612 5613 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5614 // GNU extension: subscripting on pointer to void 5615 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5616 << BaseExpr->getSourceRange(); 5617 5618 // C forbids expressions of unqualified void type from being l-values. 5619 // See IsCForbiddenLValueType. 5620 if (!ResultType.hasQualifiers()) 5621 VK = VK_PRValue; 5622 } else if (!ResultType->isDependentType() && 5623 RequireCompleteSizedType( 5624 LLoc, ResultType, 5625 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5626 return ExprError(); 5627 5628 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5629 !ResultType.isCForbiddenLValueType()); 5630 5631 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5632 FunctionScopes.size() > 1) { 5633 if (auto *TT = 5634 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5635 for (auto I = FunctionScopes.rbegin(), 5636 E = std::prev(FunctionScopes.rend()); 5637 I != E; ++I) { 5638 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5639 if (CSI == nullptr) 5640 break; 5641 DeclContext *DC = nullptr; 5642 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5643 DC = LSI->CallOperator; 5644 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5645 DC = CRSI->TheCapturedDecl; 5646 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5647 DC = BSI->TheDecl; 5648 if (DC) { 5649 if (DC->containsDecl(TT->getDecl())) 5650 break; 5651 captureVariablyModifiedType( 5652 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5653 } 5654 } 5655 } 5656 } 5657 5658 return new (Context) 5659 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5660 } 5661 5662 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5663 ParmVarDecl *Param) { 5664 if (Param->hasUnparsedDefaultArg()) { 5665 // If we've already cleared out the location for the default argument, 5666 // that means we're parsing it right now. 5667 if (!UnparsedDefaultArgLocs.count(Param)) { 5668 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5669 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5670 Param->setInvalidDecl(); 5671 return true; 5672 } 5673 5674 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5675 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5676 Diag(UnparsedDefaultArgLocs[Param], 5677 diag::note_default_argument_declared_here); 5678 return true; 5679 } 5680 5681 if (Param->hasUninstantiatedDefaultArg() && 5682 InstantiateDefaultArgument(CallLoc, FD, Param)) 5683 return true; 5684 5685 assert(Param->hasInit() && "default argument but no initializer?"); 5686 5687 // If the default expression creates temporaries, we need to 5688 // push them to the current stack of expression temporaries so they'll 5689 // be properly destroyed. 5690 // FIXME: We should really be rebuilding the default argument with new 5691 // bound temporaries; see the comment in PR5810. 5692 // We don't need to do that with block decls, though, because 5693 // blocks in default argument expression can never capture anything. 5694 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5695 // Set the "needs cleanups" bit regardless of whether there are 5696 // any explicit objects. 5697 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5698 5699 // Append all the objects to the cleanup list. Right now, this 5700 // should always be a no-op, because blocks in default argument 5701 // expressions should never be able to capture anything. 5702 assert(!Init->getNumObjects() && 5703 "default argument expression has capturing blocks?"); 5704 } 5705 5706 // We already type-checked the argument, so we know it works. 5707 // Just mark all of the declarations in this potentially-evaluated expression 5708 // as being "referenced". 5709 EnterExpressionEvaluationContext EvalContext( 5710 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5711 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5712 /*SkipLocalVariables=*/true); 5713 return false; 5714 } 5715 5716 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5717 FunctionDecl *FD, ParmVarDecl *Param) { 5718 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5719 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5720 return ExprError(); 5721 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5722 } 5723 5724 Sema::VariadicCallType 5725 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5726 Expr *Fn) { 5727 if (Proto && Proto->isVariadic()) { 5728 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5729 return VariadicConstructor; 5730 else if (Fn && Fn->getType()->isBlockPointerType()) 5731 return VariadicBlock; 5732 else if (FDecl) { 5733 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5734 if (Method->isInstance()) 5735 return VariadicMethod; 5736 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5737 return VariadicMethod; 5738 return VariadicFunction; 5739 } 5740 return VariadicDoesNotApply; 5741 } 5742 5743 namespace { 5744 class FunctionCallCCC final : public FunctionCallFilterCCC { 5745 public: 5746 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5747 unsigned NumArgs, MemberExpr *ME) 5748 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5749 FunctionName(FuncName) {} 5750 5751 bool ValidateCandidate(const TypoCorrection &candidate) override { 5752 if (!candidate.getCorrectionSpecifier() || 5753 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5754 return false; 5755 } 5756 5757 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5758 } 5759 5760 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5761 return std::make_unique<FunctionCallCCC>(*this); 5762 } 5763 5764 private: 5765 const IdentifierInfo *const FunctionName; 5766 }; 5767 } 5768 5769 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5770 FunctionDecl *FDecl, 5771 ArrayRef<Expr *> Args) { 5772 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5773 DeclarationName FuncName = FDecl->getDeclName(); 5774 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5775 5776 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5777 if (TypoCorrection Corrected = S.CorrectTypo( 5778 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5779 S.getScopeForContext(S.CurContext), nullptr, CCC, 5780 Sema::CTK_ErrorRecovery)) { 5781 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5782 if (Corrected.isOverloaded()) { 5783 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5784 OverloadCandidateSet::iterator Best; 5785 for (NamedDecl *CD : Corrected) { 5786 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5787 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5788 OCS); 5789 } 5790 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5791 case OR_Success: 5792 ND = Best->FoundDecl; 5793 Corrected.setCorrectionDecl(ND); 5794 break; 5795 default: 5796 break; 5797 } 5798 } 5799 ND = ND->getUnderlyingDecl(); 5800 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5801 return Corrected; 5802 } 5803 } 5804 return TypoCorrection(); 5805 } 5806 5807 /// ConvertArgumentsForCall - Converts the arguments specified in 5808 /// Args/NumArgs to the parameter types of the function FDecl with 5809 /// function prototype Proto. Call is the call expression itself, and 5810 /// Fn is the function expression. For a C++ member function, this 5811 /// routine does not attempt to convert the object argument. Returns 5812 /// true if the call is ill-formed. 5813 bool 5814 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5815 FunctionDecl *FDecl, 5816 const FunctionProtoType *Proto, 5817 ArrayRef<Expr *> Args, 5818 SourceLocation RParenLoc, 5819 bool IsExecConfig) { 5820 // Bail out early if calling a builtin with custom typechecking. 5821 if (FDecl) 5822 if (unsigned ID = FDecl->getBuiltinID()) 5823 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5824 return false; 5825 5826 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5827 // assignment, to the types of the corresponding parameter, ... 5828 unsigned NumParams = Proto->getNumParams(); 5829 bool Invalid = false; 5830 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5831 unsigned FnKind = Fn->getType()->isBlockPointerType() 5832 ? 1 /* block */ 5833 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5834 : 0 /* function */); 5835 5836 // If too few arguments are available (and we don't have default 5837 // arguments for the remaining parameters), don't make the call. 5838 if (Args.size() < NumParams) { 5839 if (Args.size() < MinArgs) { 5840 TypoCorrection TC; 5841 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5842 unsigned diag_id = 5843 MinArgs == NumParams && !Proto->isVariadic() 5844 ? diag::err_typecheck_call_too_few_args_suggest 5845 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5846 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5847 << static_cast<unsigned>(Args.size()) 5848 << TC.getCorrectionRange()); 5849 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5850 Diag(RParenLoc, 5851 MinArgs == NumParams && !Proto->isVariadic() 5852 ? diag::err_typecheck_call_too_few_args_one 5853 : diag::err_typecheck_call_too_few_args_at_least_one) 5854 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5855 else 5856 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5857 ? diag::err_typecheck_call_too_few_args 5858 : diag::err_typecheck_call_too_few_args_at_least) 5859 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5860 << Fn->getSourceRange(); 5861 5862 // Emit the location of the prototype. 5863 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5864 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5865 5866 return true; 5867 } 5868 // We reserve space for the default arguments when we create 5869 // the call expression, before calling ConvertArgumentsForCall. 5870 assert((Call->getNumArgs() == NumParams) && 5871 "We should have reserved space for the default arguments before!"); 5872 } 5873 5874 // If too many are passed and not variadic, error on the extras and drop 5875 // them. 5876 if (Args.size() > NumParams) { 5877 if (!Proto->isVariadic()) { 5878 TypoCorrection TC; 5879 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5880 unsigned diag_id = 5881 MinArgs == NumParams && !Proto->isVariadic() 5882 ? diag::err_typecheck_call_too_many_args_suggest 5883 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5884 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5885 << static_cast<unsigned>(Args.size()) 5886 << TC.getCorrectionRange()); 5887 } else if (NumParams == 1 && FDecl && 5888 FDecl->getParamDecl(0)->getDeclName()) 5889 Diag(Args[NumParams]->getBeginLoc(), 5890 MinArgs == NumParams 5891 ? diag::err_typecheck_call_too_many_args_one 5892 : diag::err_typecheck_call_too_many_args_at_most_one) 5893 << FnKind << FDecl->getParamDecl(0) 5894 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5895 << SourceRange(Args[NumParams]->getBeginLoc(), 5896 Args.back()->getEndLoc()); 5897 else 5898 Diag(Args[NumParams]->getBeginLoc(), 5899 MinArgs == NumParams 5900 ? diag::err_typecheck_call_too_many_args 5901 : diag::err_typecheck_call_too_many_args_at_most) 5902 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5903 << Fn->getSourceRange() 5904 << SourceRange(Args[NumParams]->getBeginLoc(), 5905 Args.back()->getEndLoc()); 5906 5907 // Emit the location of the prototype. 5908 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5909 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5910 5911 // This deletes the extra arguments. 5912 Call->shrinkNumArgs(NumParams); 5913 return true; 5914 } 5915 } 5916 SmallVector<Expr *, 8> AllArgs; 5917 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5918 5919 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5920 AllArgs, CallType); 5921 if (Invalid) 5922 return true; 5923 unsigned TotalNumArgs = AllArgs.size(); 5924 for (unsigned i = 0; i < TotalNumArgs; ++i) 5925 Call->setArg(i, AllArgs[i]); 5926 5927 return false; 5928 } 5929 5930 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5931 const FunctionProtoType *Proto, 5932 unsigned FirstParam, ArrayRef<Expr *> Args, 5933 SmallVectorImpl<Expr *> &AllArgs, 5934 VariadicCallType CallType, bool AllowExplicit, 5935 bool IsListInitialization) { 5936 unsigned NumParams = Proto->getNumParams(); 5937 bool Invalid = false; 5938 size_t ArgIx = 0; 5939 // Continue to check argument types (even if we have too few/many args). 5940 for (unsigned i = FirstParam; i < NumParams; i++) { 5941 QualType ProtoArgType = Proto->getParamType(i); 5942 5943 Expr *Arg; 5944 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5945 if (ArgIx < Args.size()) { 5946 Arg = Args[ArgIx++]; 5947 5948 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5949 diag::err_call_incomplete_argument, Arg)) 5950 return true; 5951 5952 // Strip the unbridged-cast placeholder expression off, if applicable. 5953 bool CFAudited = false; 5954 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5955 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5956 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5957 Arg = stripARCUnbridgedCast(Arg); 5958 else if (getLangOpts().ObjCAutoRefCount && 5959 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5960 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5961 CFAudited = true; 5962 5963 if (Proto->getExtParameterInfo(i).isNoEscape() && 5964 ProtoArgType->isBlockPointerType()) 5965 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5966 BE->getBlockDecl()->setDoesNotEscape(); 5967 5968 InitializedEntity Entity = 5969 Param ? InitializedEntity::InitializeParameter(Context, Param, 5970 ProtoArgType) 5971 : InitializedEntity::InitializeParameter( 5972 Context, ProtoArgType, Proto->isParamConsumed(i)); 5973 5974 // Remember that parameter belongs to a CF audited API. 5975 if (CFAudited) 5976 Entity.setParameterCFAudited(); 5977 5978 ExprResult ArgE = PerformCopyInitialization( 5979 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5980 if (ArgE.isInvalid()) 5981 return true; 5982 5983 Arg = ArgE.getAs<Expr>(); 5984 } else { 5985 assert(Param && "can't use default arguments without a known callee"); 5986 5987 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5988 if (ArgExpr.isInvalid()) 5989 return true; 5990 5991 Arg = ArgExpr.getAs<Expr>(); 5992 } 5993 5994 // Check for array bounds violations for each argument to the call. This 5995 // check only triggers warnings when the argument isn't a more complex Expr 5996 // with its own checking, such as a BinaryOperator. 5997 CheckArrayAccess(Arg); 5998 5999 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6000 CheckStaticArrayArgument(CallLoc, Param, Arg); 6001 6002 AllArgs.push_back(Arg); 6003 } 6004 6005 // If this is a variadic call, handle args passed through "...". 6006 if (CallType != VariadicDoesNotApply) { 6007 // Assume that extern "C" functions with variadic arguments that 6008 // return __unknown_anytype aren't *really* variadic. 6009 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6010 FDecl->isExternC()) { 6011 for (Expr *A : Args.slice(ArgIx)) { 6012 QualType paramType; // ignored 6013 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6014 Invalid |= arg.isInvalid(); 6015 AllArgs.push_back(arg.get()); 6016 } 6017 6018 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6019 } else { 6020 for (Expr *A : Args.slice(ArgIx)) { 6021 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6022 Invalid |= Arg.isInvalid(); 6023 AllArgs.push_back(Arg.get()); 6024 } 6025 } 6026 6027 // Check for array bounds violations. 6028 for (Expr *A : Args.slice(ArgIx)) 6029 CheckArrayAccess(A); 6030 } 6031 return Invalid; 6032 } 6033 6034 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6035 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6036 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6037 TL = DTL.getOriginalLoc(); 6038 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6039 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6040 << ATL.getLocalSourceRange(); 6041 } 6042 6043 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6044 /// array parameter, check that it is non-null, and that if it is formed by 6045 /// array-to-pointer decay, the underlying array is sufficiently large. 6046 /// 6047 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6048 /// array type derivation, then for each call to the function, the value of the 6049 /// corresponding actual argument shall provide access to the first element of 6050 /// an array with at least as many elements as specified by the size expression. 6051 void 6052 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6053 ParmVarDecl *Param, 6054 const Expr *ArgExpr) { 6055 // Static array parameters are not supported in C++. 6056 if (!Param || getLangOpts().CPlusPlus) 6057 return; 6058 6059 QualType OrigTy = Param->getOriginalType(); 6060 6061 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6062 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6063 return; 6064 6065 if (ArgExpr->isNullPointerConstant(Context, 6066 Expr::NPC_NeverValueDependent)) { 6067 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6068 DiagnoseCalleeStaticArrayParam(*this, Param); 6069 return; 6070 } 6071 6072 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6073 if (!CAT) 6074 return; 6075 6076 const ConstantArrayType *ArgCAT = 6077 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6078 if (!ArgCAT) 6079 return; 6080 6081 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6082 ArgCAT->getElementType())) { 6083 if (ArgCAT->getSize().ult(CAT->getSize())) { 6084 Diag(CallLoc, diag::warn_static_array_too_small) 6085 << ArgExpr->getSourceRange() 6086 << (unsigned)ArgCAT->getSize().getZExtValue() 6087 << (unsigned)CAT->getSize().getZExtValue() << 0; 6088 DiagnoseCalleeStaticArrayParam(*this, Param); 6089 } 6090 return; 6091 } 6092 6093 Optional<CharUnits> ArgSize = 6094 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6095 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6096 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6097 Diag(CallLoc, diag::warn_static_array_too_small) 6098 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6099 << (unsigned)ParmSize->getQuantity() << 1; 6100 DiagnoseCalleeStaticArrayParam(*this, Param); 6101 } 6102 } 6103 6104 /// Given a function expression of unknown-any type, try to rebuild it 6105 /// to have a function type. 6106 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6107 6108 /// Is the given type a placeholder that we need to lower out 6109 /// immediately during argument processing? 6110 static bool isPlaceholderToRemoveAsArg(QualType type) { 6111 // Placeholders are never sugared. 6112 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6113 if (!placeholder) return false; 6114 6115 switch (placeholder->getKind()) { 6116 // Ignore all the non-placeholder types. 6117 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6118 case BuiltinType::Id: 6119 #include "clang/Basic/OpenCLImageTypes.def" 6120 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6121 case BuiltinType::Id: 6122 #include "clang/Basic/OpenCLExtensionTypes.def" 6123 // In practice we'll never use this, since all SVE types are sugared 6124 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6125 #define SVE_TYPE(Name, Id, SingletonId) \ 6126 case BuiltinType::Id: 6127 #include "clang/Basic/AArch64SVEACLETypes.def" 6128 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6129 case BuiltinType::Id: 6130 #include "clang/Basic/PPCTypes.def" 6131 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6132 #include "clang/Basic/RISCVVTypes.def" 6133 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6134 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6135 #include "clang/AST/BuiltinTypes.def" 6136 return false; 6137 6138 // We cannot lower out overload sets; they might validly be resolved 6139 // by the call machinery. 6140 case BuiltinType::Overload: 6141 return false; 6142 6143 // Unbridged casts in ARC can be handled in some call positions and 6144 // should be left in place. 6145 case BuiltinType::ARCUnbridgedCast: 6146 return false; 6147 6148 // Pseudo-objects should be converted as soon as possible. 6149 case BuiltinType::PseudoObject: 6150 return true; 6151 6152 // The debugger mode could theoretically but currently does not try 6153 // to resolve unknown-typed arguments based on known parameter types. 6154 case BuiltinType::UnknownAny: 6155 return true; 6156 6157 // These are always invalid as call arguments and should be reported. 6158 case BuiltinType::BoundMember: 6159 case BuiltinType::BuiltinFn: 6160 case BuiltinType::IncompleteMatrixIdx: 6161 case BuiltinType::OMPArraySection: 6162 case BuiltinType::OMPArrayShaping: 6163 case BuiltinType::OMPIterator: 6164 return true; 6165 6166 } 6167 llvm_unreachable("bad builtin type kind"); 6168 } 6169 6170 /// Check an argument list for placeholders that we won't try to 6171 /// handle later. 6172 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6173 // Apply this processing to all the arguments at once instead of 6174 // dying at the first failure. 6175 bool hasInvalid = false; 6176 for (size_t i = 0, e = args.size(); i != e; i++) { 6177 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6178 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6179 if (result.isInvalid()) hasInvalid = true; 6180 else args[i] = result.get(); 6181 } 6182 } 6183 return hasInvalid; 6184 } 6185 6186 /// If a builtin function has a pointer argument with no explicit address 6187 /// space, then it should be able to accept a pointer to any address 6188 /// space as input. In order to do this, we need to replace the 6189 /// standard builtin declaration with one that uses the same address space 6190 /// as the call. 6191 /// 6192 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6193 /// it does not contain any pointer arguments without 6194 /// an address space qualifer. Otherwise the rewritten 6195 /// FunctionDecl is returned. 6196 /// TODO: Handle pointer return types. 6197 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6198 FunctionDecl *FDecl, 6199 MultiExprArg ArgExprs) { 6200 6201 QualType DeclType = FDecl->getType(); 6202 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6203 6204 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6205 ArgExprs.size() < FT->getNumParams()) 6206 return nullptr; 6207 6208 bool NeedsNewDecl = false; 6209 unsigned i = 0; 6210 SmallVector<QualType, 8> OverloadParams; 6211 6212 for (QualType ParamType : FT->param_types()) { 6213 6214 // Convert array arguments to pointer to simplify type lookup. 6215 ExprResult ArgRes = 6216 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6217 if (ArgRes.isInvalid()) 6218 return nullptr; 6219 Expr *Arg = ArgRes.get(); 6220 QualType ArgType = Arg->getType(); 6221 if (!ParamType->isPointerType() || 6222 ParamType.hasAddressSpace() || 6223 !ArgType->isPointerType() || 6224 !ArgType->getPointeeType().hasAddressSpace()) { 6225 OverloadParams.push_back(ParamType); 6226 continue; 6227 } 6228 6229 QualType PointeeType = ParamType->getPointeeType(); 6230 if (PointeeType.hasAddressSpace()) 6231 continue; 6232 6233 NeedsNewDecl = true; 6234 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6235 6236 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6237 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6238 } 6239 6240 if (!NeedsNewDecl) 6241 return nullptr; 6242 6243 FunctionProtoType::ExtProtoInfo EPI; 6244 EPI.Variadic = FT->isVariadic(); 6245 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6246 OverloadParams, EPI); 6247 DeclContext *Parent = FDecl->getParent(); 6248 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6249 FDecl->getLocation(), 6250 FDecl->getLocation(), 6251 FDecl->getIdentifier(), 6252 OverloadTy, 6253 /*TInfo=*/nullptr, 6254 SC_Extern, false, 6255 /*hasPrototype=*/true); 6256 SmallVector<ParmVarDecl*, 16> Params; 6257 FT = cast<FunctionProtoType>(OverloadTy); 6258 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6259 QualType ParamType = FT->getParamType(i); 6260 ParmVarDecl *Parm = 6261 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6262 SourceLocation(), nullptr, ParamType, 6263 /*TInfo=*/nullptr, SC_None, nullptr); 6264 Parm->setScopeInfo(0, i); 6265 Params.push_back(Parm); 6266 } 6267 OverloadDecl->setParams(Params); 6268 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6269 return OverloadDecl; 6270 } 6271 6272 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6273 FunctionDecl *Callee, 6274 MultiExprArg ArgExprs) { 6275 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6276 // similar attributes) really don't like it when functions are called with an 6277 // invalid number of args. 6278 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6279 /*PartialOverloading=*/false) && 6280 !Callee->isVariadic()) 6281 return; 6282 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6283 return; 6284 6285 if (const EnableIfAttr *Attr = 6286 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6287 S.Diag(Fn->getBeginLoc(), 6288 isa<CXXMethodDecl>(Callee) 6289 ? diag::err_ovl_no_viable_member_function_in_call 6290 : diag::err_ovl_no_viable_function_in_call) 6291 << Callee << Callee->getSourceRange(); 6292 S.Diag(Callee->getLocation(), 6293 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6294 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6295 return; 6296 } 6297 } 6298 6299 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6300 const UnresolvedMemberExpr *const UME, Sema &S) { 6301 6302 const auto GetFunctionLevelDCIfCXXClass = 6303 [](Sema &S) -> const CXXRecordDecl * { 6304 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6305 if (!DC || !DC->getParent()) 6306 return nullptr; 6307 6308 // If the call to some member function was made from within a member 6309 // function body 'M' return return 'M's parent. 6310 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6311 return MD->getParent()->getCanonicalDecl(); 6312 // else the call was made from within a default member initializer of a 6313 // class, so return the class. 6314 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6315 return RD->getCanonicalDecl(); 6316 return nullptr; 6317 }; 6318 // If our DeclContext is neither a member function nor a class (in the 6319 // case of a lambda in a default member initializer), we can't have an 6320 // enclosing 'this'. 6321 6322 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6323 if (!CurParentClass) 6324 return false; 6325 6326 // The naming class for implicit member functions call is the class in which 6327 // name lookup starts. 6328 const CXXRecordDecl *const NamingClass = 6329 UME->getNamingClass()->getCanonicalDecl(); 6330 assert(NamingClass && "Must have naming class even for implicit access"); 6331 6332 // If the unresolved member functions were found in a 'naming class' that is 6333 // related (either the same or derived from) to the class that contains the 6334 // member function that itself contained the implicit member access. 6335 6336 return CurParentClass == NamingClass || 6337 CurParentClass->isDerivedFrom(NamingClass); 6338 } 6339 6340 static void 6341 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6342 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6343 6344 if (!UME) 6345 return; 6346 6347 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6348 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6349 // already been captured, or if this is an implicit member function call (if 6350 // it isn't, an attempt to capture 'this' should already have been made). 6351 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6352 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6353 return; 6354 6355 // Check if the naming class in which the unresolved members were found is 6356 // related (same as or is a base of) to the enclosing class. 6357 6358 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6359 return; 6360 6361 6362 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6363 // If the enclosing function is not dependent, then this lambda is 6364 // capture ready, so if we can capture this, do so. 6365 if (!EnclosingFunctionCtx->isDependentContext()) { 6366 // If the current lambda and all enclosing lambdas can capture 'this' - 6367 // then go ahead and capture 'this' (since our unresolved overload set 6368 // contains at least one non-static member function). 6369 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6370 S.CheckCXXThisCapture(CallLoc); 6371 } else if (S.CurContext->isDependentContext()) { 6372 // ... since this is an implicit member reference, that might potentially 6373 // involve a 'this' capture, mark 'this' for potential capture in 6374 // enclosing lambdas. 6375 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6376 CurLSI->addPotentialThisCapture(CallLoc); 6377 } 6378 } 6379 6380 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6381 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6382 Expr *ExecConfig) { 6383 ExprResult Call = 6384 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6385 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6386 if (Call.isInvalid()) 6387 return Call; 6388 6389 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6390 // language modes. 6391 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6392 if (ULE->hasExplicitTemplateArgs() && 6393 ULE->decls_begin() == ULE->decls_end()) { 6394 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6395 ? diag::warn_cxx17_compat_adl_only_template_id 6396 : diag::ext_adl_only_template_id) 6397 << ULE->getName(); 6398 } 6399 } 6400 6401 if (LangOpts.OpenMP) 6402 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6403 ExecConfig); 6404 6405 return Call; 6406 } 6407 6408 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6409 /// This provides the location of the left/right parens and a list of comma 6410 /// locations. 6411 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6412 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6413 Expr *ExecConfig, bool IsExecConfig, 6414 bool AllowRecovery) { 6415 // Since this might be a postfix expression, get rid of ParenListExprs. 6416 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6417 if (Result.isInvalid()) return ExprError(); 6418 Fn = Result.get(); 6419 6420 if (checkArgsForPlaceholders(*this, ArgExprs)) 6421 return ExprError(); 6422 6423 if (getLangOpts().CPlusPlus) { 6424 // If this is a pseudo-destructor expression, build the call immediately. 6425 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6426 if (!ArgExprs.empty()) { 6427 // Pseudo-destructor calls should not have any arguments. 6428 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6429 << FixItHint::CreateRemoval( 6430 SourceRange(ArgExprs.front()->getBeginLoc(), 6431 ArgExprs.back()->getEndLoc())); 6432 } 6433 6434 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6435 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6436 } 6437 if (Fn->getType() == Context.PseudoObjectTy) { 6438 ExprResult result = CheckPlaceholderExpr(Fn); 6439 if (result.isInvalid()) return ExprError(); 6440 Fn = result.get(); 6441 } 6442 6443 // Determine whether this is a dependent call inside a C++ template, 6444 // in which case we won't do any semantic analysis now. 6445 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6446 if (ExecConfig) { 6447 return CUDAKernelCallExpr::Create(Context, Fn, 6448 cast<CallExpr>(ExecConfig), ArgExprs, 6449 Context.DependentTy, VK_PRValue, 6450 RParenLoc, CurFPFeatureOverrides()); 6451 } else { 6452 6453 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6454 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6455 Fn->getBeginLoc()); 6456 6457 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6458 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6459 } 6460 } 6461 6462 // Determine whether this is a call to an object (C++ [over.call.object]). 6463 if (Fn->getType()->isRecordType()) 6464 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6465 RParenLoc); 6466 6467 if (Fn->getType() == Context.UnknownAnyTy) { 6468 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6469 if (result.isInvalid()) return ExprError(); 6470 Fn = result.get(); 6471 } 6472 6473 if (Fn->getType() == Context.BoundMemberTy) { 6474 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6475 RParenLoc, AllowRecovery); 6476 } 6477 } 6478 6479 // Check for overloaded calls. This can happen even in C due to extensions. 6480 if (Fn->getType() == Context.OverloadTy) { 6481 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6482 6483 // We aren't supposed to apply this logic if there's an '&' involved. 6484 if (!find.HasFormOfMemberPointer) { 6485 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6486 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6487 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6488 OverloadExpr *ovl = find.Expression; 6489 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6490 return BuildOverloadedCallExpr( 6491 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6492 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6493 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6494 RParenLoc, AllowRecovery); 6495 } 6496 } 6497 6498 // If we're directly calling a function, get the appropriate declaration. 6499 if (Fn->getType() == Context.UnknownAnyTy) { 6500 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6501 if (result.isInvalid()) return ExprError(); 6502 Fn = result.get(); 6503 } 6504 6505 Expr *NakedFn = Fn->IgnoreParens(); 6506 6507 bool CallingNDeclIndirectly = false; 6508 NamedDecl *NDecl = nullptr; 6509 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6510 if (UnOp->getOpcode() == UO_AddrOf) { 6511 CallingNDeclIndirectly = true; 6512 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6513 } 6514 } 6515 6516 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6517 NDecl = DRE->getDecl(); 6518 6519 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6520 if (FDecl && FDecl->getBuiltinID()) { 6521 // Rewrite the function decl for this builtin by replacing parameters 6522 // with no explicit address space with the address space of the arguments 6523 // in ArgExprs. 6524 if ((FDecl = 6525 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6526 NDecl = FDecl; 6527 Fn = DeclRefExpr::Create( 6528 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6529 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6530 nullptr, DRE->isNonOdrUse()); 6531 } 6532 } 6533 } else if (isa<MemberExpr>(NakedFn)) 6534 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6535 6536 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6537 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6538 FD, /*Complain=*/true, Fn->getBeginLoc())) 6539 return ExprError(); 6540 6541 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6542 } 6543 6544 if (Context.isDependenceAllowed() && 6545 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6546 assert(!getLangOpts().CPlusPlus); 6547 assert((Fn->containsErrors() || 6548 llvm::any_of(ArgExprs, 6549 [](clang::Expr *E) { return E->containsErrors(); })) && 6550 "should only occur in error-recovery path."); 6551 QualType ReturnType = 6552 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6553 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6554 : Context.DependentTy; 6555 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6556 Expr::getValueKindForType(ReturnType), RParenLoc, 6557 CurFPFeatureOverrides()); 6558 } 6559 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6560 ExecConfig, IsExecConfig); 6561 } 6562 6563 /// Parse a __builtin_astype expression. 6564 /// 6565 /// __builtin_astype( value, dst type ) 6566 /// 6567 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6568 SourceLocation BuiltinLoc, 6569 SourceLocation RParenLoc) { 6570 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6571 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6572 } 6573 6574 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6575 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6576 SourceLocation BuiltinLoc, 6577 SourceLocation RParenLoc) { 6578 ExprValueKind VK = VK_PRValue; 6579 ExprObjectKind OK = OK_Ordinary; 6580 QualType SrcTy = E->getType(); 6581 if (!SrcTy->isDependentType() && 6582 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6583 return ExprError( 6584 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6585 << DestTy << SrcTy << E->getSourceRange()); 6586 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6587 } 6588 6589 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6590 /// provided arguments. 6591 /// 6592 /// __builtin_convertvector( value, dst type ) 6593 /// 6594 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6595 SourceLocation BuiltinLoc, 6596 SourceLocation RParenLoc) { 6597 TypeSourceInfo *TInfo; 6598 GetTypeFromParser(ParsedDestTy, &TInfo); 6599 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6600 } 6601 6602 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6603 /// i.e. an expression not of \p OverloadTy. The expression should 6604 /// unary-convert to an expression of function-pointer or 6605 /// block-pointer type. 6606 /// 6607 /// \param NDecl the declaration being called, if available 6608 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6609 SourceLocation LParenLoc, 6610 ArrayRef<Expr *> Args, 6611 SourceLocation RParenLoc, Expr *Config, 6612 bool IsExecConfig, ADLCallKind UsesADL) { 6613 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6614 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6615 6616 // Functions with 'interrupt' attribute cannot be called directly. 6617 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6618 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6619 return ExprError(); 6620 } 6621 6622 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6623 // so there's some risk when calling out to non-interrupt handler functions 6624 // that the callee might not preserve them. This is easy to diagnose here, 6625 // but can be very challenging to debug. 6626 // Likewise, X86 interrupt handlers may only call routines with attribute 6627 // no_caller_saved_registers since there is no efficient way to 6628 // save and restore the non-GPR state. 6629 if (auto *Caller = getCurFunctionDecl()) { 6630 if (Caller->hasAttr<ARMInterruptAttr>()) { 6631 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6632 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6633 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6634 if (FDecl) 6635 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6636 } 6637 } 6638 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6639 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6640 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6641 if (FDecl) 6642 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6643 } 6644 } 6645 6646 // Promote the function operand. 6647 // We special-case function promotion here because we only allow promoting 6648 // builtin functions to function pointers in the callee of a call. 6649 ExprResult Result; 6650 QualType ResultTy; 6651 if (BuiltinID && 6652 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6653 // Extract the return type from the (builtin) function pointer type. 6654 // FIXME Several builtins still have setType in 6655 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6656 // Builtins.def to ensure they are correct before removing setType calls. 6657 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6658 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6659 ResultTy = FDecl->getCallResultType(); 6660 } else { 6661 Result = CallExprUnaryConversions(Fn); 6662 ResultTy = Context.BoolTy; 6663 } 6664 if (Result.isInvalid()) 6665 return ExprError(); 6666 Fn = Result.get(); 6667 6668 // Check for a valid function type, but only if it is not a builtin which 6669 // requires custom type checking. These will be handled by 6670 // CheckBuiltinFunctionCall below just after creation of the call expression. 6671 const FunctionType *FuncT = nullptr; 6672 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6673 retry: 6674 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6675 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6676 // have type pointer to function". 6677 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6678 if (!FuncT) 6679 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6680 << Fn->getType() << Fn->getSourceRange()); 6681 } else if (const BlockPointerType *BPT = 6682 Fn->getType()->getAs<BlockPointerType>()) { 6683 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6684 } else { 6685 // Handle calls to expressions of unknown-any type. 6686 if (Fn->getType() == Context.UnknownAnyTy) { 6687 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6688 if (rewrite.isInvalid()) 6689 return ExprError(); 6690 Fn = rewrite.get(); 6691 goto retry; 6692 } 6693 6694 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6695 << Fn->getType() << Fn->getSourceRange()); 6696 } 6697 } 6698 6699 // Get the number of parameters in the function prototype, if any. 6700 // We will allocate space for max(Args.size(), NumParams) arguments 6701 // in the call expression. 6702 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6703 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6704 6705 CallExpr *TheCall; 6706 if (Config) { 6707 assert(UsesADL == ADLCallKind::NotADL && 6708 "CUDAKernelCallExpr should not use ADL"); 6709 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6710 Args, ResultTy, VK_PRValue, RParenLoc, 6711 CurFPFeatureOverrides(), NumParams); 6712 } else { 6713 TheCall = 6714 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6715 CurFPFeatureOverrides(), NumParams, UsesADL); 6716 } 6717 6718 if (!Context.isDependenceAllowed()) { 6719 // Forget about the nulled arguments since typo correction 6720 // do not handle them well. 6721 TheCall->shrinkNumArgs(Args.size()); 6722 // C cannot always handle TypoExpr nodes in builtin calls and direct 6723 // function calls as their argument checking don't necessarily handle 6724 // dependent types properly, so make sure any TypoExprs have been 6725 // dealt with. 6726 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6727 if (!Result.isUsable()) return ExprError(); 6728 CallExpr *TheOldCall = TheCall; 6729 TheCall = dyn_cast<CallExpr>(Result.get()); 6730 bool CorrectedTypos = TheCall != TheOldCall; 6731 if (!TheCall) return Result; 6732 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6733 6734 // A new call expression node was created if some typos were corrected. 6735 // However it may not have been constructed with enough storage. In this 6736 // case, rebuild the node with enough storage. The waste of space is 6737 // immaterial since this only happens when some typos were corrected. 6738 if (CorrectedTypos && Args.size() < NumParams) { 6739 if (Config) 6740 TheCall = CUDAKernelCallExpr::Create( 6741 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6742 RParenLoc, CurFPFeatureOverrides(), NumParams); 6743 else 6744 TheCall = 6745 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6746 CurFPFeatureOverrides(), NumParams, UsesADL); 6747 } 6748 // We can now handle the nulled arguments for the default arguments. 6749 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6750 } 6751 6752 // Bail out early if calling a builtin with custom type checking. 6753 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6754 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6755 6756 if (getLangOpts().CUDA) { 6757 if (Config) { 6758 // CUDA: Kernel calls must be to global functions 6759 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6760 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6761 << FDecl << Fn->getSourceRange()); 6762 6763 // CUDA: Kernel function must have 'void' return type 6764 if (!FuncT->getReturnType()->isVoidType() && 6765 !FuncT->getReturnType()->getAs<AutoType>() && 6766 !FuncT->getReturnType()->isInstantiationDependentType()) 6767 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6768 << Fn->getType() << Fn->getSourceRange()); 6769 } else { 6770 // CUDA: Calls to global functions must be configured 6771 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6772 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6773 << FDecl << Fn->getSourceRange()); 6774 } 6775 } 6776 6777 // Check for a valid return type 6778 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6779 FDecl)) 6780 return ExprError(); 6781 6782 // We know the result type of the call, set it. 6783 TheCall->setType(FuncT->getCallResultType(Context)); 6784 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6785 6786 if (Proto) { 6787 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6788 IsExecConfig)) 6789 return ExprError(); 6790 } else { 6791 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6792 6793 if (FDecl) { 6794 // Check if we have too few/too many template arguments, based 6795 // on our knowledge of the function definition. 6796 const FunctionDecl *Def = nullptr; 6797 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6798 Proto = Def->getType()->getAs<FunctionProtoType>(); 6799 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6800 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6801 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6802 } 6803 6804 // If the function we're calling isn't a function prototype, but we have 6805 // a function prototype from a prior declaratiom, use that prototype. 6806 if (!FDecl->hasPrototype()) 6807 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6808 } 6809 6810 // Promote the arguments (C99 6.5.2.2p6). 6811 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6812 Expr *Arg = Args[i]; 6813 6814 if (Proto && i < Proto->getNumParams()) { 6815 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6816 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6817 ExprResult ArgE = 6818 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6819 if (ArgE.isInvalid()) 6820 return true; 6821 6822 Arg = ArgE.getAs<Expr>(); 6823 6824 } else { 6825 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6826 6827 if (ArgE.isInvalid()) 6828 return true; 6829 6830 Arg = ArgE.getAs<Expr>(); 6831 } 6832 6833 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6834 diag::err_call_incomplete_argument, Arg)) 6835 return ExprError(); 6836 6837 TheCall->setArg(i, Arg); 6838 } 6839 } 6840 6841 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6842 if (!Method->isStatic()) 6843 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6844 << Fn->getSourceRange()); 6845 6846 // Check for sentinels 6847 if (NDecl) 6848 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6849 6850 // Warn for unions passing across security boundary (CMSE). 6851 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6852 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6853 if (const auto *RT = 6854 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6855 if (RT->getDecl()->isOrContainsUnion()) 6856 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6857 << 0 << i; 6858 } 6859 } 6860 } 6861 6862 // Do special checking on direct calls to functions. 6863 if (FDecl) { 6864 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6865 return ExprError(); 6866 6867 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6868 6869 if (BuiltinID) 6870 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6871 } else if (NDecl) { 6872 if (CheckPointerCall(NDecl, TheCall, Proto)) 6873 return ExprError(); 6874 } else { 6875 if (CheckOtherCall(TheCall, Proto)) 6876 return ExprError(); 6877 } 6878 6879 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6880 } 6881 6882 ExprResult 6883 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6884 SourceLocation RParenLoc, Expr *InitExpr) { 6885 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6886 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6887 6888 TypeSourceInfo *TInfo; 6889 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6890 if (!TInfo) 6891 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6892 6893 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6894 } 6895 6896 ExprResult 6897 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6898 SourceLocation RParenLoc, Expr *LiteralExpr) { 6899 QualType literalType = TInfo->getType(); 6900 6901 if (literalType->isArrayType()) { 6902 if (RequireCompleteSizedType( 6903 LParenLoc, Context.getBaseElementType(literalType), 6904 diag::err_array_incomplete_or_sizeless_type, 6905 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6906 return ExprError(); 6907 if (literalType->isVariableArrayType()) { 6908 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6909 diag::err_variable_object_no_init)) { 6910 return ExprError(); 6911 } 6912 } 6913 } else if (!literalType->isDependentType() && 6914 RequireCompleteType(LParenLoc, literalType, 6915 diag::err_typecheck_decl_incomplete_type, 6916 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6917 return ExprError(); 6918 6919 InitializedEntity Entity 6920 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6921 InitializationKind Kind 6922 = InitializationKind::CreateCStyleCast(LParenLoc, 6923 SourceRange(LParenLoc, RParenLoc), 6924 /*InitList=*/true); 6925 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6926 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6927 &literalType); 6928 if (Result.isInvalid()) 6929 return ExprError(); 6930 LiteralExpr = Result.get(); 6931 6932 bool isFileScope = !CurContext->isFunctionOrMethod(); 6933 6934 // In C, compound literals are l-values for some reason. 6935 // For GCC compatibility, in C++, file-scope array compound literals with 6936 // constant initializers are also l-values, and compound literals are 6937 // otherwise prvalues. 6938 // 6939 // (GCC also treats C++ list-initialized file-scope array prvalues with 6940 // constant initializers as l-values, but that's non-conforming, so we don't 6941 // follow it there.) 6942 // 6943 // FIXME: It would be better to handle the lvalue cases as materializing and 6944 // lifetime-extending a temporary object, but our materialized temporaries 6945 // representation only supports lifetime extension from a variable, not "out 6946 // of thin air". 6947 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6948 // is bound to the result of applying array-to-pointer decay to the compound 6949 // literal. 6950 // FIXME: GCC supports compound literals of reference type, which should 6951 // obviously have a value kind derived from the kind of reference involved. 6952 ExprValueKind VK = 6953 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6954 ? VK_PRValue 6955 : VK_LValue; 6956 6957 if (isFileScope) 6958 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6959 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6960 Expr *Init = ILE->getInit(i); 6961 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6962 } 6963 6964 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6965 VK, LiteralExpr, isFileScope); 6966 if (isFileScope) { 6967 if (!LiteralExpr->isTypeDependent() && 6968 !LiteralExpr->isValueDependent() && 6969 !literalType->isDependentType()) // C99 6.5.2.5p3 6970 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6971 return ExprError(); 6972 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6973 literalType.getAddressSpace() != LangAS::Default) { 6974 // Embedded-C extensions to C99 6.5.2.5: 6975 // "If the compound literal occurs inside the body of a function, the 6976 // type name shall not be qualified by an address-space qualifier." 6977 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6978 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6979 return ExprError(); 6980 } 6981 6982 if (!isFileScope && !getLangOpts().CPlusPlus) { 6983 // Compound literals that have automatic storage duration are destroyed at 6984 // the end of the scope in C; in C++, they're just temporaries. 6985 6986 // Emit diagnostics if it is or contains a C union type that is non-trivial 6987 // to destruct. 6988 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6989 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6990 NTCUC_CompoundLiteral, NTCUK_Destruct); 6991 6992 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6993 if (literalType.isDestructedType()) { 6994 Cleanup.setExprNeedsCleanups(true); 6995 ExprCleanupObjects.push_back(E); 6996 getCurFunction()->setHasBranchProtectedScope(); 6997 } 6998 } 6999 7000 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7001 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7002 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7003 E->getInitializer()->getExprLoc()); 7004 7005 return MaybeBindToTemporary(E); 7006 } 7007 7008 ExprResult 7009 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7010 SourceLocation RBraceLoc) { 7011 // Only produce each kind of designated initialization diagnostic once. 7012 SourceLocation FirstDesignator; 7013 bool DiagnosedArrayDesignator = false; 7014 bool DiagnosedNestedDesignator = false; 7015 bool DiagnosedMixedDesignator = false; 7016 7017 // Check that any designated initializers are syntactically valid in the 7018 // current language mode. 7019 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7020 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7021 if (FirstDesignator.isInvalid()) 7022 FirstDesignator = DIE->getBeginLoc(); 7023 7024 if (!getLangOpts().CPlusPlus) 7025 break; 7026 7027 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7028 DiagnosedNestedDesignator = true; 7029 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7030 << DIE->getDesignatorsSourceRange(); 7031 } 7032 7033 for (auto &Desig : DIE->designators()) { 7034 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7035 DiagnosedArrayDesignator = true; 7036 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7037 << Desig.getSourceRange(); 7038 } 7039 } 7040 7041 if (!DiagnosedMixedDesignator && 7042 !isa<DesignatedInitExpr>(InitArgList[0])) { 7043 DiagnosedMixedDesignator = true; 7044 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7045 << DIE->getSourceRange(); 7046 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7047 << InitArgList[0]->getSourceRange(); 7048 } 7049 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7050 isa<DesignatedInitExpr>(InitArgList[0])) { 7051 DiagnosedMixedDesignator = true; 7052 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7053 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7054 << DIE->getSourceRange(); 7055 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7056 << InitArgList[I]->getSourceRange(); 7057 } 7058 } 7059 7060 if (FirstDesignator.isValid()) { 7061 // Only diagnose designated initiaization as a C++20 extension if we didn't 7062 // already diagnose use of (non-C++20) C99 designator syntax. 7063 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7064 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7065 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7066 ? diag::warn_cxx17_compat_designated_init 7067 : diag::ext_cxx_designated_init); 7068 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7069 Diag(FirstDesignator, diag::ext_designated_init); 7070 } 7071 } 7072 7073 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7074 } 7075 7076 ExprResult 7077 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7078 SourceLocation RBraceLoc) { 7079 // Semantic analysis for initializers is done by ActOnDeclarator() and 7080 // CheckInitializer() - it requires knowledge of the object being initialized. 7081 7082 // Immediately handle non-overload placeholders. Overloads can be 7083 // resolved contextually, but everything else here can't. 7084 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7085 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7086 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7087 7088 // Ignore failures; dropping the entire initializer list because 7089 // of one failure would be terrible for indexing/etc. 7090 if (result.isInvalid()) continue; 7091 7092 InitArgList[I] = result.get(); 7093 } 7094 } 7095 7096 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7097 RBraceLoc); 7098 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7099 return E; 7100 } 7101 7102 /// Do an explicit extend of the given block pointer if we're in ARC. 7103 void Sema::maybeExtendBlockObject(ExprResult &E) { 7104 assert(E.get()->getType()->isBlockPointerType()); 7105 assert(E.get()->isPRValue()); 7106 7107 // Only do this in an r-value context. 7108 if (!getLangOpts().ObjCAutoRefCount) return; 7109 7110 E = ImplicitCastExpr::Create( 7111 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7112 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7113 Cleanup.setExprNeedsCleanups(true); 7114 } 7115 7116 /// Prepare a conversion of the given expression to an ObjC object 7117 /// pointer type. 7118 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7119 QualType type = E.get()->getType(); 7120 if (type->isObjCObjectPointerType()) { 7121 return CK_BitCast; 7122 } else if (type->isBlockPointerType()) { 7123 maybeExtendBlockObject(E); 7124 return CK_BlockPointerToObjCPointerCast; 7125 } else { 7126 assert(type->isPointerType()); 7127 return CK_CPointerToObjCPointerCast; 7128 } 7129 } 7130 7131 /// Prepares for a scalar cast, performing all the necessary stages 7132 /// except the final cast and returning the kind required. 7133 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7134 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7135 // Also, callers should have filtered out the invalid cases with 7136 // pointers. Everything else should be possible. 7137 7138 QualType SrcTy = Src.get()->getType(); 7139 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7140 return CK_NoOp; 7141 7142 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7143 case Type::STK_MemberPointer: 7144 llvm_unreachable("member pointer type in C"); 7145 7146 case Type::STK_CPointer: 7147 case Type::STK_BlockPointer: 7148 case Type::STK_ObjCObjectPointer: 7149 switch (DestTy->getScalarTypeKind()) { 7150 case Type::STK_CPointer: { 7151 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7152 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7153 if (SrcAS != DestAS) 7154 return CK_AddressSpaceConversion; 7155 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7156 return CK_NoOp; 7157 return CK_BitCast; 7158 } 7159 case Type::STK_BlockPointer: 7160 return (SrcKind == Type::STK_BlockPointer 7161 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7162 case Type::STK_ObjCObjectPointer: 7163 if (SrcKind == Type::STK_ObjCObjectPointer) 7164 return CK_BitCast; 7165 if (SrcKind == Type::STK_CPointer) 7166 return CK_CPointerToObjCPointerCast; 7167 maybeExtendBlockObject(Src); 7168 return CK_BlockPointerToObjCPointerCast; 7169 case Type::STK_Bool: 7170 return CK_PointerToBoolean; 7171 case Type::STK_Integral: 7172 return CK_PointerToIntegral; 7173 case Type::STK_Floating: 7174 case Type::STK_FloatingComplex: 7175 case Type::STK_IntegralComplex: 7176 case Type::STK_MemberPointer: 7177 case Type::STK_FixedPoint: 7178 llvm_unreachable("illegal cast from pointer"); 7179 } 7180 llvm_unreachable("Should have returned before this"); 7181 7182 case Type::STK_FixedPoint: 7183 switch (DestTy->getScalarTypeKind()) { 7184 case Type::STK_FixedPoint: 7185 return CK_FixedPointCast; 7186 case Type::STK_Bool: 7187 return CK_FixedPointToBoolean; 7188 case Type::STK_Integral: 7189 return CK_FixedPointToIntegral; 7190 case Type::STK_Floating: 7191 return CK_FixedPointToFloating; 7192 case Type::STK_IntegralComplex: 7193 case Type::STK_FloatingComplex: 7194 Diag(Src.get()->getExprLoc(), 7195 diag::err_unimplemented_conversion_with_fixed_point_type) 7196 << DestTy; 7197 return CK_IntegralCast; 7198 case Type::STK_CPointer: 7199 case Type::STK_ObjCObjectPointer: 7200 case Type::STK_BlockPointer: 7201 case Type::STK_MemberPointer: 7202 llvm_unreachable("illegal cast to pointer type"); 7203 } 7204 llvm_unreachable("Should have returned before this"); 7205 7206 case Type::STK_Bool: // casting from bool is like casting from an integer 7207 case Type::STK_Integral: 7208 switch (DestTy->getScalarTypeKind()) { 7209 case Type::STK_CPointer: 7210 case Type::STK_ObjCObjectPointer: 7211 case Type::STK_BlockPointer: 7212 if (Src.get()->isNullPointerConstant(Context, 7213 Expr::NPC_ValueDependentIsNull)) 7214 return CK_NullToPointer; 7215 return CK_IntegralToPointer; 7216 case Type::STK_Bool: 7217 return CK_IntegralToBoolean; 7218 case Type::STK_Integral: 7219 return CK_IntegralCast; 7220 case Type::STK_Floating: 7221 return CK_IntegralToFloating; 7222 case Type::STK_IntegralComplex: 7223 Src = ImpCastExprToType(Src.get(), 7224 DestTy->castAs<ComplexType>()->getElementType(), 7225 CK_IntegralCast); 7226 return CK_IntegralRealToComplex; 7227 case Type::STK_FloatingComplex: 7228 Src = ImpCastExprToType(Src.get(), 7229 DestTy->castAs<ComplexType>()->getElementType(), 7230 CK_IntegralToFloating); 7231 return CK_FloatingRealToComplex; 7232 case Type::STK_MemberPointer: 7233 llvm_unreachable("member pointer type in C"); 7234 case Type::STK_FixedPoint: 7235 return CK_IntegralToFixedPoint; 7236 } 7237 llvm_unreachable("Should have returned before this"); 7238 7239 case Type::STK_Floating: 7240 switch (DestTy->getScalarTypeKind()) { 7241 case Type::STK_Floating: 7242 return CK_FloatingCast; 7243 case Type::STK_Bool: 7244 return CK_FloatingToBoolean; 7245 case Type::STK_Integral: 7246 return CK_FloatingToIntegral; 7247 case Type::STK_FloatingComplex: 7248 Src = ImpCastExprToType(Src.get(), 7249 DestTy->castAs<ComplexType>()->getElementType(), 7250 CK_FloatingCast); 7251 return CK_FloatingRealToComplex; 7252 case Type::STK_IntegralComplex: 7253 Src = ImpCastExprToType(Src.get(), 7254 DestTy->castAs<ComplexType>()->getElementType(), 7255 CK_FloatingToIntegral); 7256 return CK_IntegralRealToComplex; 7257 case Type::STK_CPointer: 7258 case Type::STK_ObjCObjectPointer: 7259 case Type::STK_BlockPointer: 7260 llvm_unreachable("valid float->pointer cast?"); 7261 case Type::STK_MemberPointer: 7262 llvm_unreachable("member pointer type in C"); 7263 case Type::STK_FixedPoint: 7264 return CK_FloatingToFixedPoint; 7265 } 7266 llvm_unreachable("Should have returned before this"); 7267 7268 case Type::STK_FloatingComplex: 7269 switch (DestTy->getScalarTypeKind()) { 7270 case Type::STK_FloatingComplex: 7271 return CK_FloatingComplexCast; 7272 case Type::STK_IntegralComplex: 7273 return CK_FloatingComplexToIntegralComplex; 7274 case Type::STK_Floating: { 7275 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7276 if (Context.hasSameType(ET, DestTy)) 7277 return CK_FloatingComplexToReal; 7278 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7279 return CK_FloatingCast; 7280 } 7281 case Type::STK_Bool: 7282 return CK_FloatingComplexToBoolean; 7283 case Type::STK_Integral: 7284 Src = ImpCastExprToType(Src.get(), 7285 SrcTy->castAs<ComplexType>()->getElementType(), 7286 CK_FloatingComplexToReal); 7287 return CK_FloatingToIntegral; 7288 case Type::STK_CPointer: 7289 case Type::STK_ObjCObjectPointer: 7290 case Type::STK_BlockPointer: 7291 llvm_unreachable("valid complex float->pointer cast?"); 7292 case Type::STK_MemberPointer: 7293 llvm_unreachable("member pointer type in C"); 7294 case Type::STK_FixedPoint: 7295 Diag(Src.get()->getExprLoc(), 7296 diag::err_unimplemented_conversion_with_fixed_point_type) 7297 << SrcTy; 7298 return CK_IntegralCast; 7299 } 7300 llvm_unreachable("Should have returned before this"); 7301 7302 case Type::STK_IntegralComplex: 7303 switch (DestTy->getScalarTypeKind()) { 7304 case Type::STK_FloatingComplex: 7305 return CK_IntegralComplexToFloatingComplex; 7306 case Type::STK_IntegralComplex: 7307 return CK_IntegralComplexCast; 7308 case Type::STK_Integral: { 7309 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7310 if (Context.hasSameType(ET, DestTy)) 7311 return CK_IntegralComplexToReal; 7312 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7313 return CK_IntegralCast; 7314 } 7315 case Type::STK_Bool: 7316 return CK_IntegralComplexToBoolean; 7317 case Type::STK_Floating: 7318 Src = ImpCastExprToType(Src.get(), 7319 SrcTy->castAs<ComplexType>()->getElementType(), 7320 CK_IntegralComplexToReal); 7321 return CK_IntegralToFloating; 7322 case Type::STK_CPointer: 7323 case Type::STK_ObjCObjectPointer: 7324 case Type::STK_BlockPointer: 7325 llvm_unreachable("valid complex int->pointer cast?"); 7326 case Type::STK_MemberPointer: 7327 llvm_unreachable("member pointer type in C"); 7328 case Type::STK_FixedPoint: 7329 Diag(Src.get()->getExprLoc(), 7330 diag::err_unimplemented_conversion_with_fixed_point_type) 7331 << SrcTy; 7332 return CK_IntegralCast; 7333 } 7334 llvm_unreachable("Should have returned before this"); 7335 } 7336 7337 llvm_unreachable("Unhandled scalar cast"); 7338 } 7339 7340 static bool breakDownVectorType(QualType type, uint64_t &len, 7341 QualType &eltType) { 7342 // Vectors are simple. 7343 if (const VectorType *vecType = type->getAs<VectorType>()) { 7344 len = vecType->getNumElements(); 7345 eltType = vecType->getElementType(); 7346 assert(eltType->isScalarType()); 7347 return true; 7348 } 7349 7350 // We allow lax conversion to and from non-vector types, but only if 7351 // they're real types (i.e. non-complex, non-pointer scalar types). 7352 if (!type->isRealType()) return false; 7353 7354 len = 1; 7355 eltType = type; 7356 return true; 7357 } 7358 7359 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7360 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7361 /// allowed? 7362 /// 7363 /// This will also return false if the two given types do not make sense from 7364 /// the perspective of SVE bitcasts. 7365 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7366 assert(srcTy->isVectorType() || destTy->isVectorType()); 7367 7368 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7369 if (!FirstType->isSizelessBuiltinType()) 7370 return false; 7371 7372 const auto *VecTy = SecondType->getAs<VectorType>(); 7373 return VecTy && 7374 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7375 }; 7376 7377 return ValidScalableConversion(srcTy, destTy) || 7378 ValidScalableConversion(destTy, srcTy); 7379 } 7380 7381 /// Are the two types matrix types and do they have the same dimensions i.e. 7382 /// do they have the same number of rows and the same number of columns? 7383 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7384 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7385 return false; 7386 7387 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7388 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7389 7390 return matSrcType->getNumRows() == matDestType->getNumRows() && 7391 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7392 } 7393 7394 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7395 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7396 7397 uint64_t SrcLen, DestLen; 7398 QualType SrcEltTy, DestEltTy; 7399 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7400 return false; 7401 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7402 return false; 7403 7404 // ASTContext::getTypeSize will return the size rounded up to a 7405 // power of 2, so instead of using that, we need to use the raw 7406 // element size multiplied by the element count. 7407 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7408 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7409 7410 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7411 } 7412 7413 /// Are the two types lax-compatible vector types? That is, given 7414 /// that one of them is a vector, do they have equal storage sizes, 7415 /// where the storage size is the number of elements times the element 7416 /// size? 7417 /// 7418 /// This will also return false if either of the types is neither a 7419 /// vector nor a real type. 7420 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7421 assert(destTy->isVectorType() || srcTy->isVectorType()); 7422 7423 // Disallow lax conversions between scalars and ExtVectors (these 7424 // conversions are allowed for other vector types because common headers 7425 // depend on them). Most scalar OP ExtVector cases are handled by the 7426 // splat path anyway, which does what we want (convert, not bitcast). 7427 // What this rules out for ExtVectors is crazy things like char4*float. 7428 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7429 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7430 7431 return areVectorTypesSameSize(srcTy, destTy); 7432 } 7433 7434 /// Is this a legal conversion between two types, one of which is 7435 /// known to be a vector type? 7436 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7437 assert(destTy->isVectorType() || srcTy->isVectorType()); 7438 7439 switch (Context.getLangOpts().getLaxVectorConversions()) { 7440 case LangOptions::LaxVectorConversionKind::None: 7441 return false; 7442 7443 case LangOptions::LaxVectorConversionKind::Integer: 7444 if (!srcTy->isIntegralOrEnumerationType()) { 7445 auto *Vec = srcTy->getAs<VectorType>(); 7446 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7447 return false; 7448 } 7449 if (!destTy->isIntegralOrEnumerationType()) { 7450 auto *Vec = destTy->getAs<VectorType>(); 7451 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7452 return false; 7453 } 7454 // OK, integer (vector) -> integer (vector) bitcast. 7455 break; 7456 7457 case LangOptions::LaxVectorConversionKind::All: 7458 break; 7459 } 7460 7461 return areLaxCompatibleVectorTypes(srcTy, destTy); 7462 } 7463 7464 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7465 CastKind &Kind) { 7466 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7467 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7468 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7469 << DestTy << SrcTy << R; 7470 } 7471 } else if (SrcTy->isMatrixType()) { 7472 return Diag(R.getBegin(), 7473 diag::err_invalid_conversion_between_matrix_and_type) 7474 << SrcTy << DestTy << R; 7475 } else if (DestTy->isMatrixType()) { 7476 return Diag(R.getBegin(), 7477 diag::err_invalid_conversion_between_matrix_and_type) 7478 << DestTy << SrcTy << R; 7479 } 7480 7481 Kind = CK_MatrixCast; 7482 return false; 7483 } 7484 7485 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7486 CastKind &Kind) { 7487 assert(VectorTy->isVectorType() && "Not a vector type!"); 7488 7489 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7490 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7491 return Diag(R.getBegin(), 7492 Ty->isVectorType() ? 7493 diag::err_invalid_conversion_between_vectors : 7494 diag::err_invalid_conversion_between_vector_and_integer) 7495 << VectorTy << Ty << R; 7496 } else 7497 return Diag(R.getBegin(), 7498 diag::err_invalid_conversion_between_vector_and_scalar) 7499 << VectorTy << Ty << R; 7500 7501 Kind = CK_BitCast; 7502 return false; 7503 } 7504 7505 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7506 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7507 7508 if (DestElemTy == SplattedExpr->getType()) 7509 return SplattedExpr; 7510 7511 assert(DestElemTy->isFloatingType() || 7512 DestElemTy->isIntegralOrEnumerationType()); 7513 7514 CastKind CK; 7515 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7516 // OpenCL requires that we convert `true` boolean expressions to -1, but 7517 // only when splatting vectors. 7518 if (DestElemTy->isFloatingType()) { 7519 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7520 // in two steps: boolean to signed integral, then to floating. 7521 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7522 CK_BooleanToSignedIntegral); 7523 SplattedExpr = CastExprRes.get(); 7524 CK = CK_IntegralToFloating; 7525 } else { 7526 CK = CK_BooleanToSignedIntegral; 7527 } 7528 } else { 7529 ExprResult CastExprRes = SplattedExpr; 7530 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7531 if (CastExprRes.isInvalid()) 7532 return ExprError(); 7533 SplattedExpr = CastExprRes.get(); 7534 } 7535 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7536 } 7537 7538 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7539 Expr *CastExpr, CastKind &Kind) { 7540 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7541 7542 QualType SrcTy = CastExpr->getType(); 7543 7544 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7545 // an ExtVectorType. 7546 // In OpenCL, casts between vectors of different types are not allowed. 7547 // (See OpenCL 6.2). 7548 if (SrcTy->isVectorType()) { 7549 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7550 (getLangOpts().OpenCL && 7551 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7552 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7553 << DestTy << SrcTy << R; 7554 return ExprError(); 7555 } 7556 Kind = CK_BitCast; 7557 return CastExpr; 7558 } 7559 7560 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7561 // conversion will take place first from scalar to elt type, and then 7562 // splat from elt type to vector. 7563 if (SrcTy->isPointerType()) 7564 return Diag(R.getBegin(), 7565 diag::err_invalid_conversion_between_vector_and_scalar) 7566 << DestTy << SrcTy << R; 7567 7568 Kind = CK_VectorSplat; 7569 return prepareVectorSplat(DestTy, CastExpr); 7570 } 7571 7572 ExprResult 7573 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7574 Declarator &D, ParsedType &Ty, 7575 SourceLocation RParenLoc, Expr *CastExpr) { 7576 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7577 "ActOnCastExpr(): missing type or expr"); 7578 7579 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7580 if (D.isInvalidType()) 7581 return ExprError(); 7582 7583 if (getLangOpts().CPlusPlus) { 7584 // Check that there are no default arguments (C++ only). 7585 CheckExtraCXXDefaultArguments(D); 7586 } else { 7587 // Make sure any TypoExprs have been dealt with. 7588 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7589 if (!Res.isUsable()) 7590 return ExprError(); 7591 CastExpr = Res.get(); 7592 } 7593 7594 checkUnusedDeclAttributes(D); 7595 7596 QualType castType = castTInfo->getType(); 7597 Ty = CreateParsedType(castType, castTInfo); 7598 7599 bool isVectorLiteral = false; 7600 7601 // Check for an altivec or OpenCL literal, 7602 // i.e. all the elements are integer constants. 7603 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7604 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7605 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7606 && castType->isVectorType() && (PE || PLE)) { 7607 if (PLE && PLE->getNumExprs() == 0) { 7608 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7609 return ExprError(); 7610 } 7611 if (PE || PLE->getNumExprs() == 1) { 7612 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7613 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7614 isVectorLiteral = true; 7615 } 7616 else 7617 isVectorLiteral = true; 7618 } 7619 7620 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7621 // then handle it as such. 7622 if (isVectorLiteral) 7623 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7624 7625 // If the Expr being casted is a ParenListExpr, handle it specially. 7626 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7627 // sequence of BinOp comma operators. 7628 if (isa<ParenListExpr>(CastExpr)) { 7629 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7630 if (Result.isInvalid()) return ExprError(); 7631 CastExpr = Result.get(); 7632 } 7633 7634 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7635 !getSourceManager().isInSystemMacro(LParenLoc)) 7636 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7637 7638 CheckTollFreeBridgeCast(castType, CastExpr); 7639 7640 CheckObjCBridgeRelatedCast(castType, CastExpr); 7641 7642 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7643 7644 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7645 } 7646 7647 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7648 SourceLocation RParenLoc, Expr *E, 7649 TypeSourceInfo *TInfo) { 7650 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7651 "Expected paren or paren list expression"); 7652 7653 Expr **exprs; 7654 unsigned numExprs; 7655 Expr *subExpr; 7656 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7657 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7658 LiteralLParenLoc = PE->getLParenLoc(); 7659 LiteralRParenLoc = PE->getRParenLoc(); 7660 exprs = PE->getExprs(); 7661 numExprs = PE->getNumExprs(); 7662 } else { // isa<ParenExpr> by assertion at function entrance 7663 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7664 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7665 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7666 exprs = &subExpr; 7667 numExprs = 1; 7668 } 7669 7670 QualType Ty = TInfo->getType(); 7671 assert(Ty->isVectorType() && "Expected vector type"); 7672 7673 SmallVector<Expr *, 8> initExprs; 7674 const VectorType *VTy = Ty->castAs<VectorType>(); 7675 unsigned numElems = VTy->getNumElements(); 7676 7677 // '(...)' form of vector initialization in AltiVec: the number of 7678 // initializers must be one or must match the size of the vector. 7679 // If a single value is specified in the initializer then it will be 7680 // replicated to all the components of the vector 7681 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7682 // The number of initializers must be one or must match the size of the 7683 // vector. If a single value is specified in the initializer then it will 7684 // be replicated to all the components of the vector 7685 if (numExprs == 1) { 7686 QualType ElemTy = VTy->getElementType(); 7687 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7688 if (Literal.isInvalid()) 7689 return ExprError(); 7690 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7691 PrepareScalarCast(Literal, ElemTy)); 7692 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7693 } 7694 else if (numExprs < numElems) { 7695 Diag(E->getExprLoc(), 7696 diag::err_incorrect_number_of_vector_initializers); 7697 return ExprError(); 7698 } 7699 else 7700 initExprs.append(exprs, exprs + numExprs); 7701 } 7702 else { 7703 // For OpenCL, when the number of initializers is a single value, 7704 // it will be replicated to all components of the vector. 7705 if (getLangOpts().OpenCL && 7706 VTy->getVectorKind() == VectorType::GenericVector && 7707 numExprs == 1) { 7708 QualType ElemTy = VTy->getElementType(); 7709 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7710 if (Literal.isInvalid()) 7711 return ExprError(); 7712 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7713 PrepareScalarCast(Literal, ElemTy)); 7714 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7715 } 7716 7717 initExprs.append(exprs, exprs + numExprs); 7718 } 7719 // FIXME: This means that pretty-printing the final AST will produce curly 7720 // braces instead of the original commas. 7721 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7722 initExprs, LiteralRParenLoc); 7723 initE->setType(Ty); 7724 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7725 } 7726 7727 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7728 /// the ParenListExpr into a sequence of comma binary operators. 7729 ExprResult 7730 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7731 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7732 if (!E) 7733 return OrigExpr; 7734 7735 ExprResult Result(E->getExpr(0)); 7736 7737 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7738 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7739 E->getExpr(i)); 7740 7741 if (Result.isInvalid()) return ExprError(); 7742 7743 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7744 } 7745 7746 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7747 SourceLocation R, 7748 MultiExprArg Val) { 7749 return ParenListExpr::Create(Context, L, Val, R); 7750 } 7751 7752 /// Emit a specialized diagnostic when one expression is a null pointer 7753 /// constant and the other is not a pointer. Returns true if a diagnostic is 7754 /// emitted. 7755 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7756 SourceLocation QuestionLoc) { 7757 Expr *NullExpr = LHSExpr; 7758 Expr *NonPointerExpr = RHSExpr; 7759 Expr::NullPointerConstantKind NullKind = 7760 NullExpr->isNullPointerConstant(Context, 7761 Expr::NPC_ValueDependentIsNotNull); 7762 7763 if (NullKind == Expr::NPCK_NotNull) { 7764 NullExpr = RHSExpr; 7765 NonPointerExpr = LHSExpr; 7766 NullKind = 7767 NullExpr->isNullPointerConstant(Context, 7768 Expr::NPC_ValueDependentIsNotNull); 7769 } 7770 7771 if (NullKind == Expr::NPCK_NotNull) 7772 return false; 7773 7774 if (NullKind == Expr::NPCK_ZeroExpression) 7775 return false; 7776 7777 if (NullKind == Expr::NPCK_ZeroLiteral) { 7778 // In this case, check to make sure that we got here from a "NULL" 7779 // string in the source code. 7780 NullExpr = NullExpr->IgnoreParenImpCasts(); 7781 SourceLocation loc = NullExpr->getExprLoc(); 7782 if (!findMacroSpelling(loc, "NULL")) 7783 return false; 7784 } 7785 7786 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7787 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7788 << NonPointerExpr->getType() << DiagType 7789 << NonPointerExpr->getSourceRange(); 7790 return true; 7791 } 7792 7793 /// Return false if the condition expression is valid, true otherwise. 7794 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7795 QualType CondTy = Cond->getType(); 7796 7797 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7798 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7799 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7800 << CondTy << Cond->getSourceRange(); 7801 return true; 7802 } 7803 7804 // C99 6.5.15p2 7805 if (CondTy->isScalarType()) return false; 7806 7807 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7808 << CondTy << Cond->getSourceRange(); 7809 return true; 7810 } 7811 7812 /// Handle when one or both operands are void type. 7813 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7814 ExprResult &RHS) { 7815 Expr *LHSExpr = LHS.get(); 7816 Expr *RHSExpr = RHS.get(); 7817 7818 if (!LHSExpr->getType()->isVoidType()) 7819 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7820 << RHSExpr->getSourceRange(); 7821 if (!RHSExpr->getType()->isVoidType()) 7822 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7823 << LHSExpr->getSourceRange(); 7824 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7825 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7826 return S.Context.VoidTy; 7827 } 7828 7829 /// Return false if the NullExpr can be promoted to PointerTy, 7830 /// true otherwise. 7831 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7832 QualType PointerTy) { 7833 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7834 !NullExpr.get()->isNullPointerConstant(S.Context, 7835 Expr::NPC_ValueDependentIsNull)) 7836 return true; 7837 7838 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7839 return false; 7840 } 7841 7842 /// Checks compatibility between two pointers and return the resulting 7843 /// type. 7844 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7845 ExprResult &RHS, 7846 SourceLocation Loc) { 7847 QualType LHSTy = LHS.get()->getType(); 7848 QualType RHSTy = RHS.get()->getType(); 7849 7850 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7851 // Two identical pointers types are always compatible. 7852 return LHSTy; 7853 } 7854 7855 QualType lhptee, rhptee; 7856 7857 // Get the pointee types. 7858 bool IsBlockPointer = false; 7859 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7860 lhptee = LHSBTy->getPointeeType(); 7861 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7862 IsBlockPointer = true; 7863 } else { 7864 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7865 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7866 } 7867 7868 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7869 // differently qualified versions of compatible types, the result type is 7870 // a pointer to an appropriately qualified version of the composite 7871 // type. 7872 7873 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7874 // clause doesn't make sense for our extensions. E.g. address space 2 should 7875 // be incompatible with address space 3: they may live on different devices or 7876 // anything. 7877 Qualifiers lhQual = lhptee.getQualifiers(); 7878 Qualifiers rhQual = rhptee.getQualifiers(); 7879 7880 LangAS ResultAddrSpace = LangAS::Default; 7881 LangAS LAddrSpace = lhQual.getAddressSpace(); 7882 LangAS RAddrSpace = rhQual.getAddressSpace(); 7883 7884 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7885 // spaces is disallowed. 7886 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7887 ResultAddrSpace = LAddrSpace; 7888 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7889 ResultAddrSpace = RAddrSpace; 7890 else { 7891 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7892 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7893 << RHS.get()->getSourceRange(); 7894 return QualType(); 7895 } 7896 7897 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7898 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7899 lhQual.removeCVRQualifiers(); 7900 rhQual.removeCVRQualifiers(); 7901 7902 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7903 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7904 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7905 // qual types are compatible iff 7906 // * corresponded types are compatible 7907 // * CVR qualifiers are equal 7908 // * address spaces are equal 7909 // Thus for conditional operator we merge CVR and address space unqualified 7910 // pointees and if there is a composite type we return a pointer to it with 7911 // merged qualifiers. 7912 LHSCastKind = 7913 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7914 RHSCastKind = 7915 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7916 lhQual.removeAddressSpace(); 7917 rhQual.removeAddressSpace(); 7918 7919 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7920 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7921 7922 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7923 7924 if (CompositeTy.isNull()) { 7925 // In this situation, we assume void* type. No especially good 7926 // reason, but this is what gcc does, and we do have to pick 7927 // to get a consistent AST. 7928 QualType incompatTy; 7929 incompatTy = S.Context.getPointerType( 7930 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7931 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7932 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7933 7934 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7935 // for casts between types with incompatible address space qualifiers. 7936 // For the following code the compiler produces casts between global and 7937 // local address spaces of the corresponded innermost pointees: 7938 // local int *global *a; 7939 // global int *global *b; 7940 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7941 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7942 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7943 << RHS.get()->getSourceRange(); 7944 7945 return incompatTy; 7946 } 7947 7948 // The pointer types are compatible. 7949 // In case of OpenCL ResultTy should have the address space qualifier 7950 // which is a superset of address spaces of both the 2nd and the 3rd 7951 // operands of the conditional operator. 7952 QualType ResultTy = [&, ResultAddrSpace]() { 7953 if (S.getLangOpts().OpenCL) { 7954 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7955 CompositeQuals.setAddressSpace(ResultAddrSpace); 7956 return S.Context 7957 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7958 .withCVRQualifiers(MergedCVRQual); 7959 } 7960 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7961 }(); 7962 if (IsBlockPointer) 7963 ResultTy = S.Context.getBlockPointerType(ResultTy); 7964 else 7965 ResultTy = S.Context.getPointerType(ResultTy); 7966 7967 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7968 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7969 return ResultTy; 7970 } 7971 7972 /// Return the resulting type when the operands are both block pointers. 7973 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7974 ExprResult &LHS, 7975 ExprResult &RHS, 7976 SourceLocation Loc) { 7977 QualType LHSTy = LHS.get()->getType(); 7978 QualType RHSTy = RHS.get()->getType(); 7979 7980 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7981 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7982 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7983 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7984 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7985 return destType; 7986 } 7987 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7988 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7989 << RHS.get()->getSourceRange(); 7990 return QualType(); 7991 } 7992 7993 // We have 2 block pointer types. 7994 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7995 } 7996 7997 /// Return the resulting type when the operands are both pointers. 7998 static QualType 7999 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8000 ExprResult &RHS, 8001 SourceLocation Loc) { 8002 // get the pointer types 8003 QualType LHSTy = LHS.get()->getType(); 8004 QualType RHSTy = RHS.get()->getType(); 8005 8006 // get the "pointed to" types 8007 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8008 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8009 8010 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8011 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8012 // Figure out necessary qualifiers (C99 6.5.15p6) 8013 QualType destPointee 8014 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8015 QualType destType = S.Context.getPointerType(destPointee); 8016 // Add qualifiers if necessary. 8017 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8018 // Promote to void*. 8019 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8020 return destType; 8021 } 8022 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8023 QualType destPointee 8024 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8025 QualType destType = S.Context.getPointerType(destPointee); 8026 // Add qualifiers if necessary. 8027 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8028 // Promote to void*. 8029 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8030 return destType; 8031 } 8032 8033 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8034 } 8035 8036 /// Return false if the first expression is not an integer and the second 8037 /// expression is not a pointer, true otherwise. 8038 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8039 Expr* PointerExpr, SourceLocation Loc, 8040 bool IsIntFirstExpr) { 8041 if (!PointerExpr->getType()->isPointerType() || 8042 !Int.get()->getType()->isIntegerType()) 8043 return false; 8044 8045 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8046 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8047 8048 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8049 << Expr1->getType() << Expr2->getType() 8050 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8051 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8052 CK_IntegralToPointer); 8053 return true; 8054 } 8055 8056 /// Simple conversion between integer and floating point types. 8057 /// 8058 /// Used when handling the OpenCL conditional operator where the 8059 /// condition is a vector while the other operands are scalar. 8060 /// 8061 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8062 /// types are either integer or floating type. Between the two 8063 /// operands, the type with the higher rank is defined as the "result 8064 /// type". The other operand needs to be promoted to the same type. No 8065 /// other type promotion is allowed. We cannot use 8066 /// UsualArithmeticConversions() for this purpose, since it always 8067 /// promotes promotable types. 8068 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8069 ExprResult &RHS, 8070 SourceLocation QuestionLoc) { 8071 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8072 if (LHS.isInvalid()) 8073 return QualType(); 8074 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8075 if (RHS.isInvalid()) 8076 return QualType(); 8077 8078 // For conversion purposes, we ignore any qualifiers. 8079 // For example, "const float" and "float" are equivalent. 8080 QualType LHSType = 8081 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8082 QualType RHSType = 8083 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8084 8085 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8086 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8087 << LHSType << LHS.get()->getSourceRange(); 8088 return QualType(); 8089 } 8090 8091 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8092 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8093 << RHSType << RHS.get()->getSourceRange(); 8094 return QualType(); 8095 } 8096 8097 // If both types are identical, no conversion is needed. 8098 if (LHSType == RHSType) 8099 return LHSType; 8100 8101 // Now handle "real" floating types (i.e. float, double, long double). 8102 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8103 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8104 /*IsCompAssign = */ false); 8105 8106 // Finally, we have two differing integer types. 8107 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8108 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8109 } 8110 8111 /// Convert scalar operands to a vector that matches the 8112 /// condition in length. 8113 /// 8114 /// Used when handling the OpenCL conditional operator where the 8115 /// condition is a vector while the other operands are scalar. 8116 /// 8117 /// We first compute the "result type" for the scalar operands 8118 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8119 /// into a vector of that type where the length matches the condition 8120 /// vector type. s6.11.6 requires that the element types of the result 8121 /// and the condition must have the same number of bits. 8122 static QualType 8123 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8124 QualType CondTy, SourceLocation QuestionLoc) { 8125 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8126 if (ResTy.isNull()) return QualType(); 8127 8128 const VectorType *CV = CondTy->getAs<VectorType>(); 8129 assert(CV); 8130 8131 // Determine the vector result type 8132 unsigned NumElements = CV->getNumElements(); 8133 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8134 8135 // Ensure that all types have the same number of bits 8136 if (S.Context.getTypeSize(CV->getElementType()) 8137 != S.Context.getTypeSize(ResTy)) { 8138 // Since VectorTy is created internally, it does not pretty print 8139 // with an OpenCL name. Instead, we just print a description. 8140 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8141 SmallString<64> Str; 8142 llvm::raw_svector_ostream OS(Str); 8143 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8144 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8145 << CondTy << OS.str(); 8146 return QualType(); 8147 } 8148 8149 // Convert operands to the vector result type 8150 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8151 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8152 8153 return VectorTy; 8154 } 8155 8156 /// Return false if this is a valid OpenCL condition vector 8157 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8158 SourceLocation QuestionLoc) { 8159 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8160 // integral type. 8161 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8162 assert(CondTy); 8163 QualType EleTy = CondTy->getElementType(); 8164 if (EleTy->isIntegerType()) return false; 8165 8166 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8167 << Cond->getType() << Cond->getSourceRange(); 8168 return true; 8169 } 8170 8171 /// Return false if the vector condition type and the vector 8172 /// result type are compatible. 8173 /// 8174 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8175 /// number of elements, and their element types have the same number 8176 /// of bits. 8177 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8178 SourceLocation QuestionLoc) { 8179 const VectorType *CV = CondTy->getAs<VectorType>(); 8180 const VectorType *RV = VecResTy->getAs<VectorType>(); 8181 assert(CV && RV); 8182 8183 if (CV->getNumElements() != RV->getNumElements()) { 8184 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8185 << CondTy << VecResTy; 8186 return true; 8187 } 8188 8189 QualType CVE = CV->getElementType(); 8190 QualType RVE = RV->getElementType(); 8191 8192 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8193 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8194 << CondTy << VecResTy; 8195 return true; 8196 } 8197 8198 return false; 8199 } 8200 8201 /// Return the resulting type for the conditional operator in 8202 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8203 /// s6.3.i) when the condition is a vector type. 8204 static QualType 8205 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8206 ExprResult &LHS, ExprResult &RHS, 8207 SourceLocation QuestionLoc) { 8208 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8209 if (Cond.isInvalid()) 8210 return QualType(); 8211 QualType CondTy = Cond.get()->getType(); 8212 8213 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8214 return QualType(); 8215 8216 // If either operand is a vector then find the vector type of the 8217 // result as specified in OpenCL v1.1 s6.3.i. 8218 if (LHS.get()->getType()->isVectorType() || 8219 RHS.get()->getType()->isVectorType()) { 8220 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8221 /*isCompAssign*/false, 8222 /*AllowBothBool*/true, 8223 /*AllowBoolConversions*/false); 8224 if (VecResTy.isNull()) return QualType(); 8225 // The result type must match the condition type as specified in 8226 // OpenCL v1.1 s6.11.6. 8227 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8228 return QualType(); 8229 return VecResTy; 8230 } 8231 8232 // Both operands are scalar. 8233 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8234 } 8235 8236 /// Return true if the Expr is block type 8237 static bool checkBlockType(Sema &S, const Expr *E) { 8238 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8239 QualType Ty = CE->getCallee()->getType(); 8240 if (Ty->isBlockPointerType()) { 8241 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8242 return true; 8243 } 8244 } 8245 return false; 8246 } 8247 8248 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8249 /// In that case, LHS = cond. 8250 /// C99 6.5.15 8251 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8252 ExprResult &RHS, ExprValueKind &VK, 8253 ExprObjectKind &OK, 8254 SourceLocation QuestionLoc) { 8255 8256 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8257 if (!LHSResult.isUsable()) return QualType(); 8258 LHS = LHSResult; 8259 8260 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8261 if (!RHSResult.isUsable()) return QualType(); 8262 RHS = RHSResult; 8263 8264 // C++ is sufficiently different to merit its own checker. 8265 if (getLangOpts().CPlusPlus) 8266 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8267 8268 VK = VK_PRValue; 8269 OK = OK_Ordinary; 8270 8271 if (Context.isDependenceAllowed() && 8272 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8273 RHS.get()->isTypeDependent())) { 8274 assert(!getLangOpts().CPlusPlus); 8275 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8276 RHS.get()->containsErrors()) && 8277 "should only occur in error-recovery path."); 8278 return Context.DependentTy; 8279 } 8280 8281 // The OpenCL operator with a vector condition is sufficiently 8282 // different to merit its own checker. 8283 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8284 Cond.get()->getType()->isExtVectorType()) 8285 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8286 8287 // First, check the condition. 8288 Cond = UsualUnaryConversions(Cond.get()); 8289 if (Cond.isInvalid()) 8290 return QualType(); 8291 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8292 return QualType(); 8293 8294 // Now check the two expressions. 8295 if (LHS.get()->getType()->isVectorType() || 8296 RHS.get()->getType()->isVectorType()) 8297 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8298 /*AllowBothBool*/true, 8299 /*AllowBoolConversions*/false); 8300 8301 QualType ResTy = 8302 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8303 if (LHS.isInvalid() || RHS.isInvalid()) 8304 return QualType(); 8305 8306 QualType LHSTy = LHS.get()->getType(); 8307 QualType RHSTy = RHS.get()->getType(); 8308 8309 // Diagnose attempts to convert between __float128 and long double where 8310 // such conversions currently can't be handled. 8311 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8312 Diag(QuestionLoc, 8313 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8315 return QualType(); 8316 } 8317 8318 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8319 // selection operator (?:). 8320 if (getLangOpts().OpenCL && 8321 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8322 return QualType(); 8323 } 8324 8325 // If both operands have arithmetic type, do the usual arithmetic conversions 8326 // to find a common type: C99 6.5.15p3,5. 8327 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8328 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8329 // different sizes, or between ExtInts and other types. 8330 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8331 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8332 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8333 << RHS.get()->getSourceRange(); 8334 return QualType(); 8335 } 8336 8337 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8338 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8339 8340 return ResTy; 8341 } 8342 8343 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8344 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8345 return LHSTy; 8346 } 8347 8348 // If both operands are the same structure or union type, the result is that 8349 // type. 8350 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8351 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8352 if (LHSRT->getDecl() == RHSRT->getDecl()) 8353 // "If both the operands have structure or union type, the result has 8354 // that type." This implies that CV qualifiers are dropped. 8355 return LHSTy.getUnqualifiedType(); 8356 // FIXME: Type of conditional expression must be complete in C mode. 8357 } 8358 8359 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8360 // The following || allows only one side to be void (a GCC-ism). 8361 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8362 return checkConditionalVoidType(*this, LHS, RHS); 8363 } 8364 8365 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8366 // the type of the other operand." 8367 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8368 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8369 8370 // All objective-c pointer type analysis is done here. 8371 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8372 QuestionLoc); 8373 if (LHS.isInvalid() || RHS.isInvalid()) 8374 return QualType(); 8375 if (!compositeType.isNull()) 8376 return compositeType; 8377 8378 8379 // Handle block pointer types. 8380 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8381 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8382 QuestionLoc); 8383 8384 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8385 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8386 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8387 QuestionLoc); 8388 8389 // GCC compatibility: soften pointer/integer mismatch. Note that 8390 // null pointers have been filtered out by this point. 8391 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8392 /*IsIntFirstExpr=*/true)) 8393 return RHSTy; 8394 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8395 /*IsIntFirstExpr=*/false)) 8396 return LHSTy; 8397 8398 // Allow ?: operations in which both operands have the same 8399 // built-in sizeless type. 8400 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8401 return LHSTy; 8402 8403 // Emit a better diagnostic if one of the expressions is a null pointer 8404 // constant and the other is not a pointer type. In this case, the user most 8405 // likely forgot to take the address of the other expression. 8406 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8407 return QualType(); 8408 8409 // Otherwise, the operands are not compatible. 8410 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8411 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8412 << RHS.get()->getSourceRange(); 8413 return QualType(); 8414 } 8415 8416 /// FindCompositeObjCPointerType - Helper method to find composite type of 8417 /// two objective-c pointer types of the two input expressions. 8418 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8419 SourceLocation QuestionLoc) { 8420 QualType LHSTy = LHS.get()->getType(); 8421 QualType RHSTy = RHS.get()->getType(); 8422 8423 // Handle things like Class and struct objc_class*. Here we case the result 8424 // to the pseudo-builtin, because that will be implicitly cast back to the 8425 // redefinition type if an attempt is made to access its fields. 8426 if (LHSTy->isObjCClassType() && 8427 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8428 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8429 return LHSTy; 8430 } 8431 if (RHSTy->isObjCClassType() && 8432 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8433 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8434 return RHSTy; 8435 } 8436 // And the same for struct objc_object* / id 8437 if (LHSTy->isObjCIdType() && 8438 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8439 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8440 return LHSTy; 8441 } 8442 if (RHSTy->isObjCIdType() && 8443 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8444 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8445 return RHSTy; 8446 } 8447 // And the same for struct objc_selector* / SEL 8448 if (Context.isObjCSelType(LHSTy) && 8449 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8450 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8451 return LHSTy; 8452 } 8453 if (Context.isObjCSelType(RHSTy) && 8454 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8455 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8456 return RHSTy; 8457 } 8458 // Check constraints for Objective-C object pointers types. 8459 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8460 8461 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8462 // Two identical object pointer types are always compatible. 8463 return LHSTy; 8464 } 8465 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8466 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8467 QualType compositeType = LHSTy; 8468 8469 // If both operands are interfaces and either operand can be 8470 // assigned to the other, use that type as the composite 8471 // type. This allows 8472 // xxx ? (A*) a : (B*) b 8473 // where B is a subclass of A. 8474 // 8475 // Additionally, as for assignment, if either type is 'id' 8476 // allow silent coercion. Finally, if the types are 8477 // incompatible then make sure to use 'id' as the composite 8478 // type so the result is acceptable for sending messages to. 8479 8480 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8481 // It could return the composite type. 8482 if (!(compositeType = 8483 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8484 // Nothing more to do. 8485 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8486 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8487 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8488 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8489 } else if ((LHSOPT->isObjCQualifiedIdType() || 8490 RHSOPT->isObjCQualifiedIdType()) && 8491 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8492 true)) { 8493 // Need to handle "id<xx>" explicitly. 8494 // GCC allows qualified id and any Objective-C type to devolve to 8495 // id. Currently localizing to here until clear this should be 8496 // part of ObjCQualifiedIdTypesAreCompatible. 8497 compositeType = Context.getObjCIdType(); 8498 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8499 compositeType = Context.getObjCIdType(); 8500 } else { 8501 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8502 << LHSTy << RHSTy 8503 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8504 QualType incompatTy = Context.getObjCIdType(); 8505 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8506 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8507 return incompatTy; 8508 } 8509 // The object pointer types are compatible. 8510 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8511 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8512 return compositeType; 8513 } 8514 // Check Objective-C object pointer types and 'void *' 8515 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8516 if (getLangOpts().ObjCAutoRefCount) { 8517 // ARC forbids the implicit conversion of object pointers to 'void *', 8518 // so these types are not compatible. 8519 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8520 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8521 LHS = RHS = true; 8522 return QualType(); 8523 } 8524 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8525 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8526 QualType destPointee 8527 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8528 QualType destType = Context.getPointerType(destPointee); 8529 // Add qualifiers if necessary. 8530 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8531 // Promote to void*. 8532 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8533 return destType; 8534 } 8535 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8536 if (getLangOpts().ObjCAutoRefCount) { 8537 // ARC forbids the implicit conversion of object pointers to 'void *', 8538 // so these types are not compatible. 8539 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8541 LHS = RHS = true; 8542 return QualType(); 8543 } 8544 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8545 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8546 QualType destPointee 8547 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8548 QualType destType = Context.getPointerType(destPointee); 8549 // Add qualifiers if necessary. 8550 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8551 // Promote to void*. 8552 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8553 return destType; 8554 } 8555 return QualType(); 8556 } 8557 8558 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8559 /// ParenRange in parentheses. 8560 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8561 const PartialDiagnostic &Note, 8562 SourceRange ParenRange) { 8563 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8564 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8565 EndLoc.isValid()) { 8566 Self.Diag(Loc, Note) 8567 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8568 << FixItHint::CreateInsertion(EndLoc, ")"); 8569 } else { 8570 // We can't display the parentheses, so just show the bare note. 8571 Self.Diag(Loc, Note) << ParenRange; 8572 } 8573 } 8574 8575 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8576 return BinaryOperator::isAdditiveOp(Opc) || 8577 BinaryOperator::isMultiplicativeOp(Opc) || 8578 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8579 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8580 // not any of the logical operators. Bitwise-xor is commonly used as a 8581 // logical-xor because there is no logical-xor operator. The logical 8582 // operators, including uses of xor, have a high false positive rate for 8583 // precedence warnings. 8584 } 8585 8586 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8587 /// expression, either using a built-in or overloaded operator, 8588 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8589 /// expression. 8590 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8591 Expr **RHSExprs) { 8592 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8593 E = E->IgnoreImpCasts(); 8594 E = E->IgnoreConversionOperatorSingleStep(); 8595 E = E->IgnoreImpCasts(); 8596 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8597 E = MTE->getSubExpr(); 8598 E = E->IgnoreImpCasts(); 8599 } 8600 8601 // Built-in binary operator. 8602 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8603 if (IsArithmeticOp(OP->getOpcode())) { 8604 *Opcode = OP->getOpcode(); 8605 *RHSExprs = OP->getRHS(); 8606 return true; 8607 } 8608 } 8609 8610 // Overloaded operator. 8611 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8612 if (Call->getNumArgs() != 2) 8613 return false; 8614 8615 // Make sure this is really a binary operator that is safe to pass into 8616 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8617 OverloadedOperatorKind OO = Call->getOperator(); 8618 if (OO < OO_Plus || OO > OO_Arrow || 8619 OO == OO_PlusPlus || OO == OO_MinusMinus) 8620 return false; 8621 8622 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8623 if (IsArithmeticOp(OpKind)) { 8624 *Opcode = OpKind; 8625 *RHSExprs = Call->getArg(1); 8626 return true; 8627 } 8628 } 8629 8630 return false; 8631 } 8632 8633 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8634 /// or is a logical expression such as (x==y) which has int type, but is 8635 /// commonly interpreted as boolean. 8636 static bool ExprLooksBoolean(Expr *E) { 8637 E = E->IgnoreParenImpCasts(); 8638 8639 if (E->getType()->isBooleanType()) 8640 return true; 8641 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8642 return OP->isComparisonOp() || OP->isLogicalOp(); 8643 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8644 return OP->getOpcode() == UO_LNot; 8645 if (E->getType()->isPointerType()) 8646 return true; 8647 // FIXME: What about overloaded operator calls returning "unspecified boolean 8648 // type"s (commonly pointer-to-members)? 8649 8650 return false; 8651 } 8652 8653 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8654 /// and binary operator are mixed in a way that suggests the programmer assumed 8655 /// the conditional operator has higher precedence, for example: 8656 /// "int x = a + someBinaryCondition ? 1 : 2". 8657 static void DiagnoseConditionalPrecedence(Sema &Self, 8658 SourceLocation OpLoc, 8659 Expr *Condition, 8660 Expr *LHSExpr, 8661 Expr *RHSExpr) { 8662 BinaryOperatorKind CondOpcode; 8663 Expr *CondRHS; 8664 8665 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8666 return; 8667 if (!ExprLooksBoolean(CondRHS)) 8668 return; 8669 8670 // The condition is an arithmetic binary expression, with a right- 8671 // hand side that looks boolean, so warn. 8672 8673 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8674 ? diag::warn_precedence_bitwise_conditional 8675 : diag::warn_precedence_conditional; 8676 8677 Self.Diag(OpLoc, DiagID) 8678 << Condition->getSourceRange() 8679 << BinaryOperator::getOpcodeStr(CondOpcode); 8680 8681 SuggestParentheses( 8682 Self, OpLoc, 8683 Self.PDiag(diag::note_precedence_silence) 8684 << BinaryOperator::getOpcodeStr(CondOpcode), 8685 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8686 8687 SuggestParentheses(Self, OpLoc, 8688 Self.PDiag(diag::note_precedence_conditional_first), 8689 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8690 } 8691 8692 /// Compute the nullability of a conditional expression. 8693 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8694 QualType LHSTy, QualType RHSTy, 8695 ASTContext &Ctx) { 8696 if (!ResTy->isAnyPointerType()) 8697 return ResTy; 8698 8699 auto GetNullability = [&Ctx](QualType Ty) { 8700 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8701 if (Kind) { 8702 // For our purposes, treat _Nullable_result as _Nullable. 8703 if (*Kind == NullabilityKind::NullableResult) 8704 return NullabilityKind::Nullable; 8705 return *Kind; 8706 } 8707 return NullabilityKind::Unspecified; 8708 }; 8709 8710 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8711 NullabilityKind MergedKind; 8712 8713 // Compute nullability of a binary conditional expression. 8714 if (IsBin) { 8715 if (LHSKind == NullabilityKind::NonNull) 8716 MergedKind = NullabilityKind::NonNull; 8717 else 8718 MergedKind = RHSKind; 8719 // Compute nullability of a normal conditional expression. 8720 } else { 8721 if (LHSKind == NullabilityKind::Nullable || 8722 RHSKind == NullabilityKind::Nullable) 8723 MergedKind = NullabilityKind::Nullable; 8724 else if (LHSKind == NullabilityKind::NonNull) 8725 MergedKind = RHSKind; 8726 else if (RHSKind == NullabilityKind::NonNull) 8727 MergedKind = LHSKind; 8728 else 8729 MergedKind = NullabilityKind::Unspecified; 8730 } 8731 8732 // Return if ResTy already has the correct nullability. 8733 if (GetNullability(ResTy) == MergedKind) 8734 return ResTy; 8735 8736 // Strip all nullability from ResTy. 8737 while (ResTy->getNullability(Ctx)) 8738 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8739 8740 // Create a new AttributedType with the new nullability kind. 8741 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8742 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8743 } 8744 8745 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8746 /// in the case of a the GNU conditional expr extension. 8747 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8748 SourceLocation ColonLoc, 8749 Expr *CondExpr, Expr *LHSExpr, 8750 Expr *RHSExpr) { 8751 if (!Context.isDependenceAllowed()) { 8752 // C cannot handle TypoExpr nodes in the condition because it 8753 // doesn't handle dependent types properly, so make sure any TypoExprs have 8754 // been dealt with before checking the operands. 8755 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8756 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8757 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8758 8759 if (!CondResult.isUsable()) 8760 return ExprError(); 8761 8762 if (LHSExpr) { 8763 if (!LHSResult.isUsable()) 8764 return ExprError(); 8765 } 8766 8767 if (!RHSResult.isUsable()) 8768 return ExprError(); 8769 8770 CondExpr = CondResult.get(); 8771 LHSExpr = LHSResult.get(); 8772 RHSExpr = RHSResult.get(); 8773 } 8774 8775 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8776 // was the condition. 8777 OpaqueValueExpr *opaqueValue = nullptr; 8778 Expr *commonExpr = nullptr; 8779 if (!LHSExpr) { 8780 commonExpr = CondExpr; 8781 // Lower out placeholder types first. This is important so that we don't 8782 // try to capture a placeholder. This happens in few cases in C++; such 8783 // as Objective-C++'s dictionary subscripting syntax. 8784 if (commonExpr->hasPlaceholderType()) { 8785 ExprResult result = CheckPlaceholderExpr(commonExpr); 8786 if (!result.isUsable()) return ExprError(); 8787 commonExpr = result.get(); 8788 } 8789 // We usually want to apply unary conversions *before* saving, except 8790 // in the special case of a C++ l-value conditional. 8791 if (!(getLangOpts().CPlusPlus 8792 && !commonExpr->isTypeDependent() 8793 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8794 && commonExpr->isGLValue() 8795 && commonExpr->isOrdinaryOrBitFieldObject() 8796 && RHSExpr->isOrdinaryOrBitFieldObject() 8797 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8798 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8799 if (commonRes.isInvalid()) 8800 return ExprError(); 8801 commonExpr = commonRes.get(); 8802 } 8803 8804 // If the common expression is a class or array prvalue, materialize it 8805 // so that we can safely refer to it multiple times. 8806 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8807 commonExpr->getType()->isArrayType())) { 8808 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8809 if (MatExpr.isInvalid()) 8810 return ExprError(); 8811 commonExpr = MatExpr.get(); 8812 } 8813 8814 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8815 commonExpr->getType(), 8816 commonExpr->getValueKind(), 8817 commonExpr->getObjectKind(), 8818 commonExpr); 8819 LHSExpr = CondExpr = opaqueValue; 8820 } 8821 8822 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8823 ExprValueKind VK = VK_PRValue; 8824 ExprObjectKind OK = OK_Ordinary; 8825 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8826 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8827 VK, OK, QuestionLoc); 8828 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8829 RHS.isInvalid()) 8830 return ExprError(); 8831 8832 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8833 RHS.get()); 8834 8835 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8836 8837 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8838 Context); 8839 8840 if (!commonExpr) 8841 return new (Context) 8842 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8843 RHS.get(), result, VK, OK); 8844 8845 return new (Context) BinaryConditionalOperator( 8846 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8847 ColonLoc, result, VK, OK); 8848 } 8849 8850 // Check if we have a conversion between incompatible cmse function pointer 8851 // types, that is, a conversion between a function pointer with the 8852 // cmse_nonsecure_call attribute and one without. 8853 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8854 QualType ToType) { 8855 if (const auto *ToFn = 8856 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8857 if (const auto *FromFn = 8858 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8859 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8860 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8861 8862 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8863 } 8864 } 8865 return false; 8866 } 8867 8868 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8869 // being closely modeled after the C99 spec:-). The odd characteristic of this 8870 // routine is it effectively iqnores the qualifiers on the top level pointee. 8871 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8872 // FIXME: add a couple examples in this comment. 8873 static Sema::AssignConvertType 8874 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8875 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8876 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8877 8878 // get the "pointed to" type (ignoring qualifiers at the top level) 8879 const Type *lhptee, *rhptee; 8880 Qualifiers lhq, rhq; 8881 std::tie(lhptee, lhq) = 8882 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8883 std::tie(rhptee, rhq) = 8884 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8885 8886 Sema::AssignConvertType ConvTy = Sema::Compatible; 8887 8888 // C99 6.5.16.1p1: This following citation is common to constraints 8889 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8890 // qualifiers of the type *pointed to* by the right; 8891 8892 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8893 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8894 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8895 // Ignore lifetime for further calculation. 8896 lhq.removeObjCLifetime(); 8897 rhq.removeObjCLifetime(); 8898 } 8899 8900 if (!lhq.compatiblyIncludes(rhq)) { 8901 // Treat address-space mismatches as fatal. 8902 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8903 return Sema::IncompatiblePointerDiscardsQualifiers; 8904 8905 // It's okay to add or remove GC or lifetime qualifiers when converting to 8906 // and from void*. 8907 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8908 .compatiblyIncludes( 8909 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8910 && (lhptee->isVoidType() || rhptee->isVoidType())) 8911 ; // keep old 8912 8913 // Treat lifetime mismatches as fatal. 8914 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8915 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8916 8917 // For GCC/MS compatibility, other qualifier mismatches are treated 8918 // as still compatible in C. 8919 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8920 } 8921 8922 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8923 // incomplete type and the other is a pointer to a qualified or unqualified 8924 // version of void... 8925 if (lhptee->isVoidType()) { 8926 if (rhptee->isIncompleteOrObjectType()) 8927 return ConvTy; 8928 8929 // As an extension, we allow cast to/from void* to function pointer. 8930 assert(rhptee->isFunctionType()); 8931 return Sema::FunctionVoidPointer; 8932 } 8933 8934 if (rhptee->isVoidType()) { 8935 if (lhptee->isIncompleteOrObjectType()) 8936 return ConvTy; 8937 8938 // As an extension, we allow cast to/from void* to function pointer. 8939 assert(lhptee->isFunctionType()); 8940 return Sema::FunctionVoidPointer; 8941 } 8942 8943 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8944 // unqualified versions of compatible types, ... 8945 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8946 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8947 // Check if the pointee types are compatible ignoring the sign. 8948 // We explicitly check for char so that we catch "char" vs 8949 // "unsigned char" on systems where "char" is unsigned. 8950 if (lhptee->isCharType()) 8951 ltrans = S.Context.UnsignedCharTy; 8952 else if (lhptee->hasSignedIntegerRepresentation()) 8953 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8954 8955 if (rhptee->isCharType()) 8956 rtrans = S.Context.UnsignedCharTy; 8957 else if (rhptee->hasSignedIntegerRepresentation()) 8958 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8959 8960 if (ltrans == rtrans) { 8961 // Types are compatible ignoring the sign. Qualifier incompatibility 8962 // takes priority over sign incompatibility because the sign 8963 // warning can be disabled. 8964 if (ConvTy != Sema::Compatible) 8965 return ConvTy; 8966 8967 return Sema::IncompatiblePointerSign; 8968 } 8969 8970 // If we are a multi-level pointer, it's possible that our issue is simply 8971 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8972 // the eventual target type is the same and the pointers have the same 8973 // level of indirection, this must be the issue. 8974 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8975 do { 8976 std::tie(lhptee, lhq) = 8977 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8978 std::tie(rhptee, rhq) = 8979 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8980 8981 // Inconsistent address spaces at this point is invalid, even if the 8982 // address spaces would be compatible. 8983 // FIXME: This doesn't catch address space mismatches for pointers of 8984 // different nesting levels, like: 8985 // __local int *** a; 8986 // int ** b = a; 8987 // It's not clear how to actually determine when such pointers are 8988 // invalidly incompatible. 8989 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8990 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8991 8992 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8993 8994 if (lhptee == rhptee) 8995 return Sema::IncompatibleNestedPointerQualifiers; 8996 } 8997 8998 // General pointer incompatibility takes priority over qualifiers. 8999 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9000 return Sema::IncompatibleFunctionPointer; 9001 return Sema::IncompatiblePointer; 9002 } 9003 if (!S.getLangOpts().CPlusPlus && 9004 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9005 return Sema::IncompatibleFunctionPointer; 9006 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9007 return Sema::IncompatibleFunctionPointer; 9008 return ConvTy; 9009 } 9010 9011 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9012 /// block pointer types are compatible or whether a block and normal pointer 9013 /// are compatible. It is more restrict than comparing two function pointer 9014 // types. 9015 static Sema::AssignConvertType 9016 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9017 QualType RHSType) { 9018 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9019 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9020 9021 QualType lhptee, rhptee; 9022 9023 // get the "pointed to" type (ignoring qualifiers at the top level) 9024 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9025 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9026 9027 // In C++, the types have to match exactly. 9028 if (S.getLangOpts().CPlusPlus) 9029 return Sema::IncompatibleBlockPointer; 9030 9031 Sema::AssignConvertType ConvTy = Sema::Compatible; 9032 9033 // For blocks we enforce that qualifiers are identical. 9034 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9035 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9036 if (S.getLangOpts().OpenCL) { 9037 LQuals.removeAddressSpace(); 9038 RQuals.removeAddressSpace(); 9039 } 9040 if (LQuals != RQuals) 9041 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9042 9043 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9044 // assignment. 9045 // The current behavior is similar to C++ lambdas. A block might be 9046 // assigned to a variable iff its return type and parameters are compatible 9047 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9048 // an assignment. Presumably it should behave in way that a function pointer 9049 // assignment does in C, so for each parameter and return type: 9050 // * CVR and address space of LHS should be a superset of CVR and address 9051 // space of RHS. 9052 // * unqualified types should be compatible. 9053 if (S.getLangOpts().OpenCL) { 9054 if (!S.Context.typesAreBlockPointerCompatible( 9055 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9056 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9057 return Sema::IncompatibleBlockPointer; 9058 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9059 return Sema::IncompatibleBlockPointer; 9060 9061 return ConvTy; 9062 } 9063 9064 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9065 /// for assignment compatibility. 9066 static Sema::AssignConvertType 9067 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9068 QualType RHSType) { 9069 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9070 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9071 9072 if (LHSType->isObjCBuiltinType()) { 9073 // Class is not compatible with ObjC object pointers. 9074 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9075 !RHSType->isObjCQualifiedClassType()) 9076 return Sema::IncompatiblePointer; 9077 return Sema::Compatible; 9078 } 9079 if (RHSType->isObjCBuiltinType()) { 9080 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9081 !LHSType->isObjCQualifiedClassType()) 9082 return Sema::IncompatiblePointer; 9083 return Sema::Compatible; 9084 } 9085 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9086 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9087 9088 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9089 // make an exception for id<P> 9090 !LHSType->isObjCQualifiedIdType()) 9091 return Sema::CompatiblePointerDiscardsQualifiers; 9092 9093 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9094 return Sema::Compatible; 9095 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9096 return Sema::IncompatibleObjCQualifiedId; 9097 return Sema::IncompatiblePointer; 9098 } 9099 9100 Sema::AssignConvertType 9101 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9102 QualType LHSType, QualType RHSType) { 9103 // Fake up an opaque expression. We don't actually care about what 9104 // cast operations are required, so if CheckAssignmentConstraints 9105 // adds casts to this they'll be wasted, but fortunately that doesn't 9106 // usually happen on valid code. 9107 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9108 ExprResult RHSPtr = &RHSExpr; 9109 CastKind K; 9110 9111 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9112 } 9113 9114 /// This helper function returns true if QT is a vector type that has element 9115 /// type ElementType. 9116 static bool isVector(QualType QT, QualType ElementType) { 9117 if (const VectorType *VT = QT->getAs<VectorType>()) 9118 return VT->getElementType().getCanonicalType() == ElementType; 9119 return false; 9120 } 9121 9122 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9123 /// has code to accommodate several GCC extensions when type checking 9124 /// pointers. Here are some objectionable examples that GCC considers warnings: 9125 /// 9126 /// int a, *pint; 9127 /// short *pshort; 9128 /// struct foo *pfoo; 9129 /// 9130 /// pint = pshort; // warning: assignment from incompatible pointer type 9131 /// a = pint; // warning: assignment makes integer from pointer without a cast 9132 /// pint = a; // warning: assignment makes pointer from integer without a cast 9133 /// pint = pfoo; // warning: assignment from incompatible pointer type 9134 /// 9135 /// As a result, the code for dealing with pointers is more complex than the 9136 /// C99 spec dictates. 9137 /// 9138 /// Sets 'Kind' for any result kind except Incompatible. 9139 Sema::AssignConvertType 9140 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9141 CastKind &Kind, bool ConvertRHS) { 9142 QualType RHSType = RHS.get()->getType(); 9143 QualType OrigLHSType = LHSType; 9144 9145 // Get canonical types. We're not formatting these types, just comparing 9146 // them. 9147 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9148 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9149 9150 // Common case: no conversion required. 9151 if (LHSType == RHSType) { 9152 Kind = CK_NoOp; 9153 return Compatible; 9154 } 9155 9156 // If we have an atomic type, try a non-atomic assignment, then just add an 9157 // atomic qualification step. 9158 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9159 Sema::AssignConvertType result = 9160 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9161 if (result != Compatible) 9162 return result; 9163 if (Kind != CK_NoOp && ConvertRHS) 9164 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9165 Kind = CK_NonAtomicToAtomic; 9166 return Compatible; 9167 } 9168 9169 // If the left-hand side is a reference type, then we are in a 9170 // (rare!) case where we've allowed the use of references in C, 9171 // e.g., as a parameter type in a built-in function. In this case, 9172 // just make sure that the type referenced is compatible with the 9173 // right-hand side type. The caller is responsible for adjusting 9174 // LHSType so that the resulting expression does not have reference 9175 // type. 9176 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9177 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9178 Kind = CK_LValueBitCast; 9179 return Compatible; 9180 } 9181 return Incompatible; 9182 } 9183 9184 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9185 // to the same ExtVector type. 9186 if (LHSType->isExtVectorType()) { 9187 if (RHSType->isExtVectorType()) 9188 return Incompatible; 9189 if (RHSType->isArithmeticType()) { 9190 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9191 if (ConvertRHS) 9192 RHS = prepareVectorSplat(LHSType, RHS.get()); 9193 Kind = CK_VectorSplat; 9194 return Compatible; 9195 } 9196 } 9197 9198 // Conversions to or from vector type. 9199 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9200 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9201 // Allow assignments of an AltiVec vector type to an equivalent GCC 9202 // vector type and vice versa 9203 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9204 Kind = CK_BitCast; 9205 return Compatible; 9206 } 9207 9208 // If we are allowing lax vector conversions, and LHS and RHS are both 9209 // vectors, the total size only needs to be the same. This is a bitcast; 9210 // no bits are changed but the result type is different. 9211 if (isLaxVectorConversion(RHSType, LHSType)) { 9212 Kind = CK_BitCast; 9213 return IncompatibleVectors; 9214 } 9215 } 9216 9217 // When the RHS comes from another lax conversion (e.g. binops between 9218 // scalars and vectors) the result is canonicalized as a vector. When the 9219 // LHS is also a vector, the lax is allowed by the condition above. Handle 9220 // the case where LHS is a scalar. 9221 if (LHSType->isScalarType()) { 9222 const VectorType *VecType = RHSType->getAs<VectorType>(); 9223 if (VecType && VecType->getNumElements() == 1 && 9224 isLaxVectorConversion(RHSType, LHSType)) { 9225 ExprResult *VecExpr = &RHS; 9226 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9227 Kind = CK_BitCast; 9228 return Compatible; 9229 } 9230 } 9231 9232 // Allow assignments between fixed-length and sizeless SVE vectors. 9233 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9234 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9235 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9236 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9237 Kind = CK_BitCast; 9238 return Compatible; 9239 } 9240 9241 return Incompatible; 9242 } 9243 9244 // Diagnose attempts to convert between __float128 and long double where 9245 // such conversions currently can't be handled. 9246 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9247 return Incompatible; 9248 9249 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9250 // discards the imaginary part. 9251 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9252 !LHSType->getAs<ComplexType>()) 9253 return Incompatible; 9254 9255 // Arithmetic conversions. 9256 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9257 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9258 if (ConvertRHS) 9259 Kind = PrepareScalarCast(RHS, LHSType); 9260 return Compatible; 9261 } 9262 9263 // Conversions to normal pointers. 9264 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9265 // U* -> T* 9266 if (isa<PointerType>(RHSType)) { 9267 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9268 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9269 if (AddrSpaceL != AddrSpaceR) 9270 Kind = CK_AddressSpaceConversion; 9271 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9272 Kind = CK_NoOp; 9273 else 9274 Kind = CK_BitCast; 9275 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9276 } 9277 9278 // int -> T* 9279 if (RHSType->isIntegerType()) { 9280 Kind = CK_IntegralToPointer; // FIXME: null? 9281 return IntToPointer; 9282 } 9283 9284 // C pointers are not compatible with ObjC object pointers, 9285 // with two exceptions: 9286 if (isa<ObjCObjectPointerType>(RHSType)) { 9287 // - conversions to void* 9288 if (LHSPointer->getPointeeType()->isVoidType()) { 9289 Kind = CK_BitCast; 9290 return Compatible; 9291 } 9292 9293 // - conversions from 'Class' to the redefinition type 9294 if (RHSType->isObjCClassType() && 9295 Context.hasSameType(LHSType, 9296 Context.getObjCClassRedefinitionType())) { 9297 Kind = CK_BitCast; 9298 return Compatible; 9299 } 9300 9301 Kind = CK_BitCast; 9302 return IncompatiblePointer; 9303 } 9304 9305 // U^ -> void* 9306 if (RHSType->getAs<BlockPointerType>()) { 9307 if (LHSPointer->getPointeeType()->isVoidType()) { 9308 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9309 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9310 ->getPointeeType() 9311 .getAddressSpace(); 9312 Kind = 9313 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9314 return Compatible; 9315 } 9316 } 9317 9318 return Incompatible; 9319 } 9320 9321 // Conversions to block pointers. 9322 if (isa<BlockPointerType>(LHSType)) { 9323 // U^ -> T^ 9324 if (RHSType->isBlockPointerType()) { 9325 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9326 ->getPointeeType() 9327 .getAddressSpace(); 9328 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9329 ->getPointeeType() 9330 .getAddressSpace(); 9331 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9332 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9333 } 9334 9335 // int or null -> T^ 9336 if (RHSType->isIntegerType()) { 9337 Kind = CK_IntegralToPointer; // FIXME: null 9338 return IntToBlockPointer; 9339 } 9340 9341 // id -> T^ 9342 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9343 Kind = CK_AnyPointerToBlockPointerCast; 9344 return Compatible; 9345 } 9346 9347 // void* -> T^ 9348 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9349 if (RHSPT->getPointeeType()->isVoidType()) { 9350 Kind = CK_AnyPointerToBlockPointerCast; 9351 return Compatible; 9352 } 9353 9354 return Incompatible; 9355 } 9356 9357 // Conversions to Objective-C pointers. 9358 if (isa<ObjCObjectPointerType>(LHSType)) { 9359 // A* -> B* 9360 if (RHSType->isObjCObjectPointerType()) { 9361 Kind = CK_BitCast; 9362 Sema::AssignConvertType result = 9363 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9364 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9365 result == Compatible && 9366 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9367 result = IncompatibleObjCWeakRef; 9368 return result; 9369 } 9370 9371 // int or null -> A* 9372 if (RHSType->isIntegerType()) { 9373 Kind = CK_IntegralToPointer; // FIXME: null 9374 return IntToPointer; 9375 } 9376 9377 // In general, C pointers are not compatible with ObjC object pointers, 9378 // with two exceptions: 9379 if (isa<PointerType>(RHSType)) { 9380 Kind = CK_CPointerToObjCPointerCast; 9381 9382 // - conversions from 'void*' 9383 if (RHSType->isVoidPointerType()) { 9384 return Compatible; 9385 } 9386 9387 // - conversions to 'Class' from its redefinition type 9388 if (LHSType->isObjCClassType() && 9389 Context.hasSameType(RHSType, 9390 Context.getObjCClassRedefinitionType())) { 9391 return Compatible; 9392 } 9393 9394 return IncompatiblePointer; 9395 } 9396 9397 // Only under strict condition T^ is compatible with an Objective-C pointer. 9398 if (RHSType->isBlockPointerType() && 9399 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9400 if (ConvertRHS) 9401 maybeExtendBlockObject(RHS); 9402 Kind = CK_BlockPointerToObjCPointerCast; 9403 return Compatible; 9404 } 9405 9406 return Incompatible; 9407 } 9408 9409 // Conversions from pointers that are not covered by the above. 9410 if (isa<PointerType>(RHSType)) { 9411 // T* -> _Bool 9412 if (LHSType == Context.BoolTy) { 9413 Kind = CK_PointerToBoolean; 9414 return Compatible; 9415 } 9416 9417 // T* -> int 9418 if (LHSType->isIntegerType()) { 9419 Kind = CK_PointerToIntegral; 9420 return PointerToInt; 9421 } 9422 9423 return Incompatible; 9424 } 9425 9426 // Conversions from Objective-C pointers that are not covered by the above. 9427 if (isa<ObjCObjectPointerType>(RHSType)) { 9428 // T* -> _Bool 9429 if (LHSType == Context.BoolTy) { 9430 Kind = CK_PointerToBoolean; 9431 return Compatible; 9432 } 9433 9434 // T* -> int 9435 if (LHSType->isIntegerType()) { 9436 Kind = CK_PointerToIntegral; 9437 return PointerToInt; 9438 } 9439 9440 return Incompatible; 9441 } 9442 9443 // struct A -> struct B 9444 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9445 if (Context.typesAreCompatible(LHSType, RHSType)) { 9446 Kind = CK_NoOp; 9447 return Compatible; 9448 } 9449 } 9450 9451 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9452 Kind = CK_IntToOCLSampler; 9453 return Compatible; 9454 } 9455 9456 return Incompatible; 9457 } 9458 9459 /// Constructs a transparent union from an expression that is 9460 /// used to initialize the transparent union. 9461 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9462 ExprResult &EResult, QualType UnionType, 9463 FieldDecl *Field) { 9464 // Build an initializer list that designates the appropriate member 9465 // of the transparent union. 9466 Expr *E = EResult.get(); 9467 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9468 E, SourceLocation()); 9469 Initializer->setType(UnionType); 9470 Initializer->setInitializedFieldInUnion(Field); 9471 9472 // Build a compound literal constructing a value of the transparent 9473 // union type from this initializer list. 9474 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9475 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9476 VK_PRValue, Initializer, false); 9477 } 9478 9479 Sema::AssignConvertType 9480 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9481 ExprResult &RHS) { 9482 QualType RHSType = RHS.get()->getType(); 9483 9484 // If the ArgType is a Union type, we want to handle a potential 9485 // transparent_union GCC extension. 9486 const RecordType *UT = ArgType->getAsUnionType(); 9487 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9488 return Incompatible; 9489 9490 // The field to initialize within the transparent union. 9491 RecordDecl *UD = UT->getDecl(); 9492 FieldDecl *InitField = nullptr; 9493 // It's compatible if the expression matches any of the fields. 9494 for (auto *it : UD->fields()) { 9495 if (it->getType()->isPointerType()) { 9496 // If the transparent union contains a pointer type, we allow: 9497 // 1) void pointer 9498 // 2) null pointer constant 9499 if (RHSType->isPointerType()) 9500 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9501 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9502 InitField = it; 9503 break; 9504 } 9505 9506 if (RHS.get()->isNullPointerConstant(Context, 9507 Expr::NPC_ValueDependentIsNull)) { 9508 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9509 CK_NullToPointer); 9510 InitField = it; 9511 break; 9512 } 9513 } 9514 9515 CastKind Kind; 9516 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9517 == Compatible) { 9518 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9519 InitField = it; 9520 break; 9521 } 9522 } 9523 9524 if (!InitField) 9525 return Incompatible; 9526 9527 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9528 return Compatible; 9529 } 9530 9531 Sema::AssignConvertType 9532 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9533 bool Diagnose, 9534 bool DiagnoseCFAudited, 9535 bool ConvertRHS) { 9536 // We need to be able to tell the caller whether we diagnosed a problem, if 9537 // they ask us to issue diagnostics. 9538 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9539 9540 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9541 // we can't avoid *all* modifications at the moment, so we need some somewhere 9542 // to put the updated value. 9543 ExprResult LocalRHS = CallerRHS; 9544 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9545 9546 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9547 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9548 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9549 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9550 Diag(RHS.get()->getExprLoc(), 9551 diag::warn_noderef_to_dereferenceable_pointer) 9552 << RHS.get()->getSourceRange(); 9553 } 9554 } 9555 } 9556 9557 if (getLangOpts().CPlusPlus) { 9558 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9559 // C++ 5.17p3: If the left operand is not of class type, the 9560 // expression is implicitly converted (C++ 4) to the 9561 // cv-unqualified type of the left operand. 9562 QualType RHSType = RHS.get()->getType(); 9563 if (Diagnose) { 9564 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9565 AA_Assigning); 9566 } else { 9567 ImplicitConversionSequence ICS = 9568 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9569 /*SuppressUserConversions=*/false, 9570 AllowedExplicit::None, 9571 /*InOverloadResolution=*/false, 9572 /*CStyle=*/false, 9573 /*AllowObjCWritebackConversion=*/false); 9574 if (ICS.isFailure()) 9575 return Incompatible; 9576 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9577 ICS, AA_Assigning); 9578 } 9579 if (RHS.isInvalid()) 9580 return Incompatible; 9581 Sema::AssignConvertType result = Compatible; 9582 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9583 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9584 result = IncompatibleObjCWeakRef; 9585 return result; 9586 } 9587 9588 // FIXME: Currently, we fall through and treat C++ classes like C 9589 // structures. 9590 // FIXME: We also fall through for atomics; not sure what should 9591 // happen there, though. 9592 } else if (RHS.get()->getType() == Context.OverloadTy) { 9593 // As a set of extensions to C, we support overloading on functions. These 9594 // functions need to be resolved here. 9595 DeclAccessPair DAP; 9596 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9597 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9598 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9599 else 9600 return Incompatible; 9601 } 9602 9603 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9604 // a null pointer constant. 9605 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9606 LHSType->isBlockPointerType()) && 9607 RHS.get()->isNullPointerConstant(Context, 9608 Expr::NPC_ValueDependentIsNull)) { 9609 if (Diagnose || ConvertRHS) { 9610 CastKind Kind; 9611 CXXCastPath Path; 9612 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9613 /*IgnoreBaseAccess=*/false, Diagnose); 9614 if (ConvertRHS) 9615 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9616 } 9617 return Compatible; 9618 } 9619 9620 // OpenCL queue_t type assignment. 9621 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9622 Context, Expr::NPC_ValueDependentIsNull)) { 9623 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9624 return Compatible; 9625 } 9626 9627 // This check seems unnatural, however it is necessary to ensure the proper 9628 // conversion of functions/arrays. If the conversion were done for all 9629 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9630 // expressions that suppress this implicit conversion (&, sizeof). 9631 // 9632 // Suppress this for references: C++ 8.5.3p5. 9633 if (!LHSType->isReferenceType()) { 9634 // FIXME: We potentially allocate here even if ConvertRHS is false. 9635 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9636 if (RHS.isInvalid()) 9637 return Incompatible; 9638 } 9639 CastKind Kind; 9640 Sema::AssignConvertType result = 9641 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9642 9643 // C99 6.5.16.1p2: The value of the right operand is converted to the 9644 // type of the assignment expression. 9645 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9646 // so that we can use references in built-in functions even in C. 9647 // The getNonReferenceType() call makes sure that the resulting expression 9648 // does not have reference type. 9649 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9650 QualType Ty = LHSType.getNonLValueExprType(Context); 9651 Expr *E = RHS.get(); 9652 9653 // Check for various Objective-C errors. If we are not reporting 9654 // diagnostics and just checking for errors, e.g., during overload 9655 // resolution, return Incompatible to indicate the failure. 9656 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9657 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9658 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9659 if (!Diagnose) 9660 return Incompatible; 9661 } 9662 if (getLangOpts().ObjC && 9663 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9664 E->getType(), E, Diagnose) || 9665 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9666 if (!Diagnose) 9667 return Incompatible; 9668 // Replace the expression with a corrected version and continue so we 9669 // can find further errors. 9670 RHS = E; 9671 return Compatible; 9672 } 9673 9674 if (ConvertRHS) 9675 RHS = ImpCastExprToType(E, Ty, Kind); 9676 } 9677 9678 return result; 9679 } 9680 9681 namespace { 9682 /// The original operand to an operator, prior to the application of the usual 9683 /// arithmetic conversions and converting the arguments of a builtin operator 9684 /// candidate. 9685 struct OriginalOperand { 9686 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9687 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9688 Op = MTE->getSubExpr(); 9689 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9690 Op = BTE->getSubExpr(); 9691 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9692 Orig = ICE->getSubExprAsWritten(); 9693 Conversion = ICE->getConversionFunction(); 9694 } 9695 } 9696 9697 QualType getType() const { return Orig->getType(); } 9698 9699 Expr *Orig; 9700 NamedDecl *Conversion; 9701 }; 9702 } 9703 9704 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9705 ExprResult &RHS) { 9706 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9707 9708 Diag(Loc, diag::err_typecheck_invalid_operands) 9709 << OrigLHS.getType() << OrigRHS.getType() 9710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9711 9712 // If a user-defined conversion was applied to either of the operands prior 9713 // to applying the built-in operator rules, tell the user about it. 9714 if (OrigLHS.Conversion) { 9715 Diag(OrigLHS.Conversion->getLocation(), 9716 diag::note_typecheck_invalid_operands_converted) 9717 << 0 << LHS.get()->getType(); 9718 } 9719 if (OrigRHS.Conversion) { 9720 Diag(OrigRHS.Conversion->getLocation(), 9721 diag::note_typecheck_invalid_operands_converted) 9722 << 1 << RHS.get()->getType(); 9723 } 9724 9725 return QualType(); 9726 } 9727 9728 // Diagnose cases where a scalar was implicitly converted to a vector and 9729 // diagnose the underlying types. Otherwise, diagnose the error 9730 // as invalid vector logical operands for non-C++ cases. 9731 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9732 ExprResult &RHS) { 9733 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9734 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9735 9736 bool LHSNatVec = LHSType->isVectorType(); 9737 bool RHSNatVec = RHSType->isVectorType(); 9738 9739 if (!(LHSNatVec && RHSNatVec)) { 9740 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9741 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9742 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9743 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9744 << Vector->getSourceRange(); 9745 return QualType(); 9746 } 9747 9748 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9749 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9750 << RHS.get()->getSourceRange(); 9751 9752 return QualType(); 9753 } 9754 9755 /// Try to convert a value of non-vector type to a vector type by converting 9756 /// the type to the element type of the vector and then performing a splat. 9757 /// If the language is OpenCL, we only use conversions that promote scalar 9758 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9759 /// for float->int. 9760 /// 9761 /// OpenCL V2.0 6.2.6.p2: 9762 /// An error shall occur if any scalar operand type has greater rank 9763 /// than the type of the vector element. 9764 /// 9765 /// \param scalar - if non-null, actually perform the conversions 9766 /// \return true if the operation fails (but without diagnosing the failure) 9767 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9768 QualType scalarTy, 9769 QualType vectorEltTy, 9770 QualType vectorTy, 9771 unsigned &DiagID) { 9772 // The conversion to apply to the scalar before splatting it, 9773 // if necessary. 9774 CastKind scalarCast = CK_NoOp; 9775 9776 if (vectorEltTy->isIntegralType(S.Context)) { 9777 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9778 (scalarTy->isIntegerType() && 9779 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9780 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9781 return true; 9782 } 9783 if (!scalarTy->isIntegralType(S.Context)) 9784 return true; 9785 scalarCast = CK_IntegralCast; 9786 } else if (vectorEltTy->isRealFloatingType()) { 9787 if (scalarTy->isRealFloatingType()) { 9788 if (S.getLangOpts().OpenCL && 9789 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9790 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9791 return true; 9792 } 9793 scalarCast = CK_FloatingCast; 9794 } 9795 else if (scalarTy->isIntegralType(S.Context)) 9796 scalarCast = CK_IntegralToFloating; 9797 else 9798 return true; 9799 } else { 9800 return true; 9801 } 9802 9803 // Adjust scalar if desired. 9804 if (scalar) { 9805 if (scalarCast != CK_NoOp) 9806 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9807 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9808 } 9809 return false; 9810 } 9811 9812 /// Convert vector E to a vector with the same number of elements but different 9813 /// element type. 9814 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9815 const auto *VecTy = E->getType()->getAs<VectorType>(); 9816 assert(VecTy && "Expression E must be a vector"); 9817 QualType NewVecTy = S.Context.getVectorType(ElementType, 9818 VecTy->getNumElements(), 9819 VecTy->getVectorKind()); 9820 9821 // Look through the implicit cast. Return the subexpression if its type is 9822 // NewVecTy. 9823 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9824 if (ICE->getSubExpr()->getType() == NewVecTy) 9825 return ICE->getSubExpr(); 9826 9827 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9828 return S.ImpCastExprToType(E, NewVecTy, Cast); 9829 } 9830 9831 /// Test if a (constant) integer Int can be casted to another integer type 9832 /// IntTy without losing precision. 9833 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9834 QualType OtherIntTy) { 9835 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9836 9837 // Reject cases where the value of the Int is unknown as that would 9838 // possibly cause truncation, but accept cases where the scalar can be 9839 // demoted without loss of precision. 9840 Expr::EvalResult EVResult; 9841 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9842 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9843 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9844 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9845 9846 if (CstInt) { 9847 // If the scalar is constant and is of a higher order and has more active 9848 // bits that the vector element type, reject it. 9849 llvm::APSInt Result = EVResult.Val.getInt(); 9850 unsigned NumBits = IntSigned 9851 ? (Result.isNegative() ? Result.getMinSignedBits() 9852 : Result.getActiveBits()) 9853 : Result.getActiveBits(); 9854 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9855 return true; 9856 9857 // If the signedness of the scalar type and the vector element type 9858 // differs and the number of bits is greater than that of the vector 9859 // element reject it. 9860 return (IntSigned != OtherIntSigned && 9861 NumBits > S.Context.getIntWidth(OtherIntTy)); 9862 } 9863 9864 // Reject cases where the value of the scalar is not constant and it's 9865 // order is greater than that of the vector element type. 9866 return (Order < 0); 9867 } 9868 9869 /// Test if a (constant) integer Int can be casted to floating point type 9870 /// FloatTy without losing precision. 9871 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9872 QualType FloatTy) { 9873 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9874 9875 // Determine if the integer constant can be expressed as a floating point 9876 // number of the appropriate type. 9877 Expr::EvalResult EVResult; 9878 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9879 9880 uint64_t Bits = 0; 9881 if (CstInt) { 9882 // Reject constants that would be truncated if they were converted to 9883 // the floating point type. Test by simple to/from conversion. 9884 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9885 // could be avoided if there was a convertFromAPInt method 9886 // which could signal back if implicit truncation occurred. 9887 llvm::APSInt Result = EVResult.Val.getInt(); 9888 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9889 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9890 llvm::APFloat::rmTowardZero); 9891 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9892 !IntTy->hasSignedIntegerRepresentation()); 9893 bool Ignored = false; 9894 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9895 &Ignored); 9896 if (Result != ConvertBack) 9897 return true; 9898 } else { 9899 // Reject types that cannot be fully encoded into the mantissa of 9900 // the float. 9901 Bits = S.Context.getTypeSize(IntTy); 9902 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9903 S.Context.getFloatTypeSemantics(FloatTy)); 9904 if (Bits > FloatPrec) 9905 return true; 9906 } 9907 9908 return false; 9909 } 9910 9911 /// Attempt to convert and splat Scalar into a vector whose types matches 9912 /// Vector following GCC conversion rules. The rule is that implicit 9913 /// conversion can occur when Scalar can be casted to match Vector's element 9914 /// type without causing truncation of Scalar. 9915 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9916 ExprResult *Vector) { 9917 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9918 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9919 const VectorType *VT = VectorTy->getAs<VectorType>(); 9920 9921 assert(!isa<ExtVectorType>(VT) && 9922 "ExtVectorTypes should not be handled here!"); 9923 9924 QualType VectorEltTy = VT->getElementType(); 9925 9926 // Reject cases where the vector element type or the scalar element type are 9927 // not integral or floating point types. 9928 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9929 return true; 9930 9931 // The conversion to apply to the scalar before splatting it, 9932 // if necessary. 9933 CastKind ScalarCast = CK_NoOp; 9934 9935 // Accept cases where the vector elements are integers and the scalar is 9936 // an integer. 9937 // FIXME: Notionally if the scalar was a floating point value with a precise 9938 // integral representation, we could cast it to an appropriate integer 9939 // type and then perform the rest of the checks here. GCC will perform 9940 // this conversion in some cases as determined by the input language. 9941 // We should accept it on a language independent basis. 9942 if (VectorEltTy->isIntegralType(S.Context) && 9943 ScalarTy->isIntegralType(S.Context) && 9944 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9945 9946 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9947 return true; 9948 9949 ScalarCast = CK_IntegralCast; 9950 } else if (VectorEltTy->isIntegralType(S.Context) && 9951 ScalarTy->isRealFloatingType()) { 9952 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9953 ScalarCast = CK_FloatingToIntegral; 9954 else 9955 return true; 9956 } else if (VectorEltTy->isRealFloatingType()) { 9957 if (ScalarTy->isRealFloatingType()) { 9958 9959 // Reject cases where the scalar type is not a constant and has a higher 9960 // Order than the vector element type. 9961 llvm::APFloat Result(0.0); 9962 9963 // Determine whether this is a constant scalar. In the event that the 9964 // value is dependent (and thus cannot be evaluated by the constant 9965 // evaluator), skip the evaluation. This will then diagnose once the 9966 // expression is instantiated. 9967 bool CstScalar = Scalar->get()->isValueDependent() || 9968 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9969 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9970 if (!CstScalar && Order < 0) 9971 return true; 9972 9973 // If the scalar cannot be safely casted to the vector element type, 9974 // reject it. 9975 if (CstScalar) { 9976 bool Truncated = false; 9977 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9978 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9979 if (Truncated) 9980 return true; 9981 } 9982 9983 ScalarCast = CK_FloatingCast; 9984 } else if (ScalarTy->isIntegralType(S.Context)) { 9985 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9986 return true; 9987 9988 ScalarCast = CK_IntegralToFloating; 9989 } else 9990 return true; 9991 } else if (ScalarTy->isEnumeralType()) 9992 return true; 9993 9994 // Adjust scalar if desired. 9995 if (Scalar) { 9996 if (ScalarCast != CK_NoOp) 9997 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9998 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9999 } 10000 return false; 10001 } 10002 10003 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10004 SourceLocation Loc, bool IsCompAssign, 10005 bool AllowBothBool, 10006 bool AllowBoolConversions) { 10007 if (!IsCompAssign) { 10008 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10009 if (LHS.isInvalid()) 10010 return QualType(); 10011 } 10012 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10013 if (RHS.isInvalid()) 10014 return QualType(); 10015 10016 // For conversion purposes, we ignore any qualifiers. 10017 // For example, "const float" and "float" are equivalent. 10018 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10019 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10020 10021 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10022 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10023 assert(LHSVecType || RHSVecType); 10024 10025 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10026 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10027 return InvalidOperands(Loc, LHS, RHS); 10028 10029 // AltiVec-style "vector bool op vector bool" combinations are allowed 10030 // for some operators but not others. 10031 if (!AllowBothBool && 10032 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10033 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10034 return InvalidOperands(Loc, LHS, RHS); 10035 10036 // If the vector types are identical, return. 10037 if (Context.hasSameType(LHSType, RHSType)) 10038 return LHSType; 10039 10040 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10041 if (LHSVecType && RHSVecType && 10042 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10043 if (isa<ExtVectorType>(LHSVecType)) { 10044 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10045 return LHSType; 10046 } 10047 10048 if (!IsCompAssign) 10049 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10050 return RHSType; 10051 } 10052 10053 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10054 // can be mixed, with the result being the non-bool type. The non-bool 10055 // operand must have integer element type. 10056 if (AllowBoolConversions && LHSVecType && RHSVecType && 10057 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10058 (Context.getTypeSize(LHSVecType->getElementType()) == 10059 Context.getTypeSize(RHSVecType->getElementType()))) { 10060 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10061 LHSVecType->getElementType()->isIntegerType() && 10062 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10063 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10064 return LHSType; 10065 } 10066 if (!IsCompAssign && 10067 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10068 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10069 RHSVecType->getElementType()->isIntegerType()) { 10070 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10071 return RHSType; 10072 } 10073 } 10074 10075 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10076 // since the ambiguity can affect the ABI. 10077 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10078 const VectorType *VecType = SecondType->getAs<VectorType>(); 10079 return FirstType->isSizelessBuiltinType() && VecType && 10080 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10081 VecType->getVectorKind() == 10082 VectorType::SveFixedLengthPredicateVector); 10083 }; 10084 10085 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10086 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10087 return QualType(); 10088 } 10089 10090 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10091 // since the ambiguity can affect the ABI. 10092 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10093 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10094 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10095 10096 if (FirstVecType && SecondVecType) 10097 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10098 (SecondVecType->getVectorKind() == 10099 VectorType::SveFixedLengthDataVector || 10100 SecondVecType->getVectorKind() == 10101 VectorType::SveFixedLengthPredicateVector); 10102 10103 return FirstType->isSizelessBuiltinType() && SecondVecType && 10104 SecondVecType->getVectorKind() == VectorType::GenericVector; 10105 }; 10106 10107 if (IsSveGnuConversion(LHSType, RHSType) || 10108 IsSveGnuConversion(RHSType, LHSType)) { 10109 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10110 return QualType(); 10111 } 10112 10113 // If there's a vector type and a scalar, try to convert the scalar to 10114 // the vector element type and splat. 10115 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10116 if (!RHSVecType) { 10117 if (isa<ExtVectorType>(LHSVecType)) { 10118 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10119 LHSVecType->getElementType(), LHSType, 10120 DiagID)) 10121 return LHSType; 10122 } else { 10123 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10124 return LHSType; 10125 } 10126 } 10127 if (!LHSVecType) { 10128 if (isa<ExtVectorType>(RHSVecType)) { 10129 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10130 LHSType, RHSVecType->getElementType(), 10131 RHSType, DiagID)) 10132 return RHSType; 10133 } else { 10134 if (LHS.get()->getValueKind() == VK_LValue || 10135 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10136 return RHSType; 10137 } 10138 } 10139 10140 // FIXME: The code below also handles conversion between vectors and 10141 // non-scalars, we should break this down into fine grained specific checks 10142 // and emit proper diagnostics. 10143 QualType VecType = LHSVecType ? LHSType : RHSType; 10144 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10145 QualType OtherType = LHSVecType ? RHSType : LHSType; 10146 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10147 if (isLaxVectorConversion(OtherType, VecType)) { 10148 // If we're allowing lax vector conversions, only the total (data) size 10149 // needs to be the same. For non compound assignment, if one of the types is 10150 // scalar, the result is always the vector type. 10151 if (!IsCompAssign) { 10152 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10153 return VecType; 10154 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10155 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10156 // type. Note that this is already done by non-compound assignments in 10157 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10158 // <1 x T> -> T. The result is also a vector type. 10159 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10160 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10161 ExprResult *RHSExpr = &RHS; 10162 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10163 return VecType; 10164 } 10165 } 10166 10167 // Okay, the expression is invalid. 10168 10169 // If there's a non-vector, non-real operand, diagnose that. 10170 if ((!RHSVecType && !RHSType->isRealType()) || 10171 (!LHSVecType && !LHSType->isRealType())) { 10172 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10173 << LHSType << RHSType 10174 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10175 return QualType(); 10176 } 10177 10178 // OpenCL V1.1 6.2.6.p1: 10179 // If the operands are of more than one vector type, then an error shall 10180 // occur. Implicit conversions between vector types are not permitted, per 10181 // section 6.2.1. 10182 if (getLangOpts().OpenCL && 10183 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10184 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10185 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10186 << RHSType; 10187 return QualType(); 10188 } 10189 10190 10191 // If there is a vector type that is not a ExtVector and a scalar, we reach 10192 // this point if scalar could not be converted to the vector's element type 10193 // without truncation. 10194 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10195 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10196 QualType Scalar = LHSVecType ? RHSType : LHSType; 10197 QualType Vector = LHSVecType ? LHSType : RHSType; 10198 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10199 Diag(Loc, 10200 diag::err_typecheck_vector_not_convertable_implict_truncation) 10201 << ScalarOrVector << Scalar << Vector; 10202 10203 return QualType(); 10204 } 10205 10206 // Otherwise, use the generic diagnostic. 10207 Diag(Loc, DiagID) 10208 << LHSType << RHSType 10209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10210 return QualType(); 10211 } 10212 10213 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10214 // expression. These are mainly cases where the null pointer is used as an 10215 // integer instead of a pointer. 10216 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10217 SourceLocation Loc, bool IsCompare) { 10218 // The canonical way to check for a GNU null is with isNullPointerConstant, 10219 // but we use a bit of a hack here for speed; this is a relatively 10220 // hot path, and isNullPointerConstant is slow. 10221 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10222 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10223 10224 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10225 10226 // Avoid analyzing cases where the result will either be invalid (and 10227 // diagnosed as such) or entirely valid and not something to warn about. 10228 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10229 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10230 return; 10231 10232 // Comparison operations would not make sense with a null pointer no matter 10233 // what the other expression is. 10234 if (!IsCompare) { 10235 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10236 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10237 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10238 return; 10239 } 10240 10241 // The rest of the operations only make sense with a null pointer 10242 // if the other expression is a pointer. 10243 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10244 NonNullType->canDecayToPointerType()) 10245 return; 10246 10247 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10248 << LHSNull /* LHS is NULL */ << NonNullType 10249 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10250 } 10251 10252 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10253 SourceLocation Loc) { 10254 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10255 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10256 if (!LUE || !RUE) 10257 return; 10258 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10259 RUE->getKind() != UETT_SizeOf) 10260 return; 10261 10262 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10263 QualType LHSTy = LHSArg->getType(); 10264 QualType RHSTy; 10265 10266 if (RUE->isArgumentType()) 10267 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10268 else 10269 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10270 10271 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10272 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10273 return; 10274 10275 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10276 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10277 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10278 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10279 << LHSArgDecl; 10280 } 10281 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10282 QualType ArrayElemTy = ArrayTy->getElementType(); 10283 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10284 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10285 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10286 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10287 return; 10288 S.Diag(Loc, diag::warn_division_sizeof_array) 10289 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10290 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10291 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10292 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10293 << LHSArgDecl; 10294 } 10295 10296 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10297 } 10298 } 10299 10300 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10301 ExprResult &RHS, 10302 SourceLocation Loc, bool IsDiv) { 10303 // Check for division/remainder by zero. 10304 Expr::EvalResult RHSValue; 10305 if (!RHS.get()->isValueDependent() && 10306 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10307 RHSValue.Val.getInt() == 0) 10308 S.DiagRuntimeBehavior(Loc, RHS.get(), 10309 S.PDiag(diag::warn_remainder_division_by_zero) 10310 << IsDiv << RHS.get()->getSourceRange()); 10311 } 10312 10313 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10314 SourceLocation Loc, 10315 bool IsCompAssign, bool IsDiv) { 10316 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10317 10318 QualType LHSTy = LHS.get()->getType(); 10319 QualType RHSTy = RHS.get()->getType(); 10320 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10321 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10322 /*AllowBothBool*/getLangOpts().AltiVec, 10323 /*AllowBoolConversions*/false); 10324 if (!IsDiv && 10325 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10326 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10327 // For division, only matrix-by-scalar is supported. Other combinations with 10328 // matrix types are invalid. 10329 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10330 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10331 10332 QualType compType = UsualArithmeticConversions( 10333 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10334 if (LHS.isInvalid() || RHS.isInvalid()) 10335 return QualType(); 10336 10337 10338 if (compType.isNull() || !compType->isArithmeticType()) 10339 return InvalidOperands(Loc, LHS, RHS); 10340 if (IsDiv) { 10341 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10342 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10343 } 10344 return compType; 10345 } 10346 10347 QualType Sema::CheckRemainderOperands( 10348 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10349 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10350 10351 if (LHS.get()->getType()->isVectorType() || 10352 RHS.get()->getType()->isVectorType()) { 10353 if (LHS.get()->getType()->hasIntegerRepresentation() && 10354 RHS.get()->getType()->hasIntegerRepresentation()) 10355 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10356 /*AllowBothBool*/getLangOpts().AltiVec, 10357 /*AllowBoolConversions*/false); 10358 return InvalidOperands(Loc, LHS, RHS); 10359 } 10360 10361 QualType compType = UsualArithmeticConversions( 10362 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10363 if (LHS.isInvalid() || RHS.isInvalid()) 10364 return QualType(); 10365 10366 if (compType.isNull() || !compType->isIntegerType()) 10367 return InvalidOperands(Loc, LHS, RHS); 10368 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10369 return compType; 10370 } 10371 10372 /// Diagnose invalid arithmetic on two void pointers. 10373 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10374 Expr *LHSExpr, Expr *RHSExpr) { 10375 S.Diag(Loc, S.getLangOpts().CPlusPlus 10376 ? diag::err_typecheck_pointer_arith_void_type 10377 : diag::ext_gnu_void_ptr) 10378 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10379 << RHSExpr->getSourceRange(); 10380 } 10381 10382 /// Diagnose invalid arithmetic on a void pointer. 10383 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10384 Expr *Pointer) { 10385 S.Diag(Loc, S.getLangOpts().CPlusPlus 10386 ? diag::err_typecheck_pointer_arith_void_type 10387 : diag::ext_gnu_void_ptr) 10388 << 0 /* one pointer */ << Pointer->getSourceRange(); 10389 } 10390 10391 /// Diagnose invalid arithmetic on a null pointer. 10392 /// 10393 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10394 /// idiom, which we recognize as a GNU extension. 10395 /// 10396 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10397 Expr *Pointer, bool IsGNUIdiom) { 10398 if (IsGNUIdiom) 10399 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10400 << Pointer->getSourceRange(); 10401 else 10402 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10403 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10404 } 10405 10406 /// Diagnose invalid arithmetic on two function pointers. 10407 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10408 Expr *LHS, Expr *RHS) { 10409 assert(LHS->getType()->isAnyPointerType()); 10410 assert(RHS->getType()->isAnyPointerType()); 10411 S.Diag(Loc, S.getLangOpts().CPlusPlus 10412 ? diag::err_typecheck_pointer_arith_function_type 10413 : diag::ext_gnu_ptr_func_arith) 10414 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10415 // We only show the second type if it differs from the first. 10416 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10417 RHS->getType()) 10418 << RHS->getType()->getPointeeType() 10419 << LHS->getSourceRange() << RHS->getSourceRange(); 10420 } 10421 10422 /// Diagnose invalid arithmetic on a function pointer. 10423 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10424 Expr *Pointer) { 10425 assert(Pointer->getType()->isAnyPointerType()); 10426 S.Diag(Loc, S.getLangOpts().CPlusPlus 10427 ? diag::err_typecheck_pointer_arith_function_type 10428 : diag::ext_gnu_ptr_func_arith) 10429 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10430 << 0 /* one pointer, so only one type */ 10431 << Pointer->getSourceRange(); 10432 } 10433 10434 /// Emit error if Operand is incomplete pointer type 10435 /// 10436 /// \returns True if pointer has incomplete type 10437 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10438 Expr *Operand) { 10439 QualType ResType = Operand->getType(); 10440 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10441 ResType = ResAtomicType->getValueType(); 10442 10443 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10444 QualType PointeeTy = ResType->getPointeeType(); 10445 return S.RequireCompleteSizedType( 10446 Loc, PointeeTy, 10447 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10448 Operand->getSourceRange()); 10449 } 10450 10451 /// Check the validity of an arithmetic pointer operand. 10452 /// 10453 /// If the operand has pointer type, this code will check for pointer types 10454 /// which are invalid in arithmetic operations. These will be diagnosed 10455 /// appropriately, including whether or not the use is supported as an 10456 /// extension. 10457 /// 10458 /// \returns True when the operand is valid to use (even if as an extension). 10459 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10460 Expr *Operand) { 10461 QualType ResType = Operand->getType(); 10462 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10463 ResType = ResAtomicType->getValueType(); 10464 10465 if (!ResType->isAnyPointerType()) return true; 10466 10467 QualType PointeeTy = ResType->getPointeeType(); 10468 if (PointeeTy->isVoidType()) { 10469 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10470 return !S.getLangOpts().CPlusPlus; 10471 } 10472 if (PointeeTy->isFunctionType()) { 10473 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10474 return !S.getLangOpts().CPlusPlus; 10475 } 10476 10477 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10478 10479 return true; 10480 } 10481 10482 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10483 /// operands. 10484 /// 10485 /// This routine will diagnose any invalid arithmetic on pointer operands much 10486 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10487 /// for emitting a single diagnostic even for operations where both LHS and RHS 10488 /// are (potentially problematic) pointers. 10489 /// 10490 /// \returns True when the operand is valid to use (even if as an extension). 10491 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10492 Expr *LHSExpr, Expr *RHSExpr) { 10493 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10494 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10495 if (!isLHSPointer && !isRHSPointer) return true; 10496 10497 QualType LHSPointeeTy, RHSPointeeTy; 10498 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10499 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10500 10501 // if both are pointers check if operation is valid wrt address spaces 10502 if (isLHSPointer && isRHSPointer) { 10503 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10504 S.Diag(Loc, 10505 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10506 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10507 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10508 return false; 10509 } 10510 } 10511 10512 // Check for arithmetic on pointers to incomplete types. 10513 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10514 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10515 if (isLHSVoidPtr || isRHSVoidPtr) { 10516 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10517 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10518 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10519 10520 return !S.getLangOpts().CPlusPlus; 10521 } 10522 10523 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10524 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10525 if (isLHSFuncPtr || isRHSFuncPtr) { 10526 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10527 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10528 RHSExpr); 10529 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10530 10531 return !S.getLangOpts().CPlusPlus; 10532 } 10533 10534 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10535 return false; 10536 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10537 return false; 10538 10539 return true; 10540 } 10541 10542 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10543 /// literal. 10544 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10545 Expr *LHSExpr, Expr *RHSExpr) { 10546 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10547 Expr* IndexExpr = RHSExpr; 10548 if (!StrExpr) { 10549 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10550 IndexExpr = LHSExpr; 10551 } 10552 10553 bool IsStringPlusInt = StrExpr && 10554 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10555 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10556 return; 10557 10558 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10559 Self.Diag(OpLoc, diag::warn_string_plus_int) 10560 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10561 10562 // Only print a fixit for "str" + int, not for int + "str". 10563 if (IndexExpr == RHSExpr) { 10564 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10565 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10566 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10567 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10568 << FixItHint::CreateInsertion(EndLoc, "]"); 10569 } else 10570 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10571 } 10572 10573 /// Emit a warning when adding a char literal to a string. 10574 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10575 Expr *LHSExpr, Expr *RHSExpr) { 10576 const Expr *StringRefExpr = LHSExpr; 10577 const CharacterLiteral *CharExpr = 10578 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10579 10580 if (!CharExpr) { 10581 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10582 StringRefExpr = RHSExpr; 10583 } 10584 10585 if (!CharExpr || !StringRefExpr) 10586 return; 10587 10588 const QualType StringType = StringRefExpr->getType(); 10589 10590 // Return if not a PointerType. 10591 if (!StringType->isAnyPointerType()) 10592 return; 10593 10594 // Return if not a CharacterType. 10595 if (!StringType->getPointeeType()->isAnyCharacterType()) 10596 return; 10597 10598 ASTContext &Ctx = Self.getASTContext(); 10599 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10600 10601 const QualType CharType = CharExpr->getType(); 10602 if (!CharType->isAnyCharacterType() && 10603 CharType->isIntegerType() && 10604 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10605 Self.Diag(OpLoc, diag::warn_string_plus_char) 10606 << DiagRange << Ctx.CharTy; 10607 } else { 10608 Self.Diag(OpLoc, diag::warn_string_plus_char) 10609 << DiagRange << CharExpr->getType(); 10610 } 10611 10612 // Only print a fixit for str + char, not for char + str. 10613 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10614 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10615 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10616 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10617 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10618 << FixItHint::CreateInsertion(EndLoc, "]"); 10619 } else { 10620 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10621 } 10622 } 10623 10624 /// Emit error when two pointers are incompatible. 10625 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10626 Expr *LHSExpr, Expr *RHSExpr) { 10627 assert(LHSExpr->getType()->isAnyPointerType()); 10628 assert(RHSExpr->getType()->isAnyPointerType()); 10629 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10630 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10631 << RHSExpr->getSourceRange(); 10632 } 10633 10634 // C99 6.5.6 10635 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10636 SourceLocation Loc, BinaryOperatorKind Opc, 10637 QualType* CompLHSTy) { 10638 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10639 10640 if (LHS.get()->getType()->isVectorType() || 10641 RHS.get()->getType()->isVectorType()) { 10642 QualType compType = CheckVectorOperands( 10643 LHS, RHS, Loc, CompLHSTy, 10644 /*AllowBothBool*/getLangOpts().AltiVec, 10645 /*AllowBoolConversions*/getLangOpts().ZVector); 10646 if (CompLHSTy) *CompLHSTy = compType; 10647 return compType; 10648 } 10649 10650 if (LHS.get()->getType()->isConstantMatrixType() || 10651 RHS.get()->getType()->isConstantMatrixType()) { 10652 QualType compType = 10653 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10654 if (CompLHSTy) 10655 *CompLHSTy = compType; 10656 return compType; 10657 } 10658 10659 QualType compType = UsualArithmeticConversions( 10660 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10661 if (LHS.isInvalid() || RHS.isInvalid()) 10662 return QualType(); 10663 10664 // Diagnose "string literal" '+' int and string '+' "char literal". 10665 if (Opc == BO_Add) { 10666 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10667 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10668 } 10669 10670 // handle the common case first (both operands are arithmetic). 10671 if (!compType.isNull() && compType->isArithmeticType()) { 10672 if (CompLHSTy) *CompLHSTy = compType; 10673 return compType; 10674 } 10675 10676 // Type-checking. Ultimately the pointer's going to be in PExp; 10677 // note that we bias towards the LHS being the pointer. 10678 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10679 10680 bool isObjCPointer; 10681 if (PExp->getType()->isPointerType()) { 10682 isObjCPointer = false; 10683 } else if (PExp->getType()->isObjCObjectPointerType()) { 10684 isObjCPointer = true; 10685 } else { 10686 std::swap(PExp, IExp); 10687 if (PExp->getType()->isPointerType()) { 10688 isObjCPointer = false; 10689 } else if (PExp->getType()->isObjCObjectPointerType()) { 10690 isObjCPointer = true; 10691 } else { 10692 return InvalidOperands(Loc, LHS, RHS); 10693 } 10694 } 10695 assert(PExp->getType()->isAnyPointerType()); 10696 10697 if (!IExp->getType()->isIntegerType()) 10698 return InvalidOperands(Loc, LHS, RHS); 10699 10700 // Adding to a null pointer results in undefined behavior. 10701 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10702 Context, Expr::NPC_ValueDependentIsNotNull)) { 10703 // In C++ adding zero to a null pointer is defined. 10704 Expr::EvalResult KnownVal; 10705 if (!getLangOpts().CPlusPlus || 10706 (!IExp->isValueDependent() && 10707 (!IExp->EvaluateAsInt(KnownVal, Context) || 10708 KnownVal.Val.getInt() != 0))) { 10709 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10710 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10711 Context, BO_Add, PExp, IExp); 10712 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10713 } 10714 } 10715 10716 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10717 return QualType(); 10718 10719 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10720 return QualType(); 10721 10722 // Check array bounds for pointer arithemtic 10723 CheckArrayAccess(PExp, IExp); 10724 10725 if (CompLHSTy) { 10726 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10727 if (LHSTy.isNull()) { 10728 LHSTy = LHS.get()->getType(); 10729 if (LHSTy->isPromotableIntegerType()) 10730 LHSTy = Context.getPromotedIntegerType(LHSTy); 10731 } 10732 *CompLHSTy = LHSTy; 10733 } 10734 10735 return PExp->getType(); 10736 } 10737 10738 // C99 6.5.6 10739 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10740 SourceLocation Loc, 10741 QualType* CompLHSTy) { 10742 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10743 10744 if (LHS.get()->getType()->isVectorType() || 10745 RHS.get()->getType()->isVectorType()) { 10746 QualType compType = CheckVectorOperands( 10747 LHS, RHS, Loc, CompLHSTy, 10748 /*AllowBothBool*/getLangOpts().AltiVec, 10749 /*AllowBoolConversions*/getLangOpts().ZVector); 10750 if (CompLHSTy) *CompLHSTy = compType; 10751 return compType; 10752 } 10753 10754 if (LHS.get()->getType()->isConstantMatrixType() || 10755 RHS.get()->getType()->isConstantMatrixType()) { 10756 QualType compType = 10757 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10758 if (CompLHSTy) 10759 *CompLHSTy = compType; 10760 return compType; 10761 } 10762 10763 QualType compType = UsualArithmeticConversions( 10764 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10765 if (LHS.isInvalid() || RHS.isInvalid()) 10766 return QualType(); 10767 10768 // Enforce type constraints: C99 6.5.6p3. 10769 10770 // Handle the common case first (both operands are arithmetic). 10771 if (!compType.isNull() && compType->isArithmeticType()) { 10772 if (CompLHSTy) *CompLHSTy = compType; 10773 return compType; 10774 } 10775 10776 // Either ptr - int or ptr - ptr. 10777 if (LHS.get()->getType()->isAnyPointerType()) { 10778 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10779 10780 // Diagnose bad cases where we step over interface counts. 10781 if (LHS.get()->getType()->isObjCObjectPointerType() && 10782 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10783 return QualType(); 10784 10785 // The result type of a pointer-int computation is the pointer type. 10786 if (RHS.get()->getType()->isIntegerType()) { 10787 // Subtracting from a null pointer should produce a warning. 10788 // The last argument to the diagnose call says this doesn't match the 10789 // GNU int-to-pointer idiom. 10790 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10791 Expr::NPC_ValueDependentIsNotNull)) { 10792 // In C++ adding zero to a null pointer is defined. 10793 Expr::EvalResult KnownVal; 10794 if (!getLangOpts().CPlusPlus || 10795 (!RHS.get()->isValueDependent() && 10796 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10797 KnownVal.Val.getInt() != 0))) { 10798 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10799 } 10800 } 10801 10802 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10803 return QualType(); 10804 10805 // Check array bounds for pointer arithemtic 10806 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10807 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10808 10809 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10810 return LHS.get()->getType(); 10811 } 10812 10813 // Handle pointer-pointer subtractions. 10814 if (const PointerType *RHSPTy 10815 = RHS.get()->getType()->getAs<PointerType>()) { 10816 QualType rpointee = RHSPTy->getPointeeType(); 10817 10818 if (getLangOpts().CPlusPlus) { 10819 // Pointee types must be the same: C++ [expr.add] 10820 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10821 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10822 } 10823 } else { 10824 // Pointee types must be compatible C99 6.5.6p3 10825 if (!Context.typesAreCompatible( 10826 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10827 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10828 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10829 return QualType(); 10830 } 10831 } 10832 10833 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10834 LHS.get(), RHS.get())) 10835 return QualType(); 10836 10837 // FIXME: Add warnings for nullptr - ptr. 10838 10839 // The pointee type may have zero size. As an extension, a structure or 10840 // union may have zero size or an array may have zero length. In this 10841 // case subtraction does not make sense. 10842 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10843 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10844 if (ElementSize.isZero()) { 10845 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10846 << rpointee.getUnqualifiedType() 10847 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10848 } 10849 } 10850 10851 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10852 return Context.getPointerDiffType(); 10853 } 10854 } 10855 10856 return InvalidOperands(Loc, LHS, RHS); 10857 } 10858 10859 static bool isScopedEnumerationType(QualType T) { 10860 if (const EnumType *ET = T->getAs<EnumType>()) 10861 return ET->getDecl()->isScoped(); 10862 return false; 10863 } 10864 10865 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10866 SourceLocation Loc, BinaryOperatorKind Opc, 10867 QualType LHSType) { 10868 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10869 // so skip remaining warnings as we don't want to modify values within Sema. 10870 if (S.getLangOpts().OpenCL) 10871 return; 10872 10873 // Check right/shifter operand 10874 Expr::EvalResult RHSResult; 10875 if (RHS.get()->isValueDependent() || 10876 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10877 return; 10878 llvm::APSInt Right = RHSResult.Val.getInt(); 10879 10880 if (Right.isNegative()) { 10881 S.DiagRuntimeBehavior(Loc, RHS.get(), 10882 S.PDiag(diag::warn_shift_negative) 10883 << RHS.get()->getSourceRange()); 10884 return; 10885 } 10886 10887 QualType LHSExprType = LHS.get()->getType(); 10888 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10889 if (LHSExprType->isExtIntType()) 10890 LeftSize = S.Context.getIntWidth(LHSExprType); 10891 else if (LHSExprType->isFixedPointType()) { 10892 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10893 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10894 } 10895 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10896 if (Right.uge(LeftBits)) { 10897 S.DiagRuntimeBehavior(Loc, RHS.get(), 10898 S.PDiag(diag::warn_shift_gt_typewidth) 10899 << RHS.get()->getSourceRange()); 10900 return; 10901 } 10902 10903 // FIXME: We probably need to handle fixed point types specially here. 10904 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10905 return; 10906 10907 // When left shifting an ICE which is signed, we can check for overflow which 10908 // according to C++ standards prior to C++2a has undefined behavior 10909 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10910 // more than the maximum value representable in the result type, so never 10911 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10912 // expression is still probably a bug.) 10913 Expr::EvalResult LHSResult; 10914 if (LHS.get()->isValueDependent() || 10915 LHSType->hasUnsignedIntegerRepresentation() || 10916 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10917 return; 10918 llvm::APSInt Left = LHSResult.Val.getInt(); 10919 10920 // If LHS does not have a signed type and non-negative value 10921 // then, the behavior is undefined before C++2a. Warn about it. 10922 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10923 !S.getLangOpts().CPlusPlus20) { 10924 S.DiagRuntimeBehavior(Loc, LHS.get(), 10925 S.PDiag(diag::warn_shift_lhs_negative) 10926 << LHS.get()->getSourceRange()); 10927 return; 10928 } 10929 10930 llvm::APInt ResultBits = 10931 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10932 if (LeftBits.uge(ResultBits)) 10933 return; 10934 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10935 Result = Result.shl(Right); 10936 10937 // Print the bit representation of the signed integer as an unsigned 10938 // hexadecimal number. 10939 SmallString<40> HexResult; 10940 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10941 10942 // If we are only missing a sign bit, this is less likely to result in actual 10943 // bugs -- if the result is cast back to an unsigned type, it will have the 10944 // expected value. Thus we place this behind a different warning that can be 10945 // turned off separately if needed. 10946 if (LeftBits == ResultBits - 1) { 10947 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10948 << HexResult << LHSType 10949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10950 return; 10951 } 10952 10953 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10954 << HexResult.str() << Result.getMinSignedBits() << LHSType 10955 << Left.getBitWidth() << LHS.get()->getSourceRange() 10956 << RHS.get()->getSourceRange(); 10957 } 10958 10959 /// Return the resulting type when a vector is shifted 10960 /// by a scalar or vector shift amount. 10961 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10962 SourceLocation Loc, bool IsCompAssign) { 10963 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10964 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10965 !LHS.get()->getType()->isVectorType()) { 10966 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10967 << RHS.get()->getType() << LHS.get()->getType() 10968 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10969 return QualType(); 10970 } 10971 10972 if (!IsCompAssign) { 10973 LHS = S.UsualUnaryConversions(LHS.get()); 10974 if (LHS.isInvalid()) return QualType(); 10975 } 10976 10977 RHS = S.UsualUnaryConversions(RHS.get()); 10978 if (RHS.isInvalid()) return QualType(); 10979 10980 QualType LHSType = LHS.get()->getType(); 10981 // Note that LHS might be a scalar because the routine calls not only in 10982 // OpenCL case. 10983 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10984 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10985 10986 // Note that RHS might not be a vector. 10987 QualType RHSType = RHS.get()->getType(); 10988 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10989 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10990 10991 // The operands need to be integers. 10992 if (!LHSEleType->isIntegerType()) { 10993 S.Diag(Loc, diag::err_typecheck_expect_int) 10994 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10995 return QualType(); 10996 } 10997 10998 if (!RHSEleType->isIntegerType()) { 10999 S.Diag(Loc, diag::err_typecheck_expect_int) 11000 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11001 return QualType(); 11002 } 11003 11004 if (!LHSVecTy) { 11005 assert(RHSVecTy); 11006 if (IsCompAssign) 11007 return RHSType; 11008 if (LHSEleType != RHSEleType) { 11009 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11010 LHSEleType = RHSEleType; 11011 } 11012 QualType VecTy = 11013 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11014 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11015 LHSType = VecTy; 11016 } else if (RHSVecTy) { 11017 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11018 // are applied component-wise. So if RHS is a vector, then ensure 11019 // that the number of elements is the same as LHS... 11020 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11021 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11022 << LHS.get()->getType() << RHS.get()->getType() 11023 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11024 return QualType(); 11025 } 11026 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11027 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11028 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11029 if (LHSBT != RHSBT && 11030 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11031 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11032 << LHS.get()->getType() << RHS.get()->getType() 11033 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11034 } 11035 } 11036 } else { 11037 // ...else expand RHS to match the number of elements in LHS. 11038 QualType VecTy = 11039 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11040 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11041 } 11042 11043 return LHSType; 11044 } 11045 11046 // C99 6.5.7 11047 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11048 SourceLocation Loc, BinaryOperatorKind Opc, 11049 bool IsCompAssign) { 11050 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11051 11052 // Vector shifts promote their scalar inputs to vector type. 11053 if (LHS.get()->getType()->isVectorType() || 11054 RHS.get()->getType()->isVectorType()) { 11055 if (LangOpts.ZVector) { 11056 // The shift operators for the z vector extensions work basically 11057 // like general shifts, except that neither the LHS nor the RHS is 11058 // allowed to be a "vector bool". 11059 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11060 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11061 return InvalidOperands(Loc, LHS, RHS); 11062 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11063 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11064 return InvalidOperands(Loc, LHS, RHS); 11065 } 11066 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11067 } 11068 11069 // Shifts don't perform usual arithmetic conversions, they just do integer 11070 // promotions on each operand. C99 6.5.7p3 11071 11072 // For the LHS, do usual unary conversions, but then reset them away 11073 // if this is a compound assignment. 11074 ExprResult OldLHS = LHS; 11075 LHS = UsualUnaryConversions(LHS.get()); 11076 if (LHS.isInvalid()) 11077 return QualType(); 11078 QualType LHSType = LHS.get()->getType(); 11079 if (IsCompAssign) LHS = OldLHS; 11080 11081 // The RHS is simpler. 11082 RHS = UsualUnaryConversions(RHS.get()); 11083 if (RHS.isInvalid()) 11084 return QualType(); 11085 QualType RHSType = RHS.get()->getType(); 11086 11087 // C99 6.5.7p2: Each of the operands shall have integer type. 11088 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11089 if ((!LHSType->isFixedPointOrIntegerType() && 11090 !LHSType->hasIntegerRepresentation()) || 11091 !RHSType->hasIntegerRepresentation()) 11092 return InvalidOperands(Loc, LHS, RHS); 11093 11094 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11095 // hasIntegerRepresentation() above instead of this. 11096 if (isScopedEnumerationType(LHSType) || 11097 isScopedEnumerationType(RHSType)) { 11098 return InvalidOperands(Loc, LHS, RHS); 11099 } 11100 // Sanity-check shift operands 11101 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11102 11103 // "The type of the result is that of the promoted left operand." 11104 return LHSType; 11105 } 11106 11107 /// Diagnose bad pointer comparisons. 11108 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11109 ExprResult &LHS, ExprResult &RHS, 11110 bool IsError) { 11111 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11112 : diag::ext_typecheck_comparison_of_distinct_pointers) 11113 << LHS.get()->getType() << RHS.get()->getType() 11114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11115 } 11116 11117 /// Returns false if the pointers are converted to a composite type, 11118 /// true otherwise. 11119 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11120 ExprResult &LHS, ExprResult &RHS) { 11121 // C++ [expr.rel]p2: 11122 // [...] Pointer conversions (4.10) and qualification 11123 // conversions (4.4) are performed on pointer operands (or on 11124 // a pointer operand and a null pointer constant) to bring 11125 // them to their composite pointer type. [...] 11126 // 11127 // C++ [expr.eq]p1 uses the same notion for (in)equality 11128 // comparisons of pointers. 11129 11130 QualType LHSType = LHS.get()->getType(); 11131 QualType RHSType = RHS.get()->getType(); 11132 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11133 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11134 11135 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11136 if (T.isNull()) { 11137 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11138 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11139 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11140 else 11141 S.InvalidOperands(Loc, LHS, RHS); 11142 return true; 11143 } 11144 11145 return false; 11146 } 11147 11148 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11149 ExprResult &LHS, 11150 ExprResult &RHS, 11151 bool IsError) { 11152 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11153 : diag::ext_typecheck_comparison_of_fptr_to_void) 11154 << LHS.get()->getType() << RHS.get()->getType() 11155 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11156 } 11157 11158 static bool isObjCObjectLiteral(ExprResult &E) { 11159 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11160 case Stmt::ObjCArrayLiteralClass: 11161 case Stmt::ObjCDictionaryLiteralClass: 11162 case Stmt::ObjCStringLiteralClass: 11163 case Stmt::ObjCBoxedExprClass: 11164 return true; 11165 default: 11166 // Note that ObjCBoolLiteral is NOT an object literal! 11167 return false; 11168 } 11169 } 11170 11171 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11172 const ObjCObjectPointerType *Type = 11173 LHS->getType()->getAs<ObjCObjectPointerType>(); 11174 11175 // If this is not actually an Objective-C object, bail out. 11176 if (!Type) 11177 return false; 11178 11179 // Get the LHS object's interface type. 11180 QualType InterfaceType = Type->getPointeeType(); 11181 11182 // If the RHS isn't an Objective-C object, bail out. 11183 if (!RHS->getType()->isObjCObjectPointerType()) 11184 return false; 11185 11186 // Try to find the -isEqual: method. 11187 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11188 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11189 InterfaceType, 11190 /*IsInstance=*/true); 11191 if (!Method) { 11192 if (Type->isObjCIdType()) { 11193 // For 'id', just check the global pool. 11194 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11195 /*receiverId=*/true); 11196 } else { 11197 // Check protocols. 11198 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11199 /*IsInstance=*/true); 11200 } 11201 } 11202 11203 if (!Method) 11204 return false; 11205 11206 QualType T = Method->parameters()[0]->getType(); 11207 if (!T->isObjCObjectPointerType()) 11208 return false; 11209 11210 QualType R = Method->getReturnType(); 11211 if (!R->isScalarType()) 11212 return false; 11213 11214 return true; 11215 } 11216 11217 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11218 FromE = FromE->IgnoreParenImpCasts(); 11219 switch (FromE->getStmtClass()) { 11220 default: 11221 break; 11222 case Stmt::ObjCStringLiteralClass: 11223 // "string literal" 11224 return LK_String; 11225 case Stmt::ObjCArrayLiteralClass: 11226 // "array literal" 11227 return LK_Array; 11228 case Stmt::ObjCDictionaryLiteralClass: 11229 // "dictionary literal" 11230 return LK_Dictionary; 11231 case Stmt::BlockExprClass: 11232 return LK_Block; 11233 case Stmt::ObjCBoxedExprClass: { 11234 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11235 switch (Inner->getStmtClass()) { 11236 case Stmt::IntegerLiteralClass: 11237 case Stmt::FloatingLiteralClass: 11238 case Stmt::CharacterLiteralClass: 11239 case Stmt::ObjCBoolLiteralExprClass: 11240 case Stmt::CXXBoolLiteralExprClass: 11241 // "numeric literal" 11242 return LK_Numeric; 11243 case Stmt::ImplicitCastExprClass: { 11244 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11245 // Boolean literals can be represented by implicit casts. 11246 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11247 return LK_Numeric; 11248 break; 11249 } 11250 default: 11251 break; 11252 } 11253 return LK_Boxed; 11254 } 11255 } 11256 return LK_None; 11257 } 11258 11259 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11260 ExprResult &LHS, ExprResult &RHS, 11261 BinaryOperator::Opcode Opc){ 11262 Expr *Literal; 11263 Expr *Other; 11264 if (isObjCObjectLiteral(LHS)) { 11265 Literal = LHS.get(); 11266 Other = RHS.get(); 11267 } else { 11268 Literal = RHS.get(); 11269 Other = LHS.get(); 11270 } 11271 11272 // Don't warn on comparisons against nil. 11273 Other = Other->IgnoreParenCasts(); 11274 if (Other->isNullPointerConstant(S.getASTContext(), 11275 Expr::NPC_ValueDependentIsNotNull)) 11276 return; 11277 11278 // This should be kept in sync with warn_objc_literal_comparison. 11279 // LK_String should always be after the other literals, since it has its own 11280 // warning flag. 11281 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11282 assert(LiteralKind != Sema::LK_Block); 11283 if (LiteralKind == Sema::LK_None) { 11284 llvm_unreachable("Unknown Objective-C object literal kind"); 11285 } 11286 11287 if (LiteralKind == Sema::LK_String) 11288 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11289 << Literal->getSourceRange(); 11290 else 11291 S.Diag(Loc, diag::warn_objc_literal_comparison) 11292 << LiteralKind << Literal->getSourceRange(); 11293 11294 if (BinaryOperator::isEqualityOp(Opc) && 11295 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11296 SourceLocation Start = LHS.get()->getBeginLoc(); 11297 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11298 CharSourceRange OpRange = 11299 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11300 11301 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11302 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11303 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11304 << FixItHint::CreateInsertion(End, "]"); 11305 } 11306 } 11307 11308 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11309 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11310 ExprResult &RHS, SourceLocation Loc, 11311 BinaryOperatorKind Opc) { 11312 // Check that left hand side is !something. 11313 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11314 if (!UO || UO->getOpcode() != UO_LNot) return; 11315 11316 // Only check if the right hand side is non-bool arithmetic type. 11317 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11318 11319 // Make sure that the something in !something is not bool. 11320 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11321 if (SubExpr->isKnownToHaveBooleanValue()) return; 11322 11323 // Emit warning. 11324 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11325 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11326 << Loc << IsBitwiseOp; 11327 11328 // First note suggest !(x < y) 11329 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11330 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11331 FirstClose = S.getLocForEndOfToken(FirstClose); 11332 if (FirstClose.isInvalid()) 11333 FirstOpen = SourceLocation(); 11334 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11335 << IsBitwiseOp 11336 << FixItHint::CreateInsertion(FirstOpen, "(") 11337 << FixItHint::CreateInsertion(FirstClose, ")"); 11338 11339 // Second note suggests (!x) < y 11340 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11341 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11342 SecondClose = S.getLocForEndOfToken(SecondClose); 11343 if (SecondClose.isInvalid()) 11344 SecondOpen = SourceLocation(); 11345 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11346 << FixItHint::CreateInsertion(SecondOpen, "(") 11347 << FixItHint::CreateInsertion(SecondClose, ")"); 11348 } 11349 11350 // Returns true if E refers to a non-weak array. 11351 static bool checkForArray(const Expr *E) { 11352 const ValueDecl *D = nullptr; 11353 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11354 D = DR->getDecl(); 11355 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11356 if (Mem->isImplicitAccess()) 11357 D = Mem->getMemberDecl(); 11358 } 11359 if (!D) 11360 return false; 11361 return D->getType()->isArrayType() && !D->isWeak(); 11362 } 11363 11364 /// Diagnose some forms of syntactically-obvious tautological comparison. 11365 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11366 Expr *LHS, Expr *RHS, 11367 BinaryOperatorKind Opc) { 11368 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11369 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11370 11371 QualType LHSType = LHS->getType(); 11372 QualType RHSType = RHS->getType(); 11373 if (LHSType->hasFloatingRepresentation() || 11374 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11375 S.inTemplateInstantiation()) 11376 return; 11377 11378 // Comparisons between two array types are ill-formed for operator<=>, so 11379 // we shouldn't emit any additional warnings about it. 11380 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11381 return; 11382 11383 // For non-floating point types, check for self-comparisons of the form 11384 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11385 // often indicate logic errors in the program. 11386 // 11387 // NOTE: Don't warn about comparison expressions resulting from macro 11388 // expansion. Also don't warn about comparisons which are only self 11389 // comparisons within a template instantiation. The warnings should catch 11390 // obvious cases in the definition of the template anyways. The idea is to 11391 // warn when the typed comparison operator will always evaluate to the same 11392 // result. 11393 11394 // Used for indexing into %select in warn_comparison_always 11395 enum { 11396 AlwaysConstant, 11397 AlwaysTrue, 11398 AlwaysFalse, 11399 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11400 }; 11401 11402 // C++2a [depr.array.comp]: 11403 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11404 // operands of array type are deprecated. 11405 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11406 RHSStripped->getType()->isArrayType()) { 11407 S.Diag(Loc, diag::warn_depr_array_comparison) 11408 << LHS->getSourceRange() << RHS->getSourceRange() 11409 << LHSStripped->getType() << RHSStripped->getType(); 11410 // Carry on to produce the tautological comparison warning, if this 11411 // expression is potentially-evaluated, we can resolve the array to a 11412 // non-weak declaration, and so on. 11413 } 11414 11415 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11416 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11417 unsigned Result; 11418 switch (Opc) { 11419 case BO_EQ: 11420 case BO_LE: 11421 case BO_GE: 11422 Result = AlwaysTrue; 11423 break; 11424 case BO_NE: 11425 case BO_LT: 11426 case BO_GT: 11427 Result = AlwaysFalse; 11428 break; 11429 case BO_Cmp: 11430 Result = AlwaysEqual; 11431 break; 11432 default: 11433 Result = AlwaysConstant; 11434 break; 11435 } 11436 S.DiagRuntimeBehavior(Loc, nullptr, 11437 S.PDiag(diag::warn_comparison_always) 11438 << 0 /*self-comparison*/ 11439 << Result); 11440 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11441 // What is it always going to evaluate to? 11442 unsigned Result; 11443 switch (Opc) { 11444 case BO_EQ: // e.g. array1 == array2 11445 Result = AlwaysFalse; 11446 break; 11447 case BO_NE: // e.g. array1 != array2 11448 Result = AlwaysTrue; 11449 break; 11450 default: // e.g. array1 <= array2 11451 // The best we can say is 'a constant' 11452 Result = AlwaysConstant; 11453 break; 11454 } 11455 S.DiagRuntimeBehavior(Loc, nullptr, 11456 S.PDiag(diag::warn_comparison_always) 11457 << 1 /*array comparison*/ 11458 << Result); 11459 } 11460 } 11461 11462 if (isa<CastExpr>(LHSStripped)) 11463 LHSStripped = LHSStripped->IgnoreParenCasts(); 11464 if (isa<CastExpr>(RHSStripped)) 11465 RHSStripped = RHSStripped->IgnoreParenCasts(); 11466 11467 // Warn about comparisons against a string constant (unless the other 11468 // operand is null); the user probably wants string comparison function. 11469 Expr *LiteralString = nullptr; 11470 Expr *LiteralStringStripped = nullptr; 11471 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11472 !RHSStripped->isNullPointerConstant(S.Context, 11473 Expr::NPC_ValueDependentIsNull)) { 11474 LiteralString = LHS; 11475 LiteralStringStripped = LHSStripped; 11476 } else if ((isa<StringLiteral>(RHSStripped) || 11477 isa<ObjCEncodeExpr>(RHSStripped)) && 11478 !LHSStripped->isNullPointerConstant(S.Context, 11479 Expr::NPC_ValueDependentIsNull)) { 11480 LiteralString = RHS; 11481 LiteralStringStripped = RHSStripped; 11482 } 11483 11484 if (LiteralString) { 11485 S.DiagRuntimeBehavior(Loc, nullptr, 11486 S.PDiag(diag::warn_stringcompare) 11487 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11488 << LiteralString->getSourceRange()); 11489 } 11490 } 11491 11492 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11493 switch (CK) { 11494 default: { 11495 #ifndef NDEBUG 11496 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11497 << "\n"; 11498 #endif 11499 llvm_unreachable("unhandled cast kind"); 11500 } 11501 case CK_UserDefinedConversion: 11502 return ICK_Identity; 11503 case CK_LValueToRValue: 11504 return ICK_Lvalue_To_Rvalue; 11505 case CK_ArrayToPointerDecay: 11506 return ICK_Array_To_Pointer; 11507 case CK_FunctionToPointerDecay: 11508 return ICK_Function_To_Pointer; 11509 case CK_IntegralCast: 11510 return ICK_Integral_Conversion; 11511 case CK_FloatingCast: 11512 return ICK_Floating_Conversion; 11513 case CK_IntegralToFloating: 11514 case CK_FloatingToIntegral: 11515 return ICK_Floating_Integral; 11516 case CK_IntegralComplexCast: 11517 case CK_FloatingComplexCast: 11518 case CK_FloatingComplexToIntegralComplex: 11519 case CK_IntegralComplexToFloatingComplex: 11520 return ICK_Complex_Conversion; 11521 case CK_FloatingComplexToReal: 11522 case CK_FloatingRealToComplex: 11523 case CK_IntegralComplexToReal: 11524 case CK_IntegralRealToComplex: 11525 return ICK_Complex_Real; 11526 } 11527 } 11528 11529 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11530 QualType FromType, 11531 SourceLocation Loc) { 11532 // Check for a narrowing implicit conversion. 11533 StandardConversionSequence SCS; 11534 SCS.setAsIdentityConversion(); 11535 SCS.setToType(0, FromType); 11536 SCS.setToType(1, ToType); 11537 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11538 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11539 11540 APValue PreNarrowingValue; 11541 QualType PreNarrowingType; 11542 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11543 PreNarrowingType, 11544 /*IgnoreFloatToIntegralConversion*/ true)) { 11545 case NK_Dependent_Narrowing: 11546 // Implicit conversion to a narrower type, but the expression is 11547 // value-dependent so we can't tell whether it's actually narrowing. 11548 case NK_Not_Narrowing: 11549 return false; 11550 11551 case NK_Constant_Narrowing: 11552 // Implicit conversion to a narrower type, and the value is not a constant 11553 // expression. 11554 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11555 << /*Constant*/ 1 11556 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11557 return true; 11558 11559 case NK_Variable_Narrowing: 11560 // Implicit conversion to a narrower type, and the value is not a constant 11561 // expression. 11562 case NK_Type_Narrowing: 11563 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11564 << /*Constant*/ 0 << FromType << ToType; 11565 // TODO: It's not a constant expression, but what if the user intended it 11566 // to be? Can we produce notes to help them figure out why it isn't? 11567 return true; 11568 } 11569 llvm_unreachable("unhandled case in switch"); 11570 } 11571 11572 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11573 ExprResult &LHS, 11574 ExprResult &RHS, 11575 SourceLocation Loc) { 11576 QualType LHSType = LHS.get()->getType(); 11577 QualType RHSType = RHS.get()->getType(); 11578 // Dig out the original argument type and expression before implicit casts 11579 // were applied. These are the types/expressions we need to check the 11580 // [expr.spaceship] requirements against. 11581 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11582 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11583 QualType LHSStrippedType = LHSStripped.get()->getType(); 11584 QualType RHSStrippedType = RHSStripped.get()->getType(); 11585 11586 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11587 // other is not, the program is ill-formed. 11588 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11589 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11590 return QualType(); 11591 } 11592 11593 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11594 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11595 RHSStrippedType->isEnumeralType(); 11596 if (NumEnumArgs == 1) { 11597 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11598 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11599 if (OtherTy->hasFloatingRepresentation()) { 11600 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11601 return QualType(); 11602 } 11603 } 11604 if (NumEnumArgs == 2) { 11605 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11606 // type E, the operator yields the result of converting the operands 11607 // to the underlying type of E and applying <=> to the converted operands. 11608 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11609 S.InvalidOperands(Loc, LHS, RHS); 11610 return QualType(); 11611 } 11612 QualType IntType = 11613 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11614 assert(IntType->isArithmeticType()); 11615 11616 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11617 // promote the boolean type, and all other promotable integer types, to 11618 // avoid this. 11619 if (IntType->isPromotableIntegerType()) 11620 IntType = S.Context.getPromotedIntegerType(IntType); 11621 11622 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11623 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11624 LHSType = RHSType = IntType; 11625 } 11626 11627 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11628 // usual arithmetic conversions are applied to the operands. 11629 QualType Type = 11630 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11631 if (LHS.isInvalid() || RHS.isInvalid()) 11632 return QualType(); 11633 if (Type.isNull()) 11634 return S.InvalidOperands(Loc, LHS, RHS); 11635 11636 Optional<ComparisonCategoryType> CCT = 11637 getComparisonCategoryForBuiltinCmp(Type); 11638 if (!CCT) 11639 return S.InvalidOperands(Loc, LHS, RHS); 11640 11641 bool HasNarrowing = checkThreeWayNarrowingConversion( 11642 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11643 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11644 RHS.get()->getBeginLoc()); 11645 if (HasNarrowing) 11646 return QualType(); 11647 11648 assert(!Type.isNull() && "composite type for <=> has not been set"); 11649 11650 return S.CheckComparisonCategoryType( 11651 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11652 } 11653 11654 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11655 ExprResult &RHS, 11656 SourceLocation Loc, 11657 BinaryOperatorKind Opc) { 11658 if (Opc == BO_Cmp) 11659 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11660 11661 // C99 6.5.8p3 / C99 6.5.9p4 11662 QualType Type = 11663 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11664 if (LHS.isInvalid() || RHS.isInvalid()) 11665 return QualType(); 11666 if (Type.isNull()) 11667 return S.InvalidOperands(Loc, LHS, RHS); 11668 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11669 11670 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11671 return S.InvalidOperands(Loc, LHS, RHS); 11672 11673 // Check for comparisons of floating point operands using != and ==. 11674 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11675 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11676 11677 // The result of comparisons is 'bool' in C++, 'int' in C. 11678 return S.Context.getLogicalOperationType(); 11679 } 11680 11681 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11682 if (!NullE.get()->getType()->isAnyPointerType()) 11683 return; 11684 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11685 if (!E.get()->getType()->isAnyPointerType() && 11686 E.get()->isNullPointerConstant(Context, 11687 Expr::NPC_ValueDependentIsNotNull) == 11688 Expr::NPCK_ZeroExpression) { 11689 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11690 if (CL->getValue() == 0) 11691 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11692 << NullValue 11693 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11694 NullValue ? "NULL" : "(void *)0"); 11695 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11696 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11697 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11698 if (T == Context.CharTy) 11699 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11700 << NullValue 11701 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11702 NullValue ? "NULL" : "(void *)0"); 11703 } 11704 } 11705 } 11706 11707 // C99 6.5.8, C++ [expr.rel] 11708 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11709 SourceLocation Loc, 11710 BinaryOperatorKind Opc) { 11711 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11712 bool IsThreeWay = Opc == BO_Cmp; 11713 bool IsOrdered = IsRelational || IsThreeWay; 11714 auto IsAnyPointerType = [](ExprResult E) { 11715 QualType Ty = E.get()->getType(); 11716 return Ty->isPointerType() || Ty->isMemberPointerType(); 11717 }; 11718 11719 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11720 // type, array-to-pointer, ..., conversions are performed on both operands to 11721 // bring them to their composite type. 11722 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11723 // any type-related checks. 11724 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11725 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11726 if (LHS.isInvalid()) 11727 return QualType(); 11728 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11729 if (RHS.isInvalid()) 11730 return QualType(); 11731 } else { 11732 LHS = DefaultLvalueConversion(LHS.get()); 11733 if (LHS.isInvalid()) 11734 return QualType(); 11735 RHS = DefaultLvalueConversion(RHS.get()); 11736 if (RHS.isInvalid()) 11737 return QualType(); 11738 } 11739 11740 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11741 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11742 CheckPtrComparisonWithNullChar(LHS, RHS); 11743 CheckPtrComparisonWithNullChar(RHS, LHS); 11744 } 11745 11746 // Handle vector comparisons separately. 11747 if (LHS.get()->getType()->isVectorType() || 11748 RHS.get()->getType()->isVectorType()) 11749 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11750 11751 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11752 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11753 11754 QualType LHSType = LHS.get()->getType(); 11755 QualType RHSType = RHS.get()->getType(); 11756 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11757 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11758 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11759 11760 const Expr::NullPointerConstantKind LHSNullKind = 11761 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11762 const Expr::NullPointerConstantKind RHSNullKind = 11763 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11764 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11765 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11766 11767 auto computeResultTy = [&]() { 11768 if (Opc != BO_Cmp) 11769 return Context.getLogicalOperationType(); 11770 assert(getLangOpts().CPlusPlus); 11771 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11772 11773 QualType CompositeTy = LHS.get()->getType(); 11774 assert(!CompositeTy->isReferenceType()); 11775 11776 Optional<ComparisonCategoryType> CCT = 11777 getComparisonCategoryForBuiltinCmp(CompositeTy); 11778 if (!CCT) 11779 return InvalidOperands(Loc, LHS, RHS); 11780 11781 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11782 // P0946R0: Comparisons between a null pointer constant and an object 11783 // pointer result in std::strong_equality, which is ill-formed under 11784 // P1959R0. 11785 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11786 << (LHSIsNull ? LHS.get()->getSourceRange() 11787 : RHS.get()->getSourceRange()); 11788 return QualType(); 11789 } 11790 11791 return CheckComparisonCategoryType( 11792 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11793 }; 11794 11795 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11796 bool IsEquality = Opc == BO_EQ; 11797 if (RHSIsNull) 11798 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11799 RHS.get()->getSourceRange()); 11800 else 11801 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11802 LHS.get()->getSourceRange()); 11803 } 11804 11805 if (IsOrdered && LHSType->isFunctionPointerType() && 11806 RHSType->isFunctionPointerType()) { 11807 // Valid unless a relational comparison of function pointers 11808 bool IsError = Opc == BO_Cmp; 11809 auto DiagID = 11810 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11811 : getLangOpts().CPlusPlus 11812 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11813 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11814 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11815 << RHS.get()->getSourceRange(); 11816 if (IsError) 11817 return QualType(); 11818 } 11819 11820 if ((LHSType->isIntegerType() && !LHSIsNull) || 11821 (RHSType->isIntegerType() && !RHSIsNull)) { 11822 // Skip normal pointer conversion checks in this case; we have better 11823 // diagnostics for this below. 11824 } else if (getLangOpts().CPlusPlus) { 11825 // Equality comparison of a function pointer to a void pointer is invalid, 11826 // but we allow it as an extension. 11827 // FIXME: If we really want to allow this, should it be part of composite 11828 // pointer type computation so it works in conditionals too? 11829 if (!IsOrdered && 11830 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11831 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11832 // This is a gcc extension compatibility comparison. 11833 // In a SFINAE context, we treat this as a hard error to maintain 11834 // conformance with the C++ standard. 11835 diagnoseFunctionPointerToVoidComparison( 11836 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11837 11838 if (isSFINAEContext()) 11839 return QualType(); 11840 11841 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11842 return computeResultTy(); 11843 } 11844 11845 // C++ [expr.eq]p2: 11846 // If at least one operand is a pointer [...] bring them to their 11847 // composite pointer type. 11848 // C++ [expr.spaceship]p6 11849 // If at least one of the operands is of pointer type, [...] bring them 11850 // to their composite pointer type. 11851 // C++ [expr.rel]p2: 11852 // If both operands are pointers, [...] bring them to their composite 11853 // pointer type. 11854 // For <=>, the only valid non-pointer types are arrays and functions, and 11855 // we already decayed those, so this is really the same as the relational 11856 // comparison rule. 11857 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11858 (IsOrdered ? 2 : 1) && 11859 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11860 RHSType->isObjCObjectPointerType()))) { 11861 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11862 return QualType(); 11863 return computeResultTy(); 11864 } 11865 } else if (LHSType->isPointerType() && 11866 RHSType->isPointerType()) { // C99 6.5.8p2 11867 // All of the following pointer-related warnings are GCC extensions, except 11868 // when handling null pointer constants. 11869 QualType LCanPointeeTy = 11870 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11871 QualType RCanPointeeTy = 11872 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11873 11874 // C99 6.5.9p2 and C99 6.5.8p2 11875 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11876 RCanPointeeTy.getUnqualifiedType())) { 11877 if (IsRelational) { 11878 // Pointers both need to point to complete or incomplete types 11879 if ((LCanPointeeTy->isIncompleteType() != 11880 RCanPointeeTy->isIncompleteType()) && 11881 !getLangOpts().C11) { 11882 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11884 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11885 << RCanPointeeTy->isIncompleteType(); 11886 } 11887 } 11888 } else if (!IsRelational && 11889 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11890 // Valid unless comparison between non-null pointer and function pointer 11891 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11892 && !LHSIsNull && !RHSIsNull) 11893 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11894 /*isError*/false); 11895 } else { 11896 // Invalid 11897 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11898 } 11899 if (LCanPointeeTy != RCanPointeeTy) { 11900 // Treat NULL constant as a special case in OpenCL. 11901 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11902 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11903 Diag(Loc, 11904 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11905 << LHSType << RHSType << 0 /* comparison */ 11906 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11907 } 11908 } 11909 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11910 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11911 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11912 : CK_BitCast; 11913 if (LHSIsNull && !RHSIsNull) 11914 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11915 else 11916 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11917 } 11918 return computeResultTy(); 11919 } 11920 11921 if (getLangOpts().CPlusPlus) { 11922 // C++ [expr.eq]p4: 11923 // Two operands of type std::nullptr_t or one operand of type 11924 // std::nullptr_t and the other a null pointer constant compare equal. 11925 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11926 if (LHSType->isNullPtrType()) { 11927 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11928 return computeResultTy(); 11929 } 11930 if (RHSType->isNullPtrType()) { 11931 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11932 return computeResultTy(); 11933 } 11934 } 11935 11936 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11937 // These aren't covered by the composite pointer type rules. 11938 if (!IsOrdered && RHSType->isNullPtrType() && 11939 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11940 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11941 return computeResultTy(); 11942 } 11943 if (!IsOrdered && LHSType->isNullPtrType() && 11944 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11945 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11946 return computeResultTy(); 11947 } 11948 11949 if (IsRelational && 11950 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11951 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11952 // HACK: Relational comparison of nullptr_t against a pointer type is 11953 // invalid per DR583, but we allow it within std::less<> and friends, 11954 // since otherwise common uses of it break. 11955 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11956 // friends to have std::nullptr_t overload candidates. 11957 DeclContext *DC = CurContext; 11958 if (isa<FunctionDecl>(DC)) 11959 DC = DC->getParent(); 11960 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11961 if (CTSD->isInStdNamespace() && 11962 llvm::StringSwitch<bool>(CTSD->getName()) 11963 .Cases("less", "less_equal", "greater", "greater_equal", true) 11964 .Default(false)) { 11965 if (RHSType->isNullPtrType()) 11966 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11967 else 11968 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11969 return computeResultTy(); 11970 } 11971 } 11972 } 11973 11974 // C++ [expr.eq]p2: 11975 // If at least one operand is a pointer to member, [...] bring them to 11976 // their composite pointer type. 11977 if (!IsOrdered && 11978 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11979 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11980 return QualType(); 11981 else 11982 return computeResultTy(); 11983 } 11984 } 11985 11986 // Handle block pointer types. 11987 if (!IsOrdered && LHSType->isBlockPointerType() && 11988 RHSType->isBlockPointerType()) { 11989 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11990 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11991 11992 if (!LHSIsNull && !RHSIsNull && 11993 !Context.typesAreCompatible(lpointee, rpointee)) { 11994 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11995 << LHSType << RHSType << LHS.get()->getSourceRange() 11996 << RHS.get()->getSourceRange(); 11997 } 11998 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11999 return computeResultTy(); 12000 } 12001 12002 // Allow block pointers to be compared with null pointer constants. 12003 if (!IsOrdered 12004 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12005 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12006 if (!LHSIsNull && !RHSIsNull) { 12007 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12008 ->getPointeeType()->isVoidType()) 12009 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12010 ->getPointeeType()->isVoidType()))) 12011 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12012 << LHSType << RHSType << LHS.get()->getSourceRange() 12013 << RHS.get()->getSourceRange(); 12014 } 12015 if (LHSIsNull && !RHSIsNull) 12016 LHS = ImpCastExprToType(LHS.get(), RHSType, 12017 RHSType->isPointerType() ? CK_BitCast 12018 : CK_AnyPointerToBlockPointerCast); 12019 else 12020 RHS = ImpCastExprToType(RHS.get(), LHSType, 12021 LHSType->isPointerType() ? CK_BitCast 12022 : CK_AnyPointerToBlockPointerCast); 12023 return computeResultTy(); 12024 } 12025 12026 if (LHSType->isObjCObjectPointerType() || 12027 RHSType->isObjCObjectPointerType()) { 12028 const PointerType *LPT = LHSType->getAs<PointerType>(); 12029 const PointerType *RPT = RHSType->getAs<PointerType>(); 12030 if (LPT || RPT) { 12031 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12032 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12033 12034 if (!LPtrToVoid && !RPtrToVoid && 12035 !Context.typesAreCompatible(LHSType, RHSType)) { 12036 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12037 /*isError*/false); 12038 } 12039 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12040 // the RHS, but we have test coverage for this behavior. 12041 // FIXME: Consider using convertPointersToCompositeType in C++. 12042 if (LHSIsNull && !RHSIsNull) { 12043 Expr *E = LHS.get(); 12044 if (getLangOpts().ObjCAutoRefCount) 12045 CheckObjCConversion(SourceRange(), RHSType, E, 12046 CCK_ImplicitConversion); 12047 LHS = ImpCastExprToType(E, RHSType, 12048 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12049 } 12050 else { 12051 Expr *E = RHS.get(); 12052 if (getLangOpts().ObjCAutoRefCount) 12053 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12054 /*Diagnose=*/true, 12055 /*DiagnoseCFAudited=*/false, Opc); 12056 RHS = ImpCastExprToType(E, LHSType, 12057 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12058 } 12059 return computeResultTy(); 12060 } 12061 if (LHSType->isObjCObjectPointerType() && 12062 RHSType->isObjCObjectPointerType()) { 12063 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12064 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12065 /*isError*/false); 12066 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12067 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12068 12069 if (LHSIsNull && !RHSIsNull) 12070 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12071 else 12072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12073 return computeResultTy(); 12074 } 12075 12076 if (!IsOrdered && LHSType->isBlockPointerType() && 12077 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12078 LHS = ImpCastExprToType(LHS.get(), RHSType, 12079 CK_BlockPointerToObjCPointerCast); 12080 return computeResultTy(); 12081 } else if (!IsOrdered && 12082 LHSType->isBlockCompatibleObjCPointerType(Context) && 12083 RHSType->isBlockPointerType()) { 12084 RHS = ImpCastExprToType(RHS.get(), LHSType, 12085 CK_BlockPointerToObjCPointerCast); 12086 return computeResultTy(); 12087 } 12088 } 12089 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12090 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12091 unsigned DiagID = 0; 12092 bool isError = false; 12093 if (LangOpts.DebuggerSupport) { 12094 // Under a debugger, allow the comparison of pointers to integers, 12095 // since users tend to want to compare addresses. 12096 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12097 (RHSIsNull && RHSType->isIntegerType())) { 12098 if (IsOrdered) { 12099 isError = getLangOpts().CPlusPlus; 12100 DiagID = 12101 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12102 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12103 } 12104 } else if (getLangOpts().CPlusPlus) { 12105 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12106 isError = true; 12107 } else if (IsOrdered) 12108 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12109 else 12110 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12111 12112 if (DiagID) { 12113 Diag(Loc, DiagID) 12114 << LHSType << RHSType << LHS.get()->getSourceRange() 12115 << RHS.get()->getSourceRange(); 12116 if (isError) 12117 return QualType(); 12118 } 12119 12120 if (LHSType->isIntegerType()) 12121 LHS = ImpCastExprToType(LHS.get(), RHSType, 12122 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12123 else 12124 RHS = ImpCastExprToType(RHS.get(), LHSType, 12125 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12126 return computeResultTy(); 12127 } 12128 12129 // Handle block pointers. 12130 if (!IsOrdered && RHSIsNull 12131 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12132 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12133 return computeResultTy(); 12134 } 12135 if (!IsOrdered && LHSIsNull 12136 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12137 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12138 return computeResultTy(); 12139 } 12140 12141 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12142 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12143 return computeResultTy(); 12144 } 12145 12146 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12147 return computeResultTy(); 12148 } 12149 12150 if (LHSIsNull && RHSType->isQueueT()) { 12151 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12152 return computeResultTy(); 12153 } 12154 12155 if (LHSType->isQueueT() && RHSIsNull) { 12156 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12157 return computeResultTy(); 12158 } 12159 } 12160 12161 return InvalidOperands(Loc, LHS, RHS); 12162 } 12163 12164 // Return a signed ext_vector_type that is of identical size and number of 12165 // elements. For floating point vectors, return an integer type of identical 12166 // size and number of elements. In the non ext_vector_type case, search from 12167 // the largest type to the smallest type to avoid cases where long long == long, 12168 // where long gets picked over long long. 12169 QualType Sema::GetSignedVectorType(QualType V) { 12170 const VectorType *VTy = V->castAs<VectorType>(); 12171 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12172 12173 if (isa<ExtVectorType>(VTy)) { 12174 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12175 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12176 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12177 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12178 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12179 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12180 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12181 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12182 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12183 "Unhandled vector element size in vector compare"); 12184 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12185 } 12186 12187 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12188 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12189 VectorType::GenericVector); 12190 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12191 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12192 VectorType::GenericVector); 12193 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12194 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12195 VectorType::GenericVector); 12196 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12197 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12198 VectorType::GenericVector); 12199 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12200 "Unhandled vector element size in vector compare"); 12201 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12202 VectorType::GenericVector); 12203 } 12204 12205 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12206 /// operates on extended vector types. Instead of producing an IntTy result, 12207 /// like a scalar comparison, a vector comparison produces a vector of integer 12208 /// types. 12209 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12210 SourceLocation Loc, 12211 BinaryOperatorKind Opc) { 12212 if (Opc == BO_Cmp) { 12213 Diag(Loc, diag::err_three_way_vector_comparison); 12214 return QualType(); 12215 } 12216 12217 // Check to make sure we're operating on vectors of the same type and width, 12218 // Allowing one side to be a scalar of element type. 12219 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12220 /*AllowBothBool*/true, 12221 /*AllowBoolConversions*/getLangOpts().ZVector); 12222 if (vType.isNull()) 12223 return vType; 12224 12225 QualType LHSType = LHS.get()->getType(); 12226 12227 // If AltiVec, the comparison results in a numeric type, i.e. 12228 // bool for C++, int for C 12229 if (getLangOpts().AltiVec && 12230 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12231 return Context.getLogicalOperationType(); 12232 12233 // For non-floating point types, check for self-comparisons of the form 12234 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12235 // often indicate logic errors in the program. 12236 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12237 12238 // Check for comparisons of floating point operands using != and ==. 12239 if (BinaryOperator::isEqualityOp(Opc) && 12240 LHSType->hasFloatingRepresentation()) { 12241 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12242 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12243 } 12244 12245 // Return a signed type for the vector. 12246 return GetSignedVectorType(vType); 12247 } 12248 12249 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12250 const ExprResult &XorRHS, 12251 const SourceLocation Loc) { 12252 // Do not diagnose macros. 12253 if (Loc.isMacroID()) 12254 return; 12255 12256 // Do not diagnose if both LHS and RHS are macros. 12257 if (XorLHS.get()->getExprLoc().isMacroID() && 12258 XorRHS.get()->getExprLoc().isMacroID()) 12259 return; 12260 12261 bool Negative = false; 12262 bool ExplicitPlus = false; 12263 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12264 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12265 12266 if (!LHSInt) 12267 return; 12268 if (!RHSInt) { 12269 // Check negative literals. 12270 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12271 UnaryOperatorKind Opc = UO->getOpcode(); 12272 if (Opc != UO_Minus && Opc != UO_Plus) 12273 return; 12274 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12275 if (!RHSInt) 12276 return; 12277 Negative = (Opc == UO_Minus); 12278 ExplicitPlus = !Negative; 12279 } else { 12280 return; 12281 } 12282 } 12283 12284 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12285 llvm::APInt RightSideValue = RHSInt->getValue(); 12286 if (LeftSideValue != 2 && LeftSideValue != 10) 12287 return; 12288 12289 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12290 return; 12291 12292 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12293 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12294 llvm::StringRef ExprStr = 12295 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12296 12297 CharSourceRange XorRange = 12298 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12299 llvm::StringRef XorStr = 12300 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12301 // Do not diagnose if xor keyword/macro is used. 12302 if (XorStr == "xor") 12303 return; 12304 12305 std::string LHSStr = std::string(Lexer::getSourceText( 12306 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12307 S.getSourceManager(), S.getLangOpts())); 12308 std::string RHSStr = std::string(Lexer::getSourceText( 12309 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12310 S.getSourceManager(), S.getLangOpts())); 12311 12312 if (Negative) { 12313 RightSideValue = -RightSideValue; 12314 RHSStr = "-" + RHSStr; 12315 } else if (ExplicitPlus) { 12316 RHSStr = "+" + RHSStr; 12317 } 12318 12319 StringRef LHSStrRef = LHSStr; 12320 StringRef RHSStrRef = RHSStr; 12321 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12322 // literals. 12323 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12324 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12325 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12326 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12327 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12328 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12329 LHSStrRef.find('\'') != StringRef::npos || 12330 RHSStrRef.find('\'') != StringRef::npos) 12331 return; 12332 12333 bool SuggestXor = 12334 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12335 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12336 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12337 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12338 std::string SuggestedExpr = "1 << " + RHSStr; 12339 bool Overflow = false; 12340 llvm::APInt One = (LeftSideValue - 1); 12341 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12342 if (Overflow) { 12343 if (RightSideIntValue < 64) 12344 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12345 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12346 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12347 else if (RightSideIntValue == 64) 12348 S.Diag(Loc, diag::warn_xor_used_as_pow) 12349 << ExprStr << toString(XorValue, 10, true); 12350 else 12351 return; 12352 } else { 12353 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12354 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12355 << toString(PowValue, 10, true) 12356 << FixItHint::CreateReplacement( 12357 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12358 } 12359 12360 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12361 << ("0x2 ^ " + RHSStr) << SuggestXor; 12362 } else if (LeftSideValue == 10) { 12363 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12364 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12365 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12366 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12367 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12368 << ("0xA ^ " + RHSStr) << SuggestXor; 12369 } 12370 } 12371 12372 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12373 SourceLocation Loc) { 12374 // Ensure that either both operands are of the same vector type, or 12375 // one operand is of a vector type and the other is of its element type. 12376 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12377 /*AllowBothBool*/true, 12378 /*AllowBoolConversions*/false); 12379 if (vType.isNull()) 12380 return InvalidOperands(Loc, LHS, RHS); 12381 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12382 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12383 return InvalidOperands(Loc, LHS, RHS); 12384 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12385 // usage of the logical operators && and || with vectors in C. This 12386 // check could be notionally dropped. 12387 if (!getLangOpts().CPlusPlus && 12388 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12389 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12390 12391 return GetSignedVectorType(LHS.get()->getType()); 12392 } 12393 12394 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12395 SourceLocation Loc, 12396 bool IsCompAssign) { 12397 if (!IsCompAssign) { 12398 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12399 if (LHS.isInvalid()) 12400 return QualType(); 12401 } 12402 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12403 if (RHS.isInvalid()) 12404 return QualType(); 12405 12406 // For conversion purposes, we ignore any qualifiers. 12407 // For example, "const float" and "float" are equivalent. 12408 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12409 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12410 12411 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12412 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12413 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12414 12415 if (Context.hasSameType(LHSType, RHSType)) 12416 return LHSType; 12417 12418 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12419 // case we have to return InvalidOperands. 12420 ExprResult OriginalLHS = LHS; 12421 ExprResult OriginalRHS = RHS; 12422 if (LHSMatType && !RHSMatType) { 12423 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12424 if (!RHS.isInvalid()) 12425 return LHSType; 12426 12427 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12428 } 12429 12430 if (!LHSMatType && RHSMatType) { 12431 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12432 if (!LHS.isInvalid()) 12433 return RHSType; 12434 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12435 } 12436 12437 return InvalidOperands(Loc, LHS, RHS); 12438 } 12439 12440 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12441 SourceLocation Loc, 12442 bool IsCompAssign) { 12443 if (!IsCompAssign) { 12444 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12445 if (LHS.isInvalid()) 12446 return QualType(); 12447 } 12448 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12449 if (RHS.isInvalid()) 12450 return QualType(); 12451 12452 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12453 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12454 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12455 12456 if (LHSMatType && RHSMatType) { 12457 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12458 return InvalidOperands(Loc, LHS, RHS); 12459 12460 if (!Context.hasSameType(LHSMatType->getElementType(), 12461 RHSMatType->getElementType())) 12462 return InvalidOperands(Loc, LHS, RHS); 12463 12464 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12465 LHSMatType->getNumRows(), 12466 RHSMatType->getNumColumns()); 12467 } 12468 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12469 } 12470 12471 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12472 SourceLocation Loc, 12473 BinaryOperatorKind Opc) { 12474 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12475 12476 bool IsCompAssign = 12477 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12478 12479 if (LHS.get()->getType()->isVectorType() || 12480 RHS.get()->getType()->isVectorType()) { 12481 if (LHS.get()->getType()->hasIntegerRepresentation() && 12482 RHS.get()->getType()->hasIntegerRepresentation()) 12483 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12484 /*AllowBothBool*/true, 12485 /*AllowBoolConversions*/getLangOpts().ZVector); 12486 return InvalidOperands(Loc, LHS, RHS); 12487 } 12488 12489 if (Opc == BO_And) 12490 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12491 12492 if (LHS.get()->getType()->hasFloatingRepresentation() || 12493 RHS.get()->getType()->hasFloatingRepresentation()) 12494 return InvalidOperands(Loc, LHS, RHS); 12495 12496 ExprResult LHSResult = LHS, RHSResult = RHS; 12497 QualType compType = UsualArithmeticConversions( 12498 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12499 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12500 return QualType(); 12501 LHS = LHSResult.get(); 12502 RHS = RHSResult.get(); 12503 12504 if (Opc == BO_Xor) 12505 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12506 12507 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12508 return compType; 12509 return InvalidOperands(Loc, LHS, RHS); 12510 } 12511 12512 // C99 6.5.[13,14] 12513 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12514 SourceLocation Loc, 12515 BinaryOperatorKind Opc) { 12516 // Check vector operands differently. 12517 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12518 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12519 12520 bool EnumConstantInBoolContext = false; 12521 for (const ExprResult &HS : {LHS, RHS}) { 12522 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12523 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12524 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12525 EnumConstantInBoolContext = true; 12526 } 12527 } 12528 12529 if (EnumConstantInBoolContext) 12530 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12531 12532 // Diagnose cases where the user write a logical and/or but probably meant a 12533 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12534 // is a constant. 12535 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12536 !LHS.get()->getType()->isBooleanType() && 12537 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12538 // Don't warn in macros or template instantiations. 12539 !Loc.isMacroID() && !inTemplateInstantiation()) { 12540 // If the RHS can be constant folded, and if it constant folds to something 12541 // that isn't 0 or 1 (which indicate a potential logical operation that 12542 // happened to fold to true/false) then warn. 12543 // Parens on the RHS are ignored. 12544 Expr::EvalResult EVResult; 12545 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12546 llvm::APSInt Result = EVResult.Val.getInt(); 12547 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12548 !RHS.get()->getExprLoc().isMacroID()) || 12549 (Result != 0 && Result != 1)) { 12550 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12551 << RHS.get()->getSourceRange() 12552 << (Opc == BO_LAnd ? "&&" : "||"); 12553 // Suggest replacing the logical operator with the bitwise version 12554 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12555 << (Opc == BO_LAnd ? "&" : "|") 12556 << FixItHint::CreateReplacement(SourceRange( 12557 Loc, getLocForEndOfToken(Loc)), 12558 Opc == BO_LAnd ? "&" : "|"); 12559 if (Opc == BO_LAnd) 12560 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12561 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12562 << FixItHint::CreateRemoval( 12563 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12564 RHS.get()->getEndLoc())); 12565 } 12566 } 12567 } 12568 12569 if (!Context.getLangOpts().CPlusPlus) { 12570 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12571 // not operate on the built-in scalar and vector float types. 12572 if (Context.getLangOpts().OpenCL && 12573 Context.getLangOpts().OpenCLVersion < 120) { 12574 if (LHS.get()->getType()->isFloatingType() || 12575 RHS.get()->getType()->isFloatingType()) 12576 return InvalidOperands(Loc, LHS, RHS); 12577 } 12578 12579 LHS = UsualUnaryConversions(LHS.get()); 12580 if (LHS.isInvalid()) 12581 return QualType(); 12582 12583 RHS = UsualUnaryConversions(RHS.get()); 12584 if (RHS.isInvalid()) 12585 return QualType(); 12586 12587 if (!LHS.get()->getType()->isScalarType() || 12588 !RHS.get()->getType()->isScalarType()) 12589 return InvalidOperands(Loc, LHS, RHS); 12590 12591 return Context.IntTy; 12592 } 12593 12594 // The following is safe because we only use this method for 12595 // non-overloadable operands. 12596 12597 // C++ [expr.log.and]p1 12598 // C++ [expr.log.or]p1 12599 // The operands are both contextually converted to type bool. 12600 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12601 if (LHSRes.isInvalid()) 12602 return InvalidOperands(Loc, LHS, RHS); 12603 LHS = LHSRes; 12604 12605 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12606 if (RHSRes.isInvalid()) 12607 return InvalidOperands(Loc, LHS, RHS); 12608 RHS = RHSRes; 12609 12610 // C++ [expr.log.and]p2 12611 // C++ [expr.log.or]p2 12612 // The result is a bool. 12613 return Context.BoolTy; 12614 } 12615 12616 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12617 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12618 if (!ME) return false; 12619 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12620 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12621 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12622 if (!Base) return false; 12623 return Base->getMethodDecl() != nullptr; 12624 } 12625 12626 /// Is the given expression (which must be 'const') a reference to a 12627 /// variable which was originally non-const, but which has become 12628 /// 'const' due to being captured within a block? 12629 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12630 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12631 assert(E->isLValue() && E->getType().isConstQualified()); 12632 E = E->IgnoreParens(); 12633 12634 // Must be a reference to a declaration from an enclosing scope. 12635 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12636 if (!DRE) return NCCK_None; 12637 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12638 12639 // The declaration must be a variable which is not declared 'const'. 12640 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12641 if (!var) return NCCK_None; 12642 if (var->getType().isConstQualified()) return NCCK_None; 12643 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12644 12645 // Decide whether the first capture was for a block or a lambda. 12646 DeclContext *DC = S.CurContext, *Prev = nullptr; 12647 // Decide whether the first capture was for a block or a lambda. 12648 while (DC) { 12649 // For init-capture, it is possible that the variable belongs to the 12650 // template pattern of the current context. 12651 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12652 if (var->isInitCapture() && 12653 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12654 break; 12655 if (DC == var->getDeclContext()) 12656 break; 12657 Prev = DC; 12658 DC = DC->getParent(); 12659 } 12660 // Unless we have an init-capture, we've gone one step too far. 12661 if (!var->isInitCapture()) 12662 DC = Prev; 12663 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12664 } 12665 12666 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12667 Ty = Ty.getNonReferenceType(); 12668 if (IsDereference && Ty->isPointerType()) 12669 Ty = Ty->getPointeeType(); 12670 return !Ty.isConstQualified(); 12671 } 12672 12673 // Update err_typecheck_assign_const and note_typecheck_assign_const 12674 // when this enum is changed. 12675 enum { 12676 ConstFunction, 12677 ConstVariable, 12678 ConstMember, 12679 ConstMethod, 12680 NestedConstMember, 12681 ConstUnknown, // Keep as last element 12682 }; 12683 12684 /// Emit the "read-only variable not assignable" error and print notes to give 12685 /// more information about why the variable is not assignable, such as pointing 12686 /// to the declaration of a const variable, showing that a method is const, or 12687 /// that the function is returning a const reference. 12688 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12689 SourceLocation Loc) { 12690 SourceRange ExprRange = E->getSourceRange(); 12691 12692 // Only emit one error on the first const found. All other consts will emit 12693 // a note to the error. 12694 bool DiagnosticEmitted = false; 12695 12696 // Track if the current expression is the result of a dereference, and if the 12697 // next checked expression is the result of a dereference. 12698 bool IsDereference = false; 12699 bool NextIsDereference = false; 12700 12701 // Loop to process MemberExpr chains. 12702 while (true) { 12703 IsDereference = NextIsDereference; 12704 12705 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12706 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12707 NextIsDereference = ME->isArrow(); 12708 const ValueDecl *VD = ME->getMemberDecl(); 12709 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12710 // Mutable fields can be modified even if the class is const. 12711 if (Field->isMutable()) { 12712 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12713 break; 12714 } 12715 12716 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12717 if (!DiagnosticEmitted) { 12718 S.Diag(Loc, diag::err_typecheck_assign_const) 12719 << ExprRange << ConstMember << false /*static*/ << Field 12720 << Field->getType(); 12721 DiagnosticEmitted = true; 12722 } 12723 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12724 << ConstMember << false /*static*/ << Field << Field->getType() 12725 << Field->getSourceRange(); 12726 } 12727 E = ME->getBase(); 12728 continue; 12729 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12730 if (VDecl->getType().isConstQualified()) { 12731 if (!DiagnosticEmitted) { 12732 S.Diag(Loc, diag::err_typecheck_assign_const) 12733 << ExprRange << ConstMember << true /*static*/ << VDecl 12734 << VDecl->getType(); 12735 DiagnosticEmitted = true; 12736 } 12737 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12738 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12739 << VDecl->getSourceRange(); 12740 } 12741 // Static fields do not inherit constness from parents. 12742 break; 12743 } 12744 break; // End MemberExpr 12745 } else if (const ArraySubscriptExpr *ASE = 12746 dyn_cast<ArraySubscriptExpr>(E)) { 12747 E = ASE->getBase()->IgnoreParenImpCasts(); 12748 continue; 12749 } else if (const ExtVectorElementExpr *EVE = 12750 dyn_cast<ExtVectorElementExpr>(E)) { 12751 E = EVE->getBase()->IgnoreParenImpCasts(); 12752 continue; 12753 } 12754 break; 12755 } 12756 12757 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12758 // Function calls 12759 const FunctionDecl *FD = CE->getDirectCallee(); 12760 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12761 if (!DiagnosticEmitted) { 12762 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12763 << ConstFunction << FD; 12764 DiagnosticEmitted = true; 12765 } 12766 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12767 diag::note_typecheck_assign_const) 12768 << ConstFunction << FD << FD->getReturnType() 12769 << FD->getReturnTypeSourceRange(); 12770 } 12771 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12772 // Point to variable declaration. 12773 if (const ValueDecl *VD = DRE->getDecl()) { 12774 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12775 if (!DiagnosticEmitted) { 12776 S.Diag(Loc, diag::err_typecheck_assign_const) 12777 << ExprRange << ConstVariable << VD << VD->getType(); 12778 DiagnosticEmitted = true; 12779 } 12780 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12781 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12782 } 12783 } 12784 } else if (isa<CXXThisExpr>(E)) { 12785 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12786 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12787 if (MD->isConst()) { 12788 if (!DiagnosticEmitted) { 12789 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12790 << ConstMethod << MD; 12791 DiagnosticEmitted = true; 12792 } 12793 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12794 << ConstMethod << MD << MD->getSourceRange(); 12795 } 12796 } 12797 } 12798 } 12799 12800 if (DiagnosticEmitted) 12801 return; 12802 12803 // Can't determine a more specific message, so display the generic error. 12804 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12805 } 12806 12807 enum OriginalExprKind { 12808 OEK_Variable, 12809 OEK_Member, 12810 OEK_LValue 12811 }; 12812 12813 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12814 const RecordType *Ty, 12815 SourceLocation Loc, SourceRange Range, 12816 OriginalExprKind OEK, 12817 bool &DiagnosticEmitted) { 12818 std::vector<const RecordType *> RecordTypeList; 12819 RecordTypeList.push_back(Ty); 12820 unsigned NextToCheckIndex = 0; 12821 // We walk the record hierarchy breadth-first to ensure that we print 12822 // diagnostics in field nesting order. 12823 while (RecordTypeList.size() > NextToCheckIndex) { 12824 bool IsNested = NextToCheckIndex > 0; 12825 for (const FieldDecl *Field : 12826 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12827 // First, check every field for constness. 12828 QualType FieldTy = Field->getType(); 12829 if (FieldTy.isConstQualified()) { 12830 if (!DiagnosticEmitted) { 12831 S.Diag(Loc, diag::err_typecheck_assign_const) 12832 << Range << NestedConstMember << OEK << VD 12833 << IsNested << Field; 12834 DiagnosticEmitted = true; 12835 } 12836 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12837 << NestedConstMember << IsNested << Field 12838 << FieldTy << Field->getSourceRange(); 12839 } 12840 12841 // Then we append it to the list to check next in order. 12842 FieldTy = FieldTy.getCanonicalType(); 12843 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12844 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12845 RecordTypeList.push_back(FieldRecTy); 12846 } 12847 } 12848 ++NextToCheckIndex; 12849 } 12850 } 12851 12852 /// Emit an error for the case where a record we are trying to assign to has a 12853 /// const-qualified field somewhere in its hierarchy. 12854 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12855 SourceLocation Loc) { 12856 QualType Ty = E->getType(); 12857 assert(Ty->isRecordType() && "lvalue was not record?"); 12858 SourceRange Range = E->getSourceRange(); 12859 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12860 bool DiagEmitted = false; 12861 12862 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12863 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12864 Range, OEK_Member, DiagEmitted); 12865 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12866 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12867 Range, OEK_Variable, DiagEmitted); 12868 else 12869 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12870 Range, OEK_LValue, DiagEmitted); 12871 if (!DiagEmitted) 12872 DiagnoseConstAssignment(S, E, Loc); 12873 } 12874 12875 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12876 /// emit an error and return true. If so, return false. 12877 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12878 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12879 12880 S.CheckShadowingDeclModification(E, Loc); 12881 12882 SourceLocation OrigLoc = Loc; 12883 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12884 &Loc); 12885 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12886 IsLV = Expr::MLV_InvalidMessageExpression; 12887 if (IsLV == Expr::MLV_Valid) 12888 return false; 12889 12890 unsigned DiagID = 0; 12891 bool NeedType = false; 12892 switch (IsLV) { // C99 6.5.16p2 12893 case Expr::MLV_ConstQualified: 12894 // Use a specialized diagnostic when we're assigning to an object 12895 // from an enclosing function or block. 12896 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12897 if (NCCK == NCCK_Block) 12898 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12899 else 12900 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12901 break; 12902 } 12903 12904 // In ARC, use some specialized diagnostics for occasions where we 12905 // infer 'const'. These are always pseudo-strong variables. 12906 if (S.getLangOpts().ObjCAutoRefCount) { 12907 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12908 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12909 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12910 12911 // Use the normal diagnostic if it's pseudo-__strong but the 12912 // user actually wrote 'const'. 12913 if (var->isARCPseudoStrong() && 12914 (!var->getTypeSourceInfo() || 12915 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12916 // There are three pseudo-strong cases: 12917 // - self 12918 ObjCMethodDecl *method = S.getCurMethodDecl(); 12919 if (method && var == method->getSelfDecl()) { 12920 DiagID = method->isClassMethod() 12921 ? diag::err_typecheck_arc_assign_self_class_method 12922 : diag::err_typecheck_arc_assign_self; 12923 12924 // - Objective-C externally_retained attribute. 12925 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12926 isa<ParmVarDecl>(var)) { 12927 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12928 12929 // - fast enumeration variables 12930 } else { 12931 DiagID = diag::err_typecheck_arr_assign_enumeration; 12932 } 12933 12934 SourceRange Assign; 12935 if (Loc != OrigLoc) 12936 Assign = SourceRange(OrigLoc, OrigLoc); 12937 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12938 // We need to preserve the AST regardless, so migration tool 12939 // can do its job. 12940 return false; 12941 } 12942 } 12943 } 12944 12945 // If none of the special cases above are triggered, then this is a 12946 // simple const assignment. 12947 if (DiagID == 0) { 12948 DiagnoseConstAssignment(S, E, Loc); 12949 return true; 12950 } 12951 12952 break; 12953 case Expr::MLV_ConstAddrSpace: 12954 DiagnoseConstAssignment(S, E, Loc); 12955 return true; 12956 case Expr::MLV_ConstQualifiedField: 12957 DiagnoseRecursiveConstFields(S, E, Loc); 12958 return true; 12959 case Expr::MLV_ArrayType: 12960 case Expr::MLV_ArrayTemporary: 12961 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12962 NeedType = true; 12963 break; 12964 case Expr::MLV_NotObjectType: 12965 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12966 NeedType = true; 12967 break; 12968 case Expr::MLV_LValueCast: 12969 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12970 break; 12971 case Expr::MLV_Valid: 12972 llvm_unreachable("did not take early return for MLV_Valid"); 12973 case Expr::MLV_InvalidExpression: 12974 case Expr::MLV_MemberFunction: 12975 case Expr::MLV_ClassTemporary: 12976 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12977 break; 12978 case Expr::MLV_IncompleteType: 12979 case Expr::MLV_IncompleteVoidType: 12980 return S.RequireCompleteType(Loc, E->getType(), 12981 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12982 case Expr::MLV_DuplicateVectorComponents: 12983 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12984 break; 12985 case Expr::MLV_NoSetterProperty: 12986 llvm_unreachable("readonly properties should be processed differently"); 12987 case Expr::MLV_InvalidMessageExpression: 12988 DiagID = diag::err_readonly_message_assignment; 12989 break; 12990 case Expr::MLV_SubObjCPropertySetting: 12991 DiagID = diag::err_no_subobject_property_setting; 12992 break; 12993 } 12994 12995 SourceRange Assign; 12996 if (Loc != OrigLoc) 12997 Assign = SourceRange(OrigLoc, OrigLoc); 12998 if (NeedType) 12999 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13000 else 13001 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13002 return true; 13003 } 13004 13005 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13006 SourceLocation Loc, 13007 Sema &Sema) { 13008 if (Sema.inTemplateInstantiation()) 13009 return; 13010 if (Sema.isUnevaluatedContext()) 13011 return; 13012 if (Loc.isInvalid() || Loc.isMacroID()) 13013 return; 13014 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13015 return; 13016 13017 // C / C++ fields 13018 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13019 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13020 if (ML && MR) { 13021 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13022 return; 13023 const ValueDecl *LHSDecl = 13024 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13025 const ValueDecl *RHSDecl = 13026 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13027 if (LHSDecl != RHSDecl) 13028 return; 13029 if (LHSDecl->getType().isVolatileQualified()) 13030 return; 13031 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13032 if (RefTy->getPointeeType().isVolatileQualified()) 13033 return; 13034 13035 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13036 } 13037 13038 // Objective-C instance variables 13039 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13040 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13041 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13042 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13043 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13044 if (RL && RR && RL->getDecl() == RR->getDecl()) 13045 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13046 } 13047 } 13048 13049 // C99 6.5.16.1 13050 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13051 SourceLocation Loc, 13052 QualType CompoundType) { 13053 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13054 13055 // Verify that LHS is a modifiable lvalue, and emit error if not. 13056 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13057 return QualType(); 13058 13059 QualType LHSType = LHSExpr->getType(); 13060 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13061 CompoundType; 13062 // OpenCL v1.2 s6.1.1.1 p2: 13063 // The half data type can only be used to declare a pointer to a buffer that 13064 // contains half values 13065 if (getLangOpts().OpenCL && 13066 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13067 LHSType->isHalfType()) { 13068 Diag(Loc, diag::err_opencl_half_load_store) << 1 13069 << LHSType.getUnqualifiedType(); 13070 return QualType(); 13071 } 13072 13073 AssignConvertType ConvTy; 13074 if (CompoundType.isNull()) { 13075 Expr *RHSCheck = RHS.get(); 13076 13077 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13078 13079 QualType LHSTy(LHSType); 13080 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13081 if (RHS.isInvalid()) 13082 return QualType(); 13083 // Special case of NSObject attributes on c-style pointer types. 13084 if (ConvTy == IncompatiblePointer && 13085 ((Context.isObjCNSObjectType(LHSType) && 13086 RHSType->isObjCObjectPointerType()) || 13087 (Context.isObjCNSObjectType(RHSType) && 13088 LHSType->isObjCObjectPointerType()))) 13089 ConvTy = Compatible; 13090 13091 if (ConvTy == Compatible && 13092 LHSType->isObjCObjectType()) 13093 Diag(Loc, diag::err_objc_object_assignment) 13094 << LHSType; 13095 13096 // If the RHS is a unary plus or minus, check to see if they = and + are 13097 // right next to each other. If so, the user may have typo'd "x =+ 4" 13098 // instead of "x += 4". 13099 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13100 RHSCheck = ICE->getSubExpr(); 13101 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13102 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13103 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13104 // Only if the two operators are exactly adjacent. 13105 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13106 // And there is a space or other character before the subexpr of the 13107 // unary +/-. We don't want to warn on "x=-1". 13108 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13109 UO->getSubExpr()->getBeginLoc().isFileID()) { 13110 Diag(Loc, diag::warn_not_compound_assign) 13111 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13112 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13113 } 13114 } 13115 13116 if (ConvTy == Compatible) { 13117 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13118 // Warn about retain cycles where a block captures the LHS, but 13119 // not if the LHS is a simple variable into which the block is 13120 // being stored...unless that variable can be captured by reference! 13121 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13122 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13123 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13124 checkRetainCycles(LHSExpr, RHS.get()); 13125 } 13126 13127 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13128 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13129 // It is safe to assign a weak reference into a strong variable. 13130 // Although this code can still have problems: 13131 // id x = self.weakProp; 13132 // id y = self.weakProp; 13133 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13134 // paths through the function. This should be revisited if 13135 // -Wrepeated-use-of-weak is made flow-sensitive. 13136 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13137 // variable, which will be valid for the current autorelease scope. 13138 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13139 RHS.get()->getBeginLoc())) 13140 getCurFunction()->markSafeWeakUse(RHS.get()); 13141 13142 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13143 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13144 } 13145 } 13146 } else { 13147 // Compound assignment "x += y" 13148 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13149 } 13150 13151 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13152 RHS.get(), AA_Assigning)) 13153 return QualType(); 13154 13155 CheckForNullPointerDereference(*this, LHSExpr); 13156 13157 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13158 if (CompoundType.isNull()) { 13159 // C++2a [expr.ass]p5: 13160 // A simple-assignment whose left operand is of a volatile-qualified 13161 // type is deprecated unless the assignment is either a discarded-value 13162 // expression or an unevaluated operand 13163 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13164 } else { 13165 // C++2a [expr.ass]p6: 13166 // [Compound-assignment] expressions are deprecated if E1 has 13167 // volatile-qualified type 13168 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13169 } 13170 } 13171 13172 // C99 6.5.16p3: The type of an assignment expression is the type of the 13173 // left operand unless the left operand has qualified type, in which case 13174 // it is the unqualified version of the type of the left operand. 13175 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13176 // is converted to the type of the assignment expression (above). 13177 // C++ 5.17p1: the type of the assignment expression is that of its left 13178 // operand. 13179 return (getLangOpts().CPlusPlus 13180 ? LHSType : LHSType.getUnqualifiedType()); 13181 } 13182 13183 // Only ignore explicit casts to void. 13184 static bool IgnoreCommaOperand(const Expr *E) { 13185 E = E->IgnoreParens(); 13186 13187 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13188 if (CE->getCastKind() == CK_ToVoid) { 13189 return true; 13190 } 13191 13192 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13193 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13194 CE->getSubExpr()->getType()->isDependentType()) { 13195 return true; 13196 } 13197 } 13198 13199 return false; 13200 } 13201 13202 // Look for instances where it is likely the comma operator is confused with 13203 // another operator. There is an explicit list of acceptable expressions for 13204 // the left hand side of the comma operator, otherwise emit a warning. 13205 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13206 // No warnings in macros 13207 if (Loc.isMacroID()) 13208 return; 13209 13210 // Don't warn in template instantiations. 13211 if (inTemplateInstantiation()) 13212 return; 13213 13214 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13215 // instead, skip more than needed, then call back into here with the 13216 // CommaVisitor in SemaStmt.cpp. 13217 // The listed locations are the initialization and increment portions 13218 // of a for loop. The additional checks are on the condition of 13219 // if statements, do/while loops, and for loops. 13220 // Differences in scope flags for C89 mode requires the extra logic. 13221 const unsigned ForIncrementFlags = 13222 getLangOpts().C99 || getLangOpts().CPlusPlus 13223 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13224 : Scope::ContinueScope | Scope::BreakScope; 13225 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13226 const unsigned ScopeFlags = getCurScope()->getFlags(); 13227 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13228 (ScopeFlags & ForInitFlags) == ForInitFlags) 13229 return; 13230 13231 // If there are multiple comma operators used together, get the RHS of the 13232 // of the comma operator as the LHS. 13233 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13234 if (BO->getOpcode() != BO_Comma) 13235 break; 13236 LHS = BO->getRHS(); 13237 } 13238 13239 // Only allow some expressions on LHS to not warn. 13240 if (IgnoreCommaOperand(LHS)) 13241 return; 13242 13243 Diag(Loc, diag::warn_comma_operator); 13244 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13245 << LHS->getSourceRange() 13246 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13247 LangOpts.CPlusPlus ? "static_cast<void>(" 13248 : "(void)(") 13249 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13250 ")"); 13251 } 13252 13253 // C99 6.5.17 13254 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13255 SourceLocation Loc) { 13256 LHS = S.CheckPlaceholderExpr(LHS.get()); 13257 RHS = S.CheckPlaceholderExpr(RHS.get()); 13258 if (LHS.isInvalid() || RHS.isInvalid()) 13259 return QualType(); 13260 13261 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13262 // operands, but not unary promotions. 13263 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13264 13265 // So we treat the LHS as a ignored value, and in C++ we allow the 13266 // containing site to determine what should be done with the RHS. 13267 LHS = S.IgnoredValueConversions(LHS.get()); 13268 if (LHS.isInvalid()) 13269 return QualType(); 13270 13271 S.DiagnoseUnusedExprResult(LHS.get()); 13272 13273 if (!S.getLangOpts().CPlusPlus) { 13274 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13275 if (RHS.isInvalid()) 13276 return QualType(); 13277 if (!RHS.get()->getType()->isVoidType()) 13278 S.RequireCompleteType(Loc, RHS.get()->getType(), 13279 diag::err_incomplete_type); 13280 } 13281 13282 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13283 S.DiagnoseCommaOperator(LHS.get(), Loc); 13284 13285 return RHS.get()->getType(); 13286 } 13287 13288 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13289 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13290 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13291 ExprValueKind &VK, 13292 ExprObjectKind &OK, 13293 SourceLocation OpLoc, 13294 bool IsInc, bool IsPrefix) { 13295 if (Op->isTypeDependent()) 13296 return S.Context.DependentTy; 13297 13298 QualType ResType = Op->getType(); 13299 // Atomic types can be used for increment / decrement where the non-atomic 13300 // versions can, so ignore the _Atomic() specifier for the purpose of 13301 // checking. 13302 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13303 ResType = ResAtomicType->getValueType(); 13304 13305 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13306 13307 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13308 // Decrement of bool is not allowed. 13309 if (!IsInc) { 13310 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13311 return QualType(); 13312 } 13313 // Increment of bool sets it to true, but is deprecated. 13314 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13315 : diag::warn_increment_bool) 13316 << Op->getSourceRange(); 13317 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13318 // Error on enum increments and decrements in C++ mode 13319 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13320 return QualType(); 13321 } else if (ResType->isRealType()) { 13322 // OK! 13323 } else if (ResType->isPointerType()) { 13324 // C99 6.5.2.4p2, 6.5.6p2 13325 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13326 return QualType(); 13327 } else if (ResType->isObjCObjectPointerType()) { 13328 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13329 // Otherwise, we just need a complete type. 13330 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13331 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13332 return QualType(); 13333 } else if (ResType->isAnyComplexType()) { 13334 // C99 does not support ++/-- on complex types, we allow as an extension. 13335 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13336 << ResType << Op->getSourceRange(); 13337 } else if (ResType->isPlaceholderType()) { 13338 ExprResult PR = S.CheckPlaceholderExpr(Op); 13339 if (PR.isInvalid()) return QualType(); 13340 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13341 IsInc, IsPrefix); 13342 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13343 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13344 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13345 (ResType->castAs<VectorType>()->getVectorKind() != 13346 VectorType::AltiVecBool)) { 13347 // The z vector extensions allow ++ and -- for non-bool vectors. 13348 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13349 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13350 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13351 } else { 13352 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13353 << ResType << int(IsInc) << Op->getSourceRange(); 13354 return QualType(); 13355 } 13356 // At this point, we know we have a real, complex or pointer type. 13357 // Now make sure the operand is a modifiable lvalue. 13358 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13359 return QualType(); 13360 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13361 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13362 // An operand with volatile-qualified type is deprecated 13363 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13364 << IsInc << ResType; 13365 } 13366 // In C++, a prefix increment is the same type as the operand. Otherwise 13367 // (in C or with postfix), the increment is the unqualified type of the 13368 // operand. 13369 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13370 VK = VK_LValue; 13371 OK = Op->getObjectKind(); 13372 return ResType; 13373 } else { 13374 VK = VK_PRValue; 13375 return ResType.getUnqualifiedType(); 13376 } 13377 } 13378 13379 13380 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13381 /// This routine allows us to typecheck complex/recursive expressions 13382 /// where the declaration is needed for type checking. We only need to 13383 /// handle cases when the expression references a function designator 13384 /// or is an lvalue. Here are some examples: 13385 /// - &(x) => x 13386 /// - &*****f => f for f a function designator. 13387 /// - &s.xx => s 13388 /// - &s.zz[1].yy -> s, if zz is an array 13389 /// - *(x + 1) -> x, if x is an array 13390 /// - &"123"[2] -> 0 13391 /// - & __real__ x -> x 13392 /// 13393 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13394 /// members. 13395 static ValueDecl *getPrimaryDecl(Expr *E) { 13396 switch (E->getStmtClass()) { 13397 case Stmt::DeclRefExprClass: 13398 return cast<DeclRefExpr>(E)->getDecl(); 13399 case Stmt::MemberExprClass: 13400 // If this is an arrow operator, the address is an offset from 13401 // the base's value, so the object the base refers to is 13402 // irrelevant. 13403 if (cast<MemberExpr>(E)->isArrow()) 13404 return nullptr; 13405 // Otherwise, the expression refers to a part of the base 13406 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13407 case Stmt::ArraySubscriptExprClass: { 13408 // FIXME: This code shouldn't be necessary! We should catch the implicit 13409 // promotion of register arrays earlier. 13410 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13411 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13412 if (ICE->getSubExpr()->getType()->isArrayType()) 13413 return getPrimaryDecl(ICE->getSubExpr()); 13414 } 13415 return nullptr; 13416 } 13417 case Stmt::UnaryOperatorClass: { 13418 UnaryOperator *UO = cast<UnaryOperator>(E); 13419 13420 switch(UO->getOpcode()) { 13421 case UO_Real: 13422 case UO_Imag: 13423 case UO_Extension: 13424 return getPrimaryDecl(UO->getSubExpr()); 13425 default: 13426 return nullptr; 13427 } 13428 } 13429 case Stmt::ParenExprClass: 13430 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13431 case Stmt::ImplicitCastExprClass: 13432 // If the result of an implicit cast is an l-value, we care about 13433 // the sub-expression; otherwise, the result here doesn't matter. 13434 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13435 case Stmt::CXXUuidofExprClass: 13436 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13437 default: 13438 return nullptr; 13439 } 13440 } 13441 13442 namespace { 13443 enum { 13444 AO_Bit_Field = 0, 13445 AO_Vector_Element = 1, 13446 AO_Property_Expansion = 2, 13447 AO_Register_Variable = 3, 13448 AO_Matrix_Element = 4, 13449 AO_No_Error = 5 13450 }; 13451 } 13452 /// Diagnose invalid operand for address of operations. 13453 /// 13454 /// \param Type The type of operand which cannot have its address taken. 13455 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13456 Expr *E, unsigned Type) { 13457 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13458 } 13459 13460 /// CheckAddressOfOperand - The operand of & must be either a function 13461 /// designator or an lvalue designating an object. If it is an lvalue, the 13462 /// object cannot be declared with storage class register or be a bit field. 13463 /// Note: The usual conversions are *not* applied to the operand of the & 13464 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13465 /// In C++, the operand might be an overloaded function name, in which case 13466 /// we allow the '&' but retain the overloaded-function type. 13467 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13468 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13469 if (PTy->getKind() == BuiltinType::Overload) { 13470 Expr *E = OrigOp.get()->IgnoreParens(); 13471 if (!isa<OverloadExpr>(E)) { 13472 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13473 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13474 << OrigOp.get()->getSourceRange(); 13475 return QualType(); 13476 } 13477 13478 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13479 if (isa<UnresolvedMemberExpr>(Ovl)) 13480 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13481 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13482 << OrigOp.get()->getSourceRange(); 13483 return QualType(); 13484 } 13485 13486 return Context.OverloadTy; 13487 } 13488 13489 if (PTy->getKind() == BuiltinType::UnknownAny) 13490 return Context.UnknownAnyTy; 13491 13492 if (PTy->getKind() == BuiltinType::BoundMember) { 13493 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13494 << OrigOp.get()->getSourceRange(); 13495 return QualType(); 13496 } 13497 13498 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13499 if (OrigOp.isInvalid()) return QualType(); 13500 } 13501 13502 if (OrigOp.get()->isTypeDependent()) 13503 return Context.DependentTy; 13504 13505 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13506 13507 // Make sure to ignore parentheses in subsequent checks 13508 Expr *op = OrigOp.get()->IgnoreParens(); 13509 13510 // In OpenCL captures for blocks called as lambda functions 13511 // are located in the private address space. Blocks used in 13512 // enqueue_kernel can be located in a different address space 13513 // depending on a vendor implementation. Thus preventing 13514 // taking an address of the capture to avoid invalid AS casts. 13515 if (LangOpts.OpenCL) { 13516 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13517 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13518 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13519 return QualType(); 13520 } 13521 } 13522 13523 if (getLangOpts().C99) { 13524 // Implement C99-only parts of addressof rules. 13525 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13526 if (uOp->getOpcode() == UO_Deref) 13527 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13528 // (assuming the deref expression is valid). 13529 return uOp->getSubExpr()->getType(); 13530 } 13531 // Technically, there should be a check for array subscript 13532 // expressions here, but the result of one is always an lvalue anyway. 13533 } 13534 ValueDecl *dcl = getPrimaryDecl(op); 13535 13536 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13537 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13538 op->getBeginLoc())) 13539 return QualType(); 13540 13541 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13542 unsigned AddressOfError = AO_No_Error; 13543 13544 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13545 bool sfinae = (bool)isSFINAEContext(); 13546 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13547 : diag::ext_typecheck_addrof_temporary) 13548 << op->getType() << op->getSourceRange(); 13549 if (sfinae) 13550 return QualType(); 13551 // Materialize the temporary as an lvalue so that we can take its address. 13552 OrigOp = op = 13553 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13554 } else if (isa<ObjCSelectorExpr>(op)) { 13555 return Context.getPointerType(op->getType()); 13556 } else if (lval == Expr::LV_MemberFunction) { 13557 // If it's an instance method, make a member pointer. 13558 // The expression must have exactly the form &A::foo. 13559 13560 // If the underlying expression isn't a decl ref, give up. 13561 if (!isa<DeclRefExpr>(op)) { 13562 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13563 << OrigOp.get()->getSourceRange(); 13564 return QualType(); 13565 } 13566 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13567 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13568 13569 // The id-expression was parenthesized. 13570 if (OrigOp.get() != DRE) { 13571 Diag(OpLoc, diag::err_parens_pointer_member_function) 13572 << OrigOp.get()->getSourceRange(); 13573 13574 // The method was named without a qualifier. 13575 } else if (!DRE->getQualifier()) { 13576 if (MD->getParent()->getName().empty()) 13577 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13578 << op->getSourceRange(); 13579 else { 13580 SmallString<32> Str; 13581 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13582 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13583 << op->getSourceRange() 13584 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13585 } 13586 } 13587 13588 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13589 if (isa<CXXDestructorDecl>(MD)) 13590 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13591 13592 QualType MPTy = Context.getMemberPointerType( 13593 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13594 // Under the MS ABI, lock down the inheritance model now. 13595 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13596 (void)isCompleteType(OpLoc, MPTy); 13597 return MPTy; 13598 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13599 // C99 6.5.3.2p1 13600 // The operand must be either an l-value or a function designator 13601 if (!op->getType()->isFunctionType()) { 13602 // Use a special diagnostic for loads from property references. 13603 if (isa<PseudoObjectExpr>(op)) { 13604 AddressOfError = AO_Property_Expansion; 13605 } else { 13606 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13607 << op->getType() << op->getSourceRange(); 13608 return QualType(); 13609 } 13610 } 13611 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13612 // The operand cannot be a bit-field 13613 AddressOfError = AO_Bit_Field; 13614 } else if (op->getObjectKind() == OK_VectorComponent) { 13615 // The operand cannot be an element of a vector 13616 AddressOfError = AO_Vector_Element; 13617 } else if (op->getObjectKind() == OK_MatrixComponent) { 13618 // The operand cannot be an element of a matrix. 13619 AddressOfError = AO_Matrix_Element; 13620 } else if (dcl) { // C99 6.5.3.2p1 13621 // We have an lvalue with a decl. Make sure the decl is not declared 13622 // with the register storage-class specifier. 13623 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13624 // in C++ it is not error to take address of a register 13625 // variable (c++03 7.1.1P3) 13626 if (vd->getStorageClass() == SC_Register && 13627 !getLangOpts().CPlusPlus) { 13628 AddressOfError = AO_Register_Variable; 13629 } 13630 } else if (isa<MSPropertyDecl>(dcl)) { 13631 AddressOfError = AO_Property_Expansion; 13632 } else if (isa<FunctionTemplateDecl>(dcl)) { 13633 return Context.OverloadTy; 13634 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13635 // Okay: we can take the address of a field. 13636 // Could be a pointer to member, though, if there is an explicit 13637 // scope qualifier for the class. 13638 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13639 DeclContext *Ctx = dcl->getDeclContext(); 13640 if (Ctx && Ctx->isRecord()) { 13641 if (dcl->getType()->isReferenceType()) { 13642 Diag(OpLoc, 13643 diag::err_cannot_form_pointer_to_member_of_reference_type) 13644 << dcl->getDeclName() << dcl->getType(); 13645 return QualType(); 13646 } 13647 13648 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13649 Ctx = Ctx->getParent(); 13650 13651 QualType MPTy = Context.getMemberPointerType( 13652 op->getType(), 13653 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13654 // Under the MS ABI, lock down the inheritance model now. 13655 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13656 (void)isCompleteType(OpLoc, MPTy); 13657 return MPTy; 13658 } 13659 } 13660 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13661 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13662 llvm_unreachable("Unknown/unexpected decl type"); 13663 } 13664 13665 if (AddressOfError != AO_No_Error) { 13666 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13667 return QualType(); 13668 } 13669 13670 if (lval == Expr::LV_IncompleteVoidType) { 13671 // Taking the address of a void variable is technically illegal, but we 13672 // allow it in cases which are otherwise valid. 13673 // Example: "extern void x; void* y = &x;". 13674 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13675 } 13676 13677 // If the operand has type "type", the result has type "pointer to type". 13678 if (op->getType()->isObjCObjectType()) 13679 return Context.getObjCObjectPointerType(op->getType()); 13680 13681 CheckAddressOfPackedMember(op); 13682 13683 return Context.getPointerType(op->getType()); 13684 } 13685 13686 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13687 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13688 if (!DRE) 13689 return; 13690 const Decl *D = DRE->getDecl(); 13691 if (!D) 13692 return; 13693 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13694 if (!Param) 13695 return; 13696 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13697 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13698 return; 13699 if (FunctionScopeInfo *FD = S.getCurFunction()) 13700 if (!FD->ModifiedNonNullParams.count(Param)) 13701 FD->ModifiedNonNullParams.insert(Param); 13702 } 13703 13704 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13705 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13706 SourceLocation OpLoc) { 13707 if (Op->isTypeDependent()) 13708 return S.Context.DependentTy; 13709 13710 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13711 if (ConvResult.isInvalid()) 13712 return QualType(); 13713 Op = ConvResult.get(); 13714 QualType OpTy = Op->getType(); 13715 QualType Result; 13716 13717 if (isa<CXXReinterpretCastExpr>(Op)) { 13718 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13719 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13720 Op->getSourceRange()); 13721 } 13722 13723 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13724 { 13725 Result = PT->getPointeeType(); 13726 } 13727 else if (const ObjCObjectPointerType *OPT = 13728 OpTy->getAs<ObjCObjectPointerType>()) 13729 Result = OPT->getPointeeType(); 13730 else { 13731 ExprResult PR = S.CheckPlaceholderExpr(Op); 13732 if (PR.isInvalid()) return QualType(); 13733 if (PR.get() != Op) 13734 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13735 } 13736 13737 if (Result.isNull()) { 13738 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13739 << OpTy << Op->getSourceRange(); 13740 return QualType(); 13741 } 13742 13743 // Note that per both C89 and C99, indirection is always legal, even if Result 13744 // is an incomplete type or void. It would be possible to warn about 13745 // dereferencing a void pointer, but it's completely well-defined, and such a 13746 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13747 // for pointers to 'void' but is fine for any other pointer type: 13748 // 13749 // C++ [expr.unary.op]p1: 13750 // [...] the expression to which [the unary * operator] is applied shall 13751 // be a pointer to an object type, or a pointer to a function type 13752 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13753 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13754 << OpTy << Op->getSourceRange(); 13755 13756 // Dereferences are usually l-values... 13757 VK = VK_LValue; 13758 13759 // ...except that certain expressions are never l-values in C. 13760 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13761 VK = VK_PRValue; 13762 13763 return Result; 13764 } 13765 13766 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13767 BinaryOperatorKind Opc; 13768 switch (Kind) { 13769 default: llvm_unreachable("Unknown binop!"); 13770 case tok::periodstar: Opc = BO_PtrMemD; break; 13771 case tok::arrowstar: Opc = BO_PtrMemI; break; 13772 case tok::star: Opc = BO_Mul; break; 13773 case tok::slash: Opc = BO_Div; break; 13774 case tok::percent: Opc = BO_Rem; break; 13775 case tok::plus: Opc = BO_Add; break; 13776 case tok::minus: Opc = BO_Sub; break; 13777 case tok::lessless: Opc = BO_Shl; break; 13778 case tok::greatergreater: Opc = BO_Shr; break; 13779 case tok::lessequal: Opc = BO_LE; break; 13780 case tok::less: Opc = BO_LT; break; 13781 case tok::greaterequal: Opc = BO_GE; break; 13782 case tok::greater: Opc = BO_GT; break; 13783 case tok::exclaimequal: Opc = BO_NE; break; 13784 case tok::equalequal: Opc = BO_EQ; break; 13785 case tok::spaceship: Opc = BO_Cmp; break; 13786 case tok::amp: Opc = BO_And; break; 13787 case tok::caret: Opc = BO_Xor; break; 13788 case tok::pipe: Opc = BO_Or; break; 13789 case tok::ampamp: Opc = BO_LAnd; break; 13790 case tok::pipepipe: Opc = BO_LOr; break; 13791 case tok::equal: Opc = BO_Assign; break; 13792 case tok::starequal: Opc = BO_MulAssign; break; 13793 case tok::slashequal: Opc = BO_DivAssign; break; 13794 case tok::percentequal: Opc = BO_RemAssign; break; 13795 case tok::plusequal: Opc = BO_AddAssign; break; 13796 case tok::minusequal: Opc = BO_SubAssign; break; 13797 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13798 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13799 case tok::ampequal: Opc = BO_AndAssign; break; 13800 case tok::caretequal: Opc = BO_XorAssign; break; 13801 case tok::pipeequal: Opc = BO_OrAssign; break; 13802 case tok::comma: Opc = BO_Comma; break; 13803 } 13804 return Opc; 13805 } 13806 13807 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13808 tok::TokenKind Kind) { 13809 UnaryOperatorKind Opc; 13810 switch (Kind) { 13811 default: llvm_unreachable("Unknown unary op!"); 13812 case tok::plusplus: Opc = UO_PreInc; break; 13813 case tok::minusminus: Opc = UO_PreDec; break; 13814 case tok::amp: Opc = UO_AddrOf; break; 13815 case tok::star: Opc = UO_Deref; break; 13816 case tok::plus: Opc = UO_Plus; break; 13817 case tok::minus: Opc = UO_Minus; break; 13818 case tok::tilde: Opc = UO_Not; break; 13819 case tok::exclaim: Opc = UO_LNot; break; 13820 case tok::kw___real: Opc = UO_Real; break; 13821 case tok::kw___imag: Opc = UO_Imag; break; 13822 case tok::kw___extension__: Opc = UO_Extension; break; 13823 } 13824 return Opc; 13825 } 13826 13827 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13828 /// This warning suppressed in the event of macro expansions. 13829 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13830 SourceLocation OpLoc, bool IsBuiltin) { 13831 if (S.inTemplateInstantiation()) 13832 return; 13833 if (S.isUnevaluatedContext()) 13834 return; 13835 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13836 return; 13837 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13838 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13839 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13840 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13841 if (!LHSDeclRef || !RHSDeclRef || 13842 LHSDeclRef->getLocation().isMacroID() || 13843 RHSDeclRef->getLocation().isMacroID()) 13844 return; 13845 const ValueDecl *LHSDecl = 13846 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13847 const ValueDecl *RHSDecl = 13848 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13849 if (LHSDecl != RHSDecl) 13850 return; 13851 if (LHSDecl->getType().isVolatileQualified()) 13852 return; 13853 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13854 if (RefTy->getPointeeType().isVolatileQualified()) 13855 return; 13856 13857 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13858 : diag::warn_self_assignment_overloaded) 13859 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13860 << RHSExpr->getSourceRange(); 13861 } 13862 13863 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13864 /// is usually indicative of introspection within the Objective-C pointer. 13865 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13866 SourceLocation OpLoc) { 13867 if (!S.getLangOpts().ObjC) 13868 return; 13869 13870 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13871 const Expr *LHS = L.get(); 13872 const Expr *RHS = R.get(); 13873 13874 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13875 ObjCPointerExpr = LHS; 13876 OtherExpr = RHS; 13877 } 13878 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13879 ObjCPointerExpr = RHS; 13880 OtherExpr = LHS; 13881 } 13882 13883 // This warning is deliberately made very specific to reduce false 13884 // positives with logic that uses '&' for hashing. This logic mainly 13885 // looks for code trying to introspect into tagged pointers, which 13886 // code should generally never do. 13887 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13888 unsigned Diag = diag::warn_objc_pointer_masking; 13889 // Determine if we are introspecting the result of performSelectorXXX. 13890 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13891 // Special case messages to -performSelector and friends, which 13892 // can return non-pointer values boxed in a pointer value. 13893 // Some clients may wish to silence warnings in this subcase. 13894 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13895 Selector S = ME->getSelector(); 13896 StringRef SelArg0 = S.getNameForSlot(0); 13897 if (SelArg0.startswith("performSelector")) 13898 Diag = diag::warn_objc_pointer_masking_performSelector; 13899 } 13900 13901 S.Diag(OpLoc, Diag) 13902 << ObjCPointerExpr->getSourceRange(); 13903 } 13904 } 13905 13906 static NamedDecl *getDeclFromExpr(Expr *E) { 13907 if (!E) 13908 return nullptr; 13909 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13910 return DRE->getDecl(); 13911 if (auto *ME = dyn_cast<MemberExpr>(E)) 13912 return ME->getMemberDecl(); 13913 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13914 return IRE->getDecl(); 13915 return nullptr; 13916 } 13917 13918 // This helper function promotes a binary operator's operands (which are of a 13919 // half vector type) to a vector of floats and then truncates the result to 13920 // a vector of either half or short. 13921 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13922 BinaryOperatorKind Opc, QualType ResultTy, 13923 ExprValueKind VK, ExprObjectKind OK, 13924 bool IsCompAssign, SourceLocation OpLoc, 13925 FPOptionsOverride FPFeatures) { 13926 auto &Context = S.getASTContext(); 13927 assert((isVector(ResultTy, Context.HalfTy) || 13928 isVector(ResultTy, Context.ShortTy)) && 13929 "Result must be a vector of half or short"); 13930 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13931 isVector(RHS.get()->getType(), Context.HalfTy) && 13932 "both operands expected to be a half vector"); 13933 13934 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13935 QualType BinOpResTy = RHS.get()->getType(); 13936 13937 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13938 // change BinOpResTy to a vector of ints. 13939 if (isVector(ResultTy, Context.ShortTy)) 13940 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13941 13942 if (IsCompAssign) 13943 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13944 ResultTy, VK, OK, OpLoc, FPFeatures, 13945 BinOpResTy, BinOpResTy); 13946 13947 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13948 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13949 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13950 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13951 } 13952 13953 static std::pair<ExprResult, ExprResult> 13954 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13955 Expr *RHSExpr) { 13956 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13957 if (!S.Context.isDependenceAllowed()) { 13958 // C cannot handle TypoExpr nodes on either side of a binop because it 13959 // doesn't handle dependent types properly, so make sure any TypoExprs have 13960 // been dealt with before checking the operands. 13961 LHS = S.CorrectDelayedTyposInExpr(LHS); 13962 RHS = S.CorrectDelayedTyposInExpr( 13963 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13964 [Opc, LHS](Expr *E) { 13965 if (Opc != BO_Assign) 13966 return ExprResult(E); 13967 // Avoid correcting the RHS to the same Expr as the LHS. 13968 Decl *D = getDeclFromExpr(E); 13969 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13970 }); 13971 } 13972 return std::make_pair(LHS, RHS); 13973 } 13974 13975 /// Returns true if conversion between vectors of halfs and vectors of floats 13976 /// is needed. 13977 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13978 Expr *E0, Expr *E1 = nullptr) { 13979 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13980 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13981 return false; 13982 13983 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13984 QualType Ty = E->IgnoreImplicit()->getType(); 13985 13986 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13987 // to vectors of floats. Although the element type of the vectors is __fp16, 13988 // the vectors shouldn't be treated as storage-only types. See the 13989 // discussion here: https://reviews.llvm.org/rG825235c140e7 13990 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13991 if (VT->getVectorKind() == VectorType::NeonVector) 13992 return false; 13993 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13994 } 13995 return false; 13996 }; 13997 13998 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13999 } 14000 14001 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14002 /// operator @p Opc at location @c TokLoc. This routine only supports 14003 /// built-in operations; ActOnBinOp handles overloaded operators. 14004 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14005 BinaryOperatorKind Opc, 14006 Expr *LHSExpr, Expr *RHSExpr) { 14007 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14008 // The syntax only allows initializer lists on the RHS of assignment, 14009 // so we don't need to worry about accepting invalid code for 14010 // non-assignment operators. 14011 // C++11 5.17p9: 14012 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14013 // of x = {} is x = T(). 14014 InitializationKind Kind = InitializationKind::CreateDirectList( 14015 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14016 InitializedEntity Entity = 14017 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14018 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14019 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14020 if (Init.isInvalid()) 14021 return Init; 14022 RHSExpr = Init.get(); 14023 } 14024 14025 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14026 QualType ResultTy; // Result type of the binary operator. 14027 // The following two variables are used for compound assignment operators 14028 QualType CompLHSTy; // Type of LHS after promotions for computation 14029 QualType CompResultTy; // Type of computation result 14030 ExprValueKind VK = VK_PRValue; 14031 ExprObjectKind OK = OK_Ordinary; 14032 bool ConvertHalfVec = false; 14033 14034 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14035 if (!LHS.isUsable() || !RHS.isUsable()) 14036 return ExprError(); 14037 14038 if (getLangOpts().OpenCL) { 14039 QualType LHSTy = LHSExpr->getType(); 14040 QualType RHSTy = RHSExpr->getType(); 14041 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14042 // the ATOMIC_VAR_INIT macro. 14043 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14044 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14045 if (BO_Assign == Opc) 14046 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14047 else 14048 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14049 return ExprError(); 14050 } 14051 14052 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14053 // only with a builtin functions and therefore should be disallowed here. 14054 if (LHSTy->isImageType() || RHSTy->isImageType() || 14055 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14056 LHSTy->isPipeType() || RHSTy->isPipeType() || 14057 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14058 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14059 return ExprError(); 14060 } 14061 } 14062 14063 switch (Opc) { 14064 case BO_Assign: 14065 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14066 if (getLangOpts().CPlusPlus && 14067 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14068 VK = LHS.get()->getValueKind(); 14069 OK = LHS.get()->getObjectKind(); 14070 } 14071 if (!ResultTy.isNull()) { 14072 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14073 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14074 14075 // Avoid copying a block to the heap if the block is assigned to a local 14076 // auto variable that is declared in the same scope as the block. This 14077 // optimization is unsafe if the local variable is declared in an outer 14078 // scope. For example: 14079 // 14080 // BlockTy b; 14081 // { 14082 // b = ^{...}; 14083 // } 14084 // // It is unsafe to invoke the block here if it wasn't copied to the 14085 // // heap. 14086 // b(); 14087 14088 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14089 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14090 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14091 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14092 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14093 14094 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14095 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14096 NTCUC_Assignment, NTCUK_Copy); 14097 } 14098 RecordModifiableNonNullParam(*this, LHS.get()); 14099 break; 14100 case BO_PtrMemD: 14101 case BO_PtrMemI: 14102 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14103 Opc == BO_PtrMemI); 14104 break; 14105 case BO_Mul: 14106 case BO_Div: 14107 ConvertHalfVec = true; 14108 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14109 Opc == BO_Div); 14110 break; 14111 case BO_Rem: 14112 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14113 break; 14114 case BO_Add: 14115 ConvertHalfVec = true; 14116 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14117 break; 14118 case BO_Sub: 14119 ConvertHalfVec = true; 14120 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14121 break; 14122 case BO_Shl: 14123 case BO_Shr: 14124 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14125 break; 14126 case BO_LE: 14127 case BO_LT: 14128 case BO_GE: 14129 case BO_GT: 14130 ConvertHalfVec = true; 14131 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14132 break; 14133 case BO_EQ: 14134 case BO_NE: 14135 ConvertHalfVec = true; 14136 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14137 break; 14138 case BO_Cmp: 14139 ConvertHalfVec = true; 14140 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14141 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14142 break; 14143 case BO_And: 14144 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14145 LLVM_FALLTHROUGH; 14146 case BO_Xor: 14147 case BO_Or: 14148 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14149 break; 14150 case BO_LAnd: 14151 case BO_LOr: 14152 ConvertHalfVec = true; 14153 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14154 break; 14155 case BO_MulAssign: 14156 case BO_DivAssign: 14157 ConvertHalfVec = true; 14158 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14159 Opc == BO_DivAssign); 14160 CompLHSTy = CompResultTy; 14161 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14162 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14163 break; 14164 case BO_RemAssign: 14165 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14166 CompLHSTy = CompResultTy; 14167 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14168 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14169 break; 14170 case BO_AddAssign: 14171 ConvertHalfVec = true; 14172 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14173 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14174 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14175 break; 14176 case BO_SubAssign: 14177 ConvertHalfVec = true; 14178 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14179 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14180 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14181 break; 14182 case BO_ShlAssign: 14183 case BO_ShrAssign: 14184 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14185 CompLHSTy = CompResultTy; 14186 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14187 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14188 break; 14189 case BO_AndAssign: 14190 case BO_OrAssign: // fallthrough 14191 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14192 LLVM_FALLTHROUGH; 14193 case BO_XorAssign: 14194 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14195 CompLHSTy = CompResultTy; 14196 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14197 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14198 break; 14199 case BO_Comma: 14200 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14201 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14202 VK = RHS.get()->getValueKind(); 14203 OK = RHS.get()->getObjectKind(); 14204 } 14205 break; 14206 } 14207 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14208 return ExprError(); 14209 14210 // Some of the binary operations require promoting operands of half vector to 14211 // float vectors and truncating the result back to half vector. For now, we do 14212 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14213 // arm64). 14214 assert( 14215 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14216 isVector(LHS.get()->getType(), Context.HalfTy)) && 14217 "both sides are half vectors or neither sides are"); 14218 ConvertHalfVec = 14219 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14220 14221 // Check for array bounds violations for both sides of the BinaryOperator 14222 CheckArrayAccess(LHS.get()); 14223 CheckArrayAccess(RHS.get()); 14224 14225 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14226 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14227 &Context.Idents.get("object_setClass"), 14228 SourceLocation(), LookupOrdinaryName); 14229 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14230 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14231 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14232 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14233 "object_setClass(") 14234 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14235 ",") 14236 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14237 } 14238 else 14239 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14240 } 14241 else if (const ObjCIvarRefExpr *OIRE = 14242 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14243 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14244 14245 // Opc is not a compound assignment if CompResultTy is null. 14246 if (CompResultTy.isNull()) { 14247 if (ConvertHalfVec) 14248 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14249 OpLoc, CurFPFeatureOverrides()); 14250 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14251 VK, OK, OpLoc, CurFPFeatureOverrides()); 14252 } 14253 14254 // Handle compound assignments. 14255 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14256 OK_ObjCProperty) { 14257 VK = VK_LValue; 14258 OK = LHS.get()->getObjectKind(); 14259 } 14260 14261 // The LHS is not converted to the result type for fixed-point compound 14262 // assignment as the common type is computed on demand. Reset the CompLHSTy 14263 // to the LHS type we would have gotten after unary conversions. 14264 if (CompResultTy->isFixedPointType()) 14265 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14266 14267 if (ConvertHalfVec) 14268 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14269 OpLoc, CurFPFeatureOverrides()); 14270 14271 return CompoundAssignOperator::Create( 14272 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14273 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14274 } 14275 14276 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14277 /// operators are mixed in a way that suggests that the programmer forgot that 14278 /// comparison operators have higher precedence. The most typical example of 14279 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14280 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14281 SourceLocation OpLoc, Expr *LHSExpr, 14282 Expr *RHSExpr) { 14283 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14284 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14285 14286 // Check that one of the sides is a comparison operator and the other isn't. 14287 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14288 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14289 if (isLeftComp == isRightComp) 14290 return; 14291 14292 // Bitwise operations are sometimes used as eager logical ops. 14293 // Don't diagnose this. 14294 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14295 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14296 if (isLeftBitwise || isRightBitwise) 14297 return; 14298 14299 SourceRange DiagRange = isLeftComp 14300 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14301 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14302 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14303 SourceRange ParensRange = 14304 isLeftComp 14305 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14306 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14307 14308 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14309 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14310 SuggestParentheses(Self, OpLoc, 14311 Self.PDiag(diag::note_precedence_silence) << OpStr, 14312 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14313 SuggestParentheses(Self, OpLoc, 14314 Self.PDiag(diag::note_precedence_bitwise_first) 14315 << BinaryOperator::getOpcodeStr(Opc), 14316 ParensRange); 14317 } 14318 14319 /// It accepts a '&&' expr that is inside a '||' one. 14320 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14321 /// in parentheses. 14322 static void 14323 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14324 BinaryOperator *Bop) { 14325 assert(Bop->getOpcode() == BO_LAnd); 14326 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14327 << Bop->getSourceRange() << OpLoc; 14328 SuggestParentheses(Self, Bop->getOperatorLoc(), 14329 Self.PDiag(diag::note_precedence_silence) 14330 << Bop->getOpcodeStr(), 14331 Bop->getSourceRange()); 14332 } 14333 14334 /// Returns true if the given expression can be evaluated as a constant 14335 /// 'true'. 14336 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14337 bool Res; 14338 return !E->isValueDependent() && 14339 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14340 } 14341 14342 /// Returns true if the given expression can be evaluated as a constant 14343 /// 'false'. 14344 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14345 bool Res; 14346 return !E->isValueDependent() && 14347 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14348 } 14349 14350 /// Look for '&&' in the left hand of a '||' expr. 14351 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14352 Expr *LHSExpr, Expr *RHSExpr) { 14353 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14354 if (Bop->getOpcode() == BO_LAnd) { 14355 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14356 if (EvaluatesAsFalse(S, RHSExpr)) 14357 return; 14358 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14359 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14360 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14361 } else if (Bop->getOpcode() == BO_LOr) { 14362 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14363 // If it's "a || b && 1 || c" we didn't warn earlier for 14364 // "a || b && 1", but warn now. 14365 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14366 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14367 } 14368 } 14369 } 14370 } 14371 14372 /// Look for '&&' in the right hand of a '||' expr. 14373 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14374 Expr *LHSExpr, Expr *RHSExpr) { 14375 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14376 if (Bop->getOpcode() == BO_LAnd) { 14377 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14378 if (EvaluatesAsFalse(S, LHSExpr)) 14379 return; 14380 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14381 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14382 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14383 } 14384 } 14385 } 14386 14387 /// Look for bitwise op in the left or right hand of a bitwise op with 14388 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14389 /// the '&' expression in parentheses. 14390 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14391 SourceLocation OpLoc, Expr *SubExpr) { 14392 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14393 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14394 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14395 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14396 << Bop->getSourceRange() << OpLoc; 14397 SuggestParentheses(S, Bop->getOperatorLoc(), 14398 S.PDiag(diag::note_precedence_silence) 14399 << Bop->getOpcodeStr(), 14400 Bop->getSourceRange()); 14401 } 14402 } 14403 } 14404 14405 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14406 Expr *SubExpr, StringRef Shift) { 14407 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14408 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14409 StringRef Op = Bop->getOpcodeStr(); 14410 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14411 << Bop->getSourceRange() << OpLoc << Shift << Op; 14412 SuggestParentheses(S, Bop->getOperatorLoc(), 14413 S.PDiag(diag::note_precedence_silence) << Op, 14414 Bop->getSourceRange()); 14415 } 14416 } 14417 } 14418 14419 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14420 Expr *LHSExpr, Expr *RHSExpr) { 14421 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14422 if (!OCE) 14423 return; 14424 14425 FunctionDecl *FD = OCE->getDirectCallee(); 14426 if (!FD || !FD->isOverloadedOperator()) 14427 return; 14428 14429 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14430 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14431 return; 14432 14433 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14434 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14435 << (Kind == OO_LessLess); 14436 SuggestParentheses(S, OCE->getOperatorLoc(), 14437 S.PDiag(diag::note_precedence_silence) 14438 << (Kind == OO_LessLess ? "<<" : ">>"), 14439 OCE->getSourceRange()); 14440 SuggestParentheses( 14441 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14442 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14443 } 14444 14445 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14446 /// precedence. 14447 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14448 SourceLocation OpLoc, Expr *LHSExpr, 14449 Expr *RHSExpr){ 14450 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14451 if (BinaryOperator::isBitwiseOp(Opc)) 14452 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14453 14454 // Diagnose "arg1 & arg2 | arg3" 14455 if ((Opc == BO_Or || Opc == BO_Xor) && 14456 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14457 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14458 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14459 } 14460 14461 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14462 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14463 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14464 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14465 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14466 } 14467 14468 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14469 || Opc == BO_Shr) { 14470 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14471 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14472 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14473 } 14474 14475 // Warn on overloaded shift operators and comparisons, such as: 14476 // cout << 5 == 4; 14477 if (BinaryOperator::isComparisonOp(Opc)) 14478 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14479 } 14480 14481 // Binary Operators. 'Tok' is the token for the operator. 14482 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14483 tok::TokenKind Kind, 14484 Expr *LHSExpr, Expr *RHSExpr) { 14485 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14486 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14487 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14488 14489 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14490 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14491 14492 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14493 } 14494 14495 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14496 UnresolvedSetImpl &Functions) { 14497 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14498 if (OverOp != OO_None && OverOp != OO_Equal) 14499 LookupOverloadedOperatorName(OverOp, S, Functions); 14500 14501 // In C++20 onwards, we may have a second operator to look up. 14502 if (getLangOpts().CPlusPlus20) { 14503 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14504 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14505 } 14506 } 14507 14508 /// Build an overloaded binary operator expression in the given scope. 14509 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14510 BinaryOperatorKind Opc, 14511 Expr *LHS, Expr *RHS) { 14512 switch (Opc) { 14513 case BO_Assign: 14514 case BO_DivAssign: 14515 case BO_RemAssign: 14516 case BO_SubAssign: 14517 case BO_AndAssign: 14518 case BO_OrAssign: 14519 case BO_XorAssign: 14520 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14521 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14522 break; 14523 default: 14524 break; 14525 } 14526 14527 // Find all of the overloaded operators visible from this point. 14528 UnresolvedSet<16> Functions; 14529 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14530 14531 // Build the (potentially-overloaded, potentially-dependent) 14532 // binary operation. 14533 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14534 } 14535 14536 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14537 BinaryOperatorKind Opc, 14538 Expr *LHSExpr, Expr *RHSExpr) { 14539 ExprResult LHS, RHS; 14540 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14541 if (!LHS.isUsable() || !RHS.isUsable()) 14542 return ExprError(); 14543 LHSExpr = LHS.get(); 14544 RHSExpr = RHS.get(); 14545 14546 // We want to end up calling one of checkPseudoObjectAssignment 14547 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14548 // both expressions are overloadable or either is type-dependent), 14549 // or CreateBuiltinBinOp (in any other case). We also want to get 14550 // any placeholder types out of the way. 14551 14552 // Handle pseudo-objects in the LHS. 14553 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14554 // Assignments with a pseudo-object l-value need special analysis. 14555 if (pty->getKind() == BuiltinType::PseudoObject && 14556 BinaryOperator::isAssignmentOp(Opc)) 14557 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14558 14559 // Don't resolve overloads if the other type is overloadable. 14560 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14561 // We can't actually test that if we still have a placeholder, 14562 // though. Fortunately, none of the exceptions we see in that 14563 // code below are valid when the LHS is an overload set. Note 14564 // that an overload set can be dependently-typed, but it never 14565 // instantiates to having an overloadable type. 14566 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14567 if (resolvedRHS.isInvalid()) return ExprError(); 14568 RHSExpr = resolvedRHS.get(); 14569 14570 if (RHSExpr->isTypeDependent() || 14571 RHSExpr->getType()->isOverloadableType()) 14572 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14573 } 14574 14575 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14576 // template, diagnose the missing 'template' keyword instead of diagnosing 14577 // an invalid use of a bound member function. 14578 // 14579 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14580 // to C++1z [over.over]/1.4, but we already checked for that case above. 14581 if (Opc == BO_LT && inTemplateInstantiation() && 14582 (pty->getKind() == BuiltinType::BoundMember || 14583 pty->getKind() == BuiltinType::Overload)) { 14584 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14585 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14586 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14587 return isa<FunctionTemplateDecl>(ND); 14588 })) { 14589 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14590 : OE->getNameLoc(), 14591 diag::err_template_kw_missing) 14592 << OE->getName().getAsString() << ""; 14593 return ExprError(); 14594 } 14595 } 14596 14597 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14598 if (LHS.isInvalid()) return ExprError(); 14599 LHSExpr = LHS.get(); 14600 } 14601 14602 // Handle pseudo-objects in the RHS. 14603 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14604 // An overload in the RHS can potentially be resolved by the type 14605 // being assigned to. 14606 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14607 if (getLangOpts().CPlusPlus && 14608 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14609 LHSExpr->getType()->isOverloadableType())) 14610 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14611 14612 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14613 } 14614 14615 // Don't resolve overloads if the other type is overloadable. 14616 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14617 LHSExpr->getType()->isOverloadableType()) 14618 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14619 14620 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14621 if (!resolvedRHS.isUsable()) return ExprError(); 14622 RHSExpr = resolvedRHS.get(); 14623 } 14624 14625 if (getLangOpts().CPlusPlus) { 14626 // If either expression is type-dependent, always build an 14627 // overloaded op. 14628 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14629 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14630 14631 // Otherwise, build an overloaded op if either expression has an 14632 // overloadable type. 14633 if (LHSExpr->getType()->isOverloadableType() || 14634 RHSExpr->getType()->isOverloadableType()) 14635 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14636 } 14637 14638 if (getLangOpts().RecoveryAST && 14639 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14640 assert(!getLangOpts().CPlusPlus); 14641 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14642 "Should only occur in error-recovery path."); 14643 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14644 // C [6.15.16] p3: 14645 // An assignment expression has the value of the left operand after the 14646 // assignment, but is not an lvalue. 14647 return CompoundAssignOperator::Create( 14648 Context, LHSExpr, RHSExpr, Opc, 14649 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14650 OpLoc, CurFPFeatureOverrides()); 14651 QualType ResultType; 14652 switch (Opc) { 14653 case BO_Assign: 14654 ResultType = LHSExpr->getType().getUnqualifiedType(); 14655 break; 14656 case BO_LT: 14657 case BO_GT: 14658 case BO_LE: 14659 case BO_GE: 14660 case BO_EQ: 14661 case BO_NE: 14662 case BO_LAnd: 14663 case BO_LOr: 14664 // These operators have a fixed result type regardless of operands. 14665 ResultType = Context.IntTy; 14666 break; 14667 case BO_Comma: 14668 ResultType = RHSExpr->getType(); 14669 break; 14670 default: 14671 ResultType = Context.DependentTy; 14672 break; 14673 } 14674 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14675 VK_PRValue, OK_Ordinary, OpLoc, 14676 CurFPFeatureOverrides()); 14677 } 14678 14679 // Build a built-in binary operation. 14680 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14681 } 14682 14683 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14684 if (T.isNull() || T->isDependentType()) 14685 return false; 14686 14687 if (!T->isPromotableIntegerType()) 14688 return true; 14689 14690 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14691 } 14692 14693 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14694 UnaryOperatorKind Opc, 14695 Expr *InputExpr) { 14696 ExprResult Input = InputExpr; 14697 ExprValueKind VK = VK_PRValue; 14698 ExprObjectKind OK = OK_Ordinary; 14699 QualType resultType; 14700 bool CanOverflow = false; 14701 14702 bool ConvertHalfVec = false; 14703 if (getLangOpts().OpenCL) { 14704 QualType Ty = InputExpr->getType(); 14705 // The only legal unary operation for atomics is '&'. 14706 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14707 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14708 // only with a builtin functions and therefore should be disallowed here. 14709 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14710 || Ty->isBlockPointerType())) { 14711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14712 << InputExpr->getType() 14713 << Input.get()->getSourceRange()); 14714 } 14715 } 14716 14717 switch (Opc) { 14718 case UO_PreInc: 14719 case UO_PreDec: 14720 case UO_PostInc: 14721 case UO_PostDec: 14722 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14723 OpLoc, 14724 Opc == UO_PreInc || 14725 Opc == UO_PostInc, 14726 Opc == UO_PreInc || 14727 Opc == UO_PreDec); 14728 CanOverflow = isOverflowingIntegerType(Context, resultType); 14729 break; 14730 case UO_AddrOf: 14731 resultType = CheckAddressOfOperand(Input, OpLoc); 14732 CheckAddressOfNoDeref(InputExpr); 14733 RecordModifiableNonNullParam(*this, InputExpr); 14734 break; 14735 case UO_Deref: { 14736 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14737 if (Input.isInvalid()) return ExprError(); 14738 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14739 break; 14740 } 14741 case UO_Plus: 14742 case UO_Minus: 14743 CanOverflow = Opc == UO_Minus && 14744 isOverflowingIntegerType(Context, Input.get()->getType()); 14745 Input = UsualUnaryConversions(Input.get()); 14746 if (Input.isInvalid()) return ExprError(); 14747 // Unary plus and minus require promoting an operand of half vector to a 14748 // float vector and truncating the result back to a half vector. For now, we 14749 // do this only when HalfArgsAndReturns is set (that is, when the target is 14750 // arm or arm64). 14751 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14752 14753 // If the operand is a half vector, promote it to a float vector. 14754 if (ConvertHalfVec) 14755 Input = convertVector(Input.get(), Context.FloatTy, *this); 14756 resultType = Input.get()->getType(); 14757 if (resultType->isDependentType()) 14758 break; 14759 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14760 break; 14761 else if (resultType->isVectorType() && 14762 // The z vector extensions don't allow + or - with bool vectors. 14763 (!Context.getLangOpts().ZVector || 14764 resultType->castAs<VectorType>()->getVectorKind() != 14765 VectorType::AltiVecBool)) 14766 break; 14767 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14768 Opc == UO_Plus && 14769 resultType->isPointerType()) 14770 break; 14771 14772 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14773 << resultType << Input.get()->getSourceRange()); 14774 14775 case UO_Not: // bitwise complement 14776 Input = UsualUnaryConversions(Input.get()); 14777 if (Input.isInvalid()) 14778 return ExprError(); 14779 resultType = Input.get()->getType(); 14780 if (resultType->isDependentType()) 14781 break; 14782 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14783 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14784 // C99 does not support '~' for complex conjugation. 14785 Diag(OpLoc, diag::ext_integer_complement_complex) 14786 << resultType << Input.get()->getSourceRange(); 14787 else if (resultType->hasIntegerRepresentation()) 14788 break; 14789 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14790 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14791 // on vector float types. 14792 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14793 if (!T->isIntegerType()) 14794 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14795 << resultType << Input.get()->getSourceRange()); 14796 } else { 14797 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14798 << resultType << Input.get()->getSourceRange()); 14799 } 14800 break; 14801 14802 case UO_LNot: // logical negation 14803 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14804 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14805 if (Input.isInvalid()) return ExprError(); 14806 resultType = Input.get()->getType(); 14807 14808 // Though we still have to promote half FP to float... 14809 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14810 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14811 resultType = Context.FloatTy; 14812 } 14813 14814 if (resultType->isDependentType()) 14815 break; 14816 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14817 // C99 6.5.3.3p1: ok, fallthrough; 14818 if (Context.getLangOpts().CPlusPlus) { 14819 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14820 // operand contextually converted to bool. 14821 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14822 ScalarTypeToBooleanCastKind(resultType)); 14823 } else if (Context.getLangOpts().OpenCL && 14824 Context.getLangOpts().OpenCLVersion < 120) { 14825 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14826 // operate on scalar float types. 14827 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14828 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14829 << resultType << Input.get()->getSourceRange()); 14830 } 14831 } else if (resultType->isExtVectorType()) { 14832 if (Context.getLangOpts().OpenCL && 14833 Context.getLangOpts().OpenCLVersion < 120 && 14834 !Context.getLangOpts().OpenCLCPlusPlus) { 14835 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14836 // operate on vector float types. 14837 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14838 if (!T->isIntegerType()) 14839 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14840 << resultType << Input.get()->getSourceRange()); 14841 } 14842 // Vector logical not returns the signed variant of the operand type. 14843 resultType = GetSignedVectorType(resultType); 14844 break; 14845 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14846 const VectorType *VTy = resultType->castAs<VectorType>(); 14847 if (VTy->getVectorKind() != VectorType::GenericVector) 14848 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14849 << resultType << Input.get()->getSourceRange()); 14850 14851 // Vector logical not returns the signed variant of the operand type. 14852 resultType = GetSignedVectorType(resultType); 14853 break; 14854 } else { 14855 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14856 << resultType << Input.get()->getSourceRange()); 14857 } 14858 14859 // LNot always has type int. C99 6.5.3.3p5. 14860 // In C++, it's bool. C++ 5.3.1p8 14861 resultType = Context.getLogicalOperationType(); 14862 break; 14863 case UO_Real: 14864 case UO_Imag: 14865 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14866 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14867 // complex l-values to ordinary l-values and all other values to r-values. 14868 if (Input.isInvalid()) return ExprError(); 14869 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14870 if (Input.get()->getValueKind() != VK_PRValue && 14871 Input.get()->getObjectKind() == OK_Ordinary) 14872 VK = Input.get()->getValueKind(); 14873 } else if (!getLangOpts().CPlusPlus) { 14874 // In C, a volatile scalar is read by __imag. In C++, it is not. 14875 Input = DefaultLvalueConversion(Input.get()); 14876 } 14877 break; 14878 case UO_Extension: 14879 resultType = Input.get()->getType(); 14880 VK = Input.get()->getValueKind(); 14881 OK = Input.get()->getObjectKind(); 14882 break; 14883 case UO_Coawait: 14884 // It's unnecessary to represent the pass-through operator co_await in the 14885 // AST; just return the input expression instead. 14886 assert(!Input.get()->getType()->isDependentType() && 14887 "the co_await expression must be non-dependant before " 14888 "building operator co_await"); 14889 return Input; 14890 } 14891 if (resultType.isNull() || Input.isInvalid()) 14892 return ExprError(); 14893 14894 // Check for array bounds violations in the operand of the UnaryOperator, 14895 // except for the '*' and '&' operators that have to be handled specially 14896 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14897 // that are explicitly defined as valid by the standard). 14898 if (Opc != UO_AddrOf && Opc != UO_Deref) 14899 CheckArrayAccess(Input.get()); 14900 14901 auto *UO = 14902 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14903 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14904 14905 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14906 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14907 !isUnevaluatedContext()) 14908 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14909 14910 // Convert the result back to a half vector. 14911 if (ConvertHalfVec) 14912 return convertVector(UO, Context.HalfTy, *this); 14913 return UO; 14914 } 14915 14916 /// Determine whether the given expression is a qualified member 14917 /// access expression, of a form that could be turned into a pointer to member 14918 /// with the address-of operator. 14919 bool Sema::isQualifiedMemberAccess(Expr *E) { 14920 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14921 if (!DRE->getQualifier()) 14922 return false; 14923 14924 ValueDecl *VD = DRE->getDecl(); 14925 if (!VD->isCXXClassMember()) 14926 return false; 14927 14928 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14929 return true; 14930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14931 return Method->isInstance(); 14932 14933 return false; 14934 } 14935 14936 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14937 if (!ULE->getQualifier()) 14938 return false; 14939 14940 for (NamedDecl *D : ULE->decls()) { 14941 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14942 if (Method->isInstance()) 14943 return true; 14944 } else { 14945 // Overload set does not contain methods. 14946 break; 14947 } 14948 } 14949 14950 return false; 14951 } 14952 14953 return false; 14954 } 14955 14956 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14957 UnaryOperatorKind Opc, Expr *Input) { 14958 // First things first: handle placeholders so that the 14959 // overloaded-operator check considers the right type. 14960 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14961 // Increment and decrement of pseudo-object references. 14962 if (pty->getKind() == BuiltinType::PseudoObject && 14963 UnaryOperator::isIncrementDecrementOp(Opc)) 14964 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14965 14966 // extension is always a builtin operator. 14967 if (Opc == UO_Extension) 14968 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14969 14970 // & gets special logic for several kinds of placeholder. 14971 // The builtin code knows what to do. 14972 if (Opc == UO_AddrOf && 14973 (pty->getKind() == BuiltinType::Overload || 14974 pty->getKind() == BuiltinType::UnknownAny || 14975 pty->getKind() == BuiltinType::BoundMember)) 14976 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14977 14978 // Anything else needs to be handled now. 14979 ExprResult Result = CheckPlaceholderExpr(Input); 14980 if (Result.isInvalid()) return ExprError(); 14981 Input = Result.get(); 14982 } 14983 14984 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14985 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14986 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14987 // Find all of the overloaded operators visible from this point. 14988 UnresolvedSet<16> Functions; 14989 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14990 if (S && OverOp != OO_None) 14991 LookupOverloadedOperatorName(OverOp, S, Functions); 14992 14993 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14994 } 14995 14996 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14997 } 14998 14999 // Unary Operators. 'Tok' is the token for the operator. 15000 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15001 tok::TokenKind Op, Expr *Input) { 15002 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15003 } 15004 15005 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15006 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15007 LabelDecl *TheDecl) { 15008 TheDecl->markUsed(Context); 15009 // Create the AST node. The address of a label always has type 'void*'. 15010 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15011 Context.getPointerType(Context.VoidTy)); 15012 } 15013 15014 void Sema::ActOnStartStmtExpr() { 15015 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15016 } 15017 15018 void Sema::ActOnStmtExprError() { 15019 // Note that function is also called by TreeTransform when leaving a 15020 // StmtExpr scope without rebuilding anything. 15021 15022 DiscardCleanupsInEvaluationContext(); 15023 PopExpressionEvaluationContext(); 15024 } 15025 15026 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15027 SourceLocation RPLoc) { 15028 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15029 } 15030 15031 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15032 SourceLocation RPLoc, unsigned TemplateDepth) { 15033 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15034 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15035 15036 if (hasAnyUnrecoverableErrorsInThisFunction()) 15037 DiscardCleanupsInEvaluationContext(); 15038 assert(!Cleanup.exprNeedsCleanups() && 15039 "cleanups within StmtExpr not correctly bound!"); 15040 PopExpressionEvaluationContext(); 15041 15042 // FIXME: there are a variety of strange constraints to enforce here, for 15043 // example, it is not possible to goto into a stmt expression apparently. 15044 // More semantic analysis is needed. 15045 15046 // If there are sub-stmts in the compound stmt, take the type of the last one 15047 // as the type of the stmtexpr. 15048 QualType Ty = Context.VoidTy; 15049 bool StmtExprMayBindToTemp = false; 15050 if (!Compound->body_empty()) { 15051 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15052 if (const auto *LastStmt = 15053 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15054 if (const Expr *Value = LastStmt->getExprStmt()) { 15055 StmtExprMayBindToTemp = true; 15056 Ty = Value->getType(); 15057 } 15058 } 15059 } 15060 15061 // FIXME: Check that expression type is complete/non-abstract; statement 15062 // expressions are not lvalues. 15063 Expr *ResStmtExpr = 15064 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15065 if (StmtExprMayBindToTemp) 15066 return MaybeBindToTemporary(ResStmtExpr); 15067 return ResStmtExpr; 15068 } 15069 15070 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15071 if (ER.isInvalid()) 15072 return ExprError(); 15073 15074 // Do function/array conversion on the last expression, but not 15075 // lvalue-to-rvalue. However, initialize an unqualified type. 15076 ER = DefaultFunctionArrayConversion(ER.get()); 15077 if (ER.isInvalid()) 15078 return ExprError(); 15079 Expr *E = ER.get(); 15080 15081 if (E->isTypeDependent()) 15082 return E; 15083 15084 // In ARC, if the final expression ends in a consume, splice 15085 // the consume out and bind it later. In the alternate case 15086 // (when dealing with a retainable type), the result 15087 // initialization will create a produce. In both cases the 15088 // result will be +1, and we'll need to balance that out with 15089 // a bind. 15090 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15091 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15092 return Cast->getSubExpr(); 15093 15094 // FIXME: Provide a better location for the initialization. 15095 return PerformCopyInitialization( 15096 InitializedEntity::InitializeStmtExprResult( 15097 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15098 SourceLocation(), E); 15099 } 15100 15101 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15102 TypeSourceInfo *TInfo, 15103 ArrayRef<OffsetOfComponent> Components, 15104 SourceLocation RParenLoc) { 15105 QualType ArgTy = TInfo->getType(); 15106 bool Dependent = ArgTy->isDependentType(); 15107 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15108 15109 // We must have at least one component that refers to the type, and the first 15110 // one is known to be a field designator. Verify that the ArgTy represents 15111 // a struct/union/class. 15112 if (!Dependent && !ArgTy->isRecordType()) 15113 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15114 << ArgTy << TypeRange); 15115 15116 // Type must be complete per C99 7.17p3 because a declaring a variable 15117 // with an incomplete type would be ill-formed. 15118 if (!Dependent 15119 && RequireCompleteType(BuiltinLoc, ArgTy, 15120 diag::err_offsetof_incomplete_type, TypeRange)) 15121 return ExprError(); 15122 15123 bool DidWarnAboutNonPOD = false; 15124 QualType CurrentType = ArgTy; 15125 SmallVector<OffsetOfNode, 4> Comps; 15126 SmallVector<Expr*, 4> Exprs; 15127 for (const OffsetOfComponent &OC : Components) { 15128 if (OC.isBrackets) { 15129 // Offset of an array sub-field. TODO: Should we allow vector elements? 15130 if (!CurrentType->isDependentType()) { 15131 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15132 if(!AT) 15133 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15134 << CurrentType); 15135 CurrentType = AT->getElementType(); 15136 } else 15137 CurrentType = Context.DependentTy; 15138 15139 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15140 if (IdxRval.isInvalid()) 15141 return ExprError(); 15142 Expr *Idx = IdxRval.get(); 15143 15144 // The expression must be an integral expression. 15145 // FIXME: An integral constant expression? 15146 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15147 !Idx->getType()->isIntegerType()) 15148 return ExprError( 15149 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15150 << Idx->getSourceRange()); 15151 15152 // Record this array index. 15153 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15154 Exprs.push_back(Idx); 15155 continue; 15156 } 15157 15158 // Offset of a field. 15159 if (CurrentType->isDependentType()) { 15160 // We have the offset of a field, but we can't look into the dependent 15161 // type. Just record the identifier of the field. 15162 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15163 CurrentType = Context.DependentTy; 15164 continue; 15165 } 15166 15167 // We need to have a complete type to look into. 15168 if (RequireCompleteType(OC.LocStart, CurrentType, 15169 diag::err_offsetof_incomplete_type)) 15170 return ExprError(); 15171 15172 // Look for the designated field. 15173 const RecordType *RC = CurrentType->getAs<RecordType>(); 15174 if (!RC) 15175 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15176 << CurrentType); 15177 RecordDecl *RD = RC->getDecl(); 15178 15179 // C++ [lib.support.types]p5: 15180 // The macro offsetof accepts a restricted set of type arguments in this 15181 // International Standard. type shall be a POD structure or a POD union 15182 // (clause 9). 15183 // C++11 [support.types]p4: 15184 // If type is not a standard-layout class (Clause 9), the results are 15185 // undefined. 15186 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15187 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15188 unsigned DiagID = 15189 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15190 : diag::ext_offsetof_non_pod_type; 15191 15192 if (!IsSafe && !DidWarnAboutNonPOD && 15193 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15194 PDiag(DiagID) 15195 << SourceRange(Components[0].LocStart, OC.LocEnd) 15196 << CurrentType)) 15197 DidWarnAboutNonPOD = true; 15198 } 15199 15200 // Look for the field. 15201 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15202 LookupQualifiedName(R, RD); 15203 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15204 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15205 if (!MemberDecl) { 15206 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15207 MemberDecl = IndirectMemberDecl->getAnonField(); 15208 } 15209 15210 if (!MemberDecl) 15211 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15212 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15213 OC.LocEnd)); 15214 15215 // C99 7.17p3: 15216 // (If the specified member is a bit-field, the behavior is undefined.) 15217 // 15218 // We diagnose this as an error. 15219 if (MemberDecl->isBitField()) { 15220 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15221 << MemberDecl->getDeclName() 15222 << SourceRange(BuiltinLoc, RParenLoc); 15223 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15224 return ExprError(); 15225 } 15226 15227 RecordDecl *Parent = MemberDecl->getParent(); 15228 if (IndirectMemberDecl) 15229 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15230 15231 // If the member was found in a base class, introduce OffsetOfNodes for 15232 // the base class indirections. 15233 CXXBasePaths Paths; 15234 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15235 Paths)) { 15236 if (Paths.getDetectedVirtual()) { 15237 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15238 << MemberDecl->getDeclName() 15239 << SourceRange(BuiltinLoc, RParenLoc); 15240 return ExprError(); 15241 } 15242 15243 CXXBasePath &Path = Paths.front(); 15244 for (const CXXBasePathElement &B : Path) 15245 Comps.push_back(OffsetOfNode(B.Base)); 15246 } 15247 15248 if (IndirectMemberDecl) { 15249 for (auto *FI : IndirectMemberDecl->chain()) { 15250 assert(isa<FieldDecl>(FI)); 15251 Comps.push_back(OffsetOfNode(OC.LocStart, 15252 cast<FieldDecl>(FI), OC.LocEnd)); 15253 } 15254 } else 15255 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15256 15257 CurrentType = MemberDecl->getType().getNonReferenceType(); 15258 } 15259 15260 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15261 Comps, Exprs, RParenLoc); 15262 } 15263 15264 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15265 SourceLocation BuiltinLoc, 15266 SourceLocation TypeLoc, 15267 ParsedType ParsedArgTy, 15268 ArrayRef<OffsetOfComponent> Components, 15269 SourceLocation RParenLoc) { 15270 15271 TypeSourceInfo *ArgTInfo; 15272 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15273 if (ArgTy.isNull()) 15274 return ExprError(); 15275 15276 if (!ArgTInfo) 15277 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15278 15279 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15280 } 15281 15282 15283 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15284 Expr *CondExpr, 15285 Expr *LHSExpr, Expr *RHSExpr, 15286 SourceLocation RPLoc) { 15287 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15288 15289 ExprValueKind VK = VK_PRValue; 15290 ExprObjectKind OK = OK_Ordinary; 15291 QualType resType; 15292 bool CondIsTrue = false; 15293 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15294 resType = Context.DependentTy; 15295 } else { 15296 // The conditional expression is required to be a constant expression. 15297 llvm::APSInt condEval(32); 15298 ExprResult CondICE = VerifyIntegerConstantExpression( 15299 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15300 if (CondICE.isInvalid()) 15301 return ExprError(); 15302 CondExpr = CondICE.get(); 15303 CondIsTrue = condEval.getZExtValue(); 15304 15305 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15306 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15307 15308 resType = ActiveExpr->getType(); 15309 VK = ActiveExpr->getValueKind(); 15310 OK = ActiveExpr->getObjectKind(); 15311 } 15312 15313 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15314 resType, VK, OK, RPLoc, CondIsTrue); 15315 } 15316 15317 //===----------------------------------------------------------------------===// 15318 // Clang Extensions. 15319 //===----------------------------------------------------------------------===// 15320 15321 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15322 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15323 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15324 15325 if (LangOpts.CPlusPlus) { 15326 MangleNumberingContext *MCtx; 15327 Decl *ManglingContextDecl; 15328 std::tie(MCtx, ManglingContextDecl) = 15329 getCurrentMangleNumberContext(Block->getDeclContext()); 15330 if (MCtx) { 15331 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15332 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15333 } 15334 } 15335 15336 PushBlockScope(CurScope, Block); 15337 CurContext->addDecl(Block); 15338 if (CurScope) 15339 PushDeclContext(CurScope, Block); 15340 else 15341 CurContext = Block; 15342 15343 getCurBlock()->HasImplicitReturnType = true; 15344 15345 // Enter a new evaluation context to insulate the block from any 15346 // cleanups from the enclosing full-expression. 15347 PushExpressionEvaluationContext( 15348 ExpressionEvaluationContext::PotentiallyEvaluated); 15349 } 15350 15351 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15352 Scope *CurScope) { 15353 assert(ParamInfo.getIdentifier() == nullptr && 15354 "block-id should have no identifier!"); 15355 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15356 BlockScopeInfo *CurBlock = getCurBlock(); 15357 15358 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15359 QualType T = Sig->getType(); 15360 15361 // FIXME: We should allow unexpanded parameter packs here, but that would, 15362 // in turn, make the block expression contain unexpanded parameter packs. 15363 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15364 // Drop the parameters. 15365 FunctionProtoType::ExtProtoInfo EPI; 15366 EPI.HasTrailingReturn = false; 15367 EPI.TypeQuals.addConst(); 15368 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15369 Sig = Context.getTrivialTypeSourceInfo(T); 15370 } 15371 15372 // GetTypeForDeclarator always produces a function type for a block 15373 // literal signature. Furthermore, it is always a FunctionProtoType 15374 // unless the function was written with a typedef. 15375 assert(T->isFunctionType() && 15376 "GetTypeForDeclarator made a non-function block signature"); 15377 15378 // Look for an explicit signature in that function type. 15379 FunctionProtoTypeLoc ExplicitSignature; 15380 15381 if ((ExplicitSignature = Sig->getTypeLoc() 15382 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15383 15384 // Check whether that explicit signature was synthesized by 15385 // GetTypeForDeclarator. If so, don't save that as part of the 15386 // written signature. 15387 if (ExplicitSignature.getLocalRangeBegin() == 15388 ExplicitSignature.getLocalRangeEnd()) { 15389 // This would be much cheaper if we stored TypeLocs instead of 15390 // TypeSourceInfos. 15391 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15392 unsigned Size = Result.getFullDataSize(); 15393 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15394 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15395 15396 ExplicitSignature = FunctionProtoTypeLoc(); 15397 } 15398 } 15399 15400 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15401 CurBlock->FunctionType = T; 15402 15403 const auto *Fn = T->castAs<FunctionType>(); 15404 QualType RetTy = Fn->getReturnType(); 15405 bool isVariadic = 15406 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15407 15408 CurBlock->TheDecl->setIsVariadic(isVariadic); 15409 15410 // Context.DependentTy is used as a placeholder for a missing block 15411 // return type. TODO: what should we do with declarators like: 15412 // ^ * { ... } 15413 // If the answer is "apply template argument deduction".... 15414 if (RetTy != Context.DependentTy) { 15415 CurBlock->ReturnType = RetTy; 15416 CurBlock->TheDecl->setBlockMissingReturnType(false); 15417 CurBlock->HasImplicitReturnType = false; 15418 } 15419 15420 // Push block parameters from the declarator if we had them. 15421 SmallVector<ParmVarDecl*, 8> Params; 15422 if (ExplicitSignature) { 15423 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15424 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15425 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15426 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15427 // Diagnose this as an extension in C17 and earlier. 15428 if (!getLangOpts().C2x) 15429 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15430 } 15431 Params.push_back(Param); 15432 } 15433 15434 // Fake up parameter variables if we have a typedef, like 15435 // ^ fntype { ... } 15436 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15437 for (const auto &I : Fn->param_types()) { 15438 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15439 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15440 Params.push_back(Param); 15441 } 15442 } 15443 15444 // Set the parameters on the block decl. 15445 if (!Params.empty()) { 15446 CurBlock->TheDecl->setParams(Params); 15447 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15448 /*CheckParameterNames=*/false); 15449 } 15450 15451 // Finally we can process decl attributes. 15452 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15453 15454 // Put the parameter variables in scope. 15455 for (auto AI : CurBlock->TheDecl->parameters()) { 15456 AI->setOwningFunction(CurBlock->TheDecl); 15457 15458 // If this has an identifier, add it to the scope stack. 15459 if (AI->getIdentifier()) { 15460 CheckShadow(CurBlock->TheScope, AI); 15461 15462 PushOnScopeChains(AI, CurBlock->TheScope); 15463 } 15464 } 15465 } 15466 15467 /// ActOnBlockError - If there is an error parsing a block, this callback 15468 /// is invoked to pop the information about the block from the action impl. 15469 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15470 // Leave the expression-evaluation context. 15471 DiscardCleanupsInEvaluationContext(); 15472 PopExpressionEvaluationContext(); 15473 15474 // Pop off CurBlock, handle nested blocks. 15475 PopDeclContext(); 15476 PopFunctionScopeInfo(); 15477 } 15478 15479 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15480 /// literal was successfully completed. ^(int x){...} 15481 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15482 Stmt *Body, Scope *CurScope) { 15483 // If blocks are disabled, emit an error. 15484 if (!LangOpts.Blocks) 15485 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15486 15487 // Leave the expression-evaluation context. 15488 if (hasAnyUnrecoverableErrorsInThisFunction()) 15489 DiscardCleanupsInEvaluationContext(); 15490 assert(!Cleanup.exprNeedsCleanups() && 15491 "cleanups within block not correctly bound!"); 15492 PopExpressionEvaluationContext(); 15493 15494 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15495 BlockDecl *BD = BSI->TheDecl; 15496 15497 if (BSI->HasImplicitReturnType) 15498 deduceClosureReturnType(*BSI); 15499 15500 QualType RetTy = Context.VoidTy; 15501 if (!BSI->ReturnType.isNull()) 15502 RetTy = BSI->ReturnType; 15503 15504 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15505 QualType BlockTy; 15506 15507 // If the user wrote a function type in some form, try to use that. 15508 if (!BSI->FunctionType.isNull()) { 15509 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15510 15511 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15512 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15513 15514 // Turn protoless block types into nullary block types. 15515 if (isa<FunctionNoProtoType>(FTy)) { 15516 FunctionProtoType::ExtProtoInfo EPI; 15517 EPI.ExtInfo = Ext; 15518 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15519 15520 // Otherwise, if we don't need to change anything about the function type, 15521 // preserve its sugar structure. 15522 } else if (FTy->getReturnType() == RetTy && 15523 (!NoReturn || FTy->getNoReturnAttr())) { 15524 BlockTy = BSI->FunctionType; 15525 15526 // Otherwise, make the minimal modifications to the function type. 15527 } else { 15528 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15529 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15530 EPI.TypeQuals = Qualifiers(); 15531 EPI.ExtInfo = Ext; 15532 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15533 } 15534 15535 // If we don't have a function type, just build one from nothing. 15536 } else { 15537 FunctionProtoType::ExtProtoInfo EPI; 15538 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15539 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15540 } 15541 15542 DiagnoseUnusedParameters(BD->parameters()); 15543 BlockTy = Context.getBlockPointerType(BlockTy); 15544 15545 // If needed, diagnose invalid gotos and switches in the block. 15546 if (getCurFunction()->NeedsScopeChecking() && 15547 !PP.isCodeCompletionEnabled()) 15548 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15549 15550 BD->setBody(cast<CompoundStmt>(Body)); 15551 15552 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15553 DiagnoseUnguardedAvailabilityViolations(BD); 15554 15555 // Try to apply the named return value optimization. We have to check again 15556 // if we can do this, though, because blocks keep return statements around 15557 // to deduce an implicit return type. 15558 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15559 !BD->isDependentContext()) 15560 computeNRVO(Body, BSI); 15561 15562 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15563 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15564 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15565 NTCUK_Destruct|NTCUK_Copy); 15566 15567 PopDeclContext(); 15568 15569 // Set the captured variables on the block. 15570 SmallVector<BlockDecl::Capture, 4> Captures; 15571 for (Capture &Cap : BSI->Captures) { 15572 if (Cap.isInvalid() || Cap.isThisCapture()) 15573 continue; 15574 15575 VarDecl *Var = Cap.getVariable(); 15576 Expr *CopyExpr = nullptr; 15577 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15578 if (const RecordType *Record = 15579 Cap.getCaptureType()->getAs<RecordType>()) { 15580 // The capture logic needs the destructor, so make sure we mark it. 15581 // Usually this is unnecessary because most local variables have 15582 // their destructors marked at declaration time, but parameters are 15583 // an exception because it's technically only the call site that 15584 // actually requires the destructor. 15585 if (isa<ParmVarDecl>(Var)) 15586 FinalizeVarWithDestructor(Var, Record); 15587 15588 // Enter a separate potentially-evaluated context while building block 15589 // initializers to isolate their cleanups from those of the block 15590 // itself. 15591 // FIXME: Is this appropriate even when the block itself occurs in an 15592 // unevaluated operand? 15593 EnterExpressionEvaluationContext EvalContext( 15594 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15595 15596 SourceLocation Loc = Cap.getLocation(); 15597 15598 ExprResult Result = BuildDeclarationNameExpr( 15599 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15600 15601 // According to the blocks spec, the capture of a variable from 15602 // the stack requires a const copy constructor. This is not true 15603 // of the copy/move done to move a __block variable to the heap. 15604 if (!Result.isInvalid() && 15605 !Result.get()->getType().isConstQualified()) { 15606 Result = ImpCastExprToType(Result.get(), 15607 Result.get()->getType().withConst(), 15608 CK_NoOp, VK_LValue); 15609 } 15610 15611 if (!Result.isInvalid()) { 15612 Result = PerformCopyInitialization( 15613 InitializedEntity::InitializeBlock(Var->getLocation(), 15614 Cap.getCaptureType(), false), 15615 Loc, Result.get()); 15616 } 15617 15618 // Build a full-expression copy expression if initialization 15619 // succeeded and used a non-trivial constructor. Recover from 15620 // errors by pretending that the copy isn't necessary. 15621 if (!Result.isInvalid() && 15622 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15623 ->isTrivial()) { 15624 Result = MaybeCreateExprWithCleanups(Result); 15625 CopyExpr = Result.get(); 15626 } 15627 } 15628 } 15629 15630 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15631 CopyExpr); 15632 Captures.push_back(NewCap); 15633 } 15634 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15635 15636 // Pop the block scope now but keep it alive to the end of this function. 15637 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15638 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15639 15640 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15641 15642 // If the block isn't obviously global, i.e. it captures anything at 15643 // all, then we need to do a few things in the surrounding context: 15644 if (Result->getBlockDecl()->hasCaptures()) { 15645 // First, this expression has a new cleanup object. 15646 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15647 Cleanup.setExprNeedsCleanups(true); 15648 15649 // It also gets a branch-protected scope if any of the captured 15650 // variables needs destruction. 15651 for (const auto &CI : Result->getBlockDecl()->captures()) { 15652 const VarDecl *var = CI.getVariable(); 15653 if (var->getType().isDestructedType() != QualType::DK_none) { 15654 setFunctionHasBranchProtectedScope(); 15655 break; 15656 } 15657 } 15658 } 15659 15660 if (getCurFunction()) 15661 getCurFunction()->addBlock(BD); 15662 15663 return Result; 15664 } 15665 15666 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15667 SourceLocation RPLoc) { 15668 TypeSourceInfo *TInfo; 15669 GetTypeFromParser(Ty, &TInfo); 15670 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15671 } 15672 15673 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15674 Expr *E, TypeSourceInfo *TInfo, 15675 SourceLocation RPLoc) { 15676 Expr *OrigExpr = E; 15677 bool IsMS = false; 15678 15679 // CUDA device code does not support varargs. 15680 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15681 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15682 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15683 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15684 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15685 } 15686 } 15687 15688 // NVPTX does not support va_arg expression. 15689 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15690 Context.getTargetInfo().getTriple().isNVPTX()) 15691 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15692 15693 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15694 // as Microsoft ABI on an actual Microsoft platform, where 15695 // __builtin_ms_va_list and __builtin_va_list are the same.) 15696 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15697 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15698 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15699 if (Context.hasSameType(MSVaListType, E->getType())) { 15700 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15701 return ExprError(); 15702 IsMS = true; 15703 } 15704 } 15705 15706 // Get the va_list type 15707 QualType VaListType = Context.getBuiltinVaListType(); 15708 if (!IsMS) { 15709 if (VaListType->isArrayType()) { 15710 // Deal with implicit array decay; for example, on x86-64, 15711 // va_list is an array, but it's supposed to decay to 15712 // a pointer for va_arg. 15713 VaListType = Context.getArrayDecayedType(VaListType); 15714 // Make sure the input expression also decays appropriately. 15715 ExprResult Result = UsualUnaryConversions(E); 15716 if (Result.isInvalid()) 15717 return ExprError(); 15718 E = Result.get(); 15719 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15720 // If va_list is a record type and we are compiling in C++ mode, 15721 // check the argument using reference binding. 15722 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15723 Context, Context.getLValueReferenceType(VaListType), false); 15724 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15725 if (Init.isInvalid()) 15726 return ExprError(); 15727 E = Init.getAs<Expr>(); 15728 } else { 15729 // Otherwise, the va_list argument must be an l-value because 15730 // it is modified by va_arg. 15731 if (!E->isTypeDependent() && 15732 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15733 return ExprError(); 15734 } 15735 } 15736 15737 if (!IsMS && !E->isTypeDependent() && 15738 !Context.hasSameType(VaListType, E->getType())) 15739 return ExprError( 15740 Diag(E->getBeginLoc(), 15741 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15742 << OrigExpr->getType() << E->getSourceRange()); 15743 15744 if (!TInfo->getType()->isDependentType()) { 15745 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15746 diag::err_second_parameter_to_va_arg_incomplete, 15747 TInfo->getTypeLoc())) 15748 return ExprError(); 15749 15750 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15751 TInfo->getType(), 15752 diag::err_second_parameter_to_va_arg_abstract, 15753 TInfo->getTypeLoc())) 15754 return ExprError(); 15755 15756 if (!TInfo->getType().isPODType(Context)) { 15757 Diag(TInfo->getTypeLoc().getBeginLoc(), 15758 TInfo->getType()->isObjCLifetimeType() 15759 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15760 : diag::warn_second_parameter_to_va_arg_not_pod) 15761 << TInfo->getType() 15762 << TInfo->getTypeLoc().getSourceRange(); 15763 } 15764 15765 // Check for va_arg where arguments of the given type will be promoted 15766 // (i.e. this va_arg is guaranteed to have undefined behavior). 15767 QualType PromoteType; 15768 if (TInfo->getType()->isPromotableIntegerType()) { 15769 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15770 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15771 // and C2x 7.16.1.1p2 says, in part: 15772 // If type is not compatible with the type of the actual next argument 15773 // (as promoted according to the default argument promotions), the 15774 // behavior is undefined, except for the following cases: 15775 // - both types are pointers to qualified or unqualified versions of 15776 // compatible types; 15777 // - one type is a signed integer type, the other type is the 15778 // corresponding unsigned integer type, and the value is 15779 // representable in both types; 15780 // - one type is pointer to qualified or unqualified void and the 15781 // other is a pointer to a qualified or unqualified character type. 15782 // Given that type compatibility is the primary requirement (ignoring 15783 // qualifications), you would think we could call typesAreCompatible() 15784 // directly to test this. However, in C++, that checks for *same type*, 15785 // which causes false positives when passing an enumeration type to 15786 // va_arg. Instead, get the underlying type of the enumeration and pass 15787 // that. 15788 QualType UnderlyingType = TInfo->getType(); 15789 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15790 UnderlyingType = ET->getDecl()->getIntegerType(); 15791 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15792 /*CompareUnqualified*/ true)) 15793 PromoteType = QualType(); 15794 15795 // If the types are still not compatible, we need to test whether the 15796 // promoted type and the underlying type are the same except for 15797 // signedness. Ask the AST for the correctly corresponding type and see 15798 // if that's compatible. 15799 if (!PromoteType.isNull() && 15800 PromoteType->isUnsignedIntegerType() != 15801 UnderlyingType->isUnsignedIntegerType()) { 15802 UnderlyingType = 15803 UnderlyingType->isUnsignedIntegerType() 15804 ? Context.getCorrespondingSignedType(UnderlyingType) 15805 : Context.getCorrespondingUnsignedType(UnderlyingType); 15806 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15807 /*CompareUnqualified*/ true)) 15808 PromoteType = QualType(); 15809 } 15810 } 15811 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15812 PromoteType = Context.DoubleTy; 15813 if (!PromoteType.isNull()) 15814 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15815 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15816 << TInfo->getType() 15817 << PromoteType 15818 << TInfo->getTypeLoc().getSourceRange()); 15819 } 15820 15821 QualType T = TInfo->getType().getNonLValueExprType(Context); 15822 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15823 } 15824 15825 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15826 // The type of __null will be int or long, depending on the size of 15827 // pointers on the target. 15828 QualType Ty; 15829 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15830 if (pw == Context.getTargetInfo().getIntWidth()) 15831 Ty = Context.IntTy; 15832 else if (pw == Context.getTargetInfo().getLongWidth()) 15833 Ty = Context.LongTy; 15834 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15835 Ty = Context.LongLongTy; 15836 else { 15837 llvm_unreachable("I don't know size of pointer!"); 15838 } 15839 15840 return new (Context) GNUNullExpr(Ty, TokenLoc); 15841 } 15842 15843 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15844 SourceLocation BuiltinLoc, 15845 SourceLocation RPLoc) { 15846 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15847 } 15848 15849 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15850 SourceLocation BuiltinLoc, 15851 SourceLocation RPLoc, 15852 DeclContext *ParentContext) { 15853 return new (Context) 15854 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15855 } 15856 15857 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15858 bool Diagnose) { 15859 if (!getLangOpts().ObjC) 15860 return false; 15861 15862 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15863 if (!PT) 15864 return false; 15865 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15866 15867 // Ignore any parens, implicit casts (should only be 15868 // array-to-pointer decays), and not-so-opaque values. The last is 15869 // important for making this trigger for property assignments. 15870 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15871 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15872 if (OV->getSourceExpr()) 15873 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15874 15875 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15876 if (!PT->isObjCIdType() && 15877 !(ID && ID->getIdentifier()->isStr("NSString"))) 15878 return false; 15879 if (!SL->isAscii()) 15880 return false; 15881 15882 if (Diagnose) { 15883 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15884 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15885 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15886 } 15887 return true; 15888 } 15889 15890 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15891 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15892 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15893 !SrcExpr->isNullPointerConstant( 15894 getASTContext(), Expr::NPC_NeverValueDependent)) { 15895 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15896 return false; 15897 if (Diagnose) { 15898 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15899 << /*number*/1 15900 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15901 Expr *NumLit = 15902 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15903 if (NumLit) 15904 Exp = NumLit; 15905 } 15906 return true; 15907 } 15908 15909 return false; 15910 } 15911 15912 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15913 const Expr *SrcExpr) { 15914 if (!DstType->isFunctionPointerType() || 15915 !SrcExpr->getType()->isFunctionType()) 15916 return false; 15917 15918 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15919 if (!DRE) 15920 return false; 15921 15922 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15923 if (!FD) 15924 return false; 15925 15926 return !S.checkAddressOfFunctionIsAvailable(FD, 15927 /*Complain=*/true, 15928 SrcExpr->getBeginLoc()); 15929 } 15930 15931 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15932 SourceLocation Loc, 15933 QualType DstType, QualType SrcType, 15934 Expr *SrcExpr, AssignmentAction Action, 15935 bool *Complained) { 15936 if (Complained) 15937 *Complained = false; 15938 15939 // Decode the result (notice that AST's are still created for extensions). 15940 bool CheckInferredResultType = false; 15941 bool isInvalid = false; 15942 unsigned DiagKind = 0; 15943 ConversionFixItGenerator ConvHints; 15944 bool MayHaveConvFixit = false; 15945 bool MayHaveFunctionDiff = false; 15946 const ObjCInterfaceDecl *IFace = nullptr; 15947 const ObjCProtocolDecl *PDecl = nullptr; 15948 15949 switch (ConvTy) { 15950 case Compatible: 15951 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15952 return false; 15953 15954 case PointerToInt: 15955 if (getLangOpts().CPlusPlus) { 15956 DiagKind = diag::err_typecheck_convert_pointer_int; 15957 isInvalid = true; 15958 } else { 15959 DiagKind = diag::ext_typecheck_convert_pointer_int; 15960 } 15961 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15962 MayHaveConvFixit = true; 15963 break; 15964 case IntToPointer: 15965 if (getLangOpts().CPlusPlus) { 15966 DiagKind = diag::err_typecheck_convert_int_pointer; 15967 isInvalid = true; 15968 } else { 15969 DiagKind = diag::ext_typecheck_convert_int_pointer; 15970 } 15971 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15972 MayHaveConvFixit = true; 15973 break; 15974 case IncompatibleFunctionPointer: 15975 if (getLangOpts().CPlusPlus) { 15976 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15977 isInvalid = true; 15978 } else { 15979 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15980 } 15981 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15982 MayHaveConvFixit = true; 15983 break; 15984 case IncompatiblePointer: 15985 if (Action == AA_Passing_CFAudited) { 15986 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15987 } else if (getLangOpts().CPlusPlus) { 15988 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15989 isInvalid = true; 15990 } else { 15991 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15992 } 15993 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15994 SrcType->isObjCObjectPointerType(); 15995 if (!CheckInferredResultType) { 15996 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15997 } else if (CheckInferredResultType) { 15998 SrcType = SrcType.getUnqualifiedType(); 15999 DstType = DstType.getUnqualifiedType(); 16000 } 16001 MayHaveConvFixit = true; 16002 break; 16003 case IncompatiblePointerSign: 16004 if (getLangOpts().CPlusPlus) { 16005 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16006 isInvalid = true; 16007 } else { 16008 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16009 } 16010 break; 16011 case FunctionVoidPointer: 16012 if (getLangOpts().CPlusPlus) { 16013 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16014 isInvalid = true; 16015 } else { 16016 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16017 } 16018 break; 16019 case IncompatiblePointerDiscardsQualifiers: { 16020 // Perform array-to-pointer decay if necessary. 16021 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16022 16023 isInvalid = true; 16024 16025 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16026 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16027 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16028 DiagKind = diag::err_typecheck_incompatible_address_space; 16029 break; 16030 16031 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16032 DiagKind = diag::err_typecheck_incompatible_ownership; 16033 break; 16034 } 16035 16036 llvm_unreachable("unknown error case for discarding qualifiers!"); 16037 // fallthrough 16038 } 16039 case CompatiblePointerDiscardsQualifiers: 16040 // If the qualifiers lost were because we were applying the 16041 // (deprecated) C++ conversion from a string literal to a char* 16042 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16043 // Ideally, this check would be performed in 16044 // checkPointerTypesForAssignment. However, that would require a 16045 // bit of refactoring (so that the second argument is an 16046 // expression, rather than a type), which should be done as part 16047 // of a larger effort to fix checkPointerTypesForAssignment for 16048 // C++ semantics. 16049 if (getLangOpts().CPlusPlus && 16050 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16051 return false; 16052 if (getLangOpts().CPlusPlus) { 16053 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16054 isInvalid = true; 16055 } else { 16056 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16057 } 16058 16059 break; 16060 case IncompatibleNestedPointerQualifiers: 16061 if (getLangOpts().CPlusPlus) { 16062 isInvalid = true; 16063 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16064 } else { 16065 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16066 } 16067 break; 16068 case IncompatibleNestedPointerAddressSpaceMismatch: 16069 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16070 isInvalid = true; 16071 break; 16072 case IntToBlockPointer: 16073 DiagKind = diag::err_int_to_block_pointer; 16074 isInvalid = true; 16075 break; 16076 case IncompatibleBlockPointer: 16077 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16078 isInvalid = true; 16079 break; 16080 case IncompatibleObjCQualifiedId: { 16081 if (SrcType->isObjCQualifiedIdType()) { 16082 const ObjCObjectPointerType *srcOPT = 16083 SrcType->castAs<ObjCObjectPointerType>(); 16084 for (auto *srcProto : srcOPT->quals()) { 16085 PDecl = srcProto; 16086 break; 16087 } 16088 if (const ObjCInterfaceType *IFaceT = 16089 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16090 IFace = IFaceT->getDecl(); 16091 } 16092 else if (DstType->isObjCQualifiedIdType()) { 16093 const ObjCObjectPointerType *dstOPT = 16094 DstType->castAs<ObjCObjectPointerType>(); 16095 for (auto *dstProto : dstOPT->quals()) { 16096 PDecl = dstProto; 16097 break; 16098 } 16099 if (const ObjCInterfaceType *IFaceT = 16100 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16101 IFace = IFaceT->getDecl(); 16102 } 16103 if (getLangOpts().CPlusPlus) { 16104 DiagKind = diag::err_incompatible_qualified_id; 16105 isInvalid = true; 16106 } else { 16107 DiagKind = diag::warn_incompatible_qualified_id; 16108 } 16109 break; 16110 } 16111 case IncompatibleVectors: 16112 if (getLangOpts().CPlusPlus) { 16113 DiagKind = diag::err_incompatible_vectors; 16114 isInvalid = true; 16115 } else { 16116 DiagKind = diag::warn_incompatible_vectors; 16117 } 16118 break; 16119 case IncompatibleObjCWeakRef: 16120 DiagKind = diag::err_arc_weak_unavailable_assign; 16121 isInvalid = true; 16122 break; 16123 case Incompatible: 16124 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16125 if (Complained) 16126 *Complained = true; 16127 return true; 16128 } 16129 16130 DiagKind = diag::err_typecheck_convert_incompatible; 16131 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16132 MayHaveConvFixit = true; 16133 isInvalid = true; 16134 MayHaveFunctionDiff = true; 16135 break; 16136 } 16137 16138 QualType FirstType, SecondType; 16139 switch (Action) { 16140 case AA_Assigning: 16141 case AA_Initializing: 16142 // The destination type comes first. 16143 FirstType = DstType; 16144 SecondType = SrcType; 16145 break; 16146 16147 case AA_Returning: 16148 case AA_Passing: 16149 case AA_Passing_CFAudited: 16150 case AA_Converting: 16151 case AA_Sending: 16152 case AA_Casting: 16153 // The source type comes first. 16154 FirstType = SrcType; 16155 SecondType = DstType; 16156 break; 16157 } 16158 16159 PartialDiagnostic FDiag = PDiag(DiagKind); 16160 if (Action == AA_Passing_CFAudited) 16161 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16162 else 16163 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16164 16165 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16166 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16167 auto isPlainChar = [](const clang::Type *Type) { 16168 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16169 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16170 }; 16171 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16172 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16173 } 16174 16175 // If we can fix the conversion, suggest the FixIts. 16176 if (!ConvHints.isNull()) { 16177 for (FixItHint &H : ConvHints.Hints) 16178 FDiag << H; 16179 } 16180 16181 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16182 16183 if (MayHaveFunctionDiff) 16184 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16185 16186 Diag(Loc, FDiag); 16187 if ((DiagKind == diag::warn_incompatible_qualified_id || 16188 DiagKind == diag::err_incompatible_qualified_id) && 16189 PDecl && IFace && !IFace->hasDefinition()) 16190 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16191 << IFace << PDecl; 16192 16193 if (SecondType == Context.OverloadTy) 16194 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16195 FirstType, /*TakingAddress=*/true); 16196 16197 if (CheckInferredResultType) 16198 EmitRelatedResultTypeNote(SrcExpr); 16199 16200 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16201 EmitRelatedResultTypeNoteForReturn(DstType); 16202 16203 if (Complained) 16204 *Complained = true; 16205 return isInvalid; 16206 } 16207 16208 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16209 llvm::APSInt *Result, 16210 AllowFoldKind CanFold) { 16211 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16212 public: 16213 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16214 QualType T) override { 16215 return S.Diag(Loc, diag::err_ice_not_integral) 16216 << T << S.LangOpts.CPlusPlus; 16217 } 16218 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16219 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16220 } 16221 } Diagnoser; 16222 16223 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16224 } 16225 16226 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16227 llvm::APSInt *Result, 16228 unsigned DiagID, 16229 AllowFoldKind CanFold) { 16230 class IDDiagnoser : public VerifyICEDiagnoser { 16231 unsigned DiagID; 16232 16233 public: 16234 IDDiagnoser(unsigned DiagID) 16235 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16236 16237 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16238 return S.Diag(Loc, DiagID); 16239 } 16240 } Diagnoser(DiagID); 16241 16242 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16243 } 16244 16245 Sema::SemaDiagnosticBuilder 16246 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16247 QualType T) { 16248 return diagnoseNotICE(S, Loc); 16249 } 16250 16251 Sema::SemaDiagnosticBuilder 16252 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16253 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16254 } 16255 16256 ExprResult 16257 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16258 VerifyICEDiagnoser &Diagnoser, 16259 AllowFoldKind CanFold) { 16260 SourceLocation DiagLoc = E->getBeginLoc(); 16261 16262 if (getLangOpts().CPlusPlus11) { 16263 // C++11 [expr.const]p5: 16264 // If an expression of literal class type is used in a context where an 16265 // integral constant expression is required, then that class type shall 16266 // have a single non-explicit conversion function to an integral or 16267 // unscoped enumeration type 16268 ExprResult Converted; 16269 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16270 VerifyICEDiagnoser &BaseDiagnoser; 16271 public: 16272 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16273 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16274 BaseDiagnoser.Suppress, true), 16275 BaseDiagnoser(BaseDiagnoser) {} 16276 16277 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16278 QualType T) override { 16279 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16280 } 16281 16282 SemaDiagnosticBuilder diagnoseIncomplete( 16283 Sema &S, SourceLocation Loc, QualType T) override { 16284 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16285 } 16286 16287 SemaDiagnosticBuilder diagnoseExplicitConv( 16288 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16289 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16290 } 16291 16292 SemaDiagnosticBuilder noteExplicitConv( 16293 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16294 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16295 << ConvTy->isEnumeralType() << ConvTy; 16296 } 16297 16298 SemaDiagnosticBuilder diagnoseAmbiguous( 16299 Sema &S, SourceLocation Loc, QualType T) override { 16300 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16301 } 16302 16303 SemaDiagnosticBuilder noteAmbiguous( 16304 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16305 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16306 << ConvTy->isEnumeralType() << ConvTy; 16307 } 16308 16309 SemaDiagnosticBuilder diagnoseConversion( 16310 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16311 llvm_unreachable("conversion functions are permitted"); 16312 } 16313 } ConvertDiagnoser(Diagnoser); 16314 16315 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16316 ConvertDiagnoser); 16317 if (Converted.isInvalid()) 16318 return Converted; 16319 E = Converted.get(); 16320 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16321 return ExprError(); 16322 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16323 // An ICE must be of integral or unscoped enumeration type. 16324 if (!Diagnoser.Suppress) 16325 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16326 << E->getSourceRange(); 16327 return ExprError(); 16328 } 16329 16330 ExprResult RValueExpr = DefaultLvalueConversion(E); 16331 if (RValueExpr.isInvalid()) 16332 return ExprError(); 16333 16334 E = RValueExpr.get(); 16335 16336 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16337 // in the non-ICE case. 16338 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16339 if (Result) 16340 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16341 if (!isa<ConstantExpr>(E)) 16342 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16343 : ConstantExpr::Create(Context, E); 16344 return E; 16345 } 16346 16347 Expr::EvalResult EvalResult; 16348 SmallVector<PartialDiagnosticAt, 8> Notes; 16349 EvalResult.Diag = &Notes; 16350 16351 // Try to evaluate the expression, and produce diagnostics explaining why it's 16352 // not a constant expression as a side-effect. 16353 bool Folded = 16354 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16355 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16356 16357 if (!isa<ConstantExpr>(E)) 16358 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16359 16360 // In C++11, we can rely on diagnostics being produced for any expression 16361 // which is not a constant expression. If no diagnostics were produced, then 16362 // this is a constant expression. 16363 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16364 if (Result) 16365 *Result = EvalResult.Val.getInt(); 16366 return E; 16367 } 16368 16369 // If our only note is the usual "invalid subexpression" note, just point 16370 // the caret at its location rather than producing an essentially 16371 // redundant note. 16372 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16373 diag::note_invalid_subexpr_in_const_expr) { 16374 DiagLoc = Notes[0].first; 16375 Notes.clear(); 16376 } 16377 16378 if (!Folded || !CanFold) { 16379 if (!Diagnoser.Suppress) { 16380 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16381 for (const PartialDiagnosticAt &Note : Notes) 16382 Diag(Note.first, Note.second); 16383 } 16384 16385 return ExprError(); 16386 } 16387 16388 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16389 for (const PartialDiagnosticAt &Note : Notes) 16390 Diag(Note.first, Note.second); 16391 16392 if (Result) 16393 *Result = EvalResult.Val.getInt(); 16394 return E; 16395 } 16396 16397 namespace { 16398 // Handle the case where we conclude a expression which we speculatively 16399 // considered to be unevaluated is actually evaluated. 16400 class TransformToPE : public TreeTransform<TransformToPE> { 16401 typedef TreeTransform<TransformToPE> BaseTransform; 16402 16403 public: 16404 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16405 16406 // Make sure we redo semantic analysis 16407 bool AlwaysRebuild() { return true; } 16408 bool ReplacingOriginal() { return true; } 16409 16410 // We need to special-case DeclRefExprs referring to FieldDecls which 16411 // are not part of a member pointer formation; normal TreeTransforming 16412 // doesn't catch this case because of the way we represent them in the AST. 16413 // FIXME: This is a bit ugly; is it really the best way to handle this 16414 // case? 16415 // 16416 // Error on DeclRefExprs referring to FieldDecls. 16417 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16418 if (isa<FieldDecl>(E->getDecl()) && 16419 !SemaRef.isUnevaluatedContext()) 16420 return SemaRef.Diag(E->getLocation(), 16421 diag::err_invalid_non_static_member_use) 16422 << E->getDecl() << E->getSourceRange(); 16423 16424 return BaseTransform::TransformDeclRefExpr(E); 16425 } 16426 16427 // Exception: filter out member pointer formation 16428 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16429 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16430 return E; 16431 16432 return BaseTransform::TransformUnaryOperator(E); 16433 } 16434 16435 // The body of a lambda-expression is in a separate expression evaluation 16436 // context so never needs to be transformed. 16437 // FIXME: Ideally we wouldn't transform the closure type either, and would 16438 // just recreate the capture expressions and lambda expression. 16439 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16440 return SkipLambdaBody(E, Body); 16441 } 16442 }; 16443 } 16444 16445 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16446 assert(isUnevaluatedContext() && 16447 "Should only transform unevaluated expressions"); 16448 ExprEvalContexts.back().Context = 16449 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16450 if (isUnevaluatedContext()) 16451 return E; 16452 return TransformToPE(*this).TransformExpr(E); 16453 } 16454 16455 void 16456 Sema::PushExpressionEvaluationContext( 16457 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16458 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16459 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16460 LambdaContextDecl, ExprContext); 16461 Cleanup.reset(); 16462 if (!MaybeODRUseExprs.empty()) 16463 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16464 } 16465 16466 void 16467 Sema::PushExpressionEvaluationContext( 16468 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16469 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16470 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16471 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16472 } 16473 16474 namespace { 16475 16476 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16477 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16478 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16479 if (E->getOpcode() == UO_Deref) 16480 return CheckPossibleDeref(S, E->getSubExpr()); 16481 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16482 return CheckPossibleDeref(S, E->getBase()); 16483 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16484 return CheckPossibleDeref(S, E->getBase()); 16485 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16486 QualType Inner; 16487 QualType Ty = E->getType(); 16488 if (const auto *Ptr = Ty->getAs<PointerType>()) 16489 Inner = Ptr->getPointeeType(); 16490 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16491 Inner = Arr->getElementType(); 16492 else 16493 return nullptr; 16494 16495 if (Inner->hasAttr(attr::NoDeref)) 16496 return E; 16497 } 16498 return nullptr; 16499 } 16500 16501 } // namespace 16502 16503 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16504 for (const Expr *E : Rec.PossibleDerefs) { 16505 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16506 if (DeclRef) { 16507 const ValueDecl *Decl = DeclRef->getDecl(); 16508 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16509 << Decl->getName() << E->getSourceRange(); 16510 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16511 } else { 16512 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16513 << E->getSourceRange(); 16514 } 16515 } 16516 Rec.PossibleDerefs.clear(); 16517 } 16518 16519 /// Check whether E, which is either a discarded-value expression or an 16520 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16521 /// and if so, remove it from the list of volatile-qualified assignments that 16522 /// we are going to warn are deprecated. 16523 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16524 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16525 return; 16526 16527 // Note: ignoring parens here is not justified by the standard rules, but 16528 // ignoring parentheses seems like a more reasonable approach, and this only 16529 // drives a deprecation warning so doesn't affect conformance. 16530 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16531 if (BO->getOpcode() == BO_Assign) { 16532 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16533 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16534 LHSs.end()); 16535 } 16536 } 16537 } 16538 16539 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16540 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16541 RebuildingImmediateInvocation) 16542 return E; 16543 16544 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16545 /// It's OK if this fails; we'll also remove this in 16546 /// HandleImmediateInvocations, but catching it here allows us to avoid 16547 /// walking the AST looking for it in simple cases. 16548 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16549 if (auto *DeclRef = 16550 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16551 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16552 16553 E = MaybeCreateExprWithCleanups(E); 16554 16555 ConstantExpr *Res = ConstantExpr::Create( 16556 getASTContext(), E.get(), 16557 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16558 getASTContext()), 16559 /*IsImmediateInvocation*/ true); 16560 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16561 return Res; 16562 } 16563 16564 static void EvaluateAndDiagnoseImmediateInvocation( 16565 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16566 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16567 Expr::EvalResult Eval; 16568 Eval.Diag = &Notes; 16569 ConstantExpr *CE = Candidate.getPointer(); 16570 bool Result = CE->EvaluateAsConstantExpr( 16571 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16572 if (!Result || !Notes.empty()) { 16573 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16574 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16575 InnerExpr = FunctionalCast->getSubExpr(); 16576 FunctionDecl *FD = nullptr; 16577 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16578 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16579 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16580 FD = Call->getConstructor(); 16581 else 16582 llvm_unreachable("unhandled decl kind"); 16583 assert(FD->isConsteval()); 16584 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16585 for (auto &Note : Notes) 16586 SemaRef.Diag(Note.first, Note.second); 16587 return; 16588 } 16589 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16590 } 16591 16592 static void RemoveNestedImmediateInvocation( 16593 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16594 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16595 struct ComplexRemove : TreeTransform<ComplexRemove> { 16596 using Base = TreeTransform<ComplexRemove>; 16597 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16598 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16599 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16600 CurrentII; 16601 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16602 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16603 SmallVector<Sema::ImmediateInvocationCandidate, 16604 4>::reverse_iterator Current) 16605 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16606 void RemoveImmediateInvocation(ConstantExpr* E) { 16607 auto It = std::find_if(CurrentII, IISet.rend(), 16608 [E](Sema::ImmediateInvocationCandidate Elem) { 16609 return Elem.getPointer() == E; 16610 }); 16611 assert(It != IISet.rend() && 16612 "ConstantExpr marked IsImmediateInvocation should " 16613 "be present"); 16614 It->setInt(1); // Mark as deleted 16615 } 16616 ExprResult TransformConstantExpr(ConstantExpr *E) { 16617 if (!E->isImmediateInvocation()) 16618 return Base::TransformConstantExpr(E); 16619 RemoveImmediateInvocation(E); 16620 return Base::TransformExpr(E->getSubExpr()); 16621 } 16622 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16623 /// we need to remove its DeclRefExpr from the DRSet. 16624 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16625 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16626 return Base::TransformCXXOperatorCallExpr(E); 16627 } 16628 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16629 /// here. 16630 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16631 if (!Init) 16632 return Init; 16633 /// ConstantExpr are the first layer of implicit node to be removed so if 16634 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16635 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16636 if (CE->isImmediateInvocation()) 16637 RemoveImmediateInvocation(CE); 16638 return Base::TransformInitializer(Init, NotCopyInit); 16639 } 16640 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16641 DRSet.erase(E); 16642 return E; 16643 } 16644 bool AlwaysRebuild() { return false; } 16645 bool ReplacingOriginal() { return true; } 16646 bool AllowSkippingCXXConstructExpr() { 16647 bool Res = AllowSkippingFirstCXXConstructExpr; 16648 AllowSkippingFirstCXXConstructExpr = true; 16649 return Res; 16650 } 16651 bool AllowSkippingFirstCXXConstructExpr = true; 16652 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16653 Rec.ImmediateInvocationCandidates, It); 16654 16655 /// CXXConstructExpr with a single argument are getting skipped by 16656 /// TreeTransform in some situtation because they could be implicit. This 16657 /// can only occur for the top-level CXXConstructExpr because it is used 16658 /// nowhere in the expression being transformed therefore will not be rebuilt. 16659 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16660 /// skipping the first CXXConstructExpr. 16661 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16662 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16663 16664 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16665 assert(Res.isUsable()); 16666 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16667 It->getPointer()->setSubExpr(Res.get()); 16668 } 16669 16670 static void 16671 HandleImmediateInvocations(Sema &SemaRef, 16672 Sema::ExpressionEvaluationContextRecord &Rec) { 16673 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16674 Rec.ReferenceToConsteval.size() == 0) || 16675 SemaRef.RebuildingImmediateInvocation) 16676 return; 16677 16678 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16679 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16680 /// need to remove ReferenceToConsteval in the immediate invocation. 16681 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16682 16683 /// Prevent sema calls during the tree transform from adding pointers that 16684 /// are already in the sets. 16685 llvm::SaveAndRestore<bool> DisableIITracking( 16686 SemaRef.RebuildingImmediateInvocation, true); 16687 16688 /// Prevent diagnostic during tree transfrom as they are duplicates 16689 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16690 16691 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16692 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16693 if (!It->getInt()) 16694 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16695 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16696 Rec.ReferenceToConsteval.size()) { 16697 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16698 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16699 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16700 bool VisitDeclRefExpr(DeclRefExpr *E) { 16701 DRSet.erase(E); 16702 return DRSet.size(); 16703 } 16704 } Visitor(Rec.ReferenceToConsteval); 16705 Visitor.TraverseStmt( 16706 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16707 } 16708 for (auto CE : Rec.ImmediateInvocationCandidates) 16709 if (!CE.getInt()) 16710 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16711 for (auto DR : Rec.ReferenceToConsteval) { 16712 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16713 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16714 << FD; 16715 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16716 } 16717 } 16718 16719 void Sema::PopExpressionEvaluationContext() { 16720 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16721 unsigned NumTypos = Rec.NumTypos; 16722 16723 if (!Rec.Lambdas.empty()) { 16724 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16725 if (!getLangOpts().CPlusPlus20 && 16726 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16727 Rec.isUnevaluated() || 16728 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16729 unsigned D; 16730 if (Rec.isUnevaluated()) { 16731 // C++11 [expr.prim.lambda]p2: 16732 // A lambda-expression shall not appear in an unevaluated operand 16733 // (Clause 5). 16734 D = diag::err_lambda_unevaluated_operand; 16735 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16736 // C++1y [expr.const]p2: 16737 // A conditional-expression e is a core constant expression unless the 16738 // evaluation of e, following the rules of the abstract machine, would 16739 // evaluate [...] a lambda-expression. 16740 D = diag::err_lambda_in_constant_expression; 16741 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16742 // C++17 [expr.prim.lamda]p2: 16743 // A lambda-expression shall not appear [...] in a template-argument. 16744 D = diag::err_lambda_in_invalid_context; 16745 } else 16746 llvm_unreachable("Couldn't infer lambda error message."); 16747 16748 for (const auto *L : Rec.Lambdas) 16749 Diag(L->getBeginLoc(), D); 16750 } 16751 } 16752 16753 WarnOnPendingNoDerefs(Rec); 16754 HandleImmediateInvocations(*this, Rec); 16755 16756 // Warn on any volatile-qualified simple-assignments that are not discarded- 16757 // value expressions nor unevaluated operands (those cases get removed from 16758 // this list by CheckUnusedVolatileAssignment). 16759 for (auto *BO : Rec.VolatileAssignmentLHSs) 16760 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16761 << BO->getType(); 16762 16763 // When are coming out of an unevaluated context, clear out any 16764 // temporaries that we may have created as part of the evaluation of 16765 // the expression in that context: they aren't relevant because they 16766 // will never be constructed. 16767 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16768 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16769 ExprCleanupObjects.end()); 16770 Cleanup = Rec.ParentCleanup; 16771 CleanupVarDeclMarking(); 16772 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16773 // Otherwise, merge the contexts together. 16774 } else { 16775 Cleanup.mergeFrom(Rec.ParentCleanup); 16776 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16777 Rec.SavedMaybeODRUseExprs.end()); 16778 } 16779 16780 // Pop the current expression evaluation context off the stack. 16781 ExprEvalContexts.pop_back(); 16782 16783 // The global expression evaluation context record is never popped. 16784 ExprEvalContexts.back().NumTypos += NumTypos; 16785 } 16786 16787 void Sema::DiscardCleanupsInEvaluationContext() { 16788 ExprCleanupObjects.erase( 16789 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16790 ExprCleanupObjects.end()); 16791 Cleanup.reset(); 16792 MaybeODRUseExprs.clear(); 16793 } 16794 16795 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16796 ExprResult Result = CheckPlaceholderExpr(E); 16797 if (Result.isInvalid()) 16798 return ExprError(); 16799 E = Result.get(); 16800 if (!E->getType()->isVariablyModifiedType()) 16801 return E; 16802 return TransformToPotentiallyEvaluated(E); 16803 } 16804 16805 /// Are we in a context that is potentially constant evaluated per C++20 16806 /// [expr.const]p12? 16807 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16808 /// C++2a [expr.const]p12: 16809 // An expression or conversion is potentially constant evaluated if it is 16810 switch (SemaRef.ExprEvalContexts.back().Context) { 16811 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16812 // -- a manifestly constant-evaluated expression, 16813 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16814 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16815 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16816 // -- a potentially-evaluated expression, 16817 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16818 // -- an immediate subexpression of a braced-init-list, 16819 16820 // -- [FIXME] an expression of the form & cast-expression that occurs 16821 // within a templated entity 16822 // -- a subexpression of one of the above that is not a subexpression of 16823 // a nested unevaluated operand. 16824 return true; 16825 16826 case Sema::ExpressionEvaluationContext::Unevaluated: 16827 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16828 // Expressions in this context are never evaluated. 16829 return false; 16830 } 16831 llvm_unreachable("Invalid context"); 16832 } 16833 16834 /// Return true if this function has a calling convention that requires mangling 16835 /// in the size of the parameter pack. 16836 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16837 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16838 // we don't need parameter type sizes. 16839 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16840 if (!TT.isOSWindows() || !TT.isX86()) 16841 return false; 16842 16843 // If this is C++ and this isn't an extern "C" function, parameters do not 16844 // need to be complete. In this case, C++ mangling will apply, which doesn't 16845 // use the size of the parameters. 16846 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16847 return false; 16848 16849 // Stdcall, fastcall, and vectorcall need this special treatment. 16850 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16851 switch (CC) { 16852 case CC_X86StdCall: 16853 case CC_X86FastCall: 16854 case CC_X86VectorCall: 16855 return true; 16856 default: 16857 break; 16858 } 16859 return false; 16860 } 16861 16862 /// Require that all of the parameter types of function be complete. Normally, 16863 /// parameter types are only required to be complete when a function is called 16864 /// or defined, but to mangle functions with certain calling conventions, the 16865 /// mangler needs to know the size of the parameter list. In this situation, 16866 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16867 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16868 /// result in a linker error. Clang doesn't implement this behavior, and instead 16869 /// attempts to error at compile time. 16870 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16871 SourceLocation Loc) { 16872 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16873 FunctionDecl *FD; 16874 ParmVarDecl *Param; 16875 16876 public: 16877 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16878 : FD(FD), Param(Param) {} 16879 16880 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16881 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16882 StringRef CCName; 16883 switch (CC) { 16884 case CC_X86StdCall: 16885 CCName = "stdcall"; 16886 break; 16887 case CC_X86FastCall: 16888 CCName = "fastcall"; 16889 break; 16890 case CC_X86VectorCall: 16891 CCName = "vectorcall"; 16892 break; 16893 default: 16894 llvm_unreachable("CC does not need mangling"); 16895 } 16896 16897 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16898 << Param->getDeclName() << FD->getDeclName() << CCName; 16899 } 16900 }; 16901 16902 for (ParmVarDecl *Param : FD->parameters()) { 16903 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16904 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16905 } 16906 } 16907 16908 namespace { 16909 enum class OdrUseContext { 16910 /// Declarations in this context are not odr-used. 16911 None, 16912 /// Declarations in this context are formally odr-used, but this is a 16913 /// dependent context. 16914 Dependent, 16915 /// Declarations in this context are odr-used but not actually used (yet). 16916 FormallyOdrUsed, 16917 /// Declarations in this context are used. 16918 Used 16919 }; 16920 } 16921 16922 /// Are we within a context in which references to resolved functions or to 16923 /// variables result in odr-use? 16924 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16925 OdrUseContext Result; 16926 16927 switch (SemaRef.ExprEvalContexts.back().Context) { 16928 case Sema::ExpressionEvaluationContext::Unevaluated: 16929 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16930 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16931 return OdrUseContext::None; 16932 16933 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16934 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16935 Result = OdrUseContext::Used; 16936 break; 16937 16938 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16939 Result = OdrUseContext::FormallyOdrUsed; 16940 break; 16941 16942 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16943 // A default argument formally results in odr-use, but doesn't actually 16944 // result in a use in any real sense until it itself is used. 16945 Result = OdrUseContext::FormallyOdrUsed; 16946 break; 16947 } 16948 16949 if (SemaRef.CurContext->isDependentContext()) 16950 return OdrUseContext::Dependent; 16951 16952 return Result; 16953 } 16954 16955 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16956 if (!Func->isConstexpr()) 16957 return false; 16958 16959 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16960 return true; 16961 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16962 return CCD && CCD->getInheritedConstructor(); 16963 } 16964 16965 /// Mark a function referenced, and check whether it is odr-used 16966 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16967 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16968 bool MightBeOdrUse) { 16969 assert(Func && "No function?"); 16970 16971 Func->setReferenced(); 16972 16973 // Recursive functions aren't really used until they're used from some other 16974 // context. 16975 bool IsRecursiveCall = CurContext == Func; 16976 16977 // C++11 [basic.def.odr]p3: 16978 // A function whose name appears as a potentially-evaluated expression is 16979 // odr-used if it is the unique lookup result or the selected member of a 16980 // set of overloaded functions [...]. 16981 // 16982 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16983 // can just check that here. 16984 OdrUseContext OdrUse = 16985 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16986 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16987 OdrUse = OdrUseContext::FormallyOdrUsed; 16988 16989 // Trivial default constructors and destructors are never actually used. 16990 // FIXME: What about other special members? 16991 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16992 OdrUse == OdrUseContext::Used) { 16993 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16994 if (Constructor->isDefaultConstructor()) 16995 OdrUse = OdrUseContext::FormallyOdrUsed; 16996 if (isa<CXXDestructorDecl>(Func)) 16997 OdrUse = OdrUseContext::FormallyOdrUsed; 16998 } 16999 17000 // C++20 [expr.const]p12: 17001 // A function [...] is needed for constant evaluation if it is [...] a 17002 // constexpr function that is named by an expression that is potentially 17003 // constant evaluated 17004 bool NeededForConstantEvaluation = 17005 isPotentiallyConstantEvaluatedContext(*this) && 17006 isImplicitlyDefinableConstexprFunction(Func); 17007 17008 // Determine whether we require a function definition to exist, per 17009 // C++11 [temp.inst]p3: 17010 // Unless a function template specialization has been explicitly 17011 // instantiated or explicitly specialized, the function template 17012 // specialization is implicitly instantiated when the specialization is 17013 // referenced in a context that requires a function definition to exist. 17014 // C++20 [temp.inst]p7: 17015 // The existence of a definition of a [...] function is considered to 17016 // affect the semantics of the program if the [...] function is needed for 17017 // constant evaluation by an expression 17018 // C++20 [basic.def.odr]p10: 17019 // Every program shall contain exactly one definition of every non-inline 17020 // function or variable that is odr-used in that program outside of a 17021 // discarded statement 17022 // C++20 [special]p1: 17023 // The implementation will implicitly define [defaulted special members] 17024 // if they are odr-used or needed for constant evaluation. 17025 // 17026 // Note that we skip the implicit instantiation of templates that are only 17027 // used in unused default arguments or by recursive calls to themselves. 17028 // This is formally non-conforming, but seems reasonable in practice. 17029 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17030 NeededForConstantEvaluation); 17031 17032 // C++14 [temp.expl.spec]p6: 17033 // If a template [...] is explicitly specialized then that specialization 17034 // shall be declared before the first use of that specialization that would 17035 // cause an implicit instantiation to take place, in every translation unit 17036 // in which such a use occurs 17037 if (NeedDefinition && 17038 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17039 Func->getMemberSpecializationInfo())) 17040 checkSpecializationVisibility(Loc, Func); 17041 17042 if (getLangOpts().CUDA) 17043 CheckCUDACall(Loc, Func); 17044 17045 if (getLangOpts().SYCLIsDevice) 17046 checkSYCLDeviceFunction(Loc, Func); 17047 17048 // If we need a definition, try to create one. 17049 if (NeedDefinition && !Func->getBody()) { 17050 runWithSufficientStackSpace(Loc, [&] { 17051 if (CXXConstructorDecl *Constructor = 17052 dyn_cast<CXXConstructorDecl>(Func)) { 17053 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17054 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17055 if (Constructor->isDefaultConstructor()) { 17056 if (Constructor->isTrivial() && 17057 !Constructor->hasAttr<DLLExportAttr>()) 17058 return; 17059 DefineImplicitDefaultConstructor(Loc, Constructor); 17060 } else if (Constructor->isCopyConstructor()) { 17061 DefineImplicitCopyConstructor(Loc, Constructor); 17062 } else if (Constructor->isMoveConstructor()) { 17063 DefineImplicitMoveConstructor(Loc, Constructor); 17064 } 17065 } else if (Constructor->getInheritedConstructor()) { 17066 DefineInheritingConstructor(Loc, Constructor); 17067 } 17068 } else if (CXXDestructorDecl *Destructor = 17069 dyn_cast<CXXDestructorDecl>(Func)) { 17070 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17071 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17072 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17073 return; 17074 DefineImplicitDestructor(Loc, Destructor); 17075 } 17076 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17077 MarkVTableUsed(Loc, Destructor->getParent()); 17078 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17079 if (MethodDecl->isOverloadedOperator() && 17080 MethodDecl->getOverloadedOperator() == OO_Equal) { 17081 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17082 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17083 if (MethodDecl->isCopyAssignmentOperator()) 17084 DefineImplicitCopyAssignment(Loc, MethodDecl); 17085 else if (MethodDecl->isMoveAssignmentOperator()) 17086 DefineImplicitMoveAssignment(Loc, MethodDecl); 17087 } 17088 } else if (isa<CXXConversionDecl>(MethodDecl) && 17089 MethodDecl->getParent()->isLambda()) { 17090 CXXConversionDecl *Conversion = 17091 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17092 if (Conversion->isLambdaToBlockPointerConversion()) 17093 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17094 else 17095 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17096 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17097 MarkVTableUsed(Loc, MethodDecl->getParent()); 17098 } 17099 17100 if (Func->isDefaulted() && !Func->isDeleted()) { 17101 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17102 if (DCK != DefaultedComparisonKind::None) 17103 DefineDefaultedComparison(Loc, Func, DCK); 17104 } 17105 17106 // Implicit instantiation of function templates and member functions of 17107 // class templates. 17108 if (Func->isImplicitlyInstantiable()) { 17109 TemplateSpecializationKind TSK = 17110 Func->getTemplateSpecializationKindForInstantiation(); 17111 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17112 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17113 if (FirstInstantiation) { 17114 PointOfInstantiation = Loc; 17115 if (auto *MSI = Func->getMemberSpecializationInfo()) 17116 MSI->setPointOfInstantiation(Loc); 17117 // FIXME: Notify listener. 17118 else 17119 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17120 } else if (TSK != TSK_ImplicitInstantiation) { 17121 // Use the point of use as the point of instantiation, instead of the 17122 // point of explicit instantiation (which we track as the actual point 17123 // of instantiation). This gives better backtraces in diagnostics. 17124 PointOfInstantiation = Loc; 17125 } 17126 17127 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17128 Func->isConstexpr()) { 17129 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17130 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17131 CodeSynthesisContexts.size()) 17132 PendingLocalImplicitInstantiations.push_back( 17133 std::make_pair(Func, PointOfInstantiation)); 17134 else if (Func->isConstexpr()) 17135 // Do not defer instantiations of constexpr functions, to avoid the 17136 // expression evaluator needing to call back into Sema if it sees a 17137 // call to such a function. 17138 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17139 else { 17140 Func->setInstantiationIsPending(true); 17141 PendingInstantiations.push_back( 17142 std::make_pair(Func, PointOfInstantiation)); 17143 // Notify the consumer that a function was implicitly instantiated. 17144 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17145 } 17146 } 17147 } else { 17148 // Walk redefinitions, as some of them may be instantiable. 17149 for (auto i : Func->redecls()) { 17150 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17151 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17152 } 17153 } 17154 }); 17155 } 17156 17157 // C++14 [except.spec]p17: 17158 // An exception-specification is considered to be needed when: 17159 // - the function is odr-used or, if it appears in an unevaluated operand, 17160 // would be odr-used if the expression were potentially-evaluated; 17161 // 17162 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17163 // function is a pure virtual function we're calling, and in that case the 17164 // function was selected by overload resolution and we need to resolve its 17165 // exception specification for a different reason. 17166 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17167 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17168 ResolveExceptionSpec(Loc, FPT); 17169 17170 // If this is the first "real" use, act on that. 17171 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17172 // Keep track of used but undefined functions. 17173 if (!Func->isDefined()) { 17174 if (mightHaveNonExternalLinkage(Func)) 17175 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17176 else if (Func->getMostRecentDecl()->isInlined() && 17177 !LangOpts.GNUInline && 17178 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17179 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17180 else if (isExternalWithNoLinkageType(Func)) 17181 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17182 } 17183 17184 // Some x86 Windows calling conventions mangle the size of the parameter 17185 // pack into the name. Computing the size of the parameters requires the 17186 // parameter types to be complete. Check that now. 17187 if (funcHasParameterSizeMangling(*this, Func)) 17188 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17189 17190 // In the MS C++ ABI, the compiler emits destructor variants where they are 17191 // used. If the destructor is used here but defined elsewhere, mark the 17192 // virtual base destructors referenced. If those virtual base destructors 17193 // are inline, this will ensure they are defined when emitting the complete 17194 // destructor variant. This checking may be redundant if the destructor is 17195 // provided later in this TU. 17196 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17197 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17198 CXXRecordDecl *Parent = Dtor->getParent(); 17199 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17200 CheckCompleteDestructorVariant(Loc, Dtor); 17201 } 17202 } 17203 17204 Func->markUsed(Context); 17205 } 17206 } 17207 17208 /// Directly mark a variable odr-used. Given a choice, prefer to use 17209 /// MarkVariableReferenced since it does additional checks and then 17210 /// calls MarkVarDeclODRUsed. 17211 /// If the variable must be captured: 17212 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17213 /// - else capture it in the DeclContext that maps to the 17214 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17215 static void 17216 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17217 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17218 // Keep track of used but undefined variables. 17219 // FIXME: We shouldn't suppress this warning for static data members. 17220 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17221 (!Var->isExternallyVisible() || Var->isInline() || 17222 SemaRef.isExternalWithNoLinkageType(Var)) && 17223 !(Var->isStaticDataMember() && Var->hasInit())) { 17224 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17225 if (old.isInvalid()) 17226 old = Loc; 17227 } 17228 QualType CaptureType, DeclRefType; 17229 if (SemaRef.LangOpts.OpenMP) 17230 SemaRef.tryCaptureOpenMPLambdas(Var); 17231 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17232 /*EllipsisLoc*/ SourceLocation(), 17233 /*BuildAndDiagnose*/ true, 17234 CaptureType, DeclRefType, 17235 FunctionScopeIndexToStopAt); 17236 17237 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17238 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17239 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17240 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17241 if (VarTarget == Sema::CVT_Host && 17242 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17243 UserTarget == Sema::CFT_Global)) { 17244 // Diagnose ODR-use of host global variables in device functions. 17245 // Reference of device global variables in host functions is allowed 17246 // through shadow variables therefore it is not diagnosed. 17247 if (SemaRef.LangOpts.CUDAIsDevice) { 17248 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17249 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17250 SemaRef.targetDiag(Var->getLocation(), 17251 Var->getType().isConstQualified() 17252 ? diag::note_cuda_const_var_unpromoted 17253 : diag::note_cuda_host_var); 17254 } 17255 } else if (VarTarget == Sema::CVT_Device && 17256 (UserTarget == Sema::CFT_Host || 17257 UserTarget == Sema::CFT_HostDevice) && 17258 !Var->hasExternalStorage()) { 17259 // Record a CUDA/HIP device side variable if it is ODR-used 17260 // by host code. This is done conservatively, when the variable is 17261 // referenced in any of the following contexts: 17262 // - a non-function context 17263 // - a host function 17264 // - a host device function 17265 // This makes the ODR-use of the device side variable by host code to 17266 // be visible in the device compilation for the compiler to be able to 17267 // emit template variables instantiated by host code only and to 17268 // externalize the static device side variable ODR-used by host code. 17269 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17270 } 17271 } 17272 17273 Var->markUsed(SemaRef.Context); 17274 } 17275 17276 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17277 SourceLocation Loc, 17278 unsigned CapturingScopeIndex) { 17279 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17280 } 17281 17282 static void 17283 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17284 ValueDecl *var, DeclContext *DC) { 17285 DeclContext *VarDC = var->getDeclContext(); 17286 17287 // If the parameter still belongs to the translation unit, then 17288 // we're actually just using one parameter in the declaration of 17289 // the next. 17290 if (isa<ParmVarDecl>(var) && 17291 isa<TranslationUnitDecl>(VarDC)) 17292 return; 17293 17294 // For C code, don't diagnose about capture if we're not actually in code 17295 // right now; it's impossible to write a non-constant expression outside of 17296 // function context, so we'll get other (more useful) diagnostics later. 17297 // 17298 // For C++, things get a bit more nasty... it would be nice to suppress this 17299 // diagnostic for certain cases like using a local variable in an array bound 17300 // for a member of a local class, but the correct predicate is not obvious. 17301 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17302 return; 17303 17304 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17305 unsigned ContextKind = 3; // unknown 17306 if (isa<CXXMethodDecl>(VarDC) && 17307 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17308 ContextKind = 2; 17309 } else if (isa<FunctionDecl>(VarDC)) { 17310 ContextKind = 0; 17311 } else if (isa<BlockDecl>(VarDC)) { 17312 ContextKind = 1; 17313 } 17314 17315 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17316 << var << ValueKind << ContextKind << VarDC; 17317 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17318 << var; 17319 17320 // FIXME: Add additional diagnostic info about class etc. which prevents 17321 // capture. 17322 } 17323 17324 17325 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17326 bool &SubCapturesAreNested, 17327 QualType &CaptureType, 17328 QualType &DeclRefType) { 17329 // Check whether we've already captured it. 17330 if (CSI->CaptureMap.count(Var)) { 17331 // If we found a capture, any subcaptures are nested. 17332 SubCapturesAreNested = true; 17333 17334 // Retrieve the capture type for this variable. 17335 CaptureType = CSI->getCapture(Var).getCaptureType(); 17336 17337 // Compute the type of an expression that refers to this variable. 17338 DeclRefType = CaptureType.getNonReferenceType(); 17339 17340 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17341 // are mutable in the sense that user can change their value - they are 17342 // private instances of the captured declarations. 17343 const Capture &Cap = CSI->getCapture(Var); 17344 if (Cap.isCopyCapture() && 17345 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17346 !(isa<CapturedRegionScopeInfo>(CSI) && 17347 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17348 DeclRefType.addConst(); 17349 return true; 17350 } 17351 return false; 17352 } 17353 17354 // Only block literals, captured statements, and lambda expressions can 17355 // capture; other scopes don't work. 17356 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17357 SourceLocation Loc, 17358 const bool Diagnose, Sema &S) { 17359 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17360 return getLambdaAwareParentOfDeclContext(DC); 17361 else if (Var->hasLocalStorage()) { 17362 if (Diagnose) 17363 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17364 } 17365 return nullptr; 17366 } 17367 17368 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17369 // certain types of variables (unnamed, variably modified types etc.) 17370 // so check for eligibility. 17371 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17372 SourceLocation Loc, 17373 const bool Diagnose, Sema &S) { 17374 17375 bool IsBlock = isa<BlockScopeInfo>(CSI); 17376 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17377 17378 // Lambdas are not allowed to capture unnamed variables 17379 // (e.g. anonymous unions). 17380 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17381 // assuming that's the intent. 17382 if (IsLambda && !Var->getDeclName()) { 17383 if (Diagnose) { 17384 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17385 S.Diag(Var->getLocation(), diag::note_declared_at); 17386 } 17387 return false; 17388 } 17389 17390 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17391 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17392 if (Diagnose) { 17393 S.Diag(Loc, diag::err_ref_vm_type); 17394 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17395 } 17396 return false; 17397 } 17398 // Prohibit structs with flexible array members too. 17399 // We cannot capture what is in the tail end of the struct. 17400 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17401 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17402 if (Diagnose) { 17403 if (IsBlock) 17404 S.Diag(Loc, diag::err_ref_flexarray_type); 17405 else 17406 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17407 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17408 } 17409 return false; 17410 } 17411 } 17412 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17413 // Lambdas and captured statements are not allowed to capture __block 17414 // variables; they don't support the expected semantics. 17415 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17416 if (Diagnose) { 17417 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17418 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17419 } 17420 return false; 17421 } 17422 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17423 if (S.getLangOpts().OpenCL && IsBlock && 17424 Var->getType()->isBlockPointerType()) { 17425 if (Diagnose) 17426 S.Diag(Loc, diag::err_opencl_block_ref_block); 17427 return false; 17428 } 17429 17430 return true; 17431 } 17432 17433 // Returns true if the capture by block was successful. 17434 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17435 SourceLocation Loc, 17436 const bool BuildAndDiagnose, 17437 QualType &CaptureType, 17438 QualType &DeclRefType, 17439 const bool Nested, 17440 Sema &S, bool Invalid) { 17441 bool ByRef = false; 17442 17443 // Blocks are not allowed to capture arrays, excepting OpenCL. 17444 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17445 // (decayed to pointers). 17446 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17447 if (BuildAndDiagnose) { 17448 S.Diag(Loc, diag::err_ref_array_type); 17449 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17450 Invalid = true; 17451 } else { 17452 return false; 17453 } 17454 } 17455 17456 // Forbid the block-capture of autoreleasing variables. 17457 if (!Invalid && 17458 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17459 if (BuildAndDiagnose) { 17460 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17461 << /*block*/ 0; 17462 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17463 Invalid = true; 17464 } else { 17465 return false; 17466 } 17467 } 17468 17469 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17470 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17471 QualType PointeeTy = PT->getPointeeType(); 17472 17473 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17474 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17475 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17476 if (BuildAndDiagnose) { 17477 SourceLocation VarLoc = Var->getLocation(); 17478 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17479 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17480 } 17481 } 17482 } 17483 17484 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17485 if (HasBlocksAttr || CaptureType->isReferenceType() || 17486 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17487 // Block capture by reference does not change the capture or 17488 // declaration reference types. 17489 ByRef = true; 17490 } else { 17491 // Block capture by copy introduces 'const'. 17492 CaptureType = CaptureType.getNonReferenceType().withConst(); 17493 DeclRefType = CaptureType; 17494 } 17495 17496 // Actually capture the variable. 17497 if (BuildAndDiagnose) 17498 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17499 CaptureType, Invalid); 17500 17501 return !Invalid; 17502 } 17503 17504 17505 /// Capture the given variable in the captured region. 17506 static bool captureInCapturedRegion( 17507 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17508 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17509 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17510 bool IsTopScope, Sema &S, bool Invalid) { 17511 // By default, capture variables by reference. 17512 bool ByRef = true; 17513 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17514 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17515 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17516 // Using an LValue reference type is consistent with Lambdas (see below). 17517 if (S.isOpenMPCapturedDecl(Var)) { 17518 bool HasConst = DeclRefType.isConstQualified(); 17519 DeclRefType = DeclRefType.getUnqualifiedType(); 17520 // Don't lose diagnostics about assignments to const. 17521 if (HasConst) 17522 DeclRefType.addConst(); 17523 } 17524 // Do not capture firstprivates in tasks. 17525 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17526 OMPC_unknown) 17527 return true; 17528 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17529 RSI->OpenMPCaptureLevel); 17530 } 17531 17532 if (ByRef) 17533 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17534 else 17535 CaptureType = DeclRefType; 17536 17537 // Actually capture the variable. 17538 if (BuildAndDiagnose) 17539 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17540 Loc, SourceLocation(), CaptureType, Invalid); 17541 17542 return !Invalid; 17543 } 17544 17545 /// Capture the given variable in the lambda. 17546 static bool captureInLambda(LambdaScopeInfo *LSI, 17547 VarDecl *Var, 17548 SourceLocation Loc, 17549 const bool BuildAndDiagnose, 17550 QualType &CaptureType, 17551 QualType &DeclRefType, 17552 const bool RefersToCapturedVariable, 17553 const Sema::TryCaptureKind Kind, 17554 SourceLocation EllipsisLoc, 17555 const bool IsTopScope, 17556 Sema &S, bool Invalid) { 17557 // Determine whether we are capturing by reference or by value. 17558 bool ByRef = false; 17559 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17560 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17561 } else { 17562 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17563 } 17564 17565 // Compute the type of the field that will capture this variable. 17566 if (ByRef) { 17567 // C++11 [expr.prim.lambda]p15: 17568 // An entity is captured by reference if it is implicitly or 17569 // explicitly captured but not captured by copy. It is 17570 // unspecified whether additional unnamed non-static data 17571 // members are declared in the closure type for entities 17572 // captured by reference. 17573 // 17574 // FIXME: It is not clear whether we want to build an lvalue reference 17575 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17576 // to do the former, while EDG does the latter. Core issue 1249 will 17577 // clarify, but for now we follow GCC because it's a more permissive and 17578 // easily defensible position. 17579 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17580 } else { 17581 // C++11 [expr.prim.lambda]p14: 17582 // For each entity captured by copy, an unnamed non-static 17583 // data member is declared in the closure type. The 17584 // declaration order of these members is unspecified. The type 17585 // of such a data member is the type of the corresponding 17586 // captured entity if the entity is not a reference to an 17587 // object, or the referenced type otherwise. [Note: If the 17588 // captured entity is a reference to a function, the 17589 // corresponding data member is also a reference to a 17590 // function. - end note ] 17591 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17592 if (!RefType->getPointeeType()->isFunctionType()) 17593 CaptureType = RefType->getPointeeType(); 17594 } 17595 17596 // Forbid the lambda copy-capture of autoreleasing variables. 17597 if (!Invalid && 17598 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17599 if (BuildAndDiagnose) { 17600 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17601 S.Diag(Var->getLocation(), diag::note_previous_decl) 17602 << Var->getDeclName(); 17603 Invalid = true; 17604 } else { 17605 return false; 17606 } 17607 } 17608 17609 // Make sure that by-copy captures are of a complete and non-abstract type. 17610 if (!Invalid && BuildAndDiagnose) { 17611 if (!CaptureType->isDependentType() && 17612 S.RequireCompleteSizedType( 17613 Loc, CaptureType, 17614 diag::err_capture_of_incomplete_or_sizeless_type, 17615 Var->getDeclName())) 17616 Invalid = true; 17617 else if (S.RequireNonAbstractType(Loc, CaptureType, 17618 diag::err_capture_of_abstract_type)) 17619 Invalid = true; 17620 } 17621 } 17622 17623 // Compute the type of a reference to this captured variable. 17624 if (ByRef) 17625 DeclRefType = CaptureType.getNonReferenceType(); 17626 else { 17627 // C++ [expr.prim.lambda]p5: 17628 // The closure type for a lambda-expression has a public inline 17629 // function call operator [...]. This function call operator is 17630 // declared const (9.3.1) if and only if the lambda-expression's 17631 // parameter-declaration-clause is not followed by mutable. 17632 DeclRefType = CaptureType.getNonReferenceType(); 17633 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17634 DeclRefType.addConst(); 17635 } 17636 17637 // Add the capture. 17638 if (BuildAndDiagnose) 17639 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17640 Loc, EllipsisLoc, CaptureType, Invalid); 17641 17642 return !Invalid; 17643 } 17644 17645 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17646 // Offer a Copy fix even if the type is dependent. 17647 if (Var->getType()->isDependentType()) 17648 return true; 17649 QualType T = Var->getType().getNonReferenceType(); 17650 if (T.isTriviallyCopyableType(Context)) 17651 return true; 17652 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17653 17654 if (!(RD = RD->getDefinition())) 17655 return false; 17656 if (RD->hasSimpleCopyConstructor()) 17657 return true; 17658 if (RD->hasUserDeclaredCopyConstructor()) 17659 for (CXXConstructorDecl *Ctor : RD->ctors()) 17660 if (Ctor->isCopyConstructor()) 17661 return !Ctor->isDeleted(); 17662 } 17663 return false; 17664 } 17665 17666 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17667 /// default capture. Fixes may be omitted if they aren't allowed by the 17668 /// standard, for example we can't emit a default copy capture fix-it if we 17669 /// already explicitly copy capture capture another variable. 17670 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17671 VarDecl *Var) { 17672 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17673 // Don't offer Capture by copy of default capture by copy fixes if Var is 17674 // known not to be copy constructible. 17675 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17676 17677 SmallString<32> FixBuffer; 17678 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17679 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17680 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17681 if (ShouldOfferCopyFix) { 17682 // Offer fixes to insert an explicit capture for the variable. 17683 // [] -> [VarName] 17684 // [OtherCapture] -> [OtherCapture, VarName] 17685 FixBuffer.assign({Separator, Var->getName()}); 17686 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17687 << Var << /*value*/ 0 17688 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17689 } 17690 // As above but capture by reference. 17691 FixBuffer.assign({Separator, "&", Var->getName()}); 17692 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17693 << Var << /*reference*/ 1 17694 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17695 } 17696 17697 // Only try to offer default capture if there are no captures excluding this 17698 // and init captures. 17699 // [this]: OK. 17700 // [X = Y]: OK. 17701 // [&A, &B]: Don't offer. 17702 // [A, B]: Don't offer. 17703 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17704 return !C.isThisCapture() && !C.isInitCapture(); 17705 })) 17706 return; 17707 17708 // The default capture specifiers, '=' or '&', must appear first in the 17709 // capture body. 17710 SourceLocation DefaultInsertLoc = 17711 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17712 17713 if (ShouldOfferCopyFix) { 17714 bool CanDefaultCopyCapture = true; 17715 // [=, *this] OK since c++17 17716 // [=, this] OK since c++20 17717 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17718 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17719 ? LSI->getCXXThisCapture().isCopyCapture() 17720 : false; 17721 // We can't use default capture by copy if any captures already specified 17722 // capture by copy. 17723 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17724 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17725 })) { 17726 FixBuffer.assign({"=", Separator}); 17727 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17728 << /*value*/ 0 17729 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17730 } 17731 } 17732 17733 // We can't use default capture by reference if any captures already specified 17734 // capture by reference. 17735 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17736 return !C.isInitCapture() && C.isReferenceCapture() && 17737 !C.isThisCapture(); 17738 })) { 17739 FixBuffer.assign({"&", Separator}); 17740 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17741 << /*reference*/ 1 17742 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17743 } 17744 } 17745 17746 bool Sema::tryCaptureVariable( 17747 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17748 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17749 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17750 // An init-capture is notionally from the context surrounding its 17751 // declaration, but its parent DC is the lambda class. 17752 DeclContext *VarDC = Var->getDeclContext(); 17753 if (Var->isInitCapture()) 17754 VarDC = VarDC->getParent(); 17755 17756 DeclContext *DC = CurContext; 17757 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17758 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17759 // We need to sync up the Declaration Context with the 17760 // FunctionScopeIndexToStopAt 17761 if (FunctionScopeIndexToStopAt) { 17762 unsigned FSIndex = FunctionScopes.size() - 1; 17763 while (FSIndex != MaxFunctionScopesIndex) { 17764 DC = getLambdaAwareParentOfDeclContext(DC); 17765 --FSIndex; 17766 } 17767 } 17768 17769 17770 // If the variable is declared in the current context, there is no need to 17771 // capture it. 17772 if (VarDC == DC) return true; 17773 17774 // Capture global variables if it is required to use private copy of this 17775 // variable. 17776 bool IsGlobal = !Var->hasLocalStorage(); 17777 if (IsGlobal && 17778 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17779 MaxFunctionScopesIndex))) 17780 return true; 17781 Var = Var->getCanonicalDecl(); 17782 17783 // Walk up the stack to determine whether we can capture the variable, 17784 // performing the "simple" checks that don't depend on type. We stop when 17785 // we've either hit the declared scope of the variable or find an existing 17786 // capture of that variable. We start from the innermost capturing-entity 17787 // (the DC) and ensure that all intervening capturing-entities 17788 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17789 // declcontext can either capture the variable or have already captured 17790 // the variable. 17791 CaptureType = Var->getType(); 17792 DeclRefType = CaptureType.getNonReferenceType(); 17793 bool Nested = false; 17794 bool Explicit = (Kind != TryCapture_Implicit); 17795 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17796 do { 17797 // Only block literals, captured statements, and lambda expressions can 17798 // capture; other scopes don't work. 17799 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17800 ExprLoc, 17801 BuildAndDiagnose, 17802 *this); 17803 // We need to check for the parent *first* because, if we *have* 17804 // private-captured a global variable, we need to recursively capture it in 17805 // intermediate blocks, lambdas, etc. 17806 if (!ParentDC) { 17807 if (IsGlobal) { 17808 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17809 break; 17810 } 17811 return true; 17812 } 17813 17814 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17815 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17816 17817 17818 // Check whether we've already captured it. 17819 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17820 DeclRefType)) { 17821 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17822 break; 17823 } 17824 // If we are instantiating a generic lambda call operator body, 17825 // we do not want to capture new variables. What was captured 17826 // during either a lambdas transformation or initial parsing 17827 // should be used. 17828 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17829 if (BuildAndDiagnose) { 17830 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17831 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17832 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17833 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17834 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17835 buildLambdaCaptureFixit(*this, LSI, Var); 17836 } else 17837 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17838 } 17839 return true; 17840 } 17841 17842 // Try to capture variable-length arrays types. 17843 if (Var->getType()->isVariablyModifiedType()) { 17844 // We're going to walk down into the type and look for VLA 17845 // expressions. 17846 QualType QTy = Var->getType(); 17847 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17848 QTy = PVD->getOriginalType(); 17849 captureVariablyModifiedType(Context, QTy, CSI); 17850 } 17851 17852 if (getLangOpts().OpenMP) { 17853 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17854 // OpenMP private variables should not be captured in outer scope, so 17855 // just break here. Similarly, global variables that are captured in a 17856 // target region should not be captured outside the scope of the region. 17857 if (RSI->CapRegionKind == CR_OpenMP) { 17858 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17859 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17860 // If the variable is private (i.e. not captured) and has variably 17861 // modified type, we still need to capture the type for correct 17862 // codegen in all regions, associated with the construct. Currently, 17863 // it is captured in the innermost captured region only. 17864 if (IsOpenMPPrivateDecl != OMPC_unknown && 17865 Var->getType()->isVariablyModifiedType()) { 17866 QualType QTy = Var->getType(); 17867 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17868 QTy = PVD->getOriginalType(); 17869 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17870 I < E; ++I) { 17871 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17872 FunctionScopes[FunctionScopesIndex - I]); 17873 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17874 "Wrong number of captured regions associated with the " 17875 "OpenMP construct."); 17876 captureVariablyModifiedType(Context, QTy, OuterRSI); 17877 } 17878 } 17879 bool IsTargetCap = 17880 IsOpenMPPrivateDecl != OMPC_private && 17881 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17882 RSI->OpenMPCaptureLevel); 17883 // Do not capture global if it is not privatized in outer regions. 17884 bool IsGlobalCap = 17885 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17886 RSI->OpenMPCaptureLevel); 17887 17888 // When we detect target captures we are looking from inside the 17889 // target region, therefore we need to propagate the capture from the 17890 // enclosing region. Therefore, the capture is not initially nested. 17891 if (IsTargetCap) 17892 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17893 17894 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17895 (IsGlobal && !IsGlobalCap)) { 17896 Nested = !IsTargetCap; 17897 bool HasConst = DeclRefType.isConstQualified(); 17898 DeclRefType = DeclRefType.getUnqualifiedType(); 17899 // Don't lose diagnostics about assignments to const. 17900 if (HasConst) 17901 DeclRefType.addConst(); 17902 CaptureType = Context.getLValueReferenceType(DeclRefType); 17903 break; 17904 } 17905 } 17906 } 17907 } 17908 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17909 // No capture-default, and this is not an explicit capture 17910 // so cannot capture this variable. 17911 if (BuildAndDiagnose) { 17912 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17913 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17914 auto *LSI = cast<LambdaScopeInfo>(CSI); 17915 if (LSI->Lambda) { 17916 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17917 buildLambdaCaptureFixit(*this, LSI, Var); 17918 } 17919 // FIXME: If we error out because an outer lambda can not implicitly 17920 // capture a variable that an inner lambda explicitly captures, we 17921 // should have the inner lambda do the explicit capture - because 17922 // it makes for cleaner diagnostics later. This would purely be done 17923 // so that the diagnostic does not misleadingly claim that a variable 17924 // can not be captured by a lambda implicitly even though it is captured 17925 // explicitly. Suggestion: 17926 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17927 // at the function head 17928 // - cache the StartingDeclContext - this must be a lambda 17929 // - captureInLambda in the innermost lambda the variable. 17930 } 17931 return true; 17932 } 17933 17934 FunctionScopesIndex--; 17935 DC = ParentDC; 17936 Explicit = false; 17937 } while (!VarDC->Equals(DC)); 17938 17939 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17940 // computing the type of the capture at each step, checking type-specific 17941 // requirements, and adding captures if requested. 17942 // If the variable had already been captured previously, we start capturing 17943 // at the lambda nested within that one. 17944 bool Invalid = false; 17945 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17946 ++I) { 17947 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17948 17949 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17950 // certain types of variables (unnamed, variably modified types etc.) 17951 // so check for eligibility. 17952 if (!Invalid) 17953 Invalid = 17954 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17955 17956 // After encountering an error, if we're actually supposed to capture, keep 17957 // capturing in nested contexts to suppress any follow-on diagnostics. 17958 if (Invalid && !BuildAndDiagnose) 17959 return true; 17960 17961 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17962 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17963 DeclRefType, Nested, *this, Invalid); 17964 Nested = true; 17965 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17966 Invalid = !captureInCapturedRegion( 17967 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17968 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17969 Nested = true; 17970 } else { 17971 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17972 Invalid = 17973 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17974 DeclRefType, Nested, Kind, EllipsisLoc, 17975 /*IsTopScope*/ I == N - 1, *this, Invalid); 17976 Nested = true; 17977 } 17978 17979 if (Invalid && !BuildAndDiagnose) 17980 return true; 17981 } 17982 return Invalid; 17983 } 17984 17985 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17986 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17987 QualType CaptureType; 17988 QualType DeclRefType; 17989 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17990 /*BuildAndDiagnose=*/true, CaptureType, 17991 DeclRefType, nullptr); 17992 } 17993 17994 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17995 QualType CaptureType; 17996 QualType DeclRefType; 17997 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17998 /*BuildAndDiagnose=*/false, CaptureType, 17999 DeclRefType, nullptr); 18000 } 18001 18002 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18003 QualType CaptureType; 18004 QualType DeclRefType; 18005 18006 // Determine whether we can capture this variable. 18007 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18008 /*BuildAndDiagnose=*/false, CaptureType, 18009 DeclRefType, nullptr)) 18010 return QualType(); 18011 18012 return DeclRefType; 18013 } 18014 18015 namespace { 18016 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18017 // The produced TemplateArgumentListInfo* points to data stored within this 18018 // object, so should only be used in contexts where the pointer will not be 18019 // used after the CopiedTemplateArgs object is destroyed. 18020 class CopiedTemplateArgs { 18021 bool HasArgs; 18022 TemplateArgumentListInfo TemplateArgStorage; 18023 public: 18024 template<typename RefExpr> 18025 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18026 if (HasArgs) 18027 E->copyTemplateArgumentsInto(TemplateArgStorage); 18028 } 18029 operator TemplateArgumentListInfo*() 18030 #ifdef __has_cpp_attribute 18031 #if __has_cpp_attribute(clang::lifetimebound) 18032 [[clang::lifetimebound]] 18033 #endif 18034 #endif 18035 { 18036 return HasArgs ? &TemplateArgStorage : nullptr; 18037 } 18038 }; 18039 } 18040 18041 /// Walk the set of potential results of an expression and mark them all as 18042 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18043 /// 18044 /// \return A new expression if we found any potential results, ExprEmpty() if 18045 /// not, and ExprError() if we diagnosed an error. 18046 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18047 NonOdrUseReason NOUR) { 18048 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18049 // an object that satisfies the requirements for appearing in a 18050 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18051 // is immediately applied." This function handles the lvalue-to-rvalue 18052 // conversion part. 18053 // 18054 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18055 // transform it into the relevant kind of non-odr-use node and rebuild the 18056 // tree of nodes leading to it. 18057 // 18058 // This is a mini-TreeTransform that only transforms a restricted subset of 18059 // nodes (and only certain operands of them). 18060 18061 // Rebuild a subexpression. 18062 auto Rebuild = [&](Expr *Sub) { 18063 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18064 }; 18065 18066 // Check whether a potential result satisfies the requirements of NOUR. 18067 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18068 // Any entity other than a VarDecl is always odr-used whenever it's named 18069 // in a potentially-evaluated expression. 18070 auto *VD = dyn_cast<VarDecl>(D); 18071 if (!VD) 18072 return true; 18073 18074 // C++2a [basic.def.odr]p4: 18075 // A variable x whose name appears as a potentially-evalauted expression 18076 // e is odr-used by e unless 18077 // -- x is a reference that is usable in constant expressions, or 18078 // -- x is a variable of non-reference type that is usable in constant 18079 // expressions and has no mutable subobjects, and e is an element of 18080 // the set of potential results of an expression of 18081 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18082 // conversion is applied, or 18083 // -- x is a variable of non-reference type, and e is an element of the 18084 // set of potential results of a discarded-value expression to which 18085 // the lvalue-to-rvalue conversion is not applied 18086 // 18087 // We check the first bullet and the "potentially-evaluated" condition in 18088 // BuildDeclRefExpr. We check the type requirements in the second bullet 18089 // in CheckLValueToRValueConversionOperand below. 18090 switch (NOUR) { 18091 case NOUR_None: 18092 case NOUR_Unevaluated: 18093 llvm_unreachable("unexpected non-odr-use-reason"); 18094 18095 case NOUR_Constant: 18096 // Constant references were handled when they were built. 18097 if (VD->getType()->isReferenceType()) 18098 return true; 18099 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18100 if (RD->hasMutableFields()) 18101 return true; 18102 if (!VD->isUsableInConstantExpressions(S.Context)) 18103 return true; 18104 break; 18105 18106 case NOUR_Discarded: 18107 if (VD->getType()->isReferenceType()) 18108 return true; 18109 break; 18110 } 18111 return false; 18112 }; 18113 18114 // Mark that this expression does not constitute an odr-use. 18115 auto MarkNotOdrUsed = [&] { 18116 S.MaybeODRUseExprs.remove(E); 18117 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18118 LSI->markVariableExprAsNonODRUsed(E); 18119 }; 18120 18121 // C++2a [basic.def.odr]p2: 18122 // The set of potential results of an expression e is defined as follows: 18123 switch (E->getStmtClass()) { 18124 // -- If e is an id-expression, ... 18125 case Expr::DeclRefExprClass: { 18126 auto *DRE = cast<DeclRefExpr>(E); 18127 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18128 break; 18129 18130 // Rebuild as a non-odr-use DeclRefExpr. 18131 MarkNotOdrUsed(); 18132 return DeclRefExpr::Create( 18133 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18134 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18135 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18136 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18137 } 18138 18139 case Expr::FunctionParmPackExprClass: { 18140 auto *FPPE = cast<FunctionParmPackExpr>(E); 18141 // If any of the declarations in the pack is odr-used, then the expression 18142 // as a whole constitutes an odr-use. 18143 for (VarDecl *D : *FPPE) 18144 if (IsPotentialResultOdrUsed(D)) 18145 return ExprEmpty(); 18146 18147 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18148 // nothing cares about whether we marked this as an odr-use, but it might 18149 // be useful for non-compiler tools. 18150 MarkNotOdrUsed(); 18151 break; 18152 } 18153 18154 // -- If e is a subscripting operation with an array operand... 18155 case Expr::ArraySubscriptExprClass: { 18156 auto *ASE = cast<ArraySubscriptExpr>(E); 18157 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18158 if (!OldBase->getType()->isArrayType()) 18159 break; 18160 ExprResult Base = Rebuild(OldBase); 18161 if (!Base.isUsable()) 18162 return Base; 18163 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18164 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18165 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18166 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18167 ASE->getRBracketLoc()); 18168 } 18169 18170 case Expr::MemberExprClass: { 18171 auto *ME = cast<MemberExpr>(E); 18172 // -- If e is a class member access expression [...] naming a non-static 18173 // data member... 18174 if (isa<FieldDecl>(ME->getMemberDecl())) { 18175 ExprResult Base = Rebuild(ME->getBase()); 18176 if (!Base.isUsable()) 18177 return Base; 18178 return MemberExpr::Create( 18179 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18180 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18181 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18182 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18183 ME->getObjectKind(), ME->isNonOdrUse()); 18184 } 18185 18186 if (ME->getMemberDecl()->isCXXInstanceMember()) 18187 break; 18188 18189 // -- If e is a class member access expression naming a static data member, 18190 // ... 18191 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18192 break; 18193 18194 // Rebuild as a non-odr-use MemberExpr. 18195 MarkNotOdrUsed(); 18196 return MemberExpr::Create( 18197 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18198 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18199 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18200 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18201 return ExprEmpty(); 18202 } 18203 18204 case Expr::BinaryOperatorClass: { 18205 auto *BO = cast<BinaryOperator>(E); 18206 Expr *LHS = BO->getLHS(); 18207 Expr *RHS = BO->getRHS(); 18208 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18209 if (BO->getOpcode() == BO_PtrMemD) { 18210 ExprResult Sub = Rebuild(LHS); 18211 if (!Sub.isUsable()) 18212 return Sub; 18213 LHS = Sub.get(); 18214 // -- If e is a comma expression, ... 18215 } else if (BO->getOpcode() == BO_Comma) { 18216 ExprResult Sub = Rebuild(RHS); 18217 if (!Sub.isUsable()) 18218 return Sub; 18219 RHS = Sub.get(); 18220 } else { 18221 break; 18222 } 18223 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18224 LHS, RHS); 18225 } 18226 18227 // -- If e has the form (e1)... 18228 case Expr::ParenExprClass: { 18229 auto *PE = cast<ParenExpr>(E); 18230 ExprResult Sub = Rebuild(PE->getSubExpr()); 18231 if (!Sub.isUsable()) 18232 return Sub; 18233 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18234 } 18235 18236 // -- If e is a glvalue conditional expression, ... 18237 // We don't apply this to a binary conditional operator. FIXME: Should we? 18238 case Expr::ConditionalOperatorClass: { 18239 auto *CO = cast<ConditionalOperator>(E); 18240 ExprResult LHS = Rebuild(CO->getLHS()); 18241 if (LHS.isInvalid()) 18242 return ExprError(); 18243 ExprResult RHS = Rebuild(CO->getRHS()); 18244 if (RHS.isInvalid()) 18245 return ExprError(); 18246 if (!LHS.isUsable() && !RHS.isUsable()) 18247 return ExprEmpty(); 18248 if (!LHS.isUsable()) 18249 LHS = CO->getLHS(); 18250 if (!RHS.isUsable()) 18251 RHS = CO->getRHS(); 18252 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18253 CO->getCond(), LHS.get(), RHS.get()); 18254 } 18255 18256 // [Clang extension] 18257 // -- If e has the form __extension__ e1... 18258 case Expr::UnaryOperatorClass: { 18259 auto *UO = cast<UnaryOperator>(E); 18260 if (UO->getOpcode() != UO_Extension) 18261 break; 18262 ExprResult Sub = Rebuild(UO->getSubExpr()); 18263 if (!Sub.isUsable()) 18264 return Sub; 18265 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18266 Sub.get()); 18267 } 18268 18269 // [Clang extension] 18270 // -- If e has the form _Generic(...), the set of potential results is the 18271 // union of the sets of potential results of the associated expressions. 18272 case Expr::GenericSelectionExprClass: { 18273 auto *GSE = cast<GenericSelectionExpr>(E); 18274 18275 SmallVector<Expr *, 4> AssocExprs; 18276 bool AnyChanged = false; 18277 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18278 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18279 if (AssocExpr.isInvalid()) 18280 return ExprError(); 18281 if (AssocExpr.isUsable()) { 18282 AssocExprs.push_back(AssocExpr.get()); 18283 AnyChanged = true; 18284 } else { 18285 AssocExprs.push_back(OrigAssocExpr); 18286 } 18287 } 18288 18289 return AnyChanged ? S.CreateGenericSelectionExpr( 18290 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18291 GSE->getRParenLoc(), GSE->getControllingExpr(), 18292 GSE->getAssocTypeSourceInfos(), AssocExprs) 18293 : ExprEmpty(); 18294 } 18295 18296 // [Clang extension] 18297 // -- If e has the form __builtin_choose_expr(...), the set of potential 18298 // results is the union of the sets of potential results of the 18299 // second and third subexpressions. 18300 case Expr::ChooseExprClass: { 18301 auto *CE = cast<ChooseExpr>(E); 18302 18303 ExprResult LHS = Rebuild(CE->getLHS()); 18304 if (LHS.isInvalid()) 18305 return ExprError(); 18306 18307 ExprResult RHS = Rebuild(CE->getLHS()); 18308 if (RHS.isInvalid()) 18309 return ExprError(); 18310 18311 if (!LHS.get() && !RHS.get()) 18312 return ExprEmpty(); 18313 if (!LHS.isUsable()) 18314 LHS = CE->getLHS(); 18315 if (!RHS.isUsable()) 18316 RHS = CE->getRHS(); 18317 18318 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18319 RHS.get(), CE->getRParenLoc()); 18320 } 18321 18322 // Step through non-syntactic nodes. 18323 case Expr::ConstantExprClass: { 18324 auto *CE = cast<ConstantExpr>(E); 18325 ExprResult Sub = Rebuild(CE->getSubExpr()); 18326 if (!Sub.isUsable()) 18327 return Sub; 18328 return ConstantExpr::Create(S.Context, Sub.get()); 18329 } 18330 18331 // We could mostly rely on the recursive rebuilding to rebuild implicit 18332 // casts, but not at the top level, so rebuild them here. 18333 case Expr::ImplicitCastExprClass: { 18334 auto *ICE = cast<ImplicitCastExpr>(E); 18335 // Only step through the narrow set of cast kinds we expect to encounter. 18336 // Anything else suggests we've left the region in which potential results 18337 // can be found. 18338 switch (ICE->getCastKind()) { 18339 case CK_NoOp: 18340 case CK_DerivedToBase: 18341 case CK_UncheckedDerivedToBase: { 18342 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18343 if (!Sub.isUsable()) 18344 return Sub; 18345 CXXCastPath Path(ICE->path()); 18346 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18347 ICE->getValueKind(), &Path); 18348 } 18349 18350 default: 18351 break; 18352 } 18353 break; 18354 } 18355 18356 default: 18357 break; 18358 } 18359 18360 // Can't traverse through this node. Nothing to do. 18361 return ExprEmpty(); 18362 } 18363 18364 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18365 // Check whether the operand is or contains an object of non-trivial C union 18366 // type. 18367 if (E->getType().isVolatileQualified() && 18368 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18369 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18370 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18371 Sema::NTCUC_LValueToRValueVolatile, 18372 NTCUK_Destruct|NTCUK_Copy); 18373 18374 // C++2a [basic.def.odr]p4: 18375 // [...] an expression of non-volatile-qualified non-class type to which 18376 // the lvalue-to-rvalue conversion is applied [...] 18377 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18378 return E; 18379 18380 ExprResult Result = 18381 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18382 if (Result.isInvalid()) 18383 return ExprError(); 18384 return Result.get() ? Result : E; 18385 } 18386 18387 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18388 Res = CorrectDelayedTyposInExpr(Res); 18389 18390 if (!Res.isUsable()) 18391 return Res; 18392 18393 // If a constant-expression is a reference to a variable where we delay 18394 // deciding whether it is an odr-use, just assume we will apply the 18395 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18396 // (a non-type template argument), we have special handling anyway. 18397 return CheckLValueToRValueConversionOperand(Res.get()); 18398 } 18399 18400 void Sema::CleanupVarDeclMarking() { 18401 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18402 // call. 18403 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18404 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18405 18406 for (Expr *E : LocalMaybeODRUseExprs) { 18407 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18408 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18409 DRE->getLocation(), *this); 18410 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18411 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18412 *this); 18413 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18414 for (VarDecl *VD : *FP) 18415 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18416 } else { 18417 llvm_unreachable("Unexpected expression"); 18418 } 18419 } 18420 18421 assert(MaybeODRUseExprs.empty() && 18422 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18423 } 18424 18425 static void DoMarkVarDeclReferenced( 18426 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18427 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18428 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18429 isa<FunctionParmPackExpr>(E)) && 18430 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18431 Var->setReferenced(); 18432 18433 if (Var->isInvalidDecl()) 18434 return; 18435 18436 auto *MSI = Var->getMemberSpecializationInfo(); 18437 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18438 : Var->getTemplateSpecializationKind(); 18439 18440 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18441 bool UsableInConstantExpr = 18442 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18443 18444 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18445 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18446 } 18447 18448 // C++20 [expr.const]p12: 18449 // A variable [...] is needed for constant evaluation if it is [...] a 18450 // variable whose name appears as a potentially constant evaluated 18451 // expression that is either a contexpr variable or is of non-volatile 18452 // const-qualified integral type or of reference type 18453 bool NeededForConstantEvaluation = 18454 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18455 18456 bool NeedDefinition = 18457 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18458 18459 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18460 "Can't instantiate a partial template specialization."); 18461 18462 // If this might be a member specialization of a static data member, check 18463 // the specialization is visible. We already did the checks for variable 18464 // template specializations when we created them. 18465 if (NeedDefinition && TSK != TSK_Undeclared && 18466 !isa<VarTemplateSpecializationDecl>(Var)) 18467 SemaRef.checkSpecializationVisibility(Loc, Var); 18468 18469 // Perform implicit instantiation of static data members, static data member 18470 // templates of class templates, and variable template specializations. Delay 18471 // instantiations of variable templates, except for those that could be used 18472 // in a constant expression. 18473 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18474 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18475 // instantiation declaration if a variable is usable in a constant 18476 // expression (among other cases). 18477 bool TryInstantiating = 18478 TSK == TSK_ImplicitInstantiation || 18479 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18480 18481 if (TryInstantiating) { 18482 SourceLocation PointOfInstantiation = 18483 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18484 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18485 if (FirstInstantiation) { 18486 PointOfInstantiation = Loc; 18487 if (MSI) 18488 MSI->setPointOfInstantiation(PointOfInstantiation); 18489 // FIXME: Notify listener. 18490 else 18491 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18492 } 18493 18494 if (UsableInConstantExpr) { 18495 // Do not defer instantiations of variables that could be used in a 18496 // constant expression. 18497 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18498 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18499 }); 18500 18501 // Re-set the member to trigger a recomputation of the dependence bits 18502 // for the expression. 18503 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18504 DRE->setDecl(DRE->getDecl()); 18505 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18506 ME->setMemberDecl(ME->getMemberDecl()); 18507 } else if (FirstInstantiation || 18508 isa<VarTemplateSpecializationDecl>(Var)) { 18509 // FIXME: For a specialization of a variable template, we don't 18510 // distinguish between "declaration and type implicitly instantiated" 18511 // and "implicit instantiation of definition requested", so we have 18512 // no direct way to avoid enqueueing the pending instantiation 18513 // multiple times. 18514 SemaRef.PendingInstantiations 18515 .push_back(std::make_pair(Var, PointOfInstantiation)); 18516 } 18517 } 18518 } 18519 18520 // C++2a [basic.def.odr]p4: 18521 // A variable x whose name appears as a potentially-evaluated expression e 18522 // is odr-used by e unless 18523 // -- x is a reference that is usable in constant expressions 18524 // -- x is a variable of non-reference type that is usable in constant 18525 // expressions and has no mutable subobjects [FIXME], and e is an 18526 // element of the set of potential results of an expression of 18527 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18528 // conversion is applied 18529 // -- x is a variable of non-reference type, and e is an element of the set 18530 // of potential results of a discarded-value expression to which the 18531 // lvalue-to-rvalue conversion is not applied [FIXME] 18532 // 18533 // We check the first part of the second bullet here, and 18534 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18535 // FIXME: To get the third bullet right, we need to delay this even for 18536 // variables that are not usable in constant expressions. 18537 18538 // If we already know this isn't an odr-use, there's nothing more to do. 18539 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18540 if (DRE->isNonOdrUse()) 18541 return; 18542 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18543 if (ME->isNonOdrUse()) 18544 return; 18545 18546 switch (OdrUse) { 18547 case OdrUseContext::None: 18548 assert((!E || isa<FunctionParmPackExpr>(E)) && 18549 "missing non-odr-use marking for unevaluated decl ref"); 18550 break; 18551 18552 case OdrUseContext::FormallyOdrUsed: 18553 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18554 // behavior. 18555 break; 18556 18557 case OdrUseContext::Used: 18558 // If we might later find that this expression isn't actually an odr-use, 18559 // delay the marking. 18560 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18561 SemaRef.MaybeODRUseExprs.insert(E); 18562 else 18563 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18564 break; 18565 18566 case OdrUseContext::Dependent: 18567 // If this is a dependent context, we don't need to mark variables as 18568 // odr-used, but we may still need to track them for lambda capture. 18569 // FIXME: Do we also need to do this inside dependent typeid expressions 18570 // (which are modeled as unevaluated at this point)? 18571 const bool RefersToEnclosingScope = 18572 (SemaRef.CurContext != Var->getDeclContext() && 18573 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18574 if (RefersToEnclosingScope) { 18575 LambdaScopeInfo *const LSI = 18576 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18577 if (LSI && (!LSI->CallOperator || 18578 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18579 // If a variable could potentially be odr-used, defer marking it so 18580 // until we finish analyzing the full expression for any 18581 // lvalue-to-rvalue 18582 // or discarded value conversions that would obviate odr-use. 18583 // Add it to the list of potential captures that will be analyzed 18584 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18585 // unless the variable is a reference that was initialized by a constant 18586 // expression (this will never need to be captured or odr-used). 18587 // 18588 // FIXME: We can simplify this a lot after implementing P0588R1. 18589 assert(E && "Capture variable should be used in an expression."); 18590 if (!Var->getType()->isReferenceType() || 18591 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18592 LSI->addPotentialCapture(E->IgnoreParens()); 18593 } 18594 } 18595 break; 18596 } 18597 } 18598 18599 /// Mark a variable referenced, and check whether it is odr-used 18600 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18601 /// used directly for normal expressions referring to VarDecl. 18602 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18603 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18604 } 18605 18606 static void 18607 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18608 bool MightBeOdrUse, 18609 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18610 if (SemaRef.isInOpenMPDeclareTargetContext()) 18611 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18612 18613 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18614 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18615 return; 18616 } 18617 18618 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18619 18620 // If this is a call to a method via a cast, also mark the method in the 18621 // derived class used in case codegen can devirtualize the call. 18622 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18623 if (!ME) 18624 return; 18625 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18626 if (!MD) 18627 return; 18628 // Only attempt to devirtualize if this is truly a virtual call. 18629 bool IsVirtualCall = MD->isVirtual() && 18630 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18631 if (!IsVirtualCall) 18632 return; 18633 18634 // If it's possible to devirtualize the call, mark the called function 18635 // referenced. 18636 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18637 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18638 if (DM) 18639 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18640 } 18641 18642 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18643 /// 18644 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18645 /// handled with care if the DeclRefExpr is not newly-created. 18646 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18647 // TODO: update this with DR# once a defect report is filed. 18648 // C++11 defect. The address of a pure member should not be an ODR use, even 18649 // if it's a qualified reference. 18650 bool OdrUse = true; 18651 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18652 if (Method->isVirtual() && 18653 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18654 OdrUse = false; 18655 18656 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18657 if (!isConstantEvaluated() && FD->isConsteval() && 18658 !RebuildingImmediateInvocation) 18659 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18660 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18661 RefsMinusAssignments); 18662 } 18663 18664 /// Perform reference-marking and odr-use handling for a MemberExpr. 18665 void Sema::MarkMemberReferenced(MemberExpr *E) { 18666 // C++11 [basic.def.odr]p2: 18667 // A non-overloaded function whose name appears as a potentially-evaluated 18668 // expression or a member of a set of candidate functions, if selected by 18669 // overload resolution when referred to from a potentially-evaluated 18670 // expression, is odr-used, unless it is a pure virtual function and its 18671 // name is not explicitly qualified. 18672 bool MightBeOdrUse = true; 18673 if (E->performsVirtualDispatch(getLangOpts())) { 18674 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18675 if (Method->isPure()) 18676 MightBeOdrUse = false; 18677 } 18678 SourceLocation Loc = 18679 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18680 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18681 RefsMinusAssignments); 18682 } 18683 18684 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18685 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18686 for (VarDecl *VD : *E) 18687 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18688 RefsMinusAssignments); 18689 } 18690 18691 /// Perform marking for a reference to an arbitrary declaration. It 18692 /// marks the declaration referenced, and performs odr-use checking for 18693 /// functions and variables. This method should not be used when building a 18694 /// normal expression which refers to a variable. 18695 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18696 bool MightBeOdrUse) { 18697 if (MightBeOdrUse) { 18698 if (auto *VD = dyn_cast<VarDecl>(D)) { 18699 MarkVariableReferenced(Loc, VD); 18700 return; 18701 } 18702 } 18703 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18704 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18705 return; 18706 } 18707 D->setReferenced(); 18708 } 18709 18710 namespace { 18711 // Mark all of the declarations used by a type as referenced. 18712 // FIXME: Not fully implemented yet! We need to have a better understanding 18713 // of when we're entering a context we should not recurse into. 18714 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18715 // TreeTransforms rebuilding the type in a new context. Rather than 18716 // duplicating the TreeTransform logic, we should consider reusing it here. 18717 // Currently that causes problems when rebuilding LambdaExprs. 18718 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18719 Sema &S; 18720 SourceLocation Loc; 18721 18722 public: 18723 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18724 18725 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18726 18727 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18728 }; 18729 } 18730 18731 bool MarkReferencedDecls::TraverseTemplateArgument( 18732 const TemplateArgument &Arg) { 18733 { 18734 // A non-type template argument is a constant-evaluated context. 18735 EnterExpressionEvaluationContext Evaluated( 18736 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18737 if (Arg.getKind() == TemplateArgument::Declaration) { 18738 if (Decl *D = Arg.getAsDecl()) 18739 S.MarkAnyDeclReferenced(Loc, D, true); 18740 } else if (Arg.getKind() == TemplateArgument::Expression) { 18741 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18742 } 18743 } 18744 18745 return Inherited::TraverseTemplateArgument(Arg); 18746 } 18747 18748 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18749 MarkReferencedDecls Marker(*this, Loc); 18750 Marker.TraverseType(T); 18751 } 18752 18753 namespace { 18754 /// Helper class that marks all of the declarations referenced by 18755 /// potentially-evaluated subexpressions as "referenced". 18756 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18757 public: 18758 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18759 bool SkipLocalVariables; 18760 18761 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18762 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18763 18764 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18765 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18766 } 18767 18768 void VisitDeclRefExpr(DeclRefExpr *E) { 18769 // If we were asked not to visit local variables, don't. 18770 if (SkipLocalVariables) { 18771 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18772 if (VD->hasLocalStorage()) 18773 return; 18774 } 18775 18776 // FIXME: This can trigger the instantiation of the initializer of a 18777 // variable, which can cause the expression to become value-dependent 18778 // or error-dependent. Do we need to propagate the new dependence bits? 18779 S.MarkDeclRefReferenced(E); 18780 } 18781 18782 void VisitMemberExpr(MemberExpr *E) { 18783 S.MarkMemberReferenced(E); 18784 Visit(E->getBase()); 18785 } 18786 }; 18787 } // namespace 18788 18789 /// Mark any declarations that appear within this expression or any 18790 /// potentially-evaluated subexpressions as "referenced". 18791 /// 18792 /// \param SkipLocalVariables If true, don't mark local variables as 18793 /// 'referenced'. 18794 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18795 bool SkipLocalVariables) { 18796 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18797 } 18798 18799 /// Emit a diagnostic that describes an effect on the run-time behavior 18800 /// of the program being compiled. 18801 /// 18802 /// This routine emits the given diagnostic when the code currently being 18803 /// type-checked is "potentially evaluated", meaning that there is a 18804 /// possibility that the code will actually be executable. Code in sizeof() 18805 /// expressions, code used only during overload resolution, etc., are not 18806 /// potentially evaluated. This routine will suppress such diagnostics or, 18807 /// in the absolutely nutty case of potentially potentially evaluated 18808 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18809 /// later. 18810 /// 18811 /// This routine should be used for all diagnostics that describe the run-time 18812 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18813 /// Failure to do so will likely result in spurious diagnostics or failures 18814 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18815 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18816 const PartialDiagnostic &PD) { 18817 switch (ExprEvalContexts.back().Context) { 18818 case ExpressionEvaluationContext::Unevaluated: 18819 case ExpressionEvaluationContext::UnevaluatedList: 18820 case ExpressionEvaluationContext::UnevaluatedAbstract: 18821 case ExpressionEvaluationContext::DiscardedStatement: 18822 // The argument will never be evaluated, so don't complain. 18823 break; 18824 18825 case ExpressionEvaluationContext::ConstantEvaluated: 18826 // Relevant diagnostics should be produced by constant evaluation. 18827 break; 18828 18829 case ExpressionEvaluationContext::PotentiallyEvaluated: 18830 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18831 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18832 FunctionScopes.back()->PossiblyUnreachableDiags. 18833 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18834 return true; 18835 } 18836 18837 // The initializer of a constexpr variable or of the first declaration of a 18838 // static data member is not syntactically a constant evaluated constant, 18839 // but nonetheless is always required to be a constant expression, so we 18840 // can skip diagnosing. 18841 // FIXME: Using the mangling context here is a hack. 18842 if (auto *VD = dyn_cast_or_null<VarDecl>( 18843 ExprEvalContexts.back().ManglingContextDecl)) { 18844 if (VD->isConstexpr() || 18845 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18846 break; 18847 // FIXME: For any other kind of variable, we should build a CFG for its 18848 // initializer and check whether the context in question is reachable. 18849 } 18850 18851 Diag(Loc, PD); 18852 return true; 18853 } 18854 18855 return false; 18856 } 18857 18858 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18859 const PartialDiagnostic &PD) { 18860 return DiagRuntimeBehavior( 18861 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18862 } 18863 18864 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18865 CallExpr *CE, FunctionDecl *FD) { 18866 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18867 return false; 18868 18869 // If we're inside a decltype's expression, don't check for a valid return 18870 // type or construct temporaries until we know whether this is the last call. 18871 if (ExprEvalContexts.back().ExprContext == 18872 ExpressionEvaluationContextRecord::EK_Decltype) { 18873 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18874 return false; 18875 } 18876 18877 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18878 FunctionDecl *FD; 18879 CallExpr *CE; 18880 18881 public: 18882 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18883 : FD(FD), CE(CE) { } 18884 18885 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18886 if (!FD) { 18887 S.Diag(Loc, diag::err_call_incomplete_return) 18888 << T << CE->getSourceRange(); 18889 return; 18890 } 18891 18892 S.Diag(Loc, diag::err_call_function_incomplete_return) 18893 << CE->getSourceRange() << FD << T; 18894 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18895 << FD->getDeclName(); 18896 } 18897 } Diagnoser(FD, CE); 18898 18899 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18900 return true; 18901 18902 return false; 18903 } 18904 18905 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18906 // will prevent this condition from triggering, which is what we want. 18907 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18908 SourceLocation Loc; 18909 18910 unsigned diagnostic = diag::warn_condition_is_assignment; 18911 bool IsOrAssign = false; 18912 18913 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18914 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18915 return; 18916 18917 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18918 18919 // Greylist some idioms by putting them into a warning subcategory. 18920 if (ObjCMessageExpr *ME 18921 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18922 Selector Sel = ME->getSelector(); 18923 18924 // self = [<foo> init...] 18925 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18926 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18927 18928 // <foo> = [<bar> nextObject] 18929 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18930 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18931 } 18932 18933 Loc = Op->getOperatorLoc(); 18934 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18935 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18936 return; 18937 18938 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18939 Loc = Op->getOperatorLoc(); 18940 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18941 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18942 else { 18943 // Not an assignment. 18944 return; 18945 } 18946 18947 Diag(Loc, diagnostic) << E->getSourceRange(); 18948 18949 SourceLocation Open = E->getBeginLoc(); 18950 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18951 Diag(Loc, diag::note_condition_assign_silence) 18952 << FixItHint::CreateInsertion(Open, "(") 18953 << FixItHint::CreateInsertion(Close, ")"); 18954 18955 if (IsOrAssign) 18956 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18957 << FixItHint::CreateReplacement(Loc, "!="); 18958 else 18959 Diag(Loc, diag::note_condition_assign_to_comparison) 18960 << FixItHint::CreateReplacement(Loc, "=="); 18961 } 18962 18963 /// Redundant parentheses over an equality comparison can indicate 18964 /// that the user intended an assignment used as condition. 18965 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18966 // Don't warn if the parens came from a macro. 18967 SourceLocation parenLoc = ParenE->getBeginLoc(); 18968 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18969 return; 18970 // Don't warn for dependent expressions. 18971 if (ParenE->isTypeDependent()) 18972 return; 18973 18974 Expr *E = ParenE->IgnoreParens(); 18975 18976 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18977 if (opE->getOpcode() == BO_EQ && 18978 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18979 == Expr::MLV_Valid) { 18980 SourceLocation Loc = opE->getOperatorLoc(); 18981 18982 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18983 SourceRange ParenERange = ParenE->getSourceRange(); 18984 Diag(Loc, diag::note_equality_comparison_silence) 18985 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18986 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18987 Diag(Loc, diag::note_equality_comparison_to_assign) 18988 << FixItHint::CreateReplacement(Loc, "="); 18989 } 18990 } 18991 18992 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18993 bool IsConstexpr) { 18994 DiagnoseAssignmentAsCondition(E); 18995 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18996 DiagnoseEqualityWithExtraParens(parenE); 18997 18998 ExprResult result = CheckPlaceholderExpr(E); 18999 if (result.isInvalid()) return ExprError(); 19000 E = result.get(); 19001 19002 if (!E->isTypeDependent()) { 19003 if (getLangOpts().CPlusPlus) 19004 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19005 19006 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19007 if (ERes.isInvalid()) 19008 return ExprError(); 19009 E = ERes.get(); 19010 19011 QualType T = E->getType(); 19012 if (!T->isScalarType()) { // C99 6.8.4.1p1 19013 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19014 << T << E->getSourceRange(); 19015 return ExprError(); 19016 } 19017 CheckBoolLikeConversion(E, Loc); 19018 } 19019 19020 return E; 19021 } 19022 19023 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19024 Expr *SubExpr, ConditionKind CK) { 19025 // Empty conditions are valid in for-statements. 19026 if (!SubExpr) 19027 return ConditionResult(); 19028 19029 ExprResult Cond; 19030 switch (CK) { 19031 case ConditionKind::Boolean: 19032 Cond = CheckBooleanCondition(Loc, SubExpr); 19033 break; 19034 19035 case ConditionKind::ConstexprIf: 19036 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19037 break; 19038 19039 case ConditionKind::Switch: 19040 Cond = CheckSwitchCondition(Loc, SubExpr); 19041 break; 19042 } 19043 if (Cond.isInvalid()) { 19044 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19045 {SubExpr}); 19046 if (!Cond.get()) 19047 return ConditionError(); 19048 } 19049 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19050 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19051 if (!FullExpr.get()) 19052 return ConditionError(); 19053 19054 return ConditionResult(*this, nullptr, FullExpr, 19055 CK == ConditionKind::ConstexprIf); 19056 } 19057 19058 namespace { 19059 /// A visitor for rebuilding a call to an __unknown_any expression 19060 /// to have an appropriate type. 19061 struct RebuildUnknownAnyFunction 19062 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19063 19064 Sema &S; 19065 19066 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19067 19068 ExprResult VisitStmt(Stmt *S) { 19069 llvm_unreachable("unexpected statement!"); 19070 } 19071 19072 ExprResult VisitExpr(Expr *E) { 19073 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19074 << E->getSourceRange(); 19075 return ExprError(); 19076 } 19077 19078 /// Rebuild an expression which simply semantically wraps another 19079 /// expression which it shares the type and value kind of. 19080 template <class T> ExprResult rebuildSugarExpr(T *E) { 19081 ExprResult SubResult = Visit(E->getSubExpr()); 19082 if (SubResult.isInvalid()) return ExprError(); 19083 19084 Expr *SubExpr = SubResult.get(); 19085 E->setSubExpr(SubExpr); 19086 E->setType(SubExpr->getType()); 19087 E->setValueKind(SubExpr->getValueKind()); 19088 assert(E->getObjectKind() == OK_Ordinary); 19089 return E; 19090 } 19091 19092 ExprResult VisitParenExpr(ParenExpr *E) { 19093 return rebuildSugarExpr(E); 19094 } 19095 19096 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19097 return rebuildSugarExpr(E); 19098 } 19099 19100 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19101 ExprResult SubResult = Visit(E->getSubExpr()); 19102 if (SubResult.isInvalid()) return ExprError(); 19103 19104 Expr *SubExpr = SubResult.get(); 19105 E->setSubExpr(SubExpr); 19106 E->setType(S.Context.getPointerType(SubExpr->getType())); 19107 assert(E->getValueKind() == VK_PRValue); 19108 assert(E->getObjectKind() == OK_Ordinary); 19109 return E; 19110 } 19111 19112 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19113 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19114 19115 E->setType(VD->getType()); 19116 19117 assert(E->getValueKind() == VK_PRValue); 19118 if (S.getLangOpts().CPlusPlus && 19119 !(isa<CXXMethodDecl>(VD) && 19120 cast<CXXMethodDecl>(VD)->isInstance())) 19121 E->setValueKind(VK_LValue); 19122 19123 return E; 19124 } 19125 19126 ExprResult VisitMemberExpr(MemberExpr *E) { 19127 return resolveDecl(E, E->getMemberDecl()); 19128 } 19129 19130 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19131 return resolveDecl(E, E->getDecl()); 19132 } 19133 }; 19134 } 19135 19136 /// Given a function expression of unknown-any type, try to rebuild it 19137 /// to have a function type. 19138 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19139 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19140 if (Result.isInvalid()) return ExprError(); 19141 return S.DefaultFunctionArrayConversion(Result.get()); 19142 } 19143 19144 namespace { 19145 /// A visitor for rebuilding an expression of type __unknown_anytype 19146 /// into one which resolves the type directly on the referring 19147 /// expression. Strict preservation of the original source 19148 /// structure is not a goal. 19149 struct RebuildUnknownAnyExpr 19150 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19151 19152 Sema &S; 19153 19154 /// The current destination type. 19155 QualType DestType; 19156 19157 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19158 : S(S), DestType(CastType) {} 19159 19160 ExprResult VisitStmt(Stmt *S) { 19161 llvm_unreachable("unexpected statement!"); 19162 } 19163 19164 ExprResult VisitExpr(Expr *E) { 19165 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19166 << E->getSourceRange(); 19167 return ExprError(); 19168 } 19169 19170 ExprResult VisitCallExpr(CallExpr *E); 19171 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19172 19173 /// Rebuild an expression which simply semantically wraps another 19174 /// expression which it shares the type and value kind of. 19175 template <class T> ExprResult rebuildSugarExpr(T *E) { 19176 ExprResult SubResult = Visit(E->getSubExpr()); 19177 if (SubResult.isInvalid()) return ExprError(); 19178 Expr *SubExpr = SubResult.get(); 19179 E->setSubExpr(SubExpr); 19180 E->setType(SubExpr->getType()); 19181 E->setValueKind(SubExpr->getValueKind()); 19182 assert(E->getObjectKind() == OK_Ordinary); 19183 return E; 19184 } 19185 19186 ExprResult VisitParenExpr(ParenExpr *E) { 19187 return rebuildSugarExpr(E); 19188 } 19189 19190 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19191 return rebuildSugarExpr(E); 19192 } 19193 19194 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19195 const PointerType *Ptr = DestType->getAs<PointerType>(); 19196 if (!Ptr) { 19197 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19198 << E->getSourceRange(); 19199 return ExprError(); 19200 } 19201 19202 if (isa<CallExpr>(E->getSubExpr())) { 19203 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19204 << E->getSourceRange(); 19205 return ExprError(); 19206 } 19207 19208 assert(E->getValueKind() == VK_PRValue); 19209 assert(E->getObjectKind() == OK_Ordinary); 19210 E->setType(DestType); 19211 19212 // Build the sub-expression as if it were an object of the pointee type. 19213 DestType = Ptr->getPointeeType(); 19214 ExprResult SubResult = Visit(E->getSubExpr()); 19215 if (SubResult.isInvalid()) return ExprError(); 19216 E->setSubExpr(SubResult.get()); 19217 return E; 19218 } 19219 19220 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19221 19222 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19223 19224 ExprResult VisitMemberExpr(MemberExpr *E) { 19225 return resolveDecl(E, E->getMemberDecl()); 19226 } 19227 19228 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19229 return resolveDecl(E, E->getDecl()); 19230 } 19231 }; 19232 } 19233 19234 /// Rebuilds a call expression which yielded __unknown_anytype. 19235 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19236 Expr *CalleeExpr = E->getCallee(); 19237 19238 enum FnKind { 19239 FK_MemberFunction, 19240 FK_FunctionPointer, 19241 FK_BlockPointer 19242 }; 19243 19244 FnKind Kind; 19245 QualType CalleeType = CalleeExpr->getType(); 19246 if (CalleeType == S.Context.BoundMemberTy) { 19247 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19248 Kind = FK_MemberFunction; 19249 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19250 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19251 CalleeType = Ptr->getPointeeType(); 19252 Kind = FK_FunctionPointer; 19253 } else { 19254 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19255 Kind = FK_BlockPointer; 19256 } 19257 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19258 19259 // Verify that this is a legal result type of a function. 19260 if (DestType->isArrayType() || DestType->isFunctionType()) { 19261 unsigned diagID = diag::err_func_returning_array_function; 19262 if (Kind == FK_BlockPointer) 19263 diagID = diag::err_block_returning_array_function; 19264 19265 S.Diag(E->getExprLoc(), diagID) 19266 << DestType->isFunctionType() << DestType; 19267 return ExprError(); 19268 } 19269 19270 // Otherwise, go ahead and set DestType as the call's result. 19271 E->setType(DestType.getNonLValueExprType(S.Context)); 19272 E->setValueKind(Expr::getValueKindForType(DestType)); 19273 assert(E->getObjectKind() == OK_Ordinary); 19274 19275 // Rebuild the function type, replacing the result type with DestType. 19276 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19277 if (Proto) { 19278 // __unknown_anytype(...) is a special case used by the debugger when 19279 // it has no idea what a function's signature is. 19280 // 19281 // We want to build this call essentially under the K&R 19282 // unprototyped rules, but making a FunctionNoProtoType in C++ 19283 // would foul up all sorts of assumptions. However, we cannot 19284 // simply pass all arguments as variadic arguments, nor can we 19285 // portably just call the function under a non-variadic type; see 19286 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19287 // However, it turns out that in practice it is generally safe to 19288 // call a function declared as "A foo(B,C,D);" under the prototype 19289 // "A foo(B,C,D,...);". The only known exception is with the 19290 // Windows ABI, where any variadic function is implicitly cdecl 19291 // regardless of its normal CC. Therefore we change the parameter 19292 // types to match the types of the arguments. 19293 // 19294 // This is a hack, but it is far superior to moving the 19295 // corresponding target-specific code from IR-gen to Sema/AST. 19296 19297 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19298 SmallVector<QualType, 8> ArgTypes; 19299 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19300 ArgTypes.reserve(E->getNumArgs()); 19301 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19302 Expr *Arg = E->getArg(i); 19303 QualType ArgType = Arg->getType(); 19304 if (E->isLValue()) { 19305 ArgType = S.Context.getLValueReferenceType(ArgType); 19306 } else if (E->isXValue()) { 19307 ArgType = S.Context.getRValueReferenceType(ArgType); 19308 } 19309 ArgTypes.push_back(ArgType); 19310 } 19311 ParamTypes = ArgTypes; 19312 } 19313 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19314 Proto->getExtProtoInfo()); 19315 } else { 19316 DestType = S.Context.getFunctionNoProtoType(DestType, 19317 FnType->getExtInfo()); 19318 } 19319 19320 // Rebuild the appropriate pointer-to-function type. 19321 switch (Kind) { 19322 case FK_MemberFunction: 19323 // Nothing to do. 19324 break; 19325 19326 case FK_FunctionPointer: 19327 DestType = S.Context.getPointerType(DestType); 19328 break; 19329 19330 case FK_BlockPointer: 19331 DestType = S.Context.getBlockPointerType(DestType); 19332 break; 19333 } 19334 19335 // Finally, we can recurse. 19336 ExprResult CalleeResult = Visit(CalleeExpr); 19337 if (!CalleeResult.isUsable()) return ExprError(); 19338 E->setCallee(CalleeResult.get()); 19339 19340 // Bind a temporary if necessary. 19341 return S.MaybeBindToTemporary(E); 19342 } 19343 19344 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19345 // Verify that this is a legal result type of a call. 19346 if (DestType->isArrayType() || DestType->isFunctionType()) { 19347 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19348 << DestType->isFunctionType() << DestType; 19349 return ExprError(); 19350 } 19351 19352 // Rewrite the method result type if available. 19353 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19354 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19355 Method->setReturnType(DestType); 19356 } 19357 19358 // Change the type of the message. 19359 E->setType(DestType.getNonReferenceType()); 19360 E->setValueKind(Expr::getValueKindForType(DestType)); 19361 19362 return S.MaybeBindToTemporary(E); 19363 } 19364 19365 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19366 // The only case we should ever see here is a function-to-pointer decay. 19367 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19368 assert(E->getValueKind() == VK_PRValue); 19369 assert(E->getObjectKind() == OK_Ordinary); 19370 19371 E->setType(DestType); 19372 19373 // Rebuild the sub-expression as the pointee (function) type. 19374 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19375 19376 ExprResult Result = Visit(E->getSubExpr()); 19377 if (!Result.isUsable()) return ExprError(); 19378 19379 E->setSubExpr(Result.get()); 19380 return E; 19381 } else if (E->getCastKind() == CK_LValueToRValue) { 19382 assert(E->getValueKind() == VK_PRValue); 19383 assert(E->getObjectKind() == OK_Ordinary); 19384 19385 assert(isa<BlockPointerType>(E->getType())); 19386 19387 E->setType(DestType); 19388 19389 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19390 DestType = S.Context.getLValueReferenceType(DestType); 19391 19392 ExprResult Result = Visit(E->getSubExpr()); 19393 if (!Result.isUsable()) return ExprError(); 19394 19395 E->setSubExpr(Result.get()); 19396 return E; 19397 } else { 19398 llvm_unreachable("Unhandled cast type!"); 19399 } 19400 } 19401 19402 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19403 ExprValueKind ValueKind = VK_LValue; 19404 QualType Type = DestType; 19405 19406 // We know how to make this work for certain kinds of decls: 19407 19408 // - functions 19409 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19410 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19411 DestType = Ptr->getPointeeType(); 19412 ExprResult Result = resolveDecl(E, VD); 19413 if (Result.isInvalid()) return ExprError(); 19414 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19415 VK_PRValue); 19416 } 19417 19418 if (!Type->isFunctionType()) { 19419 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19420 << VD << E->getSourceRange(); 19421 return ExprError(); 19422 } 19423 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19424 // We must match the FunctionDecl's type to the hack introduced in 19425 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19426 // type. See the lengthy commentary in that routine. 19427 QualType FDT = FD->getType(); 19428 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19429 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19430 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19431 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19432 SourceLocation Loc = FD->getLocation(); 19433 FunctionDecl *NewFD = FunctionDecl::Create( 19434 S.Context, FD->getDeclContext(), Loc, Loc, 19435 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19436 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19437 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19438 19439 if (FD->getQualifier()) 19440 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19441 19442 SmallVector<ParmVarDecl*, 16> Params; 19443 for (const auto &AI : FT->param_types()) { 19444 ParmVarDecl *Param = 19445 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19446 Param->setScopeInfo(0, Params.size()); 19447 Params.push_back(Param); 19448 } 19449 NewFD->setParams(Params); 19450 DRE->setDecl(NewFD); 19451 VD = DRE->getDecl(); 19452 } 19453 } 19454 19455 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19456 if (MD->isInstance()) { 19457 ValueKind = VK_PRValue; 19458 Type = S.Context.BoundMemberTy; 19459 } 19460 19461 // Function references aren't l-values in C. 19462 if (!S.getLangOpts().CPlusPlus) 19463 ValueKind = VK_PRValue; 19464 19465 // - variables 19466 } else if (isa<VarDecl>(VD)) { 19467 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19468 Type = RefTy->getPointeeType(); 19469 } else if (Type->isFunctionType()) { 19470 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19471 << VD << E->getSourceRange(); 19472 return ExprError(); 19473 } 19474 19475 // - nothing else 19476 } else { 19477 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19478 << VD << E->getSourceRange(); 19479 return ExprError(); 19480 } 19481 19482 // Modifying the declaration like this is friendly to IR-gen but 19483 // also really dangerous. 19484 VD->setType(DestType); 19485 E->setType(Type); 19486 E->setValueKind(ValueKind); 19487 return E; 19488 } 19489 19490 /// Check a cast of an unknown-any type. We intentionally only 19491 /// trigger this for C-style casts. 19492 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19493 Expr *CastExpr, CastKind &CastKind, 19494 ExprValueKind &VK, CXXCastPath &Path) { 19495 // The type we're casting to must be either void or complete. 19496 if (!CastType->isVoidType() && 19497 RequireCompleteType(TypeRange.getBegin(), CastType, 19498 diag::err_typecheck_cast_to_incomplete)) 19499 return ExprError(); 19500 19501 // Rewrite the casted expression from scratch. 19502 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19503 if (!result.isUsable()) return ExprError(); 19504 19505 CastExpr = result.get(); 19506 VK = CastExpr->getValueKind(); 19507 CastKind = CK_NoOp; 19508 19509 return CastExpr; 19510 } 19511 19512 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19513 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19514 } 19515 19516 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19517 Expr *arg, QualType ¶mType) { 19518 // If the syntactic form of the argument is not an explicit cast of 19519 // any sort, just do default argument promotion. 19520 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19521 if (!castArg) { 19522 ExprResult result = DefaultArgumentPromotion(arg); 19523 if (result.isInvalid()) return ExprError(); 19524 paramType = result.get()->getType(); 19525 return result; 19526 } 19527 19528 // Otherwise, use the type that was written in the explicit cast. 19529 assert(!arg->hasPlaceholderType()); 19530 paramType = castArg->getTypeAsWritten(); 19531 19532 // Copy-initialize a parameter of that type. 19533 InitializedEntity entity = 19534 InitializedEntity::InitializeParameter(Context, paramType, 19535 /*consumed*/ false); 19536 return PerformCopyInitialization(entity, callLoc, arg); 19537 } 19538 19539 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19540 Expr *orig = E; 19541 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19542 while (true) { 19543 E = E->IgnoreParenImpCasts(); 19544 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19545 E = call->getCallee(); 19546 diagID = diag::err_uncasted_call_of_unknown_any; 19547 } else { 19548 break; 19549 } 19550 } 19551 19552 SourceLocation loc; 19553 NamedDecl *d; 19554 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19555 loc = ref->getLocation(); 19556 d = ref->getDecl(); 19557 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19558 loc = mem->getMemberLoc(); 19559 d = mem->getMemberDecl(); 19560 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19561 diagID = diag::err_uncasted_call_of_unknown_any; 19562 loc = msg->getSelectorStartLoc(); 19563 d = msg->getMethodDecl(); 19564 if (!d) { 19565 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19566 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19567 << orig->getSourceRange(); 19568 return ExprError(); 19569 } 19570 } else { 19571 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19572 << E->getSourceRange(); 19573 return ExprError(); 19574 } 19575 19576 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19577 19578 // Never recoverable. 19579 return ExprError(); 19580 } 19581 19582 /// Check for operands with placeholder types and complain if found. 19583 /// Returns ExprError() if there was an error and no recovery was possible. 19584 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19585 if (!Context.isDependenceAllowed()) { 19586 // C cannot handle TypoExpr nodes on either side of a binop because it 19587 // doesn't handle dependent types properly, so make sure any TypoExprs have 19588 // been dealt with before checking the operands. 19589 ExprResult Result = CorrectDelayedTyposInExpr(E); 19590 if (!Result.isUsable()) return ExprError(); 19591 E = Result.get(); 19592 } 19593 19594 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19595 if (!placeholderType) return E; 19596 19597 switch (placeholderType->getKind()) { 19598 19599 // Overloaded expressions. 19600 case BuiltinType::Overload: { 19601 // Try to resolve a single function template specialization. 19602 // This is obligatory. 19603 ExprResult Result = E; 19604 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19605 return Result; 19606 19607 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19608 // leaves Result unchanged on failure. 19609 Result = E; 19610 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19611 return Result; 19612 19613 // If that failed, try to recover with a call. 19614 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19615 /*complain*/ true); 19616 return Result; 19617 } 19618 19619 // Bound member functions. 19620 case BuiltinType::BoundMember: { 19621 ExprResult result = E; 19622 const Expr *BME = E->IgnoreParens(); 19623 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19624 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19625 if (isa<CXXPseudoDestructorExpr>(BME)) { 19626 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19627 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19628 if (ME->getMemberNameInfo().getName().getNameKind() == 19629 DeclarationName::CXXDestructorName) 19630 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19631 } 19632 tryToRecoverWithCall(result, PD, 19633 /*complain*/ true); 19634 return result; 19635 } 19636 19637 // ARC unbridged casts. 19638 case BuiltinType::ARCUnbridgedCast: { 19639 Expr *realCast = stripARCUnbridgedCast(E); 19640 diagnoseARCUnbridgedCast(realCast); 19641 return realCast; 19642 } 19643 19644 // Expressions of unknown type. 19645 case BuiltinType::UnknownAny: 19646 return diagnoseUnknownAnyExpr(*this, E); 19647 19648 // Pseudo-objects. 19649 case BuiltinType::PseudoObject: 19650 return checkPseudoObjectRValue(E); 19651 19652 case BuiltinType::BuiltinFn: { 19653 // Accept __noop without parens by implicitly converting it to a call expr. 19654 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19655 if (DRE) { 19656 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19657 if (FD->getBuiltinID() == Builtin::BI__noop) { 19658 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19659 CK_BuiltinFnToFnPtr) 19660 .get(); 19661 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19662 VK_PRValue, SourceLocation(), 19663 FPOptionsOverride()); 19664 } 19665 } 19666 19667 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19668 return ExprError(); 19669 } 19670 19671 case BuiltinType::IncompleteMatrixIdx: 19672 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19673 ->getRowIdx() 19674 ->getBeginLoc(), 19675 diag::err_matrix_incomplete_index); 19676 return ExprError(); 19677 19678 // Expressions of unknown type. 19679 case BuiltinType::OMPArraySection: 19680 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19681 return ExprError(); 19682 19683 // Expressions of unknown type. 19684 case BuiltinType::OMPArrayShaping: 19685 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19686 19687 case BuiltinType::OMPIterator: 19688 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19689 19690 // Everything else should be impossible. 19691 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19692 case BuiltinType::Id: 19693 #include "clang/Basic/OpenCLImageTypes.def" 19694 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19695 case BuiltinType::Id: 19696 #include "clang/Basic/OpenCLExtensionTypes.def" 19697 #define SVE_TYPE(Name, Id, SingletonId) \ 19698 case BuiltinType::Id: 19699 #include "clang/Basic/AArch64SVEACLETypes.def" 19700 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19701 case BuiltinType::Id: 19702 #include "clang/Basic/PPCTypes.def" 19703 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19704 #include "clang/Basic/RISCVVTypes.def" 19705 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19706 #define PLACEHOLDER_TYPE(Id, SingletonId) 19707 #include "clang/AST/BuiltinTypes.def" 19708 break; 19709 } 19710 19711 llvm_unreachable("invalid placeholder type!"); 19712 } 19713 19714 bool Sema::CheckCaseExpression(Expr *E) { 19715 if (E->isTypeDependent()) 19716 return true; 19717 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19718 return E->getType()->isIntegralOrEnumerationType(); 19719 return false; 19720 } 19721 19722 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19723 ExprResult 19724 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19725 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19726 "Unknown Objective-C Boolean value!"); 19727 QualType BoolT = Context.ObjCBuiltinBoolTy; 19728 if (!Context.getBOOLDecl()) { 19729 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19730 Sema::LookupOrdinaryName); 19731 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19732 NamedDecl *ND = Result.getFoundDecl(); 19733 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19734 Context.setBOOLDecl(TD); 19735 } 19736 } 19737 if (Context.getBOOLDecl()) 19738 BoolT = Context.getBOOLType(); 19739 return new (Context) 19740 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19741 } 19742 19743 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19744 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19745 SourceLocation RParen) { 19746 19747 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19748 19749 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19750 return Spec.getPlatform() == Platform; 19751 }); 19752 19753 VersionTuple Version; 19754 if (Spec != AvailSpecs.end()) 19755 Version = Spec->getVersion(); 19756 19757 // The use of `@available` in the enclosing context should be analyzed to 19758 // warn when it's used inappropriately (i.e. not if(@available)). 19759 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19760 Context->HasPotentialAvailabilityViolations = true; 19761 19762 return new (Context) 19763 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19764 } 19765 19766 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19767 ArrayRef<Expr *> SubExprs, QualType T) { 19768 if (!Context.getLangOpts().RecoveryAST) 19769 return ExprError(); 19770 19771 if (isSFINAEContext()) 19772 return ExprError(); 19773 19774 if (T.isNull() || T->isUndeducedType() || 19775 !Context.getLangOpts().RecoveryASTType) 19776 // We don't know the concrete type, fallback to dependent type. 19777 T = Context.DependentTy; 19778 19779 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19780 } 19781