1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 54 using namespace clang; 55 using namespace sema; 56 using llvm::RoundingMode; 57 58 /// Determine whether the use of this declaration is valid, without 59 /// emitting diagnostics. 60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 61 // See if this is an auto-typed variable whose initializer we are parsing. 62 if (ParsingInitForAutoVars.count(D)) 63 return false; 64 65 // See if this is a deleted function. 66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 67 if (FD->isDeleted()) 68 return false; 69 70 // If the function has a deduced return type, and we can't deduce it, 71 // then we can't use it either. 72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 74 return false; 75 76 // See if this is an aligned allocation/deallocation function that is 77 // unavailable. 78 if (TreatUnavailableAsInvalid && 79 isUnavailableAlignedAllocationFunction(*FD)) 80 return false; 81 } 82 83 // See if this function is unavailable. 84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 86 return false; 87 88 if (isa<UnresolvedUsingIfExistsDecl>(D)) 89 return false; 90 91 return true; 92 } 93 94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 95 // Warn if this is used but marked unused. 96 if (const auto *A = D->getAttr<UnusedAttr>()) { 97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 98 // should diagnose them. 99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 102 if (DC && !DC->hasAttr<UnusedAttr>()) 103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 104 } 105 } 106 } 107 108 /// Emit a note explaining that this function is deleted. 109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 110 assert(Decl && Decl->isDeleted()); 111 112 if (Decl->isDefaulted()) { 113 // If the method was explicitly defaulted, point at that declaration. 114 if (!Decl->isImplicit()) 115 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 116 117 // Try to diagnose why this special member function was implicitly 118 // deleted. This might fail, if that reason no longer applies. 119 DiagnoseDeletedDefaultedFunction(Decl); 120 return; 121 } 122 123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 124 if (Ctor && Ctor->isInheritingConstructor()) 125 return NoteDeletedInheritingConstructor(Ctor); 126 127 Diag(Decl->getLocation(), diag::note_availability_specified_here) 128 << Decl << 1; 129 } 130 131 /// Determine whether a FunctionDecl was ever declared with an 132 /// explicit storage class. 133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 134 for (auto I : D->redecls()) { 135 if (I->getStorageClass() != SC_None) 136 return true; 137 } 138 return false; 139 } 140 141 /// Check whether we're in an extern inline function and referring to a 142 /// variable or function with internal linkage (C11 6.7.4p3). 143 /// 144 /// This is only a warning because we used to silently accept this code, but 145 /// in many cases it will not behave correctly. This is not enabled in C++ mode 146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 147 /// and so while there may still be user mistakes, most of the time we can't 148 /// prove that there are errors. 149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 150 const NamedDecl *D, 151 SourceLocation Loc) { 152 // This is disabled under C++; there are too many ways for this to fire in 153 // contexts where the warning is a false positive, or where it is technically 154 // correct but benign. 155 if (S.getLangOpts().CPlusPlus) 156 return; 157 158 // Check if this is an inlined function or method. 159 FunctionDecl *Current = S.getCurFunctionDecl(); 160 if (!Current) 161 return; 162 if (!Current->isInlined()) 163 return; 164 if (!Current->isExternallyVisible()) 165 return; 166 167 // Check if the decl has internal linkage. 168 if (D->getFormalLinkage() != InternalLinkage) 169 return; 170 171 // Downgrade from ExtWarn to Extension if 172 // (1) the supposedly external inline function is in the main file, 173 // and probably won't be included anywhere else. 174 // (2) the thing we're referencing is a pure function. 175 // (3) the thing we're referencing is another inline function. 176 // This last can give us false negatives, but it's better than warning on 177 // wrappers for simple C library functions. 178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 180 if (!DowngradeWarning && UsedFn) 181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 182 183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 184 : diag::ext_internal_in_extern_inline) 185 << /*IsVar=*/!UsedFn << D; 186 187 S.MaybeSuggestAddingStaticToDecl(Current); 188 189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 190 << D; 191 } 192 193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 194 const FunctionDecl *First = Cur->getFirstDecl(); 195 196 // Suggest "static" on the function, if possible. 197 if (!hasAnyExplicitStorageClass(First)) { 198 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 199 Diag(DeclBegin, diag::note_convert_inline_to_static) 200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 201 } 202 } 203 204 /// Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 217 const ObjCInterfaceDecl *UnknownObjCClass, 218 bool ObjCPropertyAccess, 219 bool AvoidPartialAvailabilityChecks, 220 ObjCInterfaceDecl *ClassReceiver) { 221 SourceLocation Loc = Locs.front(); 222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 223 // If there were any diagnostics suppressed by template argument deduction, 224 // emit them now. 225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 226 if (Pos != SuppressedDiagnostics.end()) { 227 for (const PartialDiagnosticAt &Suppressed : Pos->second) 228 Diag(Suppressed.first, Suppressed.second); 229 230 // Clear out the list of suppressed diagnostics, so that we don't emit 231 // them again for this specialization. However, we don't obsolete this 232 // entry from the table, because we want to avoid ever emitting these 233 // diagnostics again. 234 Pos->second.clear(); 235 } 236 237 // C++ [basic.start.main]p3: 238 // The function 'main' shall not be used within a program. 239 if (cast<FunctionDecl>(D)->isMain()) 240 Diag(Loc, diag::ext_main_used); 241 242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 243 } 244 245 // See if this is an auto-typed variable whose initializer we are parsing. 246 if (ParsingInitForAutoVars.count(D)) { 247 if (isa<BindingDecl>(D)) { 248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 249 << D->getDeclName(); 250 } else { 251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 252 << D->getDeclName() << cast<VarDecl>(D)->getType(); 253 } 254 return true; 255 } 256 257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 258 // See if this is a deleted function. 259 if (FD->isDeleted()) { 260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 261 if (Ctor && Ctor->isInheritingConstructor()) 262 Diag(Loc, diag::err_deleted_inherited_ctor_use) 263 << Ctor->getParent() 264 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 265 else 266 Diag(Loc, diag::err_deleted_function_use); 267 NoteDeletedFunction(FD); 268 return true; 269 } 270 271 // [expr.prim.id]p4 272 // A program that refers explicitly or implicitly to a function with a 273 // trailing requires-clause whose constraint-expression is not satisfied, 274 // other than to declare it, is ill-formed. [...] 275 // 276 // See if this is a function with constraints that need to be satisfied. 277 // Check this before deducing the return type, as it might instantiate the 278 // definition. 279 if (FD->getTrailingRequiresClause()) { 280 ConstraintSatisfaction Satisfaction; 281 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 282 // A diagnostic will have already been generated (non-constant 283 // constraint expression, for example) 284 return true; 285 if (!Satisfaction.IsSatisfied) { 286 Diag(Loc, 287 diag::err_reference_to_function_with_unsatisfied_constraints) 288 << D; 289 DiagnoseUnsatisfiedConstraint(Satisfaction); 290 return true; 291 } 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 301 return true; 302 303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 304 return true; 305 } 306 307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 308 // Lambdas are only default-constructible or assignable in C++2a onwards. 309 if (MD->getParent()->isLambda() && 310 ((isa<CXXConstructorDecl>(MD) && 311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 314 << !isa<CXXConstructorDecl>(MD); 315 } 316 } 317 318 auto getReferencedObjCProp = [](const NamedDecl *D) -> 319 const ObjCPropertyDecl * { 320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 321 return MD->findPropertyDecl(); 322 return nullptr; 323 }; 324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 326 return true; 327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 328 return true; 329 } 330 331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 332 // Only the variables omp_in and omp_out are allowed in the combiner. 333 // Only the variables omp_priv and omp_orig are allowed in the 334 // initializer-clause. 335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 337 isa<VarDecl>(D)) { 338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 339 << getCurFunction()->HasOMPDeclareReductionCombiner; 340 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 341 return true; 342 } 343 344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 345 // List-items in map clauses on this construct may only refer to the declared 346 // variable var and entities that could be referenced by a procedure defined 347 // at the same location 348 if (LangOpts.OpenMP && isa<VarDecl>(D) && 349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 351 << getOpenMPDeclareMapperVarName(); 352 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 353 return true; 354 } 355 356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 357 Diag(Loc, diag::err_use_of_empty_using_if_exists); 358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 359 return true; 360 } 361 362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 363 AvoidPartialAvailabilityChecks, ClassReceiver); 364 365 DiagnoseUnusedOfDecl(*this, D, Loc); 366 367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 368 369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkDeviceDecl(VD, Loc); 372 373 if (!Context.getTargetInfo().isTLSSupported()) 374 if (const auto *VD = dyn_cast<VarDecl>(D)) 375 if (VD->getTLSKind() != VarDecl::TLS_None) 376 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 377 } 378 379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 380 !isUnevaluatedContext()) { 381 // C++ [expr.prim.req.nested] p3 382 // A local parameter shall only appear as an unevaluated operand 383 // (Clause 8) within the constraint-expression. 384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 385 << D; 386 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 387 return true; 388 } 389 390 return false; 391 } 392 393 /// DiagnoseSentinelCalls - This routine checks whether a call or 394 /// message-send is to a declaration with the sentinel attribute, and 395 /// if so, it checks that the requirements of the sentinel are 396 /// satisfied. 397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 398 ArrayRef<Expr *> Args) { 399 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 400 if (!attr) 401 return; 402 403 // The number of formal parameters of the declaration. 404 unsigned numFormalParams; 405 406 // The kind of declaration. This is also an index into a %select in 407 // the diagnostic. 408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 409 410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 411 numFormalParams = MD->param_size(); 412 calleeType = CT_Method; 413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 numFormalParams = FD->param_size(); 415 calleeType = CT_Function; 416 } else if (isa<VarDecl>(D)) { 417 QualType type = cast<ValueDecl>(D)->getType(); 418 const FunctionType *fn = nullptr; 419 if (const PointerType *ptr = type->getAs<PointerType>()) { 420 fn = ptr->getPointeeType()->getAs<FunctionType>(); 421 if (!fn) return; 422 calleeType = CT_Function; 423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 424 fn = ptr->getPointeeType()->castAs<FunctionType>(); 425 calleeType = CT_Block; 426 } else { 427 return; 428 } 429 430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 431 numFormalParams = proto->getNumParams(); 432 } else { 433 numFormalParams = 0; 434 } 435 } else { 436 return; 437 } 438 439 // "nullPos" is the number of formal parameters at the end which 440 // effectively count as part of the variadic arguments. This is 441 // useful if you would prefer to not have *any* formal parameters, 442 // but the language forces you to have at least one. 443 unsigned nullPos = attr->getNullPos(); 444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 446 447 // The number of arguments which should follow the sentinel. 448 unsigned numArgsAfterSentinel = attr->getSentinel(); 449 450 // If there aren't enough arguments for all the formal parameters, 451 // the sentinel, and the args after the sentinel, complain. 452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 455 return; 456 } 457 458 // Otherwise, find the sentinel expression. 459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 460 if (!sentinelExpr) return; 461 if (sentinelExpr->isValueDependent()) return; 462 if (Context.isSentinelNullExpr(sentinelExpr)) return; 463 464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 465 // or 'NULL' if those are actually defined in the context. Only use 466 // 'nil' for ObjC methods, where it's much more likely that the 467 // variadic arguments form a list of object pointers. 468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 512 return ExprError(); 513 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 529 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay); 531 if (Res.isInvalid()) 532 return ExprError(); 533 E = Res.get(); 534 } 535 } 536 return E; 537 } 538 539 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 540 // Check to see if we are dereferencing a null pointer. If so, 541 // and if not volatile-qualified, this is undefined behavior that the 542 // optimizer will delete, so warn about it. People sometimes try to use this 543 // to get a deterministic trap and are surprised by clang's behavior. This 544 // only handles the pattern "*null", which is a very syntactic check. 545 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 546 if (UO && UO->getOpcode() == UO_Deref && 547 UO->getSubExpr()->getType()->isPointerType()) { 548 const LangAS AS = 549 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 550 if ((!isTargetAddressSpace(AS) || 551 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 552 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 553 S.Context, Expr::NPC_ValueDependentIsNotNull) && 554 !UO->getType().isVolatileQualified()) { 555 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 556 S.PDiag(diag::warn_indirection_through_null) 557 << UO->getSubExpr()->getSourceRange()); 558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 559 S.PDiag(diag::note_indirection_through_null)); 560 } 561 } 562 } 563 564 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 565 SourceLocation AssignLoc, 566 const Expr* RHS) { 567 const ObjCIvarDecl *IV = OIRE->getDecl(); 568 if (!IV) 569 return; 570 571 DeclarationName MemberName = IV->getDeclName(); 572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 573 if (!Member || !Member->isStr("isa")) 574 return; 575 576 const Expr *Base = OIRE->getBase(); 577 QualType BaseType = Base->getType(); 578 if (OIRE->isArrow()) 579 BaseType = BaseType->getPointeeType(); 580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 582 ObjCInterfaceDecl *ClassDeclared = nullptr; 583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 584 if (!ClassDeclared->getSuperClass() 585 && (*ClassDeclared->ivar_begin()) == IV) { 586 if (RHS) { 587 NamedDecl *ObjectSetClass = 588 S.LookupSingleName(S.TUScope, 589 &S.Context.Idents.get("object_setClass"), 590 SourceLocation(), S.LookupOrdinaryName); 591 if (ObjectSetClass) { 592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_setClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 598 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 599 } 600 else 601 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 602 } else { 603 NamedDecl *ObjectGetClass = 604 S.LookupSingleName(S.TUScope, 605 &S.Context.Idents.get("object_getClass"), 606 SourceLocation(), S.LookupOrdinaryName); 607 if (ObjectGetClass) 608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 609 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 610 "object_getClass(") 611 << FixItHint::CreateReplacement( 612 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 613 else 614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 615 } 616 S.Diag(IV->getLocation(), diag::note_ivar_decl); 617 } 618 } 619 } 620 621 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 622 // Handle any placeholder expressions which made it here. 623 if (E->getType()->isPlaceholderType()) { 624 ExprResult result = CheckPlaceholderExpr(E); 625 if (result.isInvalid()) return ExprError(); 626 E = result.get(); 627 } 628 629 // C++ [conv.lval]p1: 630 // A glvalue of a non-function, non-array type T can be 631 // converted to a prvalue. 632 if (!E->isGLValue()) return E; 633 634 QualType T = E->getType(); 635 assert(!T.isNull() && "r-value conversion on typeless expression?"); 636 637 // lvalue-to-rvalue conversion cannot be applied to function or array types. 638 if (T->isFunctionType() || T->isArrayType()) 639 return E; 640 641 // We don't want to throw lvalue-to-rvalue casts on top of 642 // expressions of certain types in C++. 643 if (getLangOpts().CPlusPlus && 644 (E->getType() == Context.OverloadTy || 645 T->isDependentType() || 646 T->isRecordType())) 647 return E; 648 649 // The C standard is actually really unclear on this point, and 650 // DR106 tells us what the result should be but not why. It's 651 // generally best to say that void types just doesn't undergo 652 // lvalue-to-rvalue at all. Note that expressions of unqualified 653 // 'void' type are never l-values, but qualified void can be. 654 if (T->isVoidType()) 655 return E; 656 657 // OpenCL usually rejects direct accesses to values of 'half' type. 658 if (getLangOpts().OpenCL && 659 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 660 T->isHalfType()) { 661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 662 << 0 << T; 663 return ExprError(); 664 } 665 666 CheckForNullPointerDereference(*this, E); 667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 669 &Context.Idents.get("object_getClass"), 670 SourceLocation(), LookupOrdinaryName); 671 if (ObjectGetClass) 672 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 673 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 674 << FixItHint::CreateReplacement( 675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 676 else 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 678 } 679 else if (const ObjCIvarRefExpr *OIRE = 680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 682 683 // C++ [conv.lval]p1: 684 // [...] If T is a non-class type, the type of the prvalue is the 685 // cv-unqualified version of T. Otherwise, the type of the 686 // rvalue is T. 687 // 688 // C99 6.3.2.1p2: 689 // If the lvalue has qualified type, the value has the unqualified 690 // version of the type of the lvalue; otherwise, the value has the 691 // type of the lvalue. 692 if (T.hasQualifiers()) 693 T = T.getUnqualifiedType(); 694 695 // Under the MS ABI, lock down the inheritance model now. 696 if (T->isMemberPointerType() && 697 Context.getTargetInfo().getCXXABI().isMicrosoft()) 698 (void)isCompleteType(E->getExprLoc(), T); 699 700 ExprResult Res = CheckLValueToRValueConversionOperand(E); 701 if (Res.isInvalid()) 702 return Res; 703 E = Res.get(); 704 705 // Loading a __weak object implicitly retains the value, so we need a cleanup to 706 // balance that. 707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 708 Cleanup.setExprNeedsCleanups(true); 709 710 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 711 Cleanup.setExprNeedsCleanups(true); 712 713 // C++ [conv.lval]p3: 714 // If T is cv std::nullptr_t, the result is a null pointer constant. 715 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 716 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 717 CurFPFeatureOverrides()); 718 719 // C11 6.3.2.1p2: 720 // ... if the lvalue has atomic type, the value has the non-atomic version 721 // of the type of the lvalue ... 722 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 723 T = Atomic->getValueType().getUnqualifiedType(); 724 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 725 nullptr, VK_PRValue, FPOptionsOverride()); 726 } 727 728 return Res; 729 } 730 731 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 732 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 733 if (Res.isInvalid()) 734 return ExprError(); 735 Res = DefaultLvalueConversion(Res.get()); 736 if (Res.isInvalid()) 737 return ExprError(); 738 return Res; 739 } 740 741 /// CallExprUnaryConversions - a special case of an unary conversion 742 /// performed on a function designator of a call expression. 743 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 744 QualType Ty = E->getType(); 745 ExprResult Res = E; 746 // Only do implicit cast for a function type, but not for a pointer 747 // to function type. 748 if (Ty->isFunctionType()) { 749 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 750 CK_FunctionToPointerDecay); 751 if (Res.isInvalid()) 752 return ExprError(); 753 } 754 Res = DefaultLvalueConversion(Res.get()); 755 if (Res.isInvalid()) 756 return ExprError(); 757 return Res.get(); 758 } 759 760 /// UsualUnaryConversions - Performs various conversions that are common to most 761 /// operators (C99 6.3). The conversions of array and function types are 762 /// sometimes suppressed. For example, the array->pointer conversion doesn't 763 /// apply if the array is an argument to the sizeof or address (&) operators. 764 /// In these instances, this routine should *not* be called. 765 ExprResult Sema::UsualUnaryConversions(Expr *E) { 766 // First, convert to an r-value. 767 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 768 if (Res.isInvalid()) 769 return ExprError(); 770 E = Res.get(); 771 772 QualType Ty = E->getType(); 773 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 774 775 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 776 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType()) { 777 switch (EvalMethod) { 778 default: 779 llvm_unreachable("Unrecognized float evaluation method"); 780 break; 781 case LangOptions::FEM_TargetDefault: 782 // Float evaluation method not defined, use FEM_Source. 783 break; 784 case LangOptions::FEM_Double: 785 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 786 // Widen the expression to double. 787 return Ty->isComplexType() 788 ? ImpCastExprToType(E, 789 Context.getComplexType(Context.DoubleTy), 790 CK_FloatingComplexCast) 791 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 792 break; 793 case LangOptions::FEM_Extended: 794 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 795 // Widen the expression to long double. 796 return Ty->isComplexType() 797 ? ImpCastExprToType( 798 E, Context.getComplexType(Context.LongDoubleTy), 799 CK_FloatingComplexCast) 800 : ImpCastExprToType(E, Context.LongDoubleTy, 801 CK_FloatingCast); 802 break; 803 } 804 } 805 806 // Half FP have to be promoted to float unless it is natively supported 807 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 808 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 809 810 // Try to perform integral promotions if the object has a theoretically 811 // promotable type. 812 if (Ty->isIntegralOrUnscopedEnumerationType()) { 813 // C99 6.3.1.1p2: 814 // 815 // The following may be used in an expression wherever an int or 816 // unsigned int may be used: 817 // - an object or expression with an integer type whose integer 818 // conversion rank is less than or equal to the rank of int 819 // and unsigned int. 820 // - A bit-field of type _Bool, int, signed int, or unsigned int. 821 // 822 // If an int can represent all values of the original type, the 823 // value is converted to an int; otherwise, it is converted to an 824 // unsigned int. These are called the integer promotions. All 825 // other types are unchanged by the integer promotions. 826 827 QualType PTy = Context.isPromotableBitField(E); 828 if (!PTy.isNull()) { 829 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 830 return E; 831 } 832 if (Ty->isPromotableIntegerType()) { 833 QualType PT = Context.getPromotedIntegerType(Ty); 834 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 835 return E; 836 } 837 } 838 return E; 839 } 840 841 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 842 /// do not have a prototype. Arguments that have type float or __fp16 843 /// are promoted to double. All other argument types are converted by 844 /// UsualUnaryConversions(). 845 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 846 QualType Ty = E->getType(); 847 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 848 849 ExprResult Res = UsualUnaryConversions(E); 850 if (Res.isInvalid()) 851 return ExprError(); 852 E = Res.get(); 853 854 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 855 // promote to double. 856 // Note that default argument promotion applies only to float (and 857 // half/fp16); it does not apply to _Float16. 858 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 859 if (BTy && (BTy->getKind() == BuiltinType::Half || 860 BTy->getKind() == BuiltinType::Float)) { 861 if (getLangOpts().OpenCL && 862 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 863 if (BTy->getKind() == BuiltinType::Half) { 864 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 865 } 866 } else { 867 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 868 } 869 } 870 if (BTy && 871 getLangOpts().getExtendIntArgs() == 872 LangOptions::ExtendArgsKind::ExtendTo64 && 873 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 874 Context.getTypeSizeInChars(BTy) < 875 Context.getTypeSizeInChars(Context.LongLongTy)) { 876 E = (Ty->isUnsignedIntegerType()) 877 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 878 .get() 879 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 880 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 881 "Unexpected typesize for LongLongTy"); 882 } 883 884 // C++ performs lvalue-to-rvalue conversion as a default argument 885 // promotion, even on class types, but note: 886 // C++11 [conv.lval]p2: 887 // When an lvalue-to-rvalue conversion occurs in an unevaluated 888 // operand or a subexpression thereof the value contained in the 889 // referenced object is not accessed. Otherwise, if the glvalue 890 // has a class type, the conversion copy-initializes a temporary 891 // of type T from the glvalue and the result of the conversion 892 // is a prvalue for the temporary. 893 // FIXME: add some way to gate this entire thing for correctness in 894 // potentially potentially evaluated contexts. 895 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 896 ExprResult Temp = PerformCopyInitialization( 897 InitializedEntity::InitializeTemporary(E->getType()), 898 E->getExprLoc(), E); 899 if (Temp.isInvalid()) 900 return ExprError(); 901 E = Temp.get(); 902 } 903 904 return E; 905 } 906 907 /// Determine the degree of POD-ness for an expression. 908 /// Incomplete types are considered POD, since this check can be performed 909 /// when we're in an unevaluated context. 910 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 911 if (Ty->isIncompleteType()) { 912 // C++11 [expr.call]p7: 913 // After these conversions, if the argument does not have arithmetic, 914 // enumeration, pointer, pointer to member, or class type, the program 915 // is ill-formed. 916 // 917 // Since we've already performed array-to-pointer and function-to-pointer 918 // decay, the only such type in C++ is cv void. This also handles 919 // initializer lists as variadic arguments. 920 if (Ty->isVoidType()) 921 return VAK_Invalid; 922 923 if (Ty->isObjCObjectType()) 924 return VAK_Invalid; 925 return VAK_Valid; 926 } 927 928 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 929 return VAK_Invalid; 930 931 if (Ty.isCXX98PODType(Context)) 932 return VAK_Valid; 933 934 // C++11 [expr.call]p7: 935 // Passing a potentially-evaluated argument of class type (Clause 9) 936 // having a non-trivial copy constructor, a non-trivial move constructor, 937 // or a non-trivial destructor, with no corresponding parameter, 938 // is conditionally-supported with implementation-defined semantics. 939 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 940 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 941 if (!Record->hasNonTrivialCopyConstructor() && 942 !Record->hasNonTrivialMoveConstructor() && 943 !Record->hasNonTrivialDestructor()) 944 return VAK_ValidInCXX11; 945 946 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 947 return VAK_Valid; 948 949 if (Ty->isObjCObjectType()) 950 return VAK_Invalid; 951 952 if (getLangOpts().MSVCCompat) 953 return VAK_MSVCUndefined; 954 955 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 956 // permitted to reject them. We should consider doing so. 957 return VAK_Undefined; 958 } 959 960 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 961 // Don't allow one to pass an Objective-C interface to a vararg. 962 const QualType &Ty = E->getType(); 963 VarArgKind VAK = isValidVarArgType(Ty); 964 965 // Complain about passing non-POD types through varargs. 966 switch (VAK) { 967 case VAK_ValidInCXX11: 968 DiagRuntimeBehavior( 969 E->getBeginLoc(), nullptr, 970 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 971 LLVM_FALLTHROUGH; 972 case VAK_Valid: 973 if (Ty->isRecordType()) { 974 // This is unlikely to be what the user intended. If the class has a 975 // 'c_str' member function, the user probably meant to call that. 976 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 977 PDiag(diag::warn_pass_class_arg_to_vararg) 978 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 979 } 980 break; 981 982 case VAK_Undefined: 983 case VAK_MSVCUndefined: 984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 985 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 986 << getLangOpts().CPlusPlus11 << Ty << CT); 987 break; 988 989 case VAK_Invalid: 990 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 991 Diag(E->getBeginLoc(), 992 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 993 << Ty << CT; 994 else if (Ty->isObjCObjectType()) 995 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 996 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 997 << Ty << CT); 998 else 999 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1000 << isa<InitListExpr>(E) << Ty << CT; 1001 break; 1002 } 1003 } 1004 1005 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1006 /// will create a trap if the resulting type is not a POD type. 1007 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1008 FunctionDecl *FDecl) { 1009 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1010 // Strip the unbridged-cast placeholder expression off, if applicable. 1011 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1012 (CT == VariadicMethod || 1013 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1014 E = stripARCUnbridgedCast(E); 1015 1016 // Otherwise, do normal placeholder checking. 1017 } else { 1018 ExprResult ExprRes = CheckPlaceholderExpr(E); 1019 if (ExprRes.isInvalid()) 1020 return ExprError(); 1021 E = ExprRes.get(); 1022 } 1023 } 1024 1025 ExprResult ExprRes = DefaultArgumentPromotion(E); 1026 if (ExprRes.isInvalid()) 1027 return ExprError(); 1028 1029 // Copy blocks to the heap. 1030 if (ExprRes.get()->getType()->isBlockPointerType()) 1031 maybeExtendBlockObject(ExprRes); 1032 1033 E = ExprRes.get(); 1034 1035 // Diagnostics regarding non-POD argument types are 1036 // emitted along with format string checking in Sema::CheckFunctionCall(). 1037 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1038 // Turn this into a trap. 1039 CXXScopeSpec SS; 1040 SourceLocation TemplateKWLoc; 1041 UnqualifiedId Name; 1042 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1043 E->getBeginLoc()); 1044 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1045 /*HasTrailingLParen=*/true, 1046 /*IsAddressOfOperand=*/false); 1047 if (TrapFn.isInvalid()) 1048 return ExprError(); 1049 1050 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1051 None, E->getEndLoc()); 1052 if (Call.isInvalid()) 1053 return ExprError(); 1054 1055 ExprResult Comma = 1056 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1057 if (Comma.isInvalid()) 1058 return ExprError(); 1059 return Comma.get(); 1060 } 1061 1062 if (!getLangOpts().CPlusPlus && 1063 RequireCompleteType(E->getExprLoc(), E->getType(), 1064 diag::err_call_incomplete_argument)) 1065 return ExprError(); 1066 1067 return E; 1068 } 1069 1070 /// Converts an integer to complex float type. Helper function of 1071 /// UsualArithmeticConversions() 1072 /// 1073 /// \return false if the integer expression is an integer type and is 1074 /// successfully converted to the complex type. 1075 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1076 ExprResult &ComplexExpr, 1077 QualType IntTy, 1078 QualType ComplexTy, 1079 bool SkipCast) { 1080 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1081 if (SkipCast) return false; 1082 if (IntTy->isIntegerType()) { 1083 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1084 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1085 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1086 CK_FloatingRealToComplex); 1087 } else { 1088 assert(IntTy->isComplexIntegerType()); 1089 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1090 CK_IntegralComplexToFloatingComplex); 1091 } 1092 return false; 1093 } 1094 1095 /// Handle arithmetic conversion with complex types. Helper function of 1096 /// UsualArithmeticConversions() 1097 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1098 ExprResult &RHS, QualType LHSType, 1099 QualType RHSType, 1100 bool IsCompAssign) { 1101 // if we have an integer operand, the result is the complex type. 1102 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1103 /*skipCast*/false)) 1104 return LHSType; 1105 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1106 /*skipCast*/IsCompAssign)) 1107 return RHSType; 1108 1109 // This handles complex/complex, complex/float, or float/complex. 1110 // When both operands are complex, the shorter operand is converted to the 1111 // type of the longer, and that is the type of the result. This corresponds 1112 // to what is done when combining two real floating-point operands. 1113 // The fun begins when size promotion occur across type domains. 1114 // From H&S 6.3.4: When one operand is complex and the other is a real 1115 // floating-point type, the less precise type is converted, within it's 1116 // real or complex domain, to the precision of the other type. For example, 1117 // when combining a "long double" with a "double _Complex", the 1118 // "double _Complex" is promoted to "long double _Complex". 1119 1120 // Compute the rank of the two types, regardless of whether they are complex. 1121 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1122 1123 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1124 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1125 QualType LHSElementType = 1126 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1127 QualType RHSElementType = 1128 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1129 1130 QualType ResultType = S.Context.getComplexType(LHSElementType); 1131 if (Order < 0) { 1132 // Promote the precision of the LHS if not an assignment. 1133 ResultType = S.Context.getComplexType(RHSElementType); 1134 if (!IsCompAssign) { 1135 if (LHSComplexType) 1136 LHS = 1137 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1138 else 1139 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1140 } 1141 } else if (Order > 0) { 1142 // Promote the precision of the RHS. 1143 if (RHSComplexType) 1144 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1145 else 1146 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1147 } 1148 return ResultType; 1149 } 1150 1151 /// Handle arithmetic conversion from integer to float. Helper function 1152 /// of UsualArithmeticConversions() 1153 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1154 ExprResult &IntExpr, 1155 QualType FloatTy, QualType IntTy, 1156 bool ConvertFloat, bool ConvertInt) { 1157 if (IntTy->isIntegerType()) { 1158 if (ConvertInt) 1159 // Convert intExpr to the lhs floating point type. 1160 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1161 CK_IntegralToFloating); 1162 return FloatTy; 1163 } 1164 1165 // Convert both sides to the appropriate complex float. 1166 assert(IntTy->isComplexIntegerType()); 1167 QualType result = S.Context.getComplexType(FloatTy); 1168 1169 // _Complex int -> _Complex float 1170 if (ConvertInt) 1171 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1172 CK_IntegralComplexToFloatingComplex); 1173 1174 // float -> _Complex float 1175 if (ConvertFloat) 1176 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1177 CK_FloatingRealToComplex); 1178 1179 return result; 1180 } 1181 1182 /// Handle arithmethic conversion with floating point types. Helper 1183 /// function of UsualArithmeticConversions() 1184 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1185 ExprResult &RHS, QualType LHSType, 1186 QualType RHSType, bool IsCompAssign) { 1187 bool LHSFloat = LHSType->isRealFloatingType(); 1188 bool RHSFloat = RHSType->isRealFloatingType(); 1189 1190 // N1169 4.1.4: If one of the operands has a floating type and the other 1191 // operand has a fixed-point type, the fixed-point operand 1192 // is converted to the floating type [...] 1193 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1194 if (LHSFloat) 1195 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1196 else if (!IsCompAssign) 1197 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1198 return LHSFloat ? LHSType : RHSType; 1199 } 1200 1201 // If we have two real floating types, convert the smaller operand 1202 // to the bigger result. 1203 if (LHSFloat && RHSFloat) { 1204 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1205 if (order > 0) { 1206 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1207 return LHSType; 1208 } 1209 1210 assert(order < 0 && "illegal float comparison"); 1211 if (!IsCompAssign) 1212 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1213 return RHSType; 1214 } 1215 1216 if (LHSFloat) { 1217 // Half FP has to be promoted to float unless it is natively supported 1218 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1219 LHSType = S.Context.FloatTy; 1220 1221 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1222 /*ConvertFloat=*/!IsCompAssign, 1223 /*ConvertInt=*/ true); 1224 } 1225 assert(RHSFloat); 1226 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1227 /*ConvertFloat=*/ true, 1228 /*ConvertInt=*/!IsCompAssign); 1229 } 1230 1231 /// Diagnose attempts to convert between __float128 and long double if 1232 /// there is no support for such conversion. Helper function of 1233 /// UsualArithmeticConversions(). 1234 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1235 QualType RHSType) { 1236 /* No issue converting if at least one of the types is not a floating point 1237 type or the two types have the same rank. 1238 */ 1239 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1240 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1241 return false; 1242 1243 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1244 "The remaining types must be floating point types."); 1245 1246 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1247 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1248 1249 QualType LHSElemType = LHSComplex ? 1250 LHSComplex->getElementType() : LHSType; 1251 QualType RHSElemType = RHSComplex ? 1252 RHSComplex->getElementType() : RHSType; 1253 1254 // No issue if the two types have the same representation 1255 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1256 &S.Context.getFloatTypeSemantics(RHSElemType)) 1257 return false; 1258 1259 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1260 RHSElemType == S.Context.LongDoubleTy); 1261 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1262 RHSElemType == S.Context.Float128Ty); 1263 1264 // We've handled the situation where __float128 and long double have the same 1265 // representation. We allow all conversions for all possible long double types 1266 // except PPC's double double. 1267 return Float128AndLongDouble && 1268 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1269 &llvm::APFloat::PPCDoubleDouble()); 1270 } 1271 1272 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1273 1274 namespace { 1275 /// These helper callbacks are placed in an anonymous namespace to 1276 /// permit their use as function template parameters. 1277 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1278 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1279 } 1280 1281 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1282 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1283 CK_IntegralComplexCast); 1284 } 1285 } 1286 1287 /// Handle integer arithmetic conversions. Helper function of 1288 /// UsualArithmeticConversions() 1289 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1290 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1291 ExprResult &RHS, QualType LHSType, 1292 QualType RHSType, bool IsCompAssign) { 1293 // The rules for this case are in C99 6.3.1.8 1294 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1295 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1296 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1297 if (LHSSigned == RHSSigned) { 1298 // Same signedness; use the higher-ranked type 1299 if (order >= 0) { 1300 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1301 return LHSType; 1302 } else if (!IsCompAssign) 1303 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1304 return RHSType; 1305 } else if (order != (LHSSigned ? 1 : -1)) { 1306 // The unsigned type has greater than or equal rank to the 1307 // signed type, so use the unsigned type 1308 if (RHSSigned) { 1309 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1310 return LHSType; 1311 } else if (!IsCompAssign) 1312 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1313 return RHSType; 1314 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1315 // The two types are different widths; if we are here, that 1316 // means the signed type is larger than the unsigned type, so 1317 // use the signed type. 1318 if (LHSSigned) { 1319 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1320 return LHSType; 1321 } else if (!IsCompAssign) 1322 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1323 return RHSType; 1324 } else { 1325 // The signed type is higher-ranked than the unsigned type, 1326 // but isn't actually any bigger (like unsigned int and long 1327 // on most 32-bit systems). Use the unsigned type corresponding 1328 // to the signed type. 1329 QualType result = 1330 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1331 RHS = (*doRHSCast)(S, RHS.get(), result); 1332 if (!IsCompAssign) 1333 LHS = (*doLHSCast)(S, LHS.get(), result); 1334 return result; 1335 } 1336 } 1337 1338 /// Handle conversions with GCC complex int extension. Helper function 1339 /// of UsualArithmeticConversions() 1340 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1341 ExprResult &RHS, QualType LHSType, 1342 QualType RHSType, 1343 bool IsCompAssign) { 1344 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1345 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1346 1347 if (LHSComplexInt && RHSComplexInt) { 1348 QualType LHSEltType = LHSComplexInt->getElementType(); 1349 QualType RHSEltType = RHSComplexInt->getElementType(); 1350 QualType ScalarType = 1351 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1352 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1353 1354 return S.Context.getComplexType(ScalarType); 1355 } 1356 1357 if (LHSComplexInt) { 1358 QualType LHSEltType = LHSComplexInt->getElementType(); 1359 QualType ScalarType = 1360 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1361 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1362 QualType ComplexType = S.Context.getComplexType(ScalarType); 1363 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1364 CK_IntegralRealToComplex); 1365 1366 return ComplexType; 1367 } 1368 1369 assert(RHSComplexInt); 1370 1371 QualType RHSEltType = RHSComplexInt->getElementType(); 1372 QualType ScalarType = 1373 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1374 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1375 QualType ComplexType = S.Context.getComplexType(ScalarType); 1376 1377 if (!IsCompAssign) 1378 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1379 CK_IntegralRealToComplex); 1380 return ComplexType; 1381 } 1382 1383 /// Return the rank of a given fixed point or integer type. The value itself 1384 /// doesn't matter, but the values must be increasing with proper increasing 1385 /// rank as described in N1169 4.1.1. 1386 static unsigned GetFixedPointRank(QualType Ty) { 1387 const auto *BTy = Ty->getAs<BuiltinType>(); 1388 assert(BTy && "Expected a builtin type."); 1389 1390 switch (BTy->getKind()) { 1391 case BuiltinType::ShortFract: 1392 case BuiltinType::UShortFract: 1393 case BuiltinType::SatShortFract: 1394 case BuiltinType::SatUShortFract: 1395 return 1; 1396 case BuiltinType::Fract: 1397 case BuiltinType::UFract: 1398 case BuiltinType::SatFract: 1399 case BuiltinType::SatUFract: 1400 return 2; 1401 case BuiltinType::LongFract: 1402 case BuiltinType::ULongFract: 1403 case BuiltinType::SatLongFract: 1404 case BuiltinType::SatULongFract: 1405 return 3; 1406 case BuiltinType::ShortAccum: 1407 case BuiltinType::UShortAccum: 1408 case BuiltinType::SatShortAccum: 1409 case BuiltinType::SatUShortAccum: 1410 return 4; 1411 case BuiltinType::Accum: 1412 case BuiltinType::UAccum: 1413 case BuiltinType::SatAccum: 1414 case BuiltinType::SatUAccum: 1415 return 5; 1416 case BuiltinType::LongAccum: 1417 case BuiltinType::ULongAccum: 1418 case BuiltinType::SatLongAccum: 1419 case BuiltinType::SatULongAccum: 1420 return 6; 1421 default: 1422 if (BTy->isInteger()) 1423 return 0; 1424 llvm_unreachable("Unexpected fixed point or integer type"); 1425 } 1426 } 1427 1428 /// handleFixedPointConversion - Fixed point operations between fixed 1429 /// point types and integers or other fixed point types do not fall under 1430 /// usual arithmetic conversion since these conversions could result in loss 1431 /// of precsision (N1169 4.1.4). These operations should be calculated with 1432 /// the full precision of their result type (N1169 4.1.6.2.1). 1433 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1434 QualType RHSTy) { 1435 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1436 "Expected at least one of the operands to be a fixed point type"); 1437 assert((LHSTy->isFixedPointOrIntegerType() || 1438 RHSTy->isFixedPointOrIntegerType()) && 1439 "Special fixed point arithmetic operation conversions are only " 1440 "applied to ints or other fixed point types"); 1441 1442 // If one operand has signed fixed-point type and the other operand has 1443 // unsigned fixed-point type, then the unsigned fixed-point operand is 1444 // converted to its corresponding signed fixed-point type and the resulting 1445 // type is the type of the converted operand. 1446 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1447 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1448 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1449 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1450 1451 // The result type is the type with the highest rank, whereby a fixed-point 1452 // conversion rank is always greater than an integer conversion rank; if the 1453 // type of either of the operands is a saturating fixedpoint type, the result 1454 // type shall be the saturating fixed-point type corresponding to the type 1455 // with the highest rank; the resulting value is converted (taking into 1456 // account rounding and overflow) to the precision of the resulting type. 1457 // Same ranks between signed and unsigned types are resolved earlier, so both 1458 // types are either signed or both unsigned at this point. 1459 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1460 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1461 1462 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1463 1464 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1465 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1466 1467 return ResultTy; 1468 } 1469 1470 /// Check that the usual arithmetic conversions can be performed on this pair of 1471 /// expressions that might be of enumeration type. 1472 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1473 SourceLocation Loc, 1474 Sema::ArithConvKind ACK) { 1475 // C++2a [expr.arith.conv]p1: 1476 // If one operand is of enumeration type and the other operand is of a 1477 // different enumeration type or a floating-point type, this behavior is 1478 // deprecated ([depr.arith.conv.enum]). 1479 // 1480 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1481 // Eventually we will presumably reject these cases (in C++23 onwards?). 1482 QualType L = LHS->getType(), R = RHS->getType(); 1483 bool LEnum = L->isUnscopedEnumerationType(), 1484 REnum = R->isUnscopedEnumerationType(); 1485 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1486 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1487 (REnum && L->isFloatingType())) { 1488 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1489 ? diag::warn_arith_conv_enum_float_cxx20 1490 : diag::warn_arith_conv_enum_float) 1491 << LHS->getSourceRange() << RHS->getSourceRange() 1492 << (int)ACK << LEnum << L << R; 1493 } else if (!IsCompAssign && LEnum && REnum && 1494 !S.Context.hasSameUnqualifiedType(L, R)) { 1495 unsigned DiagID; 1496 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1497 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1498 // If either enumeration type is unnamed, it's less likely that the 1499 // user cares about this, but this situation is still deprecated in 1500 // C++2a. Use a different warning group. 1501 DiagID = S.getLangOpts().CPlusPlus20 1502 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1503 : diag::warn_arith_conv_mixed_anon_enum_types; 1504 } else if (ACK == Sema::ACK_Conditional) { 1505 // Conditional expressions are separated out because they have 1506 // historically had a different warning flag. 1507 DiagID = S.getLangOpts().CPlusPlus20 1508 ? diag::warn_conditional_mixed_enum_types_cxx20 1509 : diag::warn_conditional_mixed_enum_types; 1510 } else if (ACK == Sema::ACK_Comparison) { 1511 // Comparison expressions are separated out because they have 1512 // historically had a different warning flag. 1513 DiagID = S.getLangOpts().CPlusPlus20 1514 ? diag::warn_comparison_mixed_enum_types_cxx20 1515 : diag::warn_comparison_mixed_enum_types; 1516 } else { 1517 DiagID = S.getLangOpts().CPlusPlus20 1518 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1519 : diag::warn_arith_conv_mixed_enum_types; 1520 } 1521 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1522 << (int)ACK << L << R; 1523 } 1524 } 1525 1526 /// UsualArithmeticConversions - Performs various conversions that are common to 1527 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1528 /// routine returns the first non-arithmetic type found. The client is 1529 /// responsible for emitting appropriate error diagnostics. 1530 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1531 SourceLocation Loc, 1532 ArithConvKind ACK) { 1533 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1534 1535 if (ACK != ACK_CompAssign) { 1536 LHS = UsualUnaryConversions(LHS.get()); 1537 if (LHS.isInvalid()) 1538 return QualType(); 1539 } 1540 1541 RHS = UsualUnaryConversions(RHS.get()); 1542 if (RHS.isInvalid()) 1543 return QualType(); 1544 1545 // For conversion purposes, we ignore any qualifiers. 1546 // For example, "const float" and "float" are equivalent. 1547 QualType LHSType = 1548 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1549 QualType RHSType = 1550 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1551 1552 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1553 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1554 LHSType = AtomicLHS->getValueType(); 1555 1556 // If both types are identical, no conversion is needed. 1557 if (LHSType == RHSType) 1558 return LHSType; 1559 1560 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1561 // The caller can deal with this (e.g. pointer + int). 1562 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1563 return QualType(); 1564 1565 // Apply unary and bitfield promotions to the LHS's type. 1566 QualType LHSUnpromotedType = LHSType; 1567 if (LHSType->isPromotableIntegerType()) 1568 LHSType = Context.getPromotedIntegerType(LHSType); 1569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1570 if (!LHSBitfieldPromoteTy.isNull()) 1571 LHSType = LHSBitfieldPromoteTy; 1572 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1573 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1574 1575 // If both types are identical, no conversion is needed. 1576 if (LHSType == RHSType) 1577 return LHSType; 1578 1579 // At this point, we have two different arithmetic types. 1580 1581 // Diagnose attempts to convert between __float128 and long double where 1582 // such conversions currently can't be handled. 1583 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1584 return QualType(); 1585 1586 // Handle complex types first (C99 6.3.1.8p1). 1587 if (LHSType->isComplexType() || RHSType->isComplexType()) 1588 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1589 ACK == ACK_CompAssign); 1590 1591 // Now handle "real" floating types (i.e. float, double, long double). 1592 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1593 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1594 ACK == ACK_CompAssign); 1595 1596 // Handle GCC complex int extension. 1597 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1598 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1599 ACK == ACK_CompAssign); 1600 1601 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1602 return handleFixedPointConversion(*this, LHSType, RHSType); 1603 1604 // Finally, we have two differing integer types. 1605 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1606 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1607 } 1608 1609 //===----------------------------------------------------------------------===// 1610 // Semantic Analysis for various Expression Types 1611 //===----------------------------------------------------------------------===// 1612 1613 1614 ExprResult 1615 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1616 SourceLocation DefaultLoc, 1617 SourceLocation RParenLoc, 1618 Expr *ControllingExpr, 1619 ArrayRef<ParsedType> ArgTypes, 1620 ArrayRef<Expr *> ArgExprs) { 1621 unsigned NumAssocs = ArgTypes.size(); 1622 assert(NumAssocs == ArgExprs.size()); 1623 1624 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1625 for (unsigned i = 0; i < NumAssocs; ++i) { 1626 if (ArgTypes[i]) 1627 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1628 else 1629 Types[i] = nullptr; 1630 } 1631 1632 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1633 ControllingExpr, 1634 llvm::makeArrayRef(Types, NumAssocs), 1635 ArgExprs); 1636 delete [] Types; 1637 return ER; 1638 } 1639 1640 ExprResult 1641 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1642 SourceLocation DefaultLoc, 1643 SourceLocation RParenLoc, 1644 Expr *ControllingExpr, 1645 ArrayRef<TypeSourceInfo *> Types, 1646 ArrayRef<Expr *> Exprs) { 1647 unsigned NumAssocs = Types.size(); 1648 assert(NumAssocs == Exprs.size()); 1649 1650 // Decay and strip qualifiers for the controlling expression type, and handle 1651 // placeholder type replacement. See committee discussion from WG14 DR423. 1652 { 1653 EnterExpressionEvaluationContext Unevaluated( 1654 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1655 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1656 if (R.isInvalid()) 1657 return ExprError(); 1658 ControllingExpr = R.get(); 1659 } 1660 1661 // The controlling expression is an unevaluated operand, so side effects are 1662 // likely unintended. 1663 if (!inTemplateInstantiation() && 1664 ControllingExpr->HasSideEffects(Context, false)) 1665 Diag(ControllingExpr->getExprLoc(), 1666 diag::warn_side_effects_unevaluated_context); 1667 1668 bool TypeErrorFound = false, 1669 IsResultDependent = ControllingExpr->isTypeDependent(), 1670 ContainsUnexpandedParameterPack 1671 = ControllingExpr->containsUnexpandedParameterPack(); 1672 1673 for (unsigned i = 0; i < NumAssocs; ++i) { 1674 if (Exprs[i]->containsUnexpandedParameterPack()) 1675 ContainsUnexpandedParameterPack = true; 1676 1677 if (Types[i]) { 1678 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1679 ContainsUnexpandedParameterPack = true; 1680 1681 if (Types[i]->getType()->isDependentType()) { 1682 IsResultDependent = true; 1683 } else { 1684 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1685 // complete object type other than a variably modified type." 1686 unsigned D = 0; 1687 if (Types[i]->getType()->isIncompleteType()) 1688 D = diag::err_assoc_type_incomplete; 1689 else if (!Types[i]->getType()->isObjectType()) 1690 D = diag::err_assoc_type_nonobject; 1691 else if (Types[i]->getType()->isVariablyModifiedType()) 1692 D = diag::err_assoc_type_variably_modified; 1693 1694 if (D != 0) { 1695 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1696 << Types[i]->getTypeLoc().getSourceRange() 1697 << Types[i]->getType(); 1698 TypeErrorFound = true; 1699 } 1700 1701 // C11 6.5.1.1p2 "No two generic associations in the same generic 1702 // selection shall specify compatible types." 1703 for (unsigned j = i+1; j < NumAssocs; ++j) 1704 if (Types[j] && !Types[j]->getType()->isDependentType() && 1705 Context.typesAreCompatible(Types[i]->getType(), 1706 Types[j]->getType())) { 1707 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1708 diag::err_assoc_compatible_types) 1709 << Types[j]->getTypeLoc().getSourceRange() 1710 << Types[j]->getType() 1711 << Types[i]->getType(); 1712 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1713 diag::note_compat_assoc) 1714 << Types[i]->getTypeLoc().getSourceRange() 1715 << Types[i]->getType(); 1716 TypeErrorFound = true; 1717 } 1718 } 1719 } 1720 } 1721 if (TypeErrorFound) 1722 return ExprError(); 1723 1724 // If we determined that the generic selection is result-dependent, don't 1725 // try to compute the result expression. 1726 if (IsResultDependent) 1727 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1728 Exprs, DefaultLoc, RParenLoc, 1729 ContainsUnexpandedParameterPack); 1730 1731 SmallVector<unsigned, 1> CompatIndices; 1732 unsigned DefaultIndex = -1U; 1733 for (unsigned i = 0; i < NumAssocs; ++i) { 1734 if (!Types[i]) 1735 DefaultIndex = i; 1736 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1737 Types[i]->getType())) 1738 CompatIndices.push_back(i); 1739 } 1740 1741 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1742 // type compatible with at most one of the types named in its generic 1743 // association list." 1744 if (CompatIndices.size() > 1) { 1745 // We strip parens here because the controlling expression is typically 1746 // parenthesized in macro definitions. 1747 ControllingExpr = ControllingExpr->IgnoreParens(); 1748 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1749 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1750 << (unsigned)CompatIndices.size(); 1751 for (unsigned I : CompatIndices) { 1752 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1753 diag::note_compat_assoc) 1754 << Types[I]->getTypeLoc().getSourceRange() 1755 << Types[I]->getType(); 1756 } 1757 return ExprError(); 1758 } 1759 1760 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1761 // its controlling expression shall have type compatible with exactly one of 1762 // the types named in its generic association list." 1763 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1764 // We strip parens here because the controlling expression is typically 1765 // parenthesized in macro definitions. 1766 ControllingExpr = ControllingExpr->IgnoreParens(); 1767 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1768 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1769 return ExprError(); 1770 } 1771 1772 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1773 // type name that is compatible with the type of the controlling expression, 1774 // then the result expression of the generic selection is the expression 1775 // in that generic association. Otherwise, the result expression of the 1776 // generic selection is the expression in the default generic association." 1777 unsigned ResultIndex = 1778 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1779 1780 return GenericSelectionExpr::Create( 1781 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1782 ContainsUnexpandedParameterPack, ResultIndex); 1783 } 1784 1785 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1786 /// location of the token and the offset of the ud-suffix within it. 1787 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1788 unsigned Offset) { 1789 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1790 S.getLangOpts()); 1791 } 1792 1793 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1794 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1795 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1796 IdentifierInfo *UDSuffix, 1797 SourceLocation UDSuffixLoc, 1798 ArrayRef<Expr*> Args, 1799 SourceLocation LitEndLoc) { 1800 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1801 1802 QualType ArgTy[2]; 1803 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1804 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1805 if (ArgTy[ArgIdx]->isArrayType()) 1806 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1807 } 1808 1809 DeclarationName OpName = 1810 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1811 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1812 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1813 1814 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1815 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1816 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1817 /*AllowStringTemplatePack*/ false, 1818 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1819 return ExprError(); 1820 1821 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1822 } 1823 1824 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1825 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1826 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1827 /// multiple tokens. However, the common case is that StringToks points to one 1828 /// string. 1829 /// 1830 ExprResult 1831 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1832 assert(!StringToks.empty() && "Must have at least one string!"); 1833 1834 StringLiteralParser Literal(StringToks, PP); 1835 if (Literal.hadError) 1836 return ExprError(); 1837 1838 SmallVector<SourceLocation, 4> StringTokLocs; 1839 for (const Token &Tok : StringToks) 1840 StringTokLocs.push_back(Tok.getLocation()); 1841 1842 QualType CharTy = Context.CharTy; 1843 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1844 if (Literal.isWide()) { 1845 CharTy = Context.getWideCharType(); 1846 Kind = StringLiteral::Wide; 1847 } else if (Literal.isUTF8()) { 1848 if (getLangOpts().Char8) 1849 CharTy = Context.Char8Ty; 1850 Kind = StringLiteral::UTF8; 1851 } else if (Literal.isUTF16()) { 1852 CharTy = Context.Char16Ty; 1853 Kind = StringLiteral::UTF16; 1854 } else if (Literal.isUTF32()) { 1855 CharTy = Context.Char32Ty; 1856 Kind = StringLiteral::UTF32; 1857 } else if (Literal.isPascal()) { 1858 CharTy = Context.UnsignedCharTy; 1859 } 1860 1861 // Warn on initializing an array of char from a u8 string literal; this 1862 // becomes ill-formed in C++2a. 1863 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1864 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1865 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1866 1867 // Create removals for all 'u8' prefixes in the string literal(s). This 1868 // ensures C++2a compatibility (but may change the program behavior when 1869 // built by non-Clang compilers for which the execution character set is 1870 // not always UTF-8). 1871 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1872 SourceLocation RemovalDiagLoc; 1873 for (const Token &Tok : StringToks) { 1874 if (Tok.getKind() == tok::utf8_string_literal) { 1875 if (RemovalDiagLoc.isInvalid()) 1876 RemovalDiagLoc = Tok.getLocation(); 1877 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1878 Tok.getLocation(), 1879 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1880 getSourceManager(), getLangOpts()))); 1881 } 1882 } 1883 Diag(RemovalDiagLoc, RemovalDiag); 1884 } 1885 1886 QualType StrTy = 1887 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1888 1889 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1890 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1891 Kind, Literal.Pascal, StrTy, 1892 &StringTokLocs[0], 1893 StringTokLocs.size()); 1894 if (Literal.getUDSuffix().empty()) 1895 return Lit; 1896 1897 // We're building a user-defined literal. 1898 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1899 SourceLocation UDSuffixLoc = 1900 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1901 Literal.getUDSuffixOffset()); 1902 1903 // Make sure we're allowed user-defined literals here. 1904 if (!UDLScope) 1905 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1906 1907 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1908 // operator "" X (str, len) 1909 QualType SizeType = Context.getSizeType(); 1910 1911 DeclarationName OpName = 1912 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1913 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1914 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1915 1916 QualType ArgTy[] = { 1917 Context.getArrayDecayedType(StrTy), SizeType 1918 }; 1919 1920 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1921 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1922 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1923 /*AllowStringTemplatePack*/ true, 1924 /*DiagnoseMissing*/ true, Lit)) { 1925 1926 case LOLR_Cooked: { 1927 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1928 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1929 StringTokLocs[0]); 1930 Expr *Args[] = { Lit, LenArg }; 1931 1932 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1933 } 1934 1935 case LOLR_Template: { 1936 TemplateArgumentListInfo ExplicitArgs; 1937 TemplateArgument Arg(Lit); 1938 TemplateArgumentLocInfo ArgInfo(Lit); 1939 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1940 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1941 &ExplicitArgs); 1942 } 1943 1944 case LOLR_StringTemplatePack: { 1945 TemplateArgumentListInfo ExplicitArgs; 1946 1947 unsigned CharBits = Context.getIntWidth(CharTy); 1948 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1949 llvm::APSInt Value(CharBits, CharIsUnsigned); 1950 1951 TemplateArgument TypeArg(CharTy); 1952 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1953 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1954 1955 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1956 Value = Lit->getCodeUnit(I); 1957 TemplateArgument Arg(Context, Value, CharTy); 1958 TemplateArgumentLocInfo ArgInfo; 1959 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1960 } 1961 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1962 &ExplicitArgs); 1963 } 1964 case LOLR_Raw: 1965 case LOLR_ErrorNoDiagnostic: 1966 llvm_unreachable("unexpected literal operator lookup result"); 1967 case LOLR_Error: 1968 return ExprError(); 1969 } 1970 llvm_unreachable("unexpected literal operator lookup result"); 1971 } 1972 1973 DeclRefExpr * 1974 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1975 SourceLocation Loc, 1976 const CXXScopeSpec *SS) { 1977 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1978 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1979 } 1980 1981 DeclRefExpr * 1982 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1983 const DeclarationNameInfo &NameInfo, 1984 const CXXScopeSpec *SS, NamedDecl *FoundD, 1985 SourceLocation TemplateKWLoc, 1986 const TemplateArgumentListInfo *TemplateArgs) { 1987 NestedNameSpecifierLoc NNS = 1988 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1989 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1990 TemplateArgs); 1991 } 1992 1993 // CUDA/HIP: Check whether a captured reference variable is referencing a 1994 // host variable in a device or host device lambda. 1995 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1996 VarDecl *VD) { 1997 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1998 return false; 1999 assert(VD->getType()->isReferenceType()); 2000 2001 // Check whether the reference variable is referencing a host variable. 2002 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 2003 if (!DRE) 2004 return false; 2005 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2006 if (!Referee || !Referee->hasGlobalStorage() || 2007 Referee->hasAttr<CUDADeviceAttr>()) 2008 return false; 2009 2010 // Check whether the current function is a device or host device lambda. 2011 // Check whether the reference variable is a capture by getDeclContext() 2012 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2013 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2014 if (MD && MD->getParent()->isLambda() && 2015 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2016 VD->getDeclContext() != MD) 2017 return true; 2018 2019 return false; 2020 } 2021 2022 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2023 // A declaration named in an unevaluated operand never constitutes an odr-use. 2024 if (isUnevaluatedContext()) 2025 return NOUR_Unevaluated; 2026 2027 // C++2a [basic.def.odr]p4: 2028 // A variable x whose name appears as a potentially-evaluated expression e 2029 // is odr-used by e unless [...] x is a reference that is usable in 2030 // constant expressions. 2031 // CUDA/HIP: 2032 // If a reference variable referencing a host variable is captured in a 2033 // device or host device lambda, the value of the referee must be copied 2034 // to the capture and the reference variable must be treated as odr-use 2035 // since the value of the referee is not known at compile time and must 2036 // be loaded from the captured. 2037 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2038 if (VD->getType()->isReferenceType() && 2039 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2040 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2041 VD->isUsableInConstantExpressions(Context)) 2042 return NOUR_Constant; 2043 } 2044 2045 // All remaining non-variable cases constitute an odr-use. For variables, we 2046 // need to wait and see how the expression is used. 2047 return NOUR_None; 2048 } 2049 2050 /// BuildDeclRefExpr - Build an expression that references a 2051 /// declaration that does not require a closure capture. 2052 DeclRefExpr * 2053 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2054 const DeclarationNameInfo &NameInfo, 2055 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2056 SourceLocation TemplateKWLoc, 2057 const TemplateArgumentListInfo *TemplateArgs) { 2058 bool RefersToCapturedVariable = 2059 isa<VarDecl>(D) && 2060 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2061 2062 DeclRefExpr *E = DeclRefExpr::Create( 2063 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2064 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2065 MarkDeclRefReferenced(E); 2066 2067 // C++ [except.spec]p17: 2068 // An exception-specification is considered to be needed when: 2069 // - in an expression, the function is the unique lookup result or 2070 // the selected member of a set of overloaded functions. 2071 // 2072 // We delay doing this until after we've built the function reference and 2073 // marked it as used so that: 2074 // a) if the function is defaulted, we get errors from defining it before / 2075 // instead of errors from computing its exception specification, and 2076 // b) if the function is a defaulted comparison, we can use the body we 2077 // build when defining it as input to the exception specification 2078 // computation rather than computing a new body. 2079 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2080 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2081 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2082 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2083 } 2084 } 2085 2086 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2087 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2088 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2089 getCurFunction()->recordUseOfWeak(E); 2090 2091 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2092 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2093 FD = IFD->getAnonField(); 2094 if (FD) { 2095 UnusedPrivateFields.remove(FD); 2096 // Just in case we're building an illegal pointer-to-member. 2097 if (FD->isBitField()) 2098 E->setObjectKind(OK_BitField); 2099 } 2100 2101 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2102 // designates a bit-field. 2103 if (auto *BD = dyn_cast<BindingDecl>(D)) 2104 if (auto *BE = BD->getBinding()) 2105 E->setObjectKind(BE->getObjectKind()); 2106 2107 return E; 2108 } 2109 2110 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2111 /// possibly a list of template arguments. 2112 /// 2113 /// If this produces template arguments, it is permitted to call 2114 /// DecomposeTemplateName. 2115 /// 2116 /// This actually loses a lot of source location information for 2117 /// non-standard name kinds; we should consider preserving that in 2118 /// some way. 2119 void 2120 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2121 TemplateArgumentListInfo &Buffer, 2122 DeclarationNameInfo &NameInfo, 2123 const TemplateArgumentListInfo *&TemplateArgs) { 2124 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2125 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2126 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2127 2128 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2129 Id.TemplateId->NumArgs); 2130 translateTemplateArguments(TemplateArgsPtr, Buffer); 2131 2132 TemplateName TName = Id.TemplateId->Template.get(); 2133 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2134 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2135 TemplateArgs = &Buffer; 2136 } else { 2137 NameInfo = GetNameFromUnqualifiedId(Id); 2138 TemplateArgs = nullptr; 2139 } 2140 } 2141 2142 static void emitEmptyLookupTypoDiagnostic( 2143 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2144 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2145 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2146 DeclContext *Ctx = 2147 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2148 if (!TC) { 2149 // Emit a special diagnostic for failed member lookups. 2150 // FIXME: computing the declaration context might fail here (?) 2151 if (Ctx) 2152 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2153 << SS.getRange(); 2154 else 2155 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2156 return; 2157 } 2158 2159 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2160 bool DroppedSpecifier = 2161 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2162 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2163 ? diag::note_implicit_param_decl 2164 : diag::note_previous_decl; 2165 if (!Ctx) 2166 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2167 SemaRef.PDiag(NoteID)); 2168 else 2169 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2170 << Typo << Ctx << DroppedSpecifier 2171 << SS.getRange(), 2172 SemaRef.PDiag(NoteID)); 2173 } 2174 2175 /// Diagnose a lookup that found results in an enclosing class during error 2176 /// recovery. This usually indicates that the results were found in a dependent 2177 /// base class that could not be searched as part of a template definition. 2178 /// Always issues a diagnostic (though this may be only a warning in MS 2179 /// compatibility mode). 2180 /// 2181 /// Return \c true if the error is unrecoverable, or \c false if the caller 2182 /// should attempt to recover using these lookup results. 2183 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2184 // During a default argument instantiation the CurContext points 2185 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2186 // function parameter list, hence add an explicit check. 2187 bool isDefaultArgument = 2188 !CodeSynthesisContexts.empty() && 2189 CodeSynthesisContexts.back().Kind == 2190 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2191 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2192 bool isInstance = CurMethod && CurMethod->isInstance() && 2193 R.getNamingClass() == CurMethod->getParent() && 2194 !isDefaultArgument; 2195 2196 // There are two ways we can find a class-scope declaration during template 2197 // instantiation that we did not find in the template definition: if it is a 2198 // member of a dependent base class, or if it is declared after the point of 2199 // use in the same class. Distinguish these by comparing the class in which 2200 // the member was found to the naming class of the lookup. 2201 unsigned DiagID = diag::err_found_in_dependent_base; 2202 unsigned NoteID = diag::note_member_declared_at; 2203 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2204 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2205 : diag::err_found_later_in_class; 2206 } else if (getLangOpts().MSVCCompat) { 2207 DiagID = diag::ext_found_in_dependent_base; 2208 NoteID = diag::note_dependent_member_use; 2209 } 2210 2211 if (isInstance) { 2212 // Give a code modification hint to insert 'this->'. 2213 Diag(R.getNameLoc(), DiagID) 2214 << R.getLookupName() 2215 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2216 CheckCXXThisCapture(R.getNameLoc()); 2217 } else { 2218 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2219 // they're not shadowed). 2220 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2221 } 2222 2223 for (NamedDecl *D : R) 2224 Diag(D->getLocation(), NoteID); 2225 2226 // Return true if we are inside a default argument instantiation 2227 // and the found name refers to an instance member function, otherwise 2228 // the caller will try to create an implicit member call and this is wrong 2229 // for default arguments. 2230 // 2231 // FIXME: Is this special case necessary? We could allow the caller to 2232 // diagnose this. 2233 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2234 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2235 return true; 2236 } 2237 2238 // Tell the callee to try to recover. 2239 return false; 2240 } 2241 2242 /// Diagnose an empty lookup. 2243 /// 2244 /// \return false if new lookup candidates were found 2245 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2246 CorrectionCandidateCallback &CCC, 2247 TemplateArgumentListInfo *ExplicitTemplateArgs, 2248 ArrayRef<Expr *> Args, TypoExpr **Out) { 2249 DeclarationName Name = R.getLookupName(); 2250 2251 unsigned diagnostic = diag::err_undeclared_var_use; 2252 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2253 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2254 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2255 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2256 diagnostic = diag::err_undeclared_use; 2257 diagnostic_suggest = diag::err_undeclared_use_suggest; 2258 } 2259 2260 // If the original lookup was an unqualified lookup, fake an 2261 // unqualified lookup. This is useful when (for example) the 2262 // original lookup would not have found something because it was a 2263 // dependent name. 2264 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2265 while (DC) { 2266 if (isa<CXXRecordDecl>(DC)) { 2267 LookupQualifiedName(R, DC); 2268 2269 if (!R.empty()) { 2270 // Don't give errors about ambiguities in this lookup. 2271 R.suppressDiagnostics(); 2272 2273 // If there's a best viable function among the results, only mention 2274 // that one in the notes. 2275 OverloadCandidateSet Candidates(R.getNameLoc(), 2276 OverloadCandidateSet::CSK_Normal); 2277 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2278 OverloadCandidateSet::iterator Best; 2279 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2280 OR_Success) { 2281 R.clear(); 2282 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2283 R.resolveKind(); 2284 } 2285 2286 return DiagnoseDependentMemberLookup(R); 2287 } 2288 2289 R.clear(); 2290 } 2291 2292 DC = DC->getLookupParent(); 2293 } 2294 2295 // We didn't find anything, so try to correct for a typo. 2296 TypoCorrection Corrected; 2297 if (S && Out) { 2298 SourceLocation TypoLoc = R.getNameLoc(); 2299 assert(!ExplicitTemplateArgs && 2300 "Diagnosing an empty lookup with explicit template args!"); 2301 *Out = CorrectTypoDelayed( 2302 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2303 [=](const TypoCorrection &TC) { 2304 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2305 diagnostic, diagnostic_suggest); 2306 }, 2307 nullptr, CTK_ErrorRecovery); 2308 if (*Out) 2309 return true; 2310 } else if (S && 2311 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2312 S, &SS, CCC, CTK_ErrorRecovery))) { 2313 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2314 bool DroppedSpecifier = 2315 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2316 R.setLookupName(Corrected.getCorrection()); 2317 2318 bool AcceptableWithRecovery = false; 2319 bool AcceptableWithoutRecovery = false; 2320 NamedDecl *ND = Corrected.getFoundDecl(); 2321 if (ND) { 2322 if (Corrected.isOverloaded()) { 2323 OverloadCandidateSet OCS(R.getNameLoc(), 2324 OverloadCandidateSet::CSK_Normal); 2325 OverloadCandidateSet::iterator Best; 2326 for (NamedDecl *CD : Corrected) { 2327 if (FunctionTemplateDecl *FTD = 2328 dyn_cast<FunctionTemplateDecl>(CD)) 2329 AddTemplateOverloadCandidate( 2330 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2331 Args, OCS); 2332 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2333 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2334 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2335 Args, OCS); 2336 } 2337 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2338 case OR_Success: 2339 ND = Best->FoundDecl; 2340 Corrected.setCorrectionDecl(ND); 2341 break; 2342 default: 2343 // FIXME: Arbitrarily pick the first declaration for the note. 2344 Corrected.setCorrectionDecl(ND); 2345 break; 2346 } 2347 } 2348 R.addDecl(ND); 2349 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2350 CXXRecordDecl *Record = nullptr; 2351 if (Corrected.getCorrectionSpecifier()) { 2352 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2353 Record = Ty->getAsCXXRecordDecl(); 2354 } 2355 if (!Record) 2356 Record = cast<CXXRecordDecl>( 2357 ND->getDeclContext()->getRedeclContext()); 2358 R.setNamingClass(Record); 2359 } 2360 2361 auto *UnderlyingND = ND->getUnderlyingDecl(); 2362 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2363 isa<FunctionTemplateDecl>(UnderlyingND); 2364 // FIXME: If we ended up with a typo for a type name or 2365 // Objective-C class name, we're in trouble because the parser 2366 // is in the wrong place to recover. Suggest the typo 2367 // correction, but don't make it a fix-it since we're not going 2368 // to recover well anyway. 2369 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2370 getAsTypeTemplateDecl(UnderlyingND) || 2371 isa<ObjCInterfaceDecl>(UnderlyingND); 2372 } else { 2373 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2374 // because we aren't able to recover. 2375 AcceptableWithoutRecovery = true; 2376 } 2377 2378 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2379 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2380 ? diag::note_implicit_param_decl 2381 : diag::note_previous_decl; 2382 if (SS.isEmpty()) 2383 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2384 PDiag(NoteID), AcceptableWithRecovery); 2385 else 2386 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2387 << Name << computeDeclContext(SS, false) 2388 << DroppedSpecifier << SS.getRange(), 2389 PDiag(NoteID), AcceptableWithRecovery); 2390 2391 // Tell the callee whether to try to recover. 2392 return !AcceptableWithRecovery; 2393 } 2394 } 2395 R.clear(); 2396 2397 // Emit a special diagnostic for failed member lookups. 2398 // FIXME: computing the declaration context might fail here (?) 2399 if (!SS.isEmpty()) { 2400 Diag(R.getNameLoc(), diag::err_no_member) 2401 << Name << computeDeclContext(SS, false) 2402 << SS.getRange(); 2403 return true; 2404 } 2405 2406 // Give up, we can't recover. 2407 Diag(R.getNameLoc(), diagnostic) << Name; 2408 return true; 2409 } 2410 2411 /// In Microsoft mode, if we are inside a template class whose parent class has 2412 /// dependent base classes, and we can't resolve an unqualified identifier, then 2413 /// assume the identifier is a member of a dependent base class. We can only 2414 /// recover successfully in static methods, instance methods, and other contexts 2415 /// where 'this' is available. This doesn't precisely match MSVC's 2416 /// instantiation model, but it's close enough. 2417 static Expr * 2418 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2419 DeclarationNameInfo &NameInfo, 2420 SourceLocation TemplateKWLoc, 2421 const TemplateArgumentListInfo *TemplateArgs) { 2422 // Only try to recover from lookup into dependent bases in static methods or 2423 // contexts where 'this' is available. 2424 QualType ThisType = S.getCurrentThisType(); 2425 const CXXRecordDecl *RD = nullptr; 2426 if (!ThisType.isNull()) 2427 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2428 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2429 RD = MD->getParent(); 2430 if (!RD || !RD->hasAnyDependentBases()) 2431 return nullptr; 2432 2433 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2434 // is available, suggest inserting 'this->' as a fixit. 2435 SourceLocation Loc = NameInfo.getLoc(); 2436 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2437 DB << NameInfo.getName() << RD; 2438 2439 if (!ThisType.isNull()) { 2440 DB << FixItHint::CreateInsertion(Loc, "this->"); 2441 return CXXDependentScopeMemberExpr::Create( 2442 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2443 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2444 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2445 } 2446 2447 // Synthesize a fake NNS that points to the derived class. This will 2448 // perform name lookup during template instantiation. 2449 CXXScopeSpec SS; 2450 auto *NNS = 2451 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2452 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2453 return DependentScopeDeclRefExpr::Create( 2454 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2455 TemplateArgs); 2456 } 2457 2458 ExprResult 2459 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2460 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2461 bool HasTrailingLParen, bool IsAddressOfOperand, 2462 CorrectionCandidateCallback *CCC, 2463 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2464 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2465 "cannot be direct & operand and have a trailing lparen"); 2466 if (SS.isInvalid()) 2467 return ExprError(); 2468 2469 TemplateArgumentListInfo TemplateArgsBuffer; 2470 2471 // Decompose the UnqualifiedId into the following data. 2472 DeclarationNameInfo NameInfo; 2473 const TemplateArgumentListInfo *TemplateArgs; 2474 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2475 2476 DeclarationName Name = NameInfo.getName(); 2477 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2478 SourceLocation NameLoc = NameInfo.getLoc(); 2479 2480 if (II && II->isEditorPlaceholder()) { 2481 // FIXME: When typed placeholders are supported we can create a typed 2482 // placeholder expression node. 2483 return ExprError(); 2484 } 2485 2486 // C++ [temp.dep.expr]p3: 2487 // An id-expression is type-dependent if it contains: 2488 // -- an identifier that was declared with a dependent type, 2489 // (note: handled after lookup) 2490 // -- a template-id that is dependent, 2491 // (note: handled in BuildTemplateIdExpr) 2492 // -- a conversion-function-id that specifies a dependent type, 2493 // -- a nested-name-specifier that contains a class-name that 2494 // names a dependent type. 2495 // Determine whether this is a member of an unknown specialization; 2496 // we need to handle these differently. 2497 bool DependentID = false; 2498 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2499 Name.getCXXNameType()->isDependentType()) { 2500 DependentID = true; 2501 } else if (SS.isSet()) { 2502 if (DeclContext *DC = computeDeclContext(SS, false)) { 2503 if (RequireCompleteDeclContext(SS, DC)) 2504 return ExprError(); 2505 } else { 2506 DependentID = true; 2507 } 2508 } 2509 2510 if (DependentID) 2511 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2512 IsAddressOfOperand, TemplateArgs); 2513 2514 // Perform the required lookup. 2515 LookupResult R(*this, NameInfo, 2516 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2517 ? LookupObjCImplicitSelfParam 2518 : LookupOrdinaryName); 2519 if (TemplateKWLoc.isValid() || TemplateArgs) { 2520 // Lookup the template name again to correctly establish the context in 2521 // which it was found. This is really unfortunate as we already did the 2522 // lookup to determine that it was a template name in the first place. If 2523 // this becomes a performance hit, we can work harder to preserve those 2524 // results until we get here but it's likely not worth it. 2525 bool MemberOfUnknownSpecialization; 2526 AssumedTemplateKind AssumedTemplate; 2527 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2528 MemberOfUnknownSpecialization, TemplateKWLoc, 2529 &AssumedTemplate)) 2530 return ExprError(); 2531 2532 if (MemberOfUnknownSpecialization || 2533 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2534 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2535 IsAddressOfOperand, TemplateArgs); 2536 } else { 2537 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2538 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2539 2540 // If the result might be in a dependent base class, this is a dependent 2541 // id-expression. 2542 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2543 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2544 IsAddressOfOperand, TemplateArgs); 2545 2546 // If this reference is in an Objective-C method, then we need to do 2547 // some special Objective-C lookup, too. 2548 if (IvarLookupFollowUp) { 2549 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2550 if (E.isInvalid()) 2551 return ExprError(); 2552 2553 if (Expr *Ex = E.getAs<Expr>()) 2554 return Ex; 2555 } 2556 } 2557 2558 if (R.isAmbiguous()) 2559 return ExprError(); 2560 2561 // This could be an implicitly declared function reference (legal in C90, 2562 // extension in C99, forbidden in C++). 2563 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2564 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2565 if (D) R.addDecl(D); 2566 } 2567 2568 // Determine whether this name might be a candidate for 2569 // argument-dependent lookup. 2570 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2571 2572 if (R.empty() && !ADL) { 2573 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2574 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2575 TemplateKWLoc, TemplateArgs)) 2576 return E; 2577 } 2578 2579 // Don't diagnose an empty lookup for inline assembly. 2580 if (IsInlineAsmIdentifier) 2581 return ExprError(); 2582 2583 // If this name wasn't predeclared and if this is not a function 2584 // call, diagnose the problem. 2585 TypoExpr *TE = nullptr; 2586 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2587 : nullptr); 2588 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2589 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2590 "Typo correction callback misconfigured"); 2591 if (CCC) { 2592 // Make sure the callback knows what the typo being diagnosed is. 2593 CCC->setTypoName(II); 2594 if (SS.isValid()) 2595 CCC->setTypoNNS(SS.getScopeRep()); 2596 } 2597 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2598 // a template name, but we happen to have always already looked up the name 2599 // before we get here if it must be a template name. 2600 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2601 None, &TE)) { 2602 if (TE && KeywordReplacement) { 2603 auto &State = getTypoExprState(TE); 2604 auto BestTC = State.Consumer->getNextCorrection(); 2605 if (BestTC.isKeyword()) { 2606 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2607 if (State.DiagHandler) 2608 State.DiagHandler(BestTC); 2609 KeywordReplacement->startToken(); 2610 KeywordReplacement->setKind(II->getTokenID()); 2611 KeywordReplacement->setIdentifierInfo(II); 2612 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2613 // Clean up the state associated with the TypoExpr, since it has 2614 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2615 clearDelayedTypo(TE); 2616 // Signal that a correction to a keyword was performed by returning a 2617 // valid-but-null ExprResult. 2618 return (Expr*)nullptr; 2619 } 2620 State.Consumer->resetCorrectionStream(); 2621 } 2622 return TE ? TE : ExprError(); 2623 } 2624 2625 assert(!R.empty() && 2626 "DiagnoseEmptyLookup returned false but added no results"); 2627 2628 // If we found an Objective-C instance variable, let 2629 // LookupInObjCMethod build the appropriate expression to 2630 // reference the ivar. 2631 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2632 R.clear(); 2633 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2634 // In a hopelessly buggy code, Objective-C instance variable 2635 // lookup fails and no expression will be built to reference it. 2636 if (!E.isInvalid() && !E.get()) 2637 return ExprError(); 2638 return E; 2639 } 2640 } 2641 2642 // This is guaranteed from this point on. 2643 assert(!R.empty() || ADL); 2644 2645 // Check whether this might be a C++ implicit instance member access. 2646 // C++ [class.mfct.non-static]p3: 2647 // When an id-expression that is not part of a class member access 2648 // syntax and not used to form a pointer to member is used in the 2649 // body of a non-static member function of class X, if name lookup 2650 // resolves the name in the id-expression to a non-static non-type 2651 // member of some class C, the id-expression is transformed into a 2652 // class member access expression using (*this) as the 2653 // postfix-expression to the left of the . operator. 2654 // 2655 // But we don't actually need to do this for '&' operands if R 2656 // resolved to a function or overloaded function set, because the 2657 // expression is ill-formed if it actually works out to be a 2658 // non-static member function: 2659 // 2660 // C++ [expr.ref]p4: 2661 // Otherwise, if E1.E2 refers to a non-static member function. . . 2662 // [t]he expression can be used only as the left-hand operand of a 2663 // member function call. 2664 // 2665 // There are other safeguards against such uses, but it's important 2666 // to get this right here so that we don't end up making a 2667 // spuriously dependent expression if we're inside a dependent 2668 // instance method. 2669 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2670 bool MightBeImplicitMember; 2671 if (!IsAddressOfOperand) 2672 MightBeImplicitMember = true; 2673 else if (!SS.isEmpty()) 2674 MightBeImplicitMember = false; 2675 else if (R.isOverloadedResult()) 2676 MightBeImplicitMember = false; 2677 else if (R.isUnresolvableResult()) 2678 MightBeImplicitMember = true; 2679 else 2680 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2681 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2682 isa<MSPropertyDecl>(R.getFoundDecl()); 2683 2684 if (MightBeImplicitMember) 2685 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2686 R, TemplateArgs, S); 2687 } 2688 2689 if (TemplateArgs || TemplateKWLoc.isValid()) { 2690 2691 // In C++1y, if this is a variable template id, then check it 2692 // in BuildTemplateIdExpr(). 2693 // The single lookup result must be a variable template declaration. 2694 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2695 Id.TemplateId->Kind == TNK_Var_template) { 2696 assert(R.getAsSingle<VarTemplateDecl>() && 2697 "There should only be one declaration found."); 2698 } 2699 2700 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2701 } 2702 2703 return BuildDeclarationNameExpr(SS, R, ADL); 2704 } 2705 2706 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2707 /// declaration name, generally during template instantiation. 2708 /// There's a large number of things which don't need to be done along 2709 /// this path. 2710 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2711 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2712 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2713 DeclContext *DC = computeDeclContext(SS, false); 2714 if (!DC) 2715 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2716 NameInfo, /*TemplateArgs=*/nullptr); 2717 2718 if (RequireCompleteDeclContext(SS, DC)) 2719 return ExprError(); 2720 2721 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2722 LookupQualifiedName(R, DC); 2723 2724 if (R.isAmbiguous()) 2725 return ExprError(); 2726 2727 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2728 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2729 NameInfo, /*TemplateArgs=*/nullptr); 2730 2731 if (R.empty()) { 2732 // Don't diagnose problems with invalid record decl, the secondary no_member 2733 // diagnostic during template instantiation is likely bogus, e.g. if a class 2734 // is invalid because it's derived from an invalid base class, then missing 2735 // members were likely supposed to be inherited. 2736 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2737 if (CD->isInvalidDecl()) 2738 return ExprError(); 2739 Diag(NameInfo.getLoc(), diag::err_no_member) 2740 << NameInfo.getName() << DC << SS.getRange(); 2741 return ExprError(); 2742 } 2743 2744 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2745 // Diagnose a missing typename if this resolved unambiguously to a type in 2746 // a dependent context. If we can recover with a type, downgrade this to 2747 // a warning in Microsoft compatibility mode. 2748 unsigned DiagID = diag::err_typename_missing; 2749 if (RecoveryTSI && getLangOpts().MSVCCompat) 2750 DiagID = diag::ext_typename_missing; 2751 SourceLocation Loc = SS.getBeginLoc(); 2752 auto D = Diag(Loc, DiagID); 2753 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2754 << SourceRange(Loc, NameInfo.getEndLoc()); 2755 2756 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2757 // context. 2758 if (!RecoveryTSI) 2759 return ExprError(); 2760 2761 // Only issue the fixit if we're prepared to recover. 2762 D << FixItHint::CreateInsertion(Loc, "typename "); 2763 2764 // Recover by pretending this was an elaborated type. 2765 QualType Ty = Context.getTypeDeclType(TD); 2766 TypeLocBuilder TLB; 2767 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2768 2769 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2770 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2771 QTL.setElaboratedKeywordLoc(SourceLocation()); 2772 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2773 2774 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2775 2776 return ExprEmpty(); 2777 } 2778 2779 // Defend against this resolving to an implicit member access. We usually 2780 // won't get here if this might be a legitimate a class member (we end up in 2781 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2782 // a pointer-to-member or in an unevaluated context in C++11. 2783 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2784 return BuildPossibleImplicitMemberExpr(SS, 2785 /*TemplateKWLoc=*/SourceLocation(), 2786 R, /*TemplateArgs=*/nullptr, S); 2787 2788 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2789 } 2790 2791 /// The parser has read a name in, and Sema has detected that we're currently 2792 /// inside an ObjC method. Perform some additional checks and determine if we 2793 /// should form a reference to an ivar. 2794 /// 2795 /// Ideally, most of this would be done by lookup, but there's 2796 /// actually quite a lot of extra work involved. 2797 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2798 IdentifierInfo *II) { 2799 SourceLocation Loc = Lookup.getNameLoc(); 2800 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2801 2802 // Check for error condition which is already reported. 2803 if (!CurMethod) 2804 return DeclResult(true); 2805 2806 // There are two cases to handle here. 1) scoped lookup could have failed, 2807 // in which case we should look for an ivar. 2) scoped lookup could have 2808 // found a decl, but that decl is outside the current instance method (i.e. 2809 // a global variable). In these two cases, we do a lookup for an ivar with 2810 // this name, if the lookup sucedes, we replace it our current decl. 2811 2812 // If we're in a class method, we don't normally want to look for 2813 // ivars. But if we don't find anything else, and there's an 2814 // ivar, that's an error. 2815 bool IsClassMethod = CurMethod->isClassMethod(); 2816 2817 bool LookForIvars; 2818 if (Lookup.empty()) 2819 LookForIvars = true; 2820 else if (IsClassMethod) 2821 LookForIvars = false; 2822 else 2823 LookForIvars = (Lookup.isSingleResult() && 2824 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2825 ObjCInterfaceDecl *IFace = nullptr; 2826 if (LookForIvars) { 2827 IFace = CurMethod->getClassInterface(); 2828 ObjCInterfaceDecl *ClassDeclared; 2829 ObjCIvarDecl *IV = nullptr; 2830 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2831 // Diagnose using an ivar in a class method. 2832 if (IsClassMethod) { 2833 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2834 return DeclResult(true); 2835 } 2836 2837 // Diagnose the use of an ivar outside of the declaring class. 2838 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2839 !declaresSameEntity(ClassDeclared, IFace) && 2840 !getLangOpts().DebuggerSupport) 2841 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2842 2843 // Success. 2844 return IV; 2845 } 2846 } else if (CurMethod->isInstanceMethod()) { 2847 // We should warn if a local variable hides an ivar. 2848 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2849 ObjCInterfaceDecl *ClassDeclared; 2850 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2851 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2852 declaresSameEntity(IFace, ClassDeclared)) 2853 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2854 } 2855 } 2856 } else if (Lookup.isSingleResult() && 2857 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2858 // If accessing a stand-alone ivar in a class method, this is an error. 2859 if (const ObjCIvarDecl *IV = 2860 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2861 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2862 return DeclResult(true); 2863 } 2864 } 2865 2866 // Didn't encounter an error, didn't find an ivar. 2867 return DeclResult(false); 2868 } 2869 2870 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2871 ObjCIvarDecl *IV) { 2872 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2873 assert(CurMethod && CurMethod->isInstanceMethod() && 2874 "should not reference ivar from this context"); 2875 2876 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2877 assert(IFace && "should not reference ivar from this context"); 2878 2879 // If we're referencing an invalid decl, just return this as a silent 2880 // error node. The error diagnostic was already emitted on the decl. 2881 if (IV->isInvalidDecl()) 2882 return ExprError(); 2883 2884 // Check if referencing a field with __attribute__((deprecated)). 2885 if (DiagnoseUseOfDecl(IV, Loc)) 2886 return ExprError(); 2887 2888 // FIXME: This should use a new expr for a direct reference, don't 2889 // turn this into Self->ivar, just return a BareIVarExpr or something. 2890 IdentifierInfo &II = Context.Idents.get("self"); 2891 UnqualifiedId SelfName; 2892 SelfName.setImplicitSelfParam(&II); 2893 CXXScopeSpec SelfScopeSpec; 2894 SourceLocation TemplateKWLoc; 2895 ExprResult SelfExpr = 2896 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2897 /*HasTrailingLParen=*/false, 2898 /*IsAddressOfOperand=*/false); 2899 if (SelfExpr.isInvalid()) 2900 return ExprError(); 2901 2902 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2903 if (SelfExpr.isInvalid()) 2904 return ExprError(); 2905 2906 MarkAnyDeclReferenced(Loc, IV, true); 2907 2908 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2909 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2910 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2911 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2912 2913 ObjCIvarRefExpr *Result = new (Context) 2914 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2915 IV->getLocation(), SelfExpr.get(), true, true); 2916 2917 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2918 if (!isUnevaluatedContext() && 2919 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2920 getCurFunction()->recordUseOfWeak(Result); 2921 } 2922 if (getLangOpts().ObjCAutoRefCount) 2923 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2924 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2925 2926 return Result; 2927 } 2928 2929 /// The parser has read a name in, and Sema has detected that we're currently 2930 /// inside an ObjC method. Perform some additional checks and determine if we 2931 /// should form a reference to an ivar. If so, build an expression referencing 2932 /// that ivar. 2933 ExprResult 2934 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2935 IdentifierInfo *II, bool AllowBuiltinCreation) { 2936 // FIXME: Integrate this lookup step into LookupParsedName. 2937 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2938 if (Ivar.isInvalid()) 2939 return ExprError(); 2940 if (Ivar.isUsable()) 2941 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2942 cast<ObjCIvarDecl>(Ivar.get())); 2943 2944 if (Lookup.empty() && II && AllowBuiltinCreation) 2945 LookupBuiltin(Lookup); 2946 2947 // Sentinel value saying that we didn't do anything special. 2948 return ExprResult(false); 2949 } 2950 2951 /// Cast a base object to a member's actual type. 2952 /// 2953 /// There are two relevant checks: 2954 /// 2955 /// C++ [class.access.base]p7: 2956 /// 2957 /// If a class member access operator [...] is used to access a non-static 2958 /// data member or non-static member function, the reference is ill-formed if 2959 /// the left operand [...] cannot be implicitly converted to a pointer to the 2960 /// naming class of the right operand. 2961 /// 2962 /// C++ [expr.ref]p7: 2963 /// 2964 /// If E2 is a non-static data member or a non-static member function, the 2965 /// program is ill-formed if the class of which E2 is directly a member is an 2966 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2967 /// 2968 /// Note that the latter check does not consider access; the access of the 2969 /// "real" base class is checked as appropriate when checking the access of the 2970 /// member name. 2971 ExprResult 2972 Sema::PerformObjectMemberConversion(Expr *From, 2973 NestedNameSpecifier *Qualifier, 2974 NamedDecl *FoundDecl, 2975 NamedDecl *Member) { 2976 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2977 if (!RD) 2978 return From; 2979 2980 QualType DestRecordType; 2981 QualType DestType; 2982 QualType FromRecordType; 2983 QualType FromType = From->getType(); 2984 bool PointerConversions = false; 2985 if (isa<FieldDecl>(Member)) { 2986 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2987 auto FromPtrType = FromType->getAs<PointerType>(); 2988 DestRecordType = Context.getAddrSpaceQualType( 2989 DestRecordType, FromPtrType 2990 ? FromType->getPointeeType().getAddressSpace() 2991 : FromType.getAddressSpace()); 2992 2993 if (FromPtrType) { 2994 DestType = Context.getPointerType(DestRecordType); 2995 FromRecordType = FromPtrType->getPointeeType(); 2996 PointerConversions = true; 2997 } else { 2998 DestType = DestRecordType; 2999 FromRecordType = FromType; 3000 } 3001 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 3002 if (Method->isStatic()) 3003 return From; 3004 3005 DestType = Method->getThisType(); 3006 DestRecordType = DestType->getPointeeType(); 3007 3008 if (FromType->getAs<PointerType>()) { 3009 FromRecordType = FromType->getPointeeType(); 3010 PointerConversions = true; 3011 } else { 3012 FromRecordType = FromType; 3013 DestType = DestRecordType; 3014 } 3015 3016 LangAS FromAS = FromRecordType.getAddressSpace(); 3017 LangAS DestAS = DestRecordType.getAddressSpace(); 3018 if (FromAS != DestAS) { 3019 QualType FromRecordTypeWithoutAS = 3020 Context.removeAddrSpaceQualType(FromRecordType); 3021 QualType FromTypeWithDestAS = 3022 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3023 if (PointerConversions) 3024 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3025 From = ImpCastExprToType(From, FromTypeWithDestAS, 3026 CK_AddressSpaceConversion, From->getValueKind()) 3027 .get(); 3028 } 3029 } else { 3030 // No conversion necessary. 3031 return From; 3032 } 3033 3034 if (DestType->isDependentType() || FromType->isDependentType()) 3035 return From; 3036 3037 // If the unqualified types are the same, no conversion is necessary. 3038 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3039 return From; 3040 3041 SourceRange FromRange = From->getSourceRange(); 3042 SourceLocation FromLoc = FromRange.getBegin(); 3043 3044 ExprValueKind VK = From->getValueKind(); 3045 3046 // C++ [class.member.lookup]p8: 3047 // [...] Ambiguities can often be resolved by qualifying a name with its 3048 // class name. 3049 // 3050 // If the member was a qualified name and the qualified referred to a 3051 // specific base subobject type, we'll cast to that intermediate type 3052 // first and then to the object in which the member is declared. That allows 3053 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3054 // 3055 // class Base { public: int x; }; 3056 // class Derived1 : public Base { }; 3057 // class Derived2 : public Base { }; 3058 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3059 // 3060 // void VeryDerived::f() { 3061 // x = 17; // error: ambiguous base subobjects 3062 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3063 // } 3064 if (Qualifier && Qualifier->getAsType()) { 3065 QualType QType = QualType(Qualifier->getAsType(), 0); 3066 assert(QType->isRecordType() && "lookup done with non-record type"); 3067 3068 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3069 3070 // In C++98, the qualifier type doesn't actually have to be a base 3071 // type of the object type, in which case we just ignore it. 3072 // Otherwise build the appropriate casts. 3073 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3074 CXXCastPath BasePath; 3075 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3076 FromLoc, FromRange, &BasePath)) 3077 return ExprError(); 3078 3079 if (PointerConversions) 3080 QType = Context.getPointerType(QType); 3081 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3082 VK, &BasePath).get(); 3083 3084 FromType = QType; 3085 FromRecordType = QRecordType; 3086 3087 // If the qualifier type was the same as the destination type, 3088 // we're done. 3089 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3090 return From; 3091 } 3092 } 3093 3094 CXXCastPath BasePath; 3095 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3096 FromLoc, FromRange, &BasePath, 3097 /*IgnoreAccess=*/true)) 3098 return ExprError(); 3099 3100 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3101 VK, &BasePath); 3102 } 3103 3104 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3105 const LookupResult &R, 3106 bool HasTrailingLParen) { 3107 // Only when used directly as the postfix-expression of a call. 3108 if (!HasTrailingLParen) 3109 return false; 3110 3111 // Never if a scope specifier was provided. 3112 if (SS.isSet()) 3113 return false; 3114 3115 // Only in C++ or ObjC++. 3116 if (!getLangOpts().CPlusPlus) 3117 return false; 3118 3119 // Turn off ADL when we find certain kinds of declarations during 3120 // normal lookup: 3121 for (NamedDecl *D : R) { 3122 // C++0x [basic.lookup.argdep]p3: 3123 // -- a declaration of a class member 3124 // Since using decls preserve this property, we check this on the 3125 // original decl. 3126 if (D->isCXXClassMember()) 3127 return false; 3128 3129 // C++0x [basic.lookup.argdep]p3: 3130 // -- a block-scope function declaration that is not a 3131 // using-declaration 3132 // NOTE: we also trigger this for function templates (in fact, we 3133 // don't check the decl type at all, since all other decl types 3134 // turn off ADL anyway). 3135 if (isa<UsingShadowDecl>(D)) 3136 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3137 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3138 return false; 3139 3140 // C++0x [basic.lookup.argdep]p3: 3141 // -- a declaration that is neither a function or a function 3142 // template 3143 // And also for builtin functions. 3144 if (isa<FunctionDecl>(D)) { 3145 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3146 3147 // But also builtin functions. 3148 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3149 return false; 3150 } else if (!isa<FunctionTemplateDecl>(D)) 3151 return false; 3152 } 3153 3154 return true; 3155 } 3156 3157 3158 /// Diagnoses obvious problems with the use of the given declaration 3159 /// as an expression. This is only actually called for lookups that 3160 /// were not overloaded, and it doesn't promise that the declaration 3161 /// will in fact be used. 3162 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3163 if (D->isInvalidDecl()) 3164 return true; 3165 3166 if (isa<TypedefNameDecl>(D)) { 3167 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3168 return true; 3169 } 3170 3171 if (isa<ObjCInterfaceDecl>(D)) { 3172 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3173 return true; 3174 } 3175 3176 if (isa<NamespaceDecl>(D)) { 3177 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3178 return true; 3179 } 3180 3181 return false; 3182 } 3183 3184 // Certain multiversion types should be treated as overloaded even when there is 3185 // only one result. 3186 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3187 assert(R.isSingleResult() && "Expected only a single result"); 3188 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3189 return FD && 3190 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3191 } 3192 3193 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3194 LookupResult &R, bool NeedsADL, 3195 bool AcceptInvalidDecl) { 3196 // If this is a single, fully-resolved result and we don't need ADL, 3197 // just build an ordinary singleton decl ref. 3198 if (!NeedsADL && R.isSingleResult() && 3199 !R.getAsSingle<FunctionTemplateDecl>() && 3200 !ShouldLookupResultBeMultiVersionOverload(R)) 3201 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3202 R.getRepresentativeDecl(), nullptr, 3203 AcceptInvalidDecl); 3204 3205 // We only need to check the declaration if there's exactly one 3206 // result, because in the overloaded case the results can only be 3207 // functions and function templates. 3208 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3209 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3210 return ExprError(); 3211 3212 // Otherwise, just build an unresolved lookup expression. Suppress 3213 // any lookup-related diagnostics; we'll hash these out later, when 3214 // we've picked a target. 3215 R.suppressDiagnostics(); 3216 3217 UnresolvedLookupExpr *ULE 3218 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3219 SS.getWithLocInContext(Context), 3220 R.getLookupNameInfo(), 3221 NeedsADL, R.isOverloadedResult(), 3222 R.begin(), R.end()); 3223 3224 return ULE; 3225 } 3226 3227 static void 3228 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3229 ValueDecl *var, DeclContext *DC); 3230 3231 /// Complete semantic analysis for a reference to the given declaration. 3232 ExprResult Sema::BuildDeclarationNameExpr( 3233 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3234 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3235 bool AcceptInvalidDecl) { 3236 assert(D && "Cannot refer to a NULL declaration"); 3237 assert(!isa<FunctionTemplateDecl>(D) && 3238 "Cannot refer unambiguously to a function template"); 3239 3240 SourceLocation Loc = NameInfo.getLoc(); 3241 if (CheckDeclInExpr(*this, Loc, D)) 3242 return ExprError(); 3243 3244 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3245 // Specifically diagnose references to class templates that are missing 3246 // a template argument list. 3247 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3248 return ExprError(); 3249 } 3250 3251 // Make sure that we're referring to a value. 3252 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3253 Diag(Loc, diag::err_ref_non_value) 3254 << D << SS.getRange(); 3255 Diag(D->getLocation(), diag::note_declared_at); 3256 return ExprError(); 3257 } 3258 3259 // Check whether this declaration can be used. Note that we suppress 3260 // this check when we're going to perform argument-dependent lookup 3261 // on this function name, because this might not be the function 3262 // that overload resolution actually selects. 3263 if (DiagnoseUseOfDecl(D, Loc)) 3264 return ExprError(); 3265 3266 auto *VD = cast<ValueDecl>(D); 3267 3268 // Only create DeclRefExpr's for valid Decl's. 3269 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3270 return ExprError(); 3271 3272 // Handle members of anonymous structs and unions. If we got here, 3273 // and the reference is to a class member indirect field, then this 3274 // must be the subject of a pointer-to-member expression. 3275 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3276 if (!indirectField->isCXXClassMember()) 3277 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3278 indirectField); 3279 3280 { 3281 QualType type = VD->getType(); 3282 if (type.isNull()) 3283 return ExprError(); 3284 ExprValueKind valueKind = VK_PRValue; 3285 3286 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3287 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3288 // is expanded by some outer '...' in the context of the use. 3289 type = type.getNonPackExpansionType(); 3290 3291 switch (D->getKind()) { 3292 // Ignore all the non-ValueDecl kinds. 3293 #define ABSTRACT_DECL(kind) 3294 #define VALUE(type, base) 3295 #define DECL(type, base) \ 3296 case Decl::type: 3297 #include "clang/AST/DeclNodes.inc" 3298 llvm_unreachable("invalid value decl kind"); 3299 3300 // These shouldn't make it here. 3301 case Decl::ObjCAtDefsField: 3302 llvm_unreachable("forming non-member reference to ivar?"); 3303 3304 // Enum constants are always r-values and never references. 3305 // Unresolved using declarations are dependent. 3306 case Decl::EnumConstant: 3307 case Decl::UnresolvedUsingValue: 3308 case Decl::OMPDeclareReduction: 3309 case Decl::OMPDeclareMapper: 3310 valueKind = VK_PRValue; 3311 break; 3312 3313 // Fields and indirect fields that got here must be for 3314 // pointer-to-member expressions; we just call them l-values for 3315 // internal consistency, because this subexpression doesn't really 3316 // exist in the high-level semantics. 3317 case Decl::Field: 3318 case Decl::IndirectField: 3319 case Decl::ObjCIvar: 3320 assert(getLangOpts().CPlusPlus && 3321 "building reference to field in C?"); 3322 3323 // These can't have reference type in well-formed programs, but 3324 // for internal consistency we do this anyway. 3325 type = type.getNonReferenceType(); 3326 valueKind = VK_LValue; 3327 break; 3328 3329 // Non-type template parameters are either l-values or r-values 3330 // depending on the type. 3331 case Decl::NonTypeTemplateParm: { 3332 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3333 type = reftype->getPointeeType(); 3334 valueKind = VK_LValue; // even if the parameter is an r-value reference 3335 break; 3336 } 3337 3338 // [expr.prim.id.unqual]p2: 3339 // If the entity is a template parameter object for a template 3340 // parameter of type T, the type of the expression is const T. 3341 // [...] The expression is an lvalue if the entity is a [...] template 3342 // parameter object. 3343 if (type->isRecordType()) { 3344 type = type.getUnqualifiedType().withConst(); 3345 valueKind = VK_LValue; 3346 break; 3347 } 3348 3349 // For non-references, we need to strip qualifiers just in case 3350 // the template parameter was declared as 'const int' or whatever. 3351 valueKind = VK_PRValue; 3352 type = type.getUnqualifiedType(); 3353 break; 3354 } 3355 3356 case Decl::Var: 3357 case Decl::VarTemplateSpecialization: 3358 case Decl::VarTemplatePartialSpecialization: 3359 case Decl::Decomposition: 3360 case Decl::OMPCapturedExpr: 3361 // In C, "extern void blah;" is valid and is an r-value. 3362 if (!getLangOpts().CPlusPlus && 3363 !type.hasQualifiers() && 3364 type->isVoidType()) { 3365 valueKind = VK_PRValue; 3366 break; 3367 } 3368 LLVM_FALLTHROUGH; 3369 3370 case Decl::ImplicitParam: 3371 case Decl::ParmVar: { 3372 // These are always l-values. 3373 valueKind = VK_LValue; 3374 type = type.getNonReferenceType(); 3375 3376 // FIXME: Does the addition of const really only apply in 3377 // potentially-evaluated contexts? Since the variable isn't actually 3378 // captured in an unevaluated context, it seems that the answer is no. 3379 if (!isUnevaluatedContext()) { 3380 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3381 if (!CapturedType.isNull()) 3382 type = CapturedType; 3383 } 3384 3385 break; 3386 } 3387 3388 case Decl::Binding: { 3389 // These are always lvalues. 3390 valueKind = VK_LValue; 3391 type = type.getNonReferenceType(); 3392 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3393 // decides how that's supposed to work. 3394 auto *BD = cast<BindingDecl>(VD); 3395 if (BD->getDeclContext() != CurContext) { 3396 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3397 if (DD && DD->hasLocalStorage()) 3398 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3399 } 3400 break; 3401 } 3402 3403 case Decl::Function: { 3404 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3405 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3406 type = Context.BuiltinFnTy; 3407 valueKind = VK_PRValue; 3408 break; 3409 } 3410 } 3411 3412 const FunctionType *fty = type->castAs<FunctionType>(); 3413 3414 // If we're referring to a function with an __unknown_anytype 3415 // result type, make the entire expression __unknown_anytype. 3416 if (fty->getReturnType() == Context.UnknownAnyTy) { 3417 type = Context.UnknownAnyTy; 3418 valueKind = VK_PRValue; 3419 break; 3420 } 3421 3422 // Functions are l-values in C++. 3423 if (getLangOpts().CPlusPlus) { 3424 valueKind = VK_LValue; 3425 break; 3426 } 3427 3428 // C99 DR 316 says that, if a function type comes from a 3429 // function definition (without a prototype), that type is only 3430 // used for checking compatibility. Therefore, when referencing 3431 // the function, we pretend that we don't have the full function 3432 // type. 3433 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3434 isa<FunctionProtoType>(fty)) 3435 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3436 fty->getExtInfo()); 3437 3438 // Functions are r-values in C. 3439 valueKind = VK_PRValue; 3440 break; 3441 } 3442 3443 case Decl::CXXDeductionGuide: 3444 llvm_unreachable("building reference to deduction guide"); 3445 3446 case Decl::MSProperty: 3447 case Decl::MSGuid: 3448 case Decl::TemplateParamObject: 3449 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3450 // capture in OpenMP, or duplicated between host and device? 3451 valueKind = VK_LValue; 3452 break; 3453 3454 case Decl::CXXMethod: 3455 // If we're referring to a method with an __unknown_anytype 3456 // result type, make the entire expression __unknown_anytype. 3457 // This should only be possible with a type written directly. 3458 if (const FunctionProtoType *proto 3459 = dyn_cast<FunctionProtoType>(VD->getType())) 3460 if (proto->getReturnType() == Context.UnknownAnyTy) { 3461 type = Context.UnknownAnyTy; 3462 valueKind = VK_PRValue; 3463 break; 3464 } 3465 3466 // C++ methods are l-values if static, r-values if non-static. 3467 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3468 valueKind = VK_LValue; 3469 break; 3470 } 3471 LLVM_FALLTHROUGH; 3472 3473 case Decl::CXXConversion: 3474 case Decl::CXXDestructor: 3475 case Decl::CXXConstructor: 3476 valueKind = VK_PRValue; 3477 break; 3478 } 3479 3480 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3481 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3482 TemplateArgs); 3483 } 3484 } 3485 3486 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3487 SmallString<32> &Target) { 3488 Target.resize(CharByteWidth * (Source.size() + 1)); 3489 char *ResultPtr = &Target[0]; 3490 const llvm::UTF8 *ErrorPtr; 3491 bool success = 3492 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3493 (void)success; 3494 assert(success); 3495 Target.resize(ResultPtr - &Target[0]); 3496 } 3497 3498 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3499 PredefinedExpr::IdentKind IK) { 3500 // Pick the current block, lambda, captured statement or function. 3501 Decl *currentDecl = nullptr; 3502 if (const BlockScopeInfo *BSI = getCurBlock()) 3503 currentDecl = BSI->TheDecl; 3504 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3505 currentDecl = LSI->CallOperator; 3506 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3507 currentDecl = CSI->TheCapturedDecl; 3508 else 3509 currentDecl = getCurFunctionOrMethodDecl(); 3510 3511 if (!currentDecl) { 3512 Diag(Loc, diag::ext_predef_outside_function); 3513 currentDecl = Context.getTranslationUnitDecl(); 3514 } 3515 3516 QualType ResTy; 3517 StringLiteral *SL = nullptr; 3518 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3519 ResTy = Context.DependentTy; 3520 else { 3521 // Pre-defined identifiers are of type char[x], where x is the length of 3522 // the string. 3523 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3524 unsigned Length = Str.length(); 3525 3526 llvm::APInt LengthI(32, Length + 1); 3527 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3528 ResTy = 3529 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3530 SmallString<32> RawChars; 3531 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3532 Str, RawChars); 3533 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3534 ArrayType::Normal, 3535 /*IndexTypeQuals*/ 0); 3536 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3537 /*Pascal*/ false, ResTy, Loc); 3538 } else { 3539 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3540 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3541 ArrayType::Normal, 3542 /*IndexTypeQuals*/ 0); 3543 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3544 /*Pascal*/ false, ResTy, Loc); 3545 } 3546 } 3547 3548 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3549 } 3550 3551 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3552 SourceLocation LParen, 3553 SourceLocation RParen, 3554 TypeSourceInfo *TSI) { 3555 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3556 } 3557 3558 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3559 SourceLocation LParen, 3560 SourceLocation RParen, 3561 ParsedType ParsedTy) { 3562 TypeSourceInfo *TSI = nullptr; 3563 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3564 3565 if (Ty.isNull()) 3566 return ExprError(); 3567 if (!TSI) 3568 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3569 3570 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3571 } 3572 3573 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3574 PredefinedExpr::IdentKind IK; 3575 3576 switch (Kind) { 3577 default: llvm_unreachable("Unknown simple primary expr!"); 3578 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3579 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3580 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3581 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3582 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3583 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3584 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3585 } 3586 3587 return BuildPredefinedExpr(Loc, IK); 3588 } 3589 3590 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3591 SmallString<16> CharBuffer; 3592 bool Invalid = false; 3593 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3594 if (Invalid) 3595 return ExprError(); 3596 3597 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3598 PP, Tok.getKind()); 3599 if (Literal.hadError()) 3600 return ExprError(); 3601 3602 QualType Ty; 3603 if (Literal.isWide()) 3604 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3605 else if (Literal.isUTF8() && getLangOpts().Char8) 3606 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3607 else if (Literal.isUTF16()) 3608 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3609 else if (Literal.isUTF32()) 3610 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3611 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3612 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3613 else 3614 Ty = Context.CharTy; // 'x' -> char in C++ 3615 3616 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3617 if (Literal.isWide()) 3618 Kind = CharacterLiteral::Wide; 3619 else if (Literal.isUTF16()) 3620 Kind = CharacterLiteral::UTF16; 3621 else if (Literal.isUTF32()) 3622 Kind = CharacterLiteral::UTF32; 3623 else if (Literal.isUTF8()) 3624 Kind = CharacterLiteral::UTF8; 3625 3626 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3627 Tok.getLocation()); 3628 3629 if (Literal.getUDSuffix().empty()) 3630 return Lit; 3631 3632 // We're building a user-defined literal. 3633 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3634 SourceLocation UDSuffixLoc = 3635 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3636 3637 // Make sure we're allowed user-defined literals here. 3638 if (!UDLScope) 3639 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3640 3641 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3642 // operator "" X (ch) 3643 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3644 Lit, Tok.getLocation()); 3645 } 3646 3647 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3648 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3649 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3650 Context.IntTy, Loc); 3651 } 3652 3653 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3654 QualType Ty, SourceLocation Loc) { 3655 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3656 3657 using llvm::APFloat; 3658 APFloat Val(Format); 3659 3660 APFloat::opStatus result = Literal.GetFloatValue(Val); 3661 3662 // Overflow is always an error, but underflow is only an error if 3663 // we underflowed to zero (APFloat reports denormals as underflow). 3664 if ((result & APFloat::opOverflow) || 3665 ((result & APFloat::opUnderflow) && Val.isZero())) { 3666 unsigned diagnostic; 3667 SmallString<20> buffer; 3668 if (result & APFloat::opOverflow) { 3669 diagnostic = diag::warn_float_overflow; 3670 APFloat::getLargest(Format).toString(buffer); 3671 } else { 3672 diagnostic = diag::warn_float_underflow; 3673 APFloat::getSmallest(Format).toString(buffer); 3674 } 3675 3676 S.Diag(Loc, diagnostic) 3677 << Ty 3678 << StringRef(buffer.data(), buffer.size()); 3679 } 3680 3681 bool isExact = (result == APFloat::opOK); 3682 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3683 } 3684 3685 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3686 assert(E && "Invalid expression"); 3687 3688 if (E->isValueDependent()) 3689 return false; 3690 3691 QualType QT = E->getType(); 3692 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3693 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3694 return true; 3695 } 3696 3697 llvm::APSInt ValueAPS; 3698 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3699 3700 if (R.isInvalid()) 3701 return true; 3702 3703 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3704 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3705 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3706 << toString(ValueAPS, 10) << ValueIsPositive; 3707 return true; 3708 } 3709 3710 return false; 3711 } 3712 3713 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3714 // Fast path for a single digit (which is quite common). A single digit 3715 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3716 if (Tok.getLength() == 1) { 3717 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3718 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3719 } 3720 3721 SmallString<128> SpellingBuffer; 3722 // NumericLiteralParser wants to overread by one character. Add padding to 3723 // the buffer in case the token is copied to the buffer. If getSpelling() 3724 // returns a StringRef to the memory buffer, it should have a null char at 3725 // the EOF, so it is also safe. 3726 SpellingBuffer.resize(Tok.getLength() + 1); 3727 3728 // Get the spelling of the token, which eliminates trigraphs, etc. 3729 bool Invalid = false; 3730 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3731 if (Invalid) 3732 return ExprError(); 3733 3734 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3735 PP.getSourceManager(), PP.getLangOpts(), 3736 PP.getTargetInfo(), PP.getDiagnostics()); 3737 if (Literal.hadError) 3738 return ExprError(); 3739 3740 if (Literal.hasUDSuffix()) { 3741 // We're building a user-defined literal. 3742 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3743 SourceLocation UDSuffixLoc = 3744 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3745 3746 // Make sure we're allowed user-defined literals here. 3747 if (!UDLScope) 3748 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3749 3750 QualType CookedTy; 3751 if (Literal.isFloatingLiteral()) { 3752 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3753 // long double, the literal is treated as a call of the form 3754 // operator "" X (f L) 3755 CookedTy = Context.LongDoubleTy; 3756 } else { 3757 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3758 // unsigned long long, the literal is treated as a call of the form 3759 // operator "" X (n ULL) 3760 CookedTy = Context.UnsignedLongLongTy; 3761 } 3762 3763 DeclarationName OpName = 3764 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3765 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3766 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3767 3768 SourceLocation TokLoc = Tok.getLocation(); 3769 3770 // Perform literal operator lookup to determine if we're building a raw 3771 // literal or a cooked one. 3772 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3773 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3774 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3775 /*AllowStringTemplatePack*/ false, 3776 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3777 case LOLR_ErrorNoDiagnostic: 3778 // Lookup failure for imaginary constants isn't fatal, there's still the 3779 // GNU extension producing _Complex types. 3780 break; 3781 case LOLR_Error: 3782 return ExprError(); 3783 case LOLR_Cooked: { 3784 Expr *Lit; 3785 if (Literal.isFloatingLiteral()) { 3786 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3787 } else { 3788 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3789 if (Literal.GetIntegerValue(ResultVal)) 3790 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3791 << /* Unsigned */ 1; 3792 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3793 Tok.getLocation()); 3794 } 3795 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3796 } 3797 3798 case LOLR_Raw: { 3799 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3800 // literal is treated as a call of the form 3801 // operator "" X ("n") 3802 unsigned Length = Literal.getUDSuffixOffset(); 3803 QualType StrTy = Context.getConstantArrayType( 3804 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3805 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3806 Expr *Lit = StringLiteral::Create( 3807 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3808 /*Pascal*/false, StrTy, &TokLoc, 1); 3809 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3810 } 3811 3812 case LOLR_Template: { 3813 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3814 // template), L is treated as a call fo the form 3815 // operator "" X <'c1', 'c2', ... 'ck'>() 3816 // where n is the source character sequence c1 c2 ... ck. 3817 TemplateArgumentListInfo ExplicitArgs; 3818 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3819 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3820 llvm::APSInt Value(CharBits, CharIsUnsigned); 3821 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3822 Value = TokSpelling[I]; 3823 TemplateArgument Arg(Context, Value, Context.CharTy); 3824 TemplateArgumentLocInfo ArgInfo; 3825 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3826 } 3827 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3828 &ExplicitArgs); 3829 } 3830 case LOLR_StringTemplatePack: 3831 llvm_unreachable("unexpected literal operator lookup result"); 3832 } 3833 } 3834 3835 Expr *Res; 3836 3837 if (Literal.isFixedPointLiteral()) { 3838 QualType Ty; 3839 3840 if (Literal.isAccum) { 3841 if (Literal.isHalf) { 3842 Ty = Context.ShortAccumTy; 3843 } else if (Literal.isLong) { 3844 Ty = Context.LongAccumTy; 3845 } else { 3846 Ty = Context.AccumTy; 3847 } 3848 } else if (Literal.isFract) { 3849 if (Literal.isHalf) { 3850 Ty = Context.ShortFractTy; 3851 } else if (Literal.isLong) { 3852 Ty = Context.LongFractTy; 3853 } else { 3854 Ty = Context.FractTy; 3855 } 3856 } 3857 3858 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3859 3860 bool isSigned = !Literal.isUnsigned; 3861 unsigned scale = Context.getFixedPointScale(Ty); 3862 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3863 3864 llvm::APInt Val(bit_width, 0, isSigned); 3865 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3866 bool ValIsZero = Val.isNullValue() && !Overflowed; 3867 3868 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3869 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3870 // Clause 6.4.4 - The value of a constant shall be in the range of 3871 // representable values for its type, with exception for constants of a 3872 // fract type with a value of exactly 1; such a constant shall denote 3873 // the maximal value for the type. 3874 --Val; 3875 else if (Val.ugt(MaxVal) || Overflowed) 3876 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3877 3878 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3879 Tok.getLocation(), scale); 3880 } else if (Literal.isFloatingLiteral()) { 3881 QualType Ty; 3882 if (Literal.isHalf){ 3883 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3884 Ty = Context.HalfTy; 3885 else { 3886 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3887 return ExprError(); 3888 } 3889 } else if (Literal.isFloat) 3890 Ty = Context.FloatTy; 3891 else if (Literal.isLong) 3892 Ty = Context.LongDoubleTy; 3893 else if (Literal.isFloat16) 3894 Ty = Context.Float16Ty; 3895 else if (Literal.isFloat128) 3896 Ty = Context.Float128Ty; 3897 else 3898 Ty = Context.DoubleTy; 3899 3900 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3901 3902 if (Ty == Context.DoubleTy) { 3903 if (getLangOpts().SinglePrecisionConstants) { 3904 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3905 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3906 } 3907 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3908 "cl_khr_fp64", getLangOpts())) { 3909 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3910 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3911 << (getLangOpts().OpenCLVersion >= 300); 3912 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3913 } 3914 } 3915 } else if (!Literal.isIntegerLiteral()) { 3916 return ExprError(); 3917 } else { 3918 QualType Ty; 3919 3920 // 'long long' is a C99 or C++11 feature. 3921 if (!getLangOpts().C99 && Literal.isLongLong) { 3922 if (getLangOpts().CPlusPlus) 3923 Diag(Tok.getLocation(), 3924 getLangOpts().CPlusPlus11 ? 3925 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3926 else 3927 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3928 } 3929 3930 // 'z/uz' literals are a C++2b feature. 3931 if (Literal.isSizeT) 3932 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3933 ? getLangOpts().CPlusPlus2b 3934 ? diag::warn_cxx20_compat_size_t_suffix 3935 : diag::ext_cxx2b_size_t_suffix 3936 : diag::err_cxx2b_size_t_suffix); 3937 3938 // Get the value in the widest-possible width. 3939 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3940 llvm::APInt ResultVal(MaxWidth, 0); 3941 3942 if (Literal.GetIntegerValue(ResultVal)) { 3943 // If this value didn't fit into uintmax_t, error and force to ull. 3944 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3945 << /* Unsigned */ 1; 3946 Ty = Context.UnsignedLongLongTy; 3947 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3948 "long long is not intmax_t?"); 3949 } else { 3950 // If this value fits into a ULL, try to figure out what else it fits into 3951 // according to the rules of C99 6.4.4.1p5. 3952 3953 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3954 // be an unsigned int. 3955 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3956 3957 // Check from smallest to largest, picking the smallest type we can. 3958 unsigned Width = 0; 3959 3960 // Microsoft specific integer suffixes are explicitly sized. 3961 if (Literal.MicrosoftInteger) { 3962 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3963 Width = 8; 3964 Ty = Context.CharTy; 3965 } else { 3966 Width = Literal.MicrosoftInteger; 3967 Ty = Context.getIntTypeForBitwidth(Width, 3968 /*Signed=*/!Literal.isUnsigned); 3969 } 3970 } 3971 3972 // Check C++2b size_t literals. 3973 if (Literal.isSizeT) { 3974 assert(!Literal.MicrosoftInteger && 3975 "size_t literals can't be Microsoft literals"); 3976 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3977 Context.getTargetInfo().getSizeType()); 3978 3979 // Does it fit in size_t? 3980 if (ResultVal.isIntN(SizeTSize)) { 3981 // Does it fit in ssize_t? 3982 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3983 Ty = Context.getSignedSizeType(); 3984 else if (AllowUnsigned) 3985 Ty = Context.getSizeType(); 3986 Width = SizeTSize; 3987 } 3988 } 3989 3990 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3991 !Literal.isSizeT) { 3992 // Are int/unsigned possibilities? 3993 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3994 3995 // Does it fit in a unsigned int? 3996 if (ResultVal.isIntN(IntSize)) { 3997 // Does it fit in a signed int? 3998 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3999 Ty = Context.IntTy; 4000 else if (AllowUnsigned) 4001 Ty = Context.UnsignedIntTy; 4002 Width = IntSize; 4003 } 4004 } 4005 4006 // Are long/unsigned long possibilities? 4007 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4008 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4009 4010 // Does it fit in a unsigned long? 4011 if (ResultVal.isIntN(LongSize)) { 4012 // Does it fit in a signed long? 4013 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4014 Ty = Context.LongTy; 4015 else if (AllowUnsigned) 4016 Ty = Context.UnsignedLongTy; 4017 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4018 // is compatible. 4019 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4020 const unsigned LongLongSize = 4021 Context.getTargetInfo().getLongLongWidth(); 4022 Diag(Tok.getLocation(), 4023 getLangOpts().CPlusPlus 4024 ? Literal.isLong 4025 ? diag::warn_old_implicitly_unsigned_long_cxx 4026 : /*C++98 UB*/ diag:: 4027 ext_old_implicitly_unsigned_long_cxx 4028 : diag::warn_old_implicitly_unsigned_long) 4029 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4030 : /*will be ill-formed*/ 1); 4031 Ty = Context.UnsignedLongTy; 4032 } 4033 Width = LongSize; 4034 } 4035 } 4036 4037 // Check long long if needed. 4038 if (Ty.isNull() && !Literal.isSizeT) { 4039 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4040 4041 // Does it fit in a unsigned long long? 4042 if (ResultVal.isIntN(LongLongSize)) { 4043 // Does it fit in a signed long long? 4044 // To be compatible with MSVC, hex integer literals ending with the 4045 // LL or i64 suffix are always signed in Microsoft mode. 4046 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4047 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4048 Ty = Context.LongLongTy; 4049 else if (AllowUnsigned) 4050 Ty = Context.UnsignedLongLongTy; 4051 Width = LongLongSize; 4052 } 4053 } 4054 4055 // If we still couldn't decide a type, we either have 'size_t' literal 4056 // that is out of range, or a decimal literal that does not fit in a 4057 // signed long long and has no U suffix. 4058 if (Ty.isNull()) { 4059 if (Literal.isSizeT) 4060 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4061 << Literal.isUnsigned; 4062 else 4063 Diag(Tok.getLocation(), 4064 diag::ext_integer_literal_too_large_for_signed); 4065 Ty = Context.UnsignedLongLongTy; 4066 Width = Context.getTargetInfo().getLongLongWidth(); 4067 } 4068 4069 if (ResultVal.getBitWidth() != Width) 4070 ResultVal = ResultVal.trunc(Width); 4071 } 4072 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4073 } 4074 4075 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4076 if (Literal.isImaginary) { 4077 Res = new (Context) ImaginaryLiteral(Res, 4078 Context.getComplexType(Res->getType())); 4079 4080 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4081 } 4082 return Res; 4083 } 4084 4085 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4086 assert(E && "ActOnParenExpr() missing expr"); 4087 QualType ExprTy = E->getType(); 4088 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4089 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4090 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4091 return new (Context) ParenExpr(L, R, E); 4092 } 4093 4094 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4095 SourceLocation Loc, 4096 SourceRange ArgRange) { 4097 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4098 // scalar or vector data type argument..." 4099 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4100 // type (C99 6.2.5p18) or void. 4101 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4102 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4103 << T << ArgRange; 4104 return true; 4105 } 4106 4107 assert((T->isVoidType() || !T->isIncompleteType()) && 4108 "Scalar types should always be complete"); 4109 return false; 4110 } 4111 4112 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4113 SourceLocation Loc, 4114 SourceRange ArgRange, 4115 UnaryExprOrTypeTrait TraitKind) { 4116 // Invalid types must be hard errors for SFINAE in C++. 4117 if (S.LangOpts.CPlusPlus) 4118 return true; 4119 4120 // C99 6.5.3.4p1: 4121 if (T->isFunctionType() && 4122 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4123 TraitKind == UETT_PreferredAlignOf)) { 4124 // sizeof(function)/alignof(function) is allowed as an extension. 4125 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4126 << getTraitSpelling(TraitKind) << ArgRange; 4127 return false; 4128 } 4129 4130 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4131 // this is an error (OpenCL v1.1 s6.3.k) 4132 if (T->isVoidType()) { 4133 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4134 : diag::ext_sizeof_alignof_void_type; 4135 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4136 return false; 4137 } 4138 4139 return true; 4140 } 4141 4142 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4143 SourceLocation Loc, 4144 SourceRange ArgRange, 4145 UnaryExprOrTypeTrait TraitKind) { 4146 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4147 // runtime doesn't allow it. 4148 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4149 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4150 << T << (TraitKind == UETT_SizeOf) 4151 << ArgRange; 4152 return true; 4153 } 4154 4155 return false; 4156 } 4157 4158 /// Check whether E is a pointer from a decayed array type (the decayed 4159 /// pointer type is equal to T) and emit a warning if it is. 4160 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4161 Expr *E) { 4162 // Don't warn if the operation changed the type. 4163 if (T != E->getType()) 4164 return; 4165 4166 // Now look for array decays. 4167 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4168 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4169 return; 4170 4171 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4172 << ICE->getType() 4173 << ICE->getSubExpr()->getType(); 4174 } 4175 4176 /// Check the constraints on expression operands to unary type expression 4177 /// and type traits. 4178 /// 4179 /// Completes any types necessary and validates the constraints on the operand 4180 /// expression. The logic mostly mirrors the type-based overload, but may modify 4181 /// the expression as it completes the type for that expression through template 4182 /// instantiation, etc. 4183 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4184 UnaryExprOrTypeTrait ExprKind) { 4185 QualType ExprTy = E->getType(); 4186 assert(!ExprTy->isReferenceType()); 4187 4188 bool IsUnevaluatedOperand = 4189 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4190 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4191 if (IsUnevaluatedOperand) { 4192 ExprResult Result = CheckUnevaluatedOperand(E); 4193 if (Result.isInvalid()) 4194 return true; 4195 E = Result.get(); 4196 } 4197 4198 // The operand for sizeof and alignof is in an unevaluated expression context, 4199 // so side effects could result in unintended consequences. 4200 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4201 // used to build SFINAE gadgets. 4202 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4203 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4204 !E->isInstantiationDependent() && 4205 E->HasSideEffects(Context, false)) 4206 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4207 4208 if (ExprKind == UETT_VecStep) 4209 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4210 E->getSourceRange()); 4211 4212 // Explicitly list some types as extensions. 4213 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4214 E->getSourceRange(), ExprKind)) 4215 return false; 4216 4217 // 'alignof' applied to an expression only requires the base element type of 4218 // the expression to be complete. 'sizeof' requires the expression's type to 4219 // be complete (and will attempt to complete it if it's an array of unknown 4220 // bound). 4221 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4222 if (RequireCompleteSizedType( 4223 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4224 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4225 getTraitSpelling(ExprKind), E->getSourceRange())) 4226 return true; 4227 } else { 4228 if (RequireCompleteSizedExprType( 4229 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4230 getTraitSpelling(ExprKind), E->getSourceRange())) 4231 return true; 4232 } 4233 4234 // Completing the expression's type may have changed it. 4235 ExprTy = E->getType(); 4236 assert(!ExprTy->isReferenceType()); 4237 4238 if (ExprTy->isFunctionType()) { 4239 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4240 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4241 return true; 4242 } 4243 4244 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4245 E->getSourceRange(), ExprKind)) 4246 return true; 4247 4248 if (ExprKind == UETT_SizeOf) { 4249 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4250 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4251 QualType OType = PVD->getOriginalType(); 4252 QualType Type = PVD->getType(); 4253 if (Type->isPointerType() && OType->isArrayType()) { 4254 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4255 << Type << OType; 4256 Diag(PVD->getLocation(), diag::note_declared_at); 4257 } 4258 } 4259 } 4260 4261 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4262 // decays into a pointer and returns an unintended result. This is most 4263 // likely a typo for "sizeof(array) op x". 4264 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4265 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4266 BO->getLHS()); 4267 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4268 BO->getRHS()); 4269 } 4270 } 4271 4272 return false; 4273 } 4274 4275 /// Check the constraints on operands to unary expression and type 4276 /// traits. 4277 /// 4278 /// This will complete any types necessary, and validate the various constraints 4279 /// on those operands. 4280 /// 4281 /// The UsualUnaryConversions() function is *not* called by this routine. 4282 /// C99 6.3.2.1p[2-4] all state: 4283 /// Except when it is the operand of the sizeof operator ... 4284 /// 4285 /// C++ [expr.sizeof]p4 4286 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4287 /// standard conversions are not applied to the operand of sizeof. 4288 /// 4289 /// This policy is followed for all of the unary trait expressions. 4290 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4291 SourceLocation OpLoc, 4292 SourceRange ExprRange, 4293 UnaryExprOrTypeTrait ExprKind) { 4294 if (ExprType->isDependentType()) 4295 return false; 4296 4297 // C++ [expr.sizeof]p2: 4298 // When applied to a reference or a reference type, the result 4299 // is the size of the referenced type. 4300 // C++11 [expr.alignof]p3: 4301 // When alignof is applied to a reference type, the result 4302 // shall be the alignment of the referenced type. 4303 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4304 ExprType = Ref->getPointeeType(); 4305 4306 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4307 // When alignof or _Alignof is applied to an array type, the result 4308 // is the alignment of the element type. 4309 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4310 ExprKind == UETT_OpenMPRequiredSimdAlign) 4311 ExprType = Context.getBaseElementType(ExprType); 4312 4313 if (ExprKind == UETT_VecStep) 4314 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4315 4316 // Explicitly list some types as extensions. 4317 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4318 ExprKind)) 4319 return false; 4320 4321 if (RequireCompleteSizedType( 4322 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4323 getTraitSpelling(ExprKind), ExprRange)) 4324 return true; 4325 4326 if (ExprType->isFunctionType()) { 4327 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4328 << getTraitSpelling(ExprKind) << ExprRange; 4329 return true; 4330 } 4331 4332 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4333 ExprKind)) 4334 return true; 4335 4336 return false; 4337 } 4338 4339 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4340 // Cannot know anything else if the expression is dependent. 4341 if (E->isTypeDependent()) 4342 return false; 4343 4344 if (E->getObjectKind() == OK_BitField) { 4345 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4346 << 1 << E->getSourceRange(); 4347 return true; 4348 } 4349 4350 ValueDecl *D = nullptr; 4351 Expr *Inner = E->IgnoreParens(); 4352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4353 D = DRE->getDecl(); 4354 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4355 D = ME->getMemberDecl(); 4356 } 4357 4358 // If it's a field, require the containing struct to have a 4359 // complete definition so that we can compute the layout. 4360 // 4361 // This can happen in C++11 onwards, either by naming the member 4362 // in a way that is not transformed into a member access expression 4363 // (in an unevaluated operand, for instance), or by naming the member 4364 // in a trailing-return-type. 4365 // 4366 // For the record, since __alignof__ on expressions is a GCC 4367 // extension, GCC seems to permit this but always gives the 4368 // nonsensical answer 0. 4369 // 4370 // We don't really need the layout here --- we could instead just 4371 // directly check for all the appropriate alignment-lowing 4372 // attributes --- but that would require duplicating a lot of 4373 // logic that just isn't worth duplicating for such a marginal 4374 // use-case. 4375 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4376 // Fast path this check, since we at least know the record has a 4377 // definition if we can find a member of it. 4378 if (!FD->getParent()->isCompleteDefinition()) { 4379 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4380 << E->getSourceRange(); 4381 return true; 4382 } 4383 4384 // Otherwise, if it's a field, and the field doesn't have 4385 // reference type, then it must have a complete type (or be a 4386 // flexible array member, which we explicitly want to 4387 // white-list anyway), which makes the following checks trivial. 4388 if (!FD->getType()->isReferenceType()) 4389 return false; 4390 } 4391 4392 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4393 } 4394 4395 bool Sema::CheckVecStepExpr(Expr *E) { 4396 E = E->IgnoreParens(); 4397 4398 // Cannot know anything else if the expression is dependent. 4399 if (E->isTypeDependent()) 4400 return false; 4401 4402 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4403 } 4404 4405 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4406 CapturingScopeInfo *CSI) { 4407 assert(T->isVariablyModifiedType()); 4408 assert(CSI != nullptr); 4409 4410 // We're going to walk down into the type and look for VLA expressions. 4411 do { 4412 const Type *Ty = T.getTypePtr(); 4413 switch (Ty->getTypeClass()) { 4414 #define TYPE(Class, Base) 4415 #define ABSTRACT_TYPE(Class, Base) 4416 #define NON_CANONICAL_TYPE(Class, Base) 4417 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4418 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4419 #include "clang/AST/TypeNodes.inc" 4420 T = QualType(); 4421 break; 4422 // These types are never variably-modified. 4423 case Type::Builtin: 4424 case Type::Complex: 4425 case Type::Vector: 4426 case Type::ExtVector: 4427 case Type::ConstantMatrix: 4428 case Type::Record: 4429 case Type::Enum: 4430 case Type::Elaborated: 4431 case Type::TemplateSpecialization: 4432 case Type::ObjCObject: 4433 case Type::ObjCInterface: 4434 case Type::ObjCObjectPointer: 4435 case Type::ObjCTypeParam: 4436 case Type::Pipe: 4437 case Type::ExtInt: 4438 llvm_unreachable("type class is never variably-modified!"); 4439 case Type::Adjusted: 4440 T = cast<AdjustedType>(Ty)->getOriginalType(); 4441 break; 4442 case Type::Decayed: 4443 T = cast<DecayedType>(Ty)->getPointeeType(); 4444 break; 4445 case Type::Pointer: 4446 T = cast<PointerType>(Ty)->getPointeeType(); 4447 break; 4448 case Type::BlockPointer: 4449 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4450 break; 4451 case Type::LValueReference: 4452 case Type::RValueReference: 4453 T = cast<ReferenceType>(Ty)->getPointeeType(); 4454 break; 4455 case Type::MemberPointer: 4456 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4457 break; 4458 case Type::ConstantArray: 4459 case Type::IncompleteArray: 4460 // Losing element qualification here is fine. 4461 T = cast<ArrayType>(Ty)->getElementType(); 4462 break; 4463 case Type::VariableArray: { 4464 // Losing element qualification here is fine. 4465 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4466 4467 // Unknown size indication requires no size computation. 4468 // Otherwise, evaluate and record it. 4469 auto Size = VAT->getSizeExpr(); 4470 if (Size && !CSI->isVLATypeCaptured(VAT) && 4471 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4472 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4473 4474 T = VAT->getElementType(); 4475 break; 4476 } 4477 case Type::FunctionProto: 4478 case Type::FunctionNoProto: 4479 T = cast<FunctionType>(Ty)->getReturnType(); 4480 break; 4481 case Type::Paren: 4482 case Type::TypeOf: 4483 case Type::UnaryTransform: 4484 case Type::Attributed: 4485 case Type::SubstTemplateTypeParm: 4486 case Type::MacroQualified: 4487 // Keep walking after single level desugaring. 4488 T = T.getSingleStepDesugaredType(Context); 4489 break; 4490 case Type::Typedef: 4491 T = cast<TypedefType>(Ty)->desugar(); 4492 break; 4493 case Type::Decltype: 4494 T = cast<DecltypeType>(Ty)->desugar(); 4495 break; 4496 case Type::Auto: 4497 case Type::DeducedTemplateSpecialization: 4498 T = cast<DeducedType>(Ty)->getDeducedType(); 4499 break; 4500 case Type::TypeOfExpr: 4501 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4502 break; 4503 case Type::Atomic: 4504 T = cast<AtomicType>(Ty)->getValueType(); 4505 break; 4506 } 4507 } while (!T.isNull() && T->isVariablyModifiedType()); 4508 } 4509 4510 /// Build a sizeof or alignof expression given a type operand. 4511 ExprResult 4512 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4513 SourceLocation OpLoc, 4514 UnaryExprOrTypeTrait ExprKind, 4515 SourceRange R) { 4516 if (!TInfo) 4517 return ExprError(); 4518 4519 QualType T = TInfo->getType(); 4520 4521 if (!T->isDependentType() && 4522 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4523 return ExprError(); 4524 4525 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4526 if (auto *TT = T->getAs<TypedefType>()) { 4527 for (auto I = FunctionScopes.rbegin(), 4528 E = std::prev(FunctionScopes.rend()); 4529 I != E; ++I) { 4530 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4531 if (CSI == nullptr) 4532 break; 4533 DeclContext *DC = nullptr; 4534 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4535 DC = LSI->CallOperator; 4536 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4537 DC = CRSI->TheCapturedDecl; 4538 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4539 DC = BSI->TheDecl; 4540 if (DC) { 4541 if (DC->containsDecl(TT->getDecl())) 4542 break; 4543 captureVariablyModifiedType(Context, T, CSI); 4544 } 4545 } 4546 } 4547 } 4548 4549 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4550 return new (Context) UnaryExprOrTypeTraitExpr( 4551 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4552 } 4553 4554 /// Build a sizeof or alignof expression given an expression 4555 /// operand. 4556 ExprResult 4557 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4558 UnaryExprOrTypeTrait ExprKind) { 4559 ExprResult PE = CheckPlaceholderExpr(E); 4560 if (PE.isInvalid()) 4561 return ExprError(); 4562 4563 E = PE.get(); 4564 4565 // Verify that the operand is valid. 4566 bool isInvalid = false; 4567 if (E->isTypeDependent()) { 4568 // Delay type-checking for type-dependent expressions. 4569 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4570 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4571 } else if (ExprKind == UETT_VecStep) { 4572 isInvalid = CheckVecStepExpr(E); 4573 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4574 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4575 isInvalid = true; 4576 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4577 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4578 isInvalid = true; 4579 } else { 4580 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4581 } 4582 4583 if (isInvalid) 4584 return ExprError(); 4585 4586 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4587 PE = TransformToPotentiallyEvaluated(E); 4588 if (PE.isInvalid()) return ExprError(); 4589 E = PE.get(); 4590 } 4591 4592 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4593 return new (Context) UnaryExprOrTypeTraitExpr( 4594 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4595 } 4596 4597 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4598 /// expr and the same for @c alignof and @c __alignof 4599 /// Note that the ArgRange is invalid if isType is false. 4600 ExprResult 4601 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4602 UnaryExprOrTypeTrait ExprKind, bool IsType, 4603 void *TyOrEx, SourceRange ArgRange) { 4604 // If error parsing type, ignore. 4605 if (!TyOrEx) return ExprError(); 4606 4607 if (IsType) { 4608 TypeSourceInfo *TInfo; 4609 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4610 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4611 } 4612 4613 Expr *ArgEx = (Expr *)TyOrEx; 4614 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4615 return Result; 4616 } 4617 4618 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4619 bool IsReal) { 4620 if (V.get()->isTypeDependent()) 4621 return S.Context.DependentTy; 4622 4623 // _Real and _Imag are only l-values for normal l-values. 4624 if (V.get()->getObjectKind() != OK_Ordinary) { 4625 V = S.DefaultLvalueConversion(V.get()); 4626 if (V.isInvalid()) 4627 return QualType(); 4628 } 4629 4630 // These operators return the element type of a complex type. 4631 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4632 return CT->getElementType(); 4633 4634 // Otherwise they pass through real integer and floating point types here. 4635 if (V.get()->getType()->isArithmeticType()) 4636 return V.get()->getType(); 4637 4638 // Test for placeholders. 4639 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4640 if (PR.isInvalid()) return QualType(); 4641 if (PR.get() != V.get()) { 4642 V = PR; 4643 return CheckRealImagOperand(S, V, Loc, IsReal); 4644 } 4645 4646 // Reject anything else. 4647 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4648 << (IsReal ? "__real" : "__imag"); 4649 return QualType(); 4650 } 4651 4652 4653 4654 ExprResult 4655 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4656 tok::TokenKind Kind, Expr *Input) { 4657 UnaryOperatorKind Opc; 4658 switch (Kind) { 4659 default: llvm_unreachable("Unknown unary op!"); 4660 case tok::plusplus: Opc = UO_PostInc; break; 4661 case tok::minusminus: Opc = UO_PostDec; break; 4662 } 4663 4664 // Since this might is a postfix expression, get rid of ParenListExprs. 4665 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4666 if (Result.isInvalid()) return ExprError(); 4667 Input = Result.get(); 4668 4669 return BuildUnaryOp(S, OpLoc, Opc, Input); 4670 } 4671 4672 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4673 /// 4674 /// \return true on error 4675 static bool checkArithmeticOnObjCPointer(Sema &S, 4676 SourceLocation opLoc, 4677 Expr *op) { 4678 assert(op->getType()->isObjCObjectPointerType()); 4679 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4680 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4681 return false; 4682 4683 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4684 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4685 << op->getSourceRange(); 4686 return true; 4687 } 4688 4689 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4690 auto *BaseNoParens = Base->IgnoreParens(); 4691 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4692 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4693 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4694 } 4695 4696 ExprResult 4697 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4698 Expr *idx, SourceLocation rbLoc) { 4699 if (base && !base->getType().isNull() && 4700 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4701 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4702 SourceLocation(), /*Length*/ nullptr, 4703 /*Stride=*/nullptr, rbLoc); 4704 4705 // Since this might be a postfix expression, get rid of ParenListExprs. 4706 if (isa<ParenListExpr>(base)) { 4707 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4708 if (result.isInvalid()) return ExprError(); 4709 base = result.get(); 4710 } 4711 4712 // Check if base and idx form a MatrixSubscriptExpr. 4713 // 4714 // Helper to check for comma expressions, which are not allowed as indices for 4715 // matrix subscript expressions. 4716 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4717 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4718 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4719 << SourceRange(base->getBeginLoc(), rbLoc); 4720 return true; 4721 } 4722 return false; 4723 }; 4724 // The matrix subscript operator ([][])is considered a single operator. 4725 // Separating the index expressions by parenthesis is not allowed. 4726 if (base->getType()->isSpecificPlaceholderType( 4727 BuiltinType::IncompleteMatrixIdx) && 4728 !isa<MatrixSubscriptExpr>(base)) { 4729 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4730 << SourceRange(base->getBeginLoc(), rbLoc); 4731 return ExprError(); 4732 } 4733 // If the base is a MatrixSubscriptExpr, try to create a new 4734 // MatrixSubscriptExpr. 4735 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4736 if (matSubscriptE) { 4737 if (CheckAndReportCommaError(idx)) 4738 return ExprError(); 4739 4740 assert(matSubscriptE->isIncomplete() && 4741 "base has to be an incomplete matrix subscript"); 4742 return CreateBuiltinMatrixSubscriptExpr( 4743 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4744 } 4745 4746 // Handle any non-overload placeholder types in the base and index 4747 // expressions. We can't handle overloads here because the other 4748 // operand might be an overloadable type, in which case the overload 4749 // resolution for the operator overload should get the first crack 4750 // at the overload. 4751 bool IsMSPropertySubscript = false; 4752 if (base->getType()->isNonOverloadPlaceholderType()) { 4753 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4754 if (!IsMSPropertySubscript) { 4755 ExprResult result = CheckPlaceholderExpr(base); 4756 if (result.isInvalid()) 4757 return ExprError(); 4758 base = result.get(); 4759 } 4760 } 4761 4762 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4763 if (base->getType()->isMatrixType()) { 4764 if (CheckAndReportCommaError(idx)) 4765 return ExprError(); 4766 4767 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4768 } 4769 4770 // A comma-expression as the index is deprecated in C++2a onwards. 4771 if (getLangOpts().CPlusPlus20 && 4772 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4773 (isa<CXXOperatorCallExpr>(idx) && 4774 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4775 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4776 << SourceRange(base->getBeginLoc(), rbLoc); 4777 } 4778 4779 if (idx->getType()->isNonOverloadPlaceholderType()) { 4780 ExprResult result = CheckPlaceholderExpr(idx); 4781 if (result.isInvalid()) return ExprError(); 4782 idx = result.get(); 4783 } 4784 4785 // Build an unanalyzed expression if either operand is type-dependent. 4786 if (getLangOpts().CPlusPlus && 4787 (base->isTypeDependent() || idx->isTypeDependent())) { 4788 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4789 VK_LValue, OK_Ordinary, rbLoc); 4790 } 4791 4792 // MSDN, property (C++) 4793 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4794 // This attribute can also be used in the declaration of an empty array in a 4795 // class or structure definition. For example: 4796 // __declspec(property(get=GetX, put=PutX)) int x[]; 4797 // The above statement indicates that x[] can be used with one or more array 4798 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4799 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4800 if (IsMSPropertySubscript) { 4801 // Build MS property subscript expression if base is MS property reference 4802 // or MS property subscript. 4803 return new (Context) MSPropertySubscriptExpr( 4804 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4805 } 4806 4807 // Use C++ overloaded-operator rules if either operand has record 4808 // type. The spec says to do this if either type is *overloadable*, 4809 // but enum types can't declare subscript operators or conversion 4810 // operators, so there's nothing interesting for overload resolution 4811 // to do if there aren't any record types involved. 4812 // 4813 // ObjC pointers have their own subscripting logic that is not tied 4814 // to overload resolution and so should not take this path. 4815 if (getLangOpts().CPlusPlus && 4816 (base->getType()->isRecordType() || 4817 (!base->getType()->isObjCObjectPointerType() && 4818 idx->getType()->isRecordType()))) { 4819 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4820 } 4821 4822 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4823 4824 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4825 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4826 4827 return Res; 4828 } 4829 4830 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4831 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4832 InitializationKind Kind = 4833 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4834 InitializationSequence InitSeq(*this, Entity, Kind, E); 4835 return InitSeq.Perform(*this, Entity, Kind, E); 4836 } 4837 4838 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4839 Expr *ColumnIdx, 4840 SourceLocation RBLoc) { 4841 ExprResult BaseR = CheckPlaceholderExpr(Base); 4842 if (BaseR.isInvalid()) 4843 return BaseR; 4844 Base = BaseR.get(); 4845 4846 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4847 if (RowR.isInvalid()) 4848 return RowR; 4849 RowIdx = RowR.get(); 4850 4851 if (!ColumnIdx) 4852 return new (Context) MatrixSubscriptExpr( 4853 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4854 4855 // Build an unanalyzed expression if any of the operands is type-dependent. 4856 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4857 ColumnIdx->isTypeDependent()) 4858 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4859 Context.DependentTy, RBLoc); 4860 4861 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4862 if (ColumnR.isInvalid()) 4863 return ColumnR; 4864 ColumnIdx = ColumnR.get(); 4865 4866 // Check that IndexExpr is an integer expression. If it is a constant 4867 // expression, check that it is less than Dim (= the number of elements in the 4868 // corresponding dimension). 4869 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4870 bool IsColumnIdx) -> Expr * { 4871 if (!IndexExpr->getType()->isIntegerType() && 4872 !IndexExpr->isTypeDependent()) { 4873 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4874 << IsColumnIdx; 4875 return nullptr; 4876 } 4877 4878 if (Optional<llvm::APSInt> Idx = 4879 IndexExpr->getIntegerConstantExpr(Context)) { 4880 if ((*Idx < 0 || *Idx >= Dim)) { 4881 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4882 << IsColumnIdx << Dim; 4883 return nullptr; 4884 } 4885 } 4886 4887 ExprResult ConvExpr = 4888 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4889 assert(!ConvExpr.isInvalid() && 4890 "should be able to convert any integer type to size type"); 4891 return ConvExpr.get(); 4892 }; 4893 4894 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4895 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4896 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4897 if (!RowIdx || !ColumnIdx) 4898 return ExprError(); 4899 4900 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4901 MTy->getElementType(), RBLoc); 4902 } 4903 4904 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4905 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4906 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4907 4908 // For expressions like `&(*s).b`, the base is recorded and what should be 4909 // checked. 4910 const MemberExpr *Member = nullptr; 4911 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4912 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4913 4914 LastRecord.PossibleDerefs.erase(StrippedExpr); 4915 } 4916 4917 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4918 if (isUnevaluatedContext()) 4919 return; 4920 4921 QualType ResultTy = E->getType(); 4922 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4923 4924 // Bail if the element is an array since it is not memory access. 4925 if (isa<ArrayType>(ResultTy)) 4926 return; 4927 4928 if (ResultTy->hasAttr(attr::NoDeref)) { 4929 LastRecord.PossibleDerefs.insert(E); 4930 return; 4931 } 4932 4933 // Check if the base type is a pointer to a member access of a struct 4934 // marked with noderef. 4935 const Expr *Base = E->getBase(); 4936 QualType BaseTy = Base->getType(); 4937 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4938 // Not a pointer access 4939 return; 4940 4941 const MemberExpr *Member = nullptr; 4942 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4943 Member->isArrow()) 4944 Base = Member->getBase(); 4945 4946 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4947 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4948 LastRecord.PossibleDerefs.insert(E); 4949 } 4950 } 4951 4952 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4953 Expr *LowerBound, 4954 SourceLocation ColonLocFirst, 4955 SourceLocation ColonLocSecond, 4956 Expr *Length, Expr *Stride, 4957 SourceLocation RBLoc) { 4958 if (Base->getType()->isPlaceholderType() && 4959 !Base->getType()->isSpecificPlaceholderType( 4960 BuiltinType::OMPArraySection)) { 4961 ExprResult Result = CheckPlaceholderExpr(Base); 4962 if (Result.isInvalid()) 4963 return ExprError(); 4964 Base = Result.get(); 4965 } 4966 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4967 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4968 if (Result.isInvalid()) 4969 return ExprError(); 4970 Result = DefaultLvalueConversion(Result.get()); 4971 if (Result.isInvalid()) 4972 return ExprError(); 4973 LowerBound = Result.get(); 4974 } 4975 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4976 ExprResult Result = CheckPlaceholderExpr(Length); 4977 if (Result.isInvalid()) 4978 return ExprError(); 4979 Result = DefaultLvalueConversion(Result.get()); 4980 if (Result.isInvalid()) 4981 return ExprError(); 4982 Length = Result.get(); 4983 } 4984 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4985 ExprResult Result = CheckPlaceholderExpr(Stride); 4986 if (Result.isInvalid()) 4987 return ExprError(); 4988 Result = DefaultLvalueConversion(Result.get()); 4989 if (Result.isInvalid()) 4990 return ExprError(); 4991 Stride = Result.get(); 4992 } 4993 4994 // Build an unanalyzed expression if either operand is type-dependent. 4995 if (Base->isTypeDependent() || 4996 (LowerBound && 4997 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4998 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4999 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5000 return new (Context) OMPArraySectionExpr( 5001 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5002 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5003 } 5004 5005 // Perform default conversions. 5006 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5007 QualType ResultTy; 5008 if (OriginalTy->isAnyPointerType()) { 5009 ResultTy = OriginalTy->getPointeeType(); 5010 } else if (OriginalTy->isArrayType()) { 5011 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5012 } else { 5013 return ExprError( 5014 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5015 << Base->getSourceRange()); 5016 } 5017 // C99 6.5.2.1p1 5018 if (LowerBound) { 5019 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5020 LowerBound); 5021 if (Res.isInvalid()) 5022 return ExprError(Diag(LowerBound->getExprLoc(), 5023 diag::err_omp_typecheck_section_not_integer) 5024 << 0 << LowerBound->getSourceRange()); 5025 LowerBound = Res.get(); 5026 5027 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5028 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5029 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5030 << 0 << LowerBound->getSourceRange(); 5031 } 5032 if (Length) { 5033 auto Res = 5034 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5035 if (Res.isInvalid()) 5036 return ExprError(Diag(Length->getExprLoc(), 5037 diag::err_omp_typecheck_section_not_integer) 5038 << 1 << Length->getSourceRange()); 5039 Length = Res.get(); 5040 5041 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5042 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5043 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5044 << 1 << Length->getSourceRange(); 5045 } 5046 if (Stride) { 5047 ExprResult Res = 5048 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5049 if (Res.isInvalid()) 5050 return ExprError(Diag(Stride->getExprLoc(), 5051 diag::err_omp_typecheck_section_not_integer) 5052 << 1 << Stride->getSourceRange()); 5053 Stride = Res.get(); 5054 5055 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5056 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5057 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5058 << 1 << Stride->getSourceRange(); 5059 } 5060 5061 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5062 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5063 // type. Note that functions are not objects, and that (in C99 parlance) 5064 // incomplete types are not object types. 5065 if (ResultTy->isFunctionType()) { 5066 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5067 << ResultTy << Base->getSourceRange(); 5068 return ExprError(); 5069 } 5070 5071 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5072 diag::err_omp_section_incomplete_type, Base)) 5073 return ExprError(); 5074 5075 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5076 Expr::EvalResult Result; 5077 if (LowerBound->EvaluateAsInt(Result, Context)) { 5078 // OpenMP 5.0, [2.1.5 Array Sections] 5079 // The array section must be a subset of the original array. 5080 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5081 if (LowerBoundValue.isNegative()) { 5082 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5083 << LowerBound->getSourceRange(); 5084 return ExprError(); 5085 } 5086 } 5087 } 5088 5089 if (Length) { 5090 Expr::EvalResult Result; 5091 if (Length->EvaluateAsInt(Result, Context)) { 5092 // OpenMP 5.0, [2.1.5 Array Sections] 5093 // The length must evaluate to non-negative integers. 5094 llvm::APSInt LengthValue = Result.Val.getInt(); 5095 if (LengthValue.isNegative()) { 5096 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5097 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5098 << Length->getSourceRange(); 5099 return ExprError(); 5100 } 5101 } 5102 } else if (ColonLocFirst.isValid() && 5103 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5104 !OriginalTy->isVariableArrayType()))) { 5105 // OpenMP 5.0, [2.1.5 Array Sections] 5106 // When the size of the array dimension is not known, the length must be 5107 // specified explicitly. 5108 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5109 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5110 return ExprError(); 5111 } 5112 5113 if (Stride) { 5114 Expr::EvalResult Result; 5115 if (Stride->EvaluateAsInt(Result, Context)) { 5116 // OpenMP 5.0, [2.1.5 Array Sections] 5117 // The stride must evaluate to a positive integer. 5118 llvm::APSInt StrideValue = Result.Val.getInt(); 5119 if (!StrideValue.isStrictlyPositive()) { 5120 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5121 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5122 << Stride->getSourceRange(); 5123 return ExprError(); 5124 } 5125 } 5126 } 5127 5128 if (!Base->getType()->isSpecificPlaceholderType( 5129 BuiltinType::OMPArraySection)) { 5130 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5131 if (Result.isInvalid()) 5132 return ExprError(); 5133 Base = Result.get(); 5134 } 5135 return new (Context) OMPArraySectionExpr( 5136 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5137 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5138 } 5139 5140 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5141 SourceLocation RParenLoc, 5142 ArrayRef<Expr *> Dims, 5143 ArrayRef<SourceRange> Brackets) { 5144 if (Base->getType()->isPlaceholderType()) { 5145 ExprResult Result = CheckPlaceholderExpr(Base); 5146 if (Result.isInvalid()) 5147 return ExprError(); 5148 Result = DefaultLvalueConversion(Result.get()); 5149 if (Result.isInvalid()) 5150 return ExprError(); 5151 Base = Result.get(); 5152 } 5153 QualType BaseTy = Base->getType(); 5154 // Delay analysis of the types/expressions if instantiation/specialization is 5155 // required. 5156 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5157 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5158 LParenLoc, RParenLoc, Dims, Brackets); 5159 if (!BaseTy->isPointerType() || 5160 (!Base->isTypeDependent() && 5161 BaseTy->getPointeeType()->isIncompleteType())) 5162 return ExprError(Diag(Base->getExprLoc(), 5163 diag::err_omp_non_pointer_type_array_shaping_base) 5164 << Base->getSourceRange()); 5165 5166 SmallVector<Expr *, 4> NewDims; 5167 bool ErrorFound = false; 5168 for (Expr *Dim : Dims) { 5169 if (Dim->getType()->isPlaceholderType()) { 5170 ExprResult Result = CheckPlaceholderExpr(Dim); 5171 if (Result.isInvalid()) { 5172 ErrorFound = true; 5173 continue; 5174 } 5175 Result = DefaultLvalueConversion(Result.get()); 5176 if (Result.isInvalid()) { 5177 ErrorFound = true; 5178 continue; 5179 } 5180 Dim = Result.get(); 5181 } 5182 if (!Dim->isTypeDependent()) { 5183 ExprResult Result = 5184 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5185 if (Result.isInvalid()) { 5186 ErrorFound = true; 5187 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5188 << Dim->getSourceRange(); 5189 continue; 5190 } 5191 Dim = Result.get(); 5192 Expr::EvalResult EvResult; 5193 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5194 // OpenMP 5.0, [2.1.4 Array Shaping] 5195 // Each si is an integral type expression that must evaluate to a 5196 // positive integer. 5197 llvm::APSInt Value = EvResult.Val.getInt(); 5198 if (!Value.isStrictlyPositive()) { 5199 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5200 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5201 << Dim->getSourceRange(); 5202 ErrorFound = true; 5203 continue; 5204 } 5205 } 5206 } 5207 NewDims.push_back(Dim); 5208 } 5209 if (ErrorFound) 5210 return ExprError(); 5211 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5212 LParenLoc, RParenLoc, NewDims, Brackets); 5213 } 5214 5215 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5216 SourceLocation LLoc, SourceLocation RLoc, 5217 ArrayRef<OMPIteratorData> Data) { 5218 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5219 bool IsCorrect = true; 5220 for (const OMPIteratorData &D : Data) { 5221 TypeSourceInfo *TInfo = nullptr; 5222 SourceLocation StartLoc; 5223 QualType DeclTy; 5224 if (!D.Type.getAsOpaquePtr()) { 5225 // OpenMP 5.0, 2.1.6 Iterators 5226 // In an iterator-specifier, if the iterator-type is not specified then 5227 // the type of that iterator is of int type. 5228 DeclTy = Context.IntTy; 5229 StartLoc = D.DeclIdentLoc; 5230 } else { 5231 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5232 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5233 } 5234 5235 bool IsDeclTyDependent = DeclTy->isDependentType() || 5236 DeclTy->containsUnexpandedParameterPack() || 5237 DeclTy->isInstantiationDependentType(); 5238 if (!IsDeclTyDependent) { 5239 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5240 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5241 // The iterator-type must be an integral or pointer type. 5242 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5243 << DeclTy; 5244 IsCorrect = false; 5245 continue; 5246 } 5247 if (DeclTy.isConstant(Context)) { 5248 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5249 // The iterator-type must not be const qualified. 5250 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5251 << DeclTy; 5252 IsCorrect = false; 5253 continue; 5254 } 5255 } 5256 5257 // Iterator declaration. 5258 assert(D.DeclIdent && "Identifier expected."); 5259 // Always try to create iterator declarator to avoid extra error messages 5260 // about unknown declarations use. 5261 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5262 D.DeclIdent, DeclTy, TInfo, SC_None); 5263 VD->setImplicit(); 5264 if (S) { 5265 // Check for conflicting previous declaration. 5266 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5267 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5268 ForVisibleRedeclaration); 5269 Previous.suppressDiagnostics(); 5270 LookupName(Previous, S); 5271 5272 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5273 /*AllowInlineNamespace=*/false); 5274 if (!Previous.empty()) { 5275 NamedDecl *Old = Previous.getRepresentativeDecl(); 5276 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5277 Diag(Old->getLocation(), diag::note_previous_definition); 5278 } else { 5279 PushOnScopeChains(VD, S); 5280 } 5281 } else { 5282 CurContext->addDecl(VD); 5283 } 5284 Expr *Begin = D.Range.Begin; 5285 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5286 ExprResult BeginRes = 5287 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5288 Begin = BeginRes.get(); 5289 } 5290 Expr *End = D.Range.End; 5291 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5292 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5293 End = EndRes.get(); 5294 } 5295 Expr *Step = D.Range.Step; 5296 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5297 if (!Step->getType()->isIntegralType(Context)) { 5298 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5299 << Step << Step->getSourceRange(); 5300 IsCorrect = false; 5301 continue; 5302 } 5303 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5304 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5305 // If the step expression of a range-specification equals zero, the 5306 // behavior is unspecified. 5307 if (Result && Result->isNullValue()) { 5308 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5309 << Step << Step->getSourceRange(); 5310 IsCorrect = false; 5311 continue; 5312 } 5313 } 5314 if (!Begin || !End || !IsCorrect) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5319 IDElem.IteratorDecl = VD; 5320 IDElem.AssignmentLoc = D.AssignLoc; 5321 IDElem.Range.Begin = Begin; 5322 IDElem.Range.End = End; 5323 IDElem.Range.Step = Step; 5324 IDElem.ColonLoc = D.ColonLoc; 5325 IDElem.SecondColonLoc = D.SecColonLoc; 5326 } 5327 if (!IsCorrect) { 5328 // Invalidate all created iterator declarations if error is found. 5329 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5330 if (Decl *ID = D.IteratorDecl) 5331 ID->setInvalidDecl(); 5332 } 5333 return ExprError(); 5334 } 5335 SmallVector<OMPIteratorHelperData, 4> Helpers; 5336 if (!CurContext->isDependentContext()) { 5337 // Build number of ityeration for each iteration range. 5338 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5339 // ((Begini-Stepi-1-Endi) / -Stepi); 5340 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5341 // (Endi - Begini) 5342 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5343 D.Range.Begin); 5344 if(!Res.isUsable()) { 5345 IsCorrect = false; 5346 continue; 5347 } 5348 ExprResult St, St1; 5349 if (D.Range.Step) { 5350 St = D.Range.Step; 5351 // (Endi - Begini) + Stepi 5352 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5353 if (!Res.isUsable()) { 5354 IsCorrect = false; 5355 continue; 5356 } 5357 // (Endi - Begini) + Stepi - 1 5358 Res = 5359 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5360 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5361 if (!Res.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 // ((Endi - Begini) + Stepi - 1) / Stepi 5366 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5367 if (!Res.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5372 // (Begini - Endi) 5373 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5374 D.Range.Begin, D.Range.End); 5375 if (!Res1.isUsable()) { 5376 IsCorrect = false; 5377 continue; 5378 } 5379 // (Begini - Endi) - Stepi 5380 Res1 = 5381 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5382 if (!Res1.isUsable()) { 5383 IsCorrect = false; 5384 continue; 5385 } 5386 // (Begini - Endi) - Stepi - 1 5387 Res1 = 5388 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5389 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5390 if (!Res1.isUsable()) { 5391 IsCorrect = false; 5392 continue; 5393 } 5394 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5395 Res1 = 5396 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5397 if (!Res1.isUsable()) { 5398 IsCorrect = false; 5399 continue; 5400 } 5401 // Stepi > 0. 5402 ExprResult CmpRes = 5403 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5404 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5405 if (!CmpRes.isUsable()) { 5406 IsCorrect = false; 5407 continue; 5408 } 5409 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5410 Res.get(), Res1.get()); 5411 if (!Res.isUsable()) { 5412 IsCorrect = false; 5413 continue; 5414 } 5415 } 5416 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5417 if (!Res.isUsable()) { 5418 IsCorrect = false; 5419 continue; 5420 } 5421 5422 // Build counter update. 5423 // Build counter. 5424 auto *CounterVD = 5425 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5426 D.IteratorDecl->getBeginLoc(), nullptr, 5427 Res.get()->getType(), nullptr, SC_None); 5428 CounterVD->setImplicit(); 5429 ExprResult RefRes = 5430 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5431 D.IteratorDecl->getBeginLoc()); 5432 // Build counter update. 5433 // I = Begini + counter * Stepi; 5434 ExprResult UpdateRes; 5435 if (D.Range.Step) { 5436 UpdateRes = CreateBuiltinBinOp( 5437 D.AssignmentLoc, BO_Mul, 5438 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5439 } else { 5440 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5441 } 5442 if (!UpdateRes.isUsable()) { 5443 IsCorrect = false; 5444 continue; 5445 } 5446 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5447 UpdateRes.get()); 5448 if (!UpdateRes.isUsable()) { 5449 IsCorrect = false; 5450 continue; 5451 } 5452 ExprResult VDRes = 5453 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5454 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5455 D.IteratorDecl->getBeginLoc()); 5456 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5457 UpdateRes.get()); 5458 if (!UpdateRes.isUsable()) { 5459 IsCorrect = false; 5460 continue; 5461 } 5462 UpdateRes = 5463 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5464 if (!UpdateRes.isUsable()) { 5465 IsCorrect = false; 5466 continue; 5467 } 5468 ExprResult CounterUpdateRes = 5469 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5470 if (!CounterUpdateRes.isUsable()) { 5471 IsCorrect = false; 5472 continue; 5473 } 5474 CounterUpdateRes = 5475 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5476 if (!CounterUpdateRes.isUsable()) { 5477 IsCorrect = false; 5478 continue; 5479 } 5480 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5481 HD.CounterVD = CounterVD; 5482 HD.Upper = Res.get(); 5483 HD.Update = UpdateRes.get(); 5484 HD.CounterUpdate = CounterUpdateRes.get(); 5485 } 5486 } else { 5487 Helpers.assign(ID.size(), {}); 5488 } 5489 if (!IsCorrect) { 5490 // Invalidate all created iterator declarations if error is found. 5491 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5492 if (Decl *ID = D.IteratorDecl) 5493 ID->setInvalidDecl(); 5494 } 5495 return ExprError(); 5496 } 5497 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5498 LLoc, RLoc, ID, Helpers); 5499 } 5500 5501 ExprResult 5502 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5503 Expr *Idx, SourceLocation RLoc) { 5504 Expr *LHSExp = Base; 5505 Expr *RHSExp = Idx; 5506 5507 ExprValueKind VK = VK_LValue; 5508 ExprObjectKind OK = OK_Ordinary; 5509 5510 // Per C++ core issue 1213, the result is an xvalue if either operand is 5511 // a non-lvalue array, and an lvalue otherwise. 5512 if (getLangOpts().CPlusPlus11) { 5513 for (auto *Op : {LHSExp, RHSExp}) { 5514 Op = Op->IgnoreImplicit(); 5515 if (Op->getType()->isArrayType() && !Op->isLValue()) 5516 VK = VK_XValue; 5517 } 5518 } 5519 5520 // Perform default conversions. 5521 if (!LHSExp->getType()->getAs<VectorType>()) { 5522 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5523 if (Result.isInvalid()) 5524 return ExprError(); 5525 LHSExp = Result.get(); 5526 } 5527 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5528 if (Result.isInvalid()) 5529 return ExprError(); 5530 RHSExp = Result.get(); 5531 5532 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5533 5534 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5535 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5536 // in the subscript position. As a result, we need to derive the array base 5537 // and index from the expression types. 5538 Expr *BaseExpr, *IndexExpr; 5539 QualType ResultType; 5540 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5541 BaseExpr = LHSExp; 5542 IndexExpr = RHSExp; 5543 ResultType = Context.DependentTy; 5544 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5545 BaseExpr = LHSExp; 5546 IndexExpr = RHSExp; 5547 ResultType = PTy->getPointeeType(); 5548 } else if (const ObjCObjectPointerType *PTy = 5549 LHSTy->getAs<ObjCObjectPointerType>()) { 5550 BaseExpr = LHSExp; 5551 IndexExpr = RHSExp; 5552 5553 // Use custom logic if this should be the pseudo-object subscript 5554 // expression. 5555 if (!LangOpts.isSubscriptPointerArithmetic()) 5556 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5557 nullptr); 5558 5559 ResultType = PTy->getPointeeType(); 5560 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5561 // Handle the uncommon case of "123[Ptr]". 5562 BaseExpr = RHSExp; 5563 IndexExpr = LHSExp; 5564 ResultType = PTy->getPointeeType(); 5565 } else if (const ObjCObjectPointerType *PTy = 5566 RHSTy->getAs<ObjCObjectPointerType>()) { 5567 // Handle the uncommon case of "123[Ptr]". 5568 BaseExpr = RHSExp; 5569 IndexExpr = LHSExp; 5570 ResultType = PTy->getPointeeType(); 5571 if (!LangOpts.isSubscriptPointerArithmetic()) { 5572 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5573 << ResultType << BaseExpr->getSourceRange(); 5574 return ExprError(); 5575 } 5576 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5577 BaseExpr = LHSExp; // vectors: V[123] 5578 IndexExpr = RHSExp; 5579 // We apply C++ DR1213 to vector subscripting too. 5580 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5581 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5582 if (Materialized.isInvalid()) 5583 return ExprError(); 5584 LHSExp = Materialized.get(); 5585 } 5586 VK = LHSExp->getValueKind(); 5587 if (VK != VK_PRValue) 5588 OK = OK_VectorComponent; 5589 5590 ResultType = VTy->getElementType(); 5591 QualType BaseType = BaseExpr->getType(); 5592 Qualifiers BaseQuals = BaseType.getQualifiers(); 5593 Qualifiers MemberQuals = ResultType.getQualifiers(); 5594 Qualifiers Combined = BaseQuals + MemberQuals; 5595 if (Combined != MemberQuals) 5596 ResultType = Context.getQualifiedType(ResultType, Combined); 5597 } else if (LHSTy->isArrayType()) { 5598 // If we see an array that wasn't promoted by 5599 // DefaultFunctionArrayLvalueConversion, it must be an array that 5600 // wasn't promoted because of the C90 rule that doesn't 5601 // allow promoting non-lvalue arrays. Warn, then 5602 // force the promotion here. 5603 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5604 << LHSExp->getSourceRange(); 5605 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5606 CK_ArrayToPointerDecay).get(); 5607 LHSTy = LHSExp->getType(); 5608 5609 BaseExpr = LHSExp; 5610 IndexExpr = RHSExp; 5611 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5612 } else if (RHSTy->isArrayType()) { 5613 // Same as previous, except for 123[f().a] case 5614 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5615 << RHSExp->getSourceRange(); 5616 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5617 CK_ArrayToPointerDecay).get(); 5618 RHSTy = RHSExp->getType(); 5619 5620 BaseExpr = RHSExp; 5621 IndexExpr = LHSExp; 5622 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5623 } else { 5624 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5625 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5626 } 5627 // C99 6.5.2.1p1 5628 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5629 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5630 << IndexExpr->getSourceRange()); 5631 5632 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5633 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5634 && !IndexExpr->isTypeDependent()) 5635 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5636 5637 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5638 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5639 // type. Note that Functions are not objects, and that (in C99 parlance) 5640 // incomplete types are not object types. 5641 if (ResultType->isFunctionType()) { 5642 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5643 << ResultType << BaseExpr->getSourceRange(); 5644 return ExprError(); 5645 } 5646 5647 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5648 // GNU extension: subscripting on pointer to void 5649 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5650 << BaseExpr->getSourceRange(); 5651 5652 // C forbids expressions of unqualified void type from being l-values. 5653 // See IsCForbiddenLValueType. 5654 if (!ResultType.hasQualifiers()) 5655 VK = VK_PRValue; 5656 } else if (!ResultType->isDependentType() && 5657 RequireCompleteSizedType( 5658 LLoc, ResultType, 5659 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5660 return ExprError(); 5661 5662 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5663 !ResultType.isCForbiddenLValueType()); 5664 5665 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5666 FunctionScopes.size() > 1) { 5667 if (auto *TT = 5668 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5669 for (auto I = FunctionScopes.rbegin(), 5670 E = std::prev(FunctionScopes.rend()); 5671 I != E; ++I) { 5672 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5673 if (CSI == nullptr) 5674 break; 5675 DeclContext *DC = nullptr; 5676 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5677 DC = LSI->CallOperator; 5678 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5679 DC = CRSI->TheCapturedDecl; 5680 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5681 DC = BSI->TheDecl; 5682 if (DC) { 5683 if (DC->containsDecl(TT->getDecl())) 5684 break; 5685 captureVariablyModifiedType( 5686 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5687 } 5688 } 5689 } 5690 } 5691 5692 return new (Context) 5693 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5694 } 5695 5696 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5697 ParmVarDecl *Param) { 5698 if (Param->hasUnparsedDefaultArg()) { 5699 // If we've already cleared out the location for the default argument, 5700 // that means we're parsing it right now. 5701 if (!UnparsedDefaultArgLocs.count(Param)) { 5702 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5703 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5704 Param->setInvalidDecl(); 5705 return true; 5706 } 5707 5708 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5709 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5710 Diag(UnparsedDefaultArgLocs[Param], 5711 diag::note_default_argument_declared_here); 5712 return true; 5713 } 5714 5715 if (Param->hasUninstantiatedDefaultArg() && 5716 InstantiateDefaultArgument(CallLoc, FD, Param)) 5717 return true; 5718 5719 assert(Param->hasInit() && "default argument but no initializer?"); 5720 5721 // If the default expression creates temporaries, we need to 5722 // push them to the current stack of expression temporaries so they'll 5723 // be properly destroyed. 5724 // FIXME: We should really be rebuilding the default argument with new 5725 // bound temporaries; see the comment in PR5810. 5726 // We don't need to do that with block decls, though, because 5727 // blocks in default argument expression can never capture anything. 5728 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5729 // Set the "needs cleanups" bit regardless of whether there are 5730 // any explicit objects. 5731 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5732 5733 // Append all the objects to the cleanup list. Right now, this 5734 // should always be a no-op, because blocks in default argument 5735 // expressions should never be able to capture anything. 5736 assert(!Init->getNumObjects() && 5737 "default argument expression has capturing blocks?"); 5738 } 5739 5740 // We already type-checked the argument, so we know it works. 5741 // Just mark all of the declarations in this potentially-evaluated expression 5742 // as being "referenced". 5743 EnterExpressionEvaluationContext EvalContext( 5744 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5745 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5746 /*SkipLocalVariables=*/true); 5747 return false; 5748 } 5749 5750 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5751 FunctionDecl *FD, ParmVarDecl *Param) { 5752 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5753 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5754 return ExprError(); 5755 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5756 } 5757 5758 Sema::VariadicCallType 5759 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5760 Expr *Fn) { 5761 if (Proto && Proto->isVariadic()) { 5762 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5763 return VariadicConstructor; 5764 else if (Fn && Fn->getType()->isBlockPointerType()) 5765 return VariadicBlock; 5766 else if (FDecl) { 5767 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5768 if (Method->isInstance()) 5769 return VariadicMethod; 5770 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5771 return VariadicMethod; 5772 return VariadicFunction; 5773 } 5774 return VariadicDoesNotApply; 5775 } 5776 5777 namespace { 5778 class FunctionCallCCC final : public FunctionCallFilterCCC { 5779 public: 5780 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5781 unsigned NumArgs, MemberExpr *ME) 5782 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5783 FunctionName(FuncName) {} 5784 5785 bool ValidateCandidate(const TypoCorrection &candidate) override { 5786 if (!candidate.getCorrectionSpecifier() || 5787 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5788 return false; 5789 } 5790 5791 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5792 } 5793 5794 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5795 return std::make_unique<FunctionCallCCC>(*this); 5796 } 5797 5798 private: 5799 const IdentifierInfo *const FunctionName; 5800 }; 5801 } 5802 5803 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5804 FunctionDecl *FDecl, 5805 ArrayRef<Expr *> Args) { 5806 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5807 DeclarationName FuncName = FDecl->getDeclName(); 5808 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5809 5810 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5811 if (TypoCorrection Corrected = S.CorrectTypo( 5812 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5813 S.getScopeForContext(S.CurContext), nullptr, CCC, 5814 Sema::CTK_ErrorRecovery)) { 5815 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5816 if (Corrected.isOverloaded()) { 5817 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5818 OverloadCandidateSet::iterator Best; 5819 for (NamedDecl *CD : Corrected) { 5820 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5821 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5822 OCS); 5823 } 5824 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5825 case OR_Success: 5826 ND = Best->FoundDecl; 5827 Corrected.setCorrectionDecl(ND); 5828 break; 5829 default: 5830 break; 5831 } 5832 } 5833 ND = ND->getUnderlyingDecl(); 5834 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5835 return Corrected; 5836 } 5837 } 5838 return TypoCorrection(); 5839 } 5840 5841 /// ConvertArgumentsForCall - Converts the arguments specified in 5842 /// Args/NumArgs to the parameter types of the function FDecl with 5843 /// function prototype Proto. Call is the call expression itself, and 5844 /// Fn is the function expression. For a C++ member function, this 5845 /// routine does not attempt to convert the object argument. Returns 5846 /// true if the call is ill-formed. 5847 bool 5848 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5849 FunctionDecl *FDecl, 5850 const FunctionProtoType *Proto, 5851 ArrayRef<Expr *> Args, 5852 SourceLocation RParenLoc, 5853 bool IsExecConfig) { 5854 // Bail out early if calling a builtin with custom typechecking. 5855 if (FDecl) 5856 if (unsigned ID = FDecl->getBuiltinID()) 5857 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5858 return false; 5859 5860 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5861 // assignment, to the types of the corresponding parameter, ... 5862 unsigned NumParams = Proto->getNumParams(); 5863 bool Invalid = false; 5864 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5865 unsigned FnKind = Fn->getType()->isBlockPointerType() 5866 ? 1 /* block */ 5867 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5868 : 0 /* function */); 5869 5870 // If too few arguments are available (and we don't have default 5871 // arguments for the remaining parameters), don't make the call. 5872 if (Args.size() < NumParams) { 5873 if (Args.size() < MinArgs) { 5874 TypoCorrection TC; 5875 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5876 unsigned diag_id = 5877 MinArgs == NumParams && !Proto->isVariadic() 5878 ? diag::err_typecheck_call_too_few_args_suggest 5879 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5880 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5881 << static_cast<unsigned>(Args.size()) 5882 << TC.getCorrectionRange()); 5883 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5884 Diag(RParenLoc, 5885 MinArgs == NumParams && !Proto->isVariadic() 5886 ? diag::err_typecheck_call_too_few_args_one 5887 : diag::err_typecheck_call_too_few_args_at_least_one) 5888 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5889 else 5890 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5891 ? diag::err_typecheck_call_too_few_args 5892 : diag::err_typecheck_call_too_few_args_at_least) 5893 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5894 << Fn->getSourceRange(); 5895 5896 // Emit the location of the prototype. 5897 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5898 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5899 5900 return true; 5901 } 5902 // We reserve space for the default arguments when we create 5903 // the call expression, before calling ConvertArgumentsForCall. 5904 assert((Call->getNumArgs() == NumParams) && 5905 "We should have reserved space for the default arguments before!"); 5906 } 5907 5908 // If too many are passed and not variadic, error on the extras and drop 5909 // them. 5910 if (Args.size() > NumParams) { 5911 if (!Proto->isVariadic()) { 5912 TypoCorrection TC; 5913 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5914 unsigned diag_id = 5915 MinArgs == NumParams && !Proto->isVariadic() 5916 ? diag::err_typecheck_call_too_many_args_suggest 5917 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5918 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5919 << static_cast<unsigned>(Args.size()) 5920 << TC.getCorrectionRange()); 5921 } else if (NumParams == 1 && FDecl && 5922 FDecl->getParamDecl(0)->getDeclName()) 5923 Diag(Args[NumParams]->getBeginLoc(), 5924 MinArgs == NumParams 5925 ? diag::err_typecheck_call_too_many_args_one 5926 : diag::err_typecheck_call_too_many_args_at_most_one) 5927 << FnKind << FDecl->getParamDecl(0) 5928 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5929 << SourceRange(Args[NumParams]->getBeginLoc(), 5930 Args.back()->getEndLoc()); 5931 else 5932 Diag(Args[NumParams]->getBeginLoc(), 5933 MinArgs == NumParams 5934 ? diag::err_typecheck_call_too_many_args 5935 : diag::err_typecheck_call_too_many_args_at_most) 5936 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5937 << Fn->getSourceRange() 5938 << SourceRange(Args[NumParams]->getBeginLoc(), 5939 Args.back()->getEndLoc()); 5940 5941 // Emit the location of the prototype. 5942 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5943 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5944 5945 // This deletes the extra arguments. 5946 Call->shrinkNumArgs(NumParams); 5947 return true; 5948 } 5949 } 5950 SmallVector<Expr *, 8> AllArgs; 5951 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5952 5953 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5954 AllArgs, CallType); 5955 if (Invalid) 5956 return true; 5957 unsigned TotalNumArgs = AllArgs.size(); 5958 for (unsigned i = 0; i < TotalNumArgs; ++i) 5959 Call->setArg(i, AllArgs[i]); 5960 5961 Call->computeDependence(); 5962 return false; 5963 } 5964 5965 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5966 const FunctionProtoType *Proto, 5967 unsigned FirstParam, ArrayRef<Expr *> Args, 5968 SmallVectorImpl<Expr *> &AllArgs, 5969 VariadicCallType CallType, bool AllowExplicit, 5970 bool IsListInitialization) { 5971 unsigned NumParams = Proto->getNumParams(); 5972 bool Invalid = false; 5973 size_t ArgIx = 0; 5974 // Continue to check argument types (even if we have too few/many args). 5975 for (unsigned i = FirstParam; i < NumParams; i++) { 5976 QualType ProtoArgType = Proto->getParamType(i); 5977 5978 Expr *Arg; 5979 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5980 if (ArgIx < Args.size()) { 5981 Arg = Args[ArgIx++]; 5982 5983 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5984 diag::err_call_incomplete_argument, Arg)) 5985 return true; 5986 5987 // Strip the unbridged-cast placeholder expression off, if applicable. 5988 bool CFAudited = false; 5989 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5990 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5991 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5992 Arg = stripARCUnbridgedCast(Arg); 5993 else if (getLangOpts().ObjCAutoRefCount && 5994 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5995 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5996 CFAudited = true; 5997 5998 if (Proto->getExtParameterInfo(i).isNoEscape() && 5999 ProtoArgType->isBlockPointerType()) 6000 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6001 BE->getBlockDecl()->setDoesNotEscape(); 6002 6003 InitializedEntity Entity = 6004 Param ? InitializedEntity::InitializeParameter(Context, Param, 6005 ProtoArgType) 6006 : InitializedEntity::InitializeParameter( 6007 Context, ProtoArgType, Proto->isParamConsumed(i)); 6008 6009 // Remember that parameter belongs to a CF audited API. 6010 if (CFAudited) 6011 Entity.setParameterCFAudited(); 6012 6013 ExprResult ArgE = PerformCopyInitialization( 6014 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6015 if (ArgE.isInvalid()) 6016 return true; 6017 6018 Arg = ArgE.getAs<Expr>(); 6019 } else { 6020 assert(Param && "can't use default arguments without a known callee"); 6021 6022 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6023 if (ArgExpr.isInvalid()) 6024 return true; 6025 6026 Arg = ArgExpr.getAs<Expr>(); 6027 } 6028 6029 // Check for array bounds violations for each argument to the call. This 6030 // check only triggers warnings when the argument isn't a more complex Expr 6031 // with its own checking, such as a BinaryOperator. 6032 CheckArrayAccess(Arg); 6033 6034 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6035 CheckStaticArrayArgument(CallLoc, Param, Arg); 6036 6037 AllArgs.push_back(Arg); 6038 } 6039 6040 // If this is a variadic call, handle args passed through "...". 6041 if (CallType != VariadicDoesNotApply) { 6042 // Assume that extern "C" functions with variadic arguments that 6043 // return __unknown_anytype aren't *really* variadic. 6044 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6045 FDecl->isExternC()) { 6046 for (Expr *A : Args.slice(ArgIx)) { 6047 QualType paramType; // ignored 6048 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6049 Invalid |= arg.isInvalid(); 6050 AllArgs.push_back(arg.get()); 6051 } 6052 6053 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6054 } else { 6055 for (Expr *A : Args.slice(ArgIx)) { 6056 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6057 Invalid |= Arg.isInvalid(); 6058 AllArgs.push_back(Arg.get()); 6059 } 6060 } 6061 6062 // Check for array bounds violations. 6063 for (Expr *A : Args.slice(ArgIx)) 6064 CheckArrayAccess(A); 6065 } 6066 return Invalid; 6067 } 6068 6069 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6070 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6071 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6072 TL = DTL.getOriginalLoc(); 6073 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6074 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6075 << ATL.getLocalSourceRange(); 6076 } 6077 6078 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6079 /// array parameter, check that it is non-null, and that if it is formed by 6080 /// array-to-pointer decay, the underlying array is sufficiently large. 6081 /// 6082 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6083 /// array type derivation, then for each call to the function, the value of the 6084 /// corresponding actual argument shall provide access to the first element of 6085 /// an array with at least as many elements as specified by the size expression. 6086 void 6087 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6088 ParmVarDecl *Param, 6089 const Expr *ArgExpr) { 6090 // Static array parameters are not supported in C++. 6091 if (!Param || getLangOpts().CPlusPlus) 6092 return; 6093 6094 QualType OrigTy = Param->getOriginalType(); 6095 6096 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6097 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6098 return; 6099 6100 if (ArgExpr->isNullPointerConstant(Context, 6101 Expr::NPC_NeverValueDependent)) { 6102 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6103 DiagnoseCalleeStaticArrayParam(*this, Param); 6104 return; 6105 } 6106 6107 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6108 if (!CAT) 6109 return; 6110 6111 const ConstantArrayType *ArgCAT = 6112 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6113 if (!ArgCAT) 6114 return; 6115 6116 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6117 ArgCAT->getElementType())) { 6118 if (ArgCAT->getSize().ult(CAT->getSize())) { 6119 Diag(CallLoc, diag::warn_static_array_too_small) 6120 << ArgExpr->getSourceRange() 6121 << (unsigned)ArgCAT->getSize().getZExtValue() 6122 << (unsigned)CAT->getSize().getZExtValue() << 0; 6123 DiagnoseCalleeStaticArrayParam(*this, Param); 6124 } 6125 return; 6126 } 6127 6128 Optional<CharUnits> ArgSize = 6129 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6130 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6131 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6132 Diag(CallLoc, diag::warn_static_array_too_small) 6133 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6134 << (unsigned)ParmSize->getQuantity() << 1; 6135 DiagnoseCalleeStaticArrayParam(*this, Param); 6136 } 6137 } 6138 6139 /// Given a function expression of unknown-any type, try to rebuild it 6140 /// to have a function type. 6141 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6142 6143 /// Is the given type a placeholder that we need to lower out 6144 /// immediately during argument processing? 6145 static bool isPlaceholderToRemoveAsArg(QualType type) { 6146 // Placeholders are never sugared. 6147 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6148 if (!placeholder) return false; 6149 6150 switch (placeholder->getKind()) { 6151 // Ignore all the non-placeholder types. 6152 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6153 case BuiltinType::Id: 6154 #include "clang/Basic/OpenCLImageTypes.def" 6155 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6156 case BuiltinType::Id: 6157 #include "clang/Basic/OpenCLExtensionTypes.def" 6158 // In practice we'll never use this, since all SVE types are sugared 6159 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6160 #define SVE_TYPE(Name, Id, SingletonId) \ 6161 case BuiltinType::Id: 6162 #include "clang/Basic/AArch64SVEACLETypes.def" 6163 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6164 case BuiltinType::Id: 6165 #include "clang/Basic/PPCTypes.def" 6166 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6167 #include "clang/Basic/RISCVVTypes.def" 6168 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6169 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6170 #include "clang/AST/BuiltinTypes.def" 6171 return false; 6172 6173 // We cannot lower out overload sets; they might validly be resolved 6174 // by the call machinery. 6175 case BuiltinType::Overload: 6176 return false; 6177 6178 // Unbridged casts in ARC can be handled in some call positions and 6179 // should be left in place. 6180 case BuiltinType::ARCUnbridgedCast: 6181 return false; 6182 6183 // Pseudo-objects should be converted as soon as possible. 6184 case BuiltinType::PseudoObject: 6185 return true; 6186 6187 // The debugger mode could theoretically but currently does not try 6188 // to resolve unknown-typed arguments based on known parameter types. 6189 case BuiltinType::UnknownAny: 6190 return true; 6191 6192 // These are always invalid as call arguments and should be reported. 6193 case BuiltinType::BoundMember: 6194 case BuiltinType::BuiltinFn: 6195 case BuiltinType::IncompleteMatrixIdx: 6196 case BuiltinType::OMPArraySection: 6197 case BuiltinType::OMPArrayShaping: 6198 case BuiltinType::OMPIterator: 6199 return true; 6200 6201 } 6202 llvm_unreachable("bad builtin type kind"); 6203 } 6204 6205 /// Check an argument list for placeholders that we won't try to 6206 /// handle later. 6207 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6208 // Apply this processing to all the arguments at once instead of 6209 // dying at the first failure. 6210 bool hasInvalid = false; 6211 for (size_t i = 0, e = args.size(); i != e; i++) { 6212 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6213 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6214 if (result.isInvalid()) hasInvalid = true; 6215 else args[i] = result.get(); 6216 } 6217 } 6218 return hasInvalid; 6219 } 6220 6221 /// If a builtin function has a pointer argument with no explicit address 6222 /// space, then it should be able to accept a pointer to any address 6223 /// space as input. In order to do this, we need to replace the 6224 /// standard builtin declaration with one that uses the same address space 6225 /// as the call. 6226 /// 6227 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6228 /// it does not contain any pointer arguments without 6229 /// an address space qualifer. Otherwise the rewritten 6230 /// FunctionDecl is returned. 6231 /// TODO: Handle pointer return types. 6232 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6233 FunctionDecl *FDecl, 6234 MultiExprArg ArgExprs) { 6235 6236 QualType DeclType = FDecl->getType(); 6237 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6238 6239 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6240 ArgExprs.size() < FT->getNumParams()) 6241 return nullptr; 6242 6243 bool NeedsNewDecl = false; 6244 unsigned i = 0; 6245 SmallVector<QualType, 8> OverloadParams; 6246 6247 for (QualType ParamType : FT->param_types()) { 6248 6249 // Convert array arguments to pointer to simplify type lookup. 6250 ExprResult ArgRes = 6251 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6252 if (ArgRes.isInvalid()) 6253 return nullptr; 6254 Expr *Arg = ArgRes.get(); 6255 QualType ArgType = Arg->getType(); 6256 if (!ParamType->isPointerType() || 6257 ParamType.hasAddressSpace() || 6258 !ArgType->isPointerType() || 6259 !ArgType->getPointeeType().hasAddressSpace()) { 6260 OverloadParams.push_back(ParamType); 6261 continue; 6262 } 6263 6264 QualType PointeeType = ParamType->getPointeeType(); 6265 if (PointeeType.hasAddressSpace()) 6266 continue; 6267 6268 NeedsNewDecl = true; 6269 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6270 6271 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6272 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6273 } 6274 6275 if (!NeedsNewDecl) 6276 return nullptr; 6277 6278 FunctionProtoType::ExtProtoInfo EPI; 6279 EPI.Variadic = FT->isVariadic(); 6280 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6281 OverloadParams, EPI); 6282 DeclContext *Parent = FDecl->getParent(); 6283 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6284 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6285 FDecl->getIdentifier(), OverloadTy, 6286 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6287 false, 6288 /*hasPrototype=*/true); 6289 SmallVector<ParmVarDecl*, 16> Params; 6290 FT = cast<FunctionProtoType>(OverloadTy); 6291 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6292 QualType ParamType = FT->getParamType(i); 6293 ParmVarDecl *Parm = 6294 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6295 SourceLocation(), nullptr, ParamType, 6296 /*TInfo=*/nullptr, SC_None, nullptr); 6297 Parm->setScopeInfo(0, i); 6298 Params.push_back(Parm); 6299 } 6300 OverloadDecl->setParams(Params); 6301 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6302 return OverloadDecl; 6303 } 6304 6305 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6306 FunctionDecl *Callee, 6307 MultiExprArg ArgExprs) { 6308 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6309 // similar attributes) really don't like it when functions are called with an 6310 // invalid number of args. 6311 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6312 /*PartialOverloading=*/false) && 6313 !Callee->isVariadic()) 6314 return; 6315 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6316 return; 6317 6318 if (const EnableIfAttr *Attr = 6319 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6320 S.Diag(Fn->getBeginLoc(), 6321 isa<CXXMethodDecl>(Callee) 6322 ? diag::err_ovl_no_viable_member_function_in_call 6323 : diag::err_ovl_no_viable_function_in_call) 6324 << Callee << Callee->getSourceRange(); 6325 S.Diag(Callee->getLocation(), 6326 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6327 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6328 return; 6329 } 6330 } 6331 6332 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6333 const UnresolvedMemberExpr *const UME, Sema &S) { 6334 6335 const auto GetFunctionLevelDCIfCXXClass = 6336 [](Sema &S) -> const CXXRecordDecl * { 6337 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6338 if (!DC || !DC->getParent()) 6339 return nullptr; 6340 6341 // If the call to some member function was made from within a member 6342 // function body 'M' return return 'M's parent. 6343 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6344 return MD->getParent()->getCanonicalDecl(); 6345 // else the call was made from within a default member initializer of a 6346 // class, so return the class. 6347 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6348 return RD->getCanonicalDecl(); 6349 return nullptr; 6350 }; 6351 // If our DeclContext is neither a member function nor a class (in the 6352 // case of a lambda in a default member initializer), we can't have an 6353 // enclosing 'this'. 6354 6355 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6356 if (!CurParentClass) 6357 return false; 6358 6359 // The naming class for implicit member functions call is the class in which 6360 // name lookup starts. 6361 const CXXRecordDecl *const NamingClass = 6362 UME->getNamingClass()->getCanonicalDecl(); 6363 assert(NamingClass && "Must have naming class even for implicit access"); 6364 6365 // If the unresolved member functions were found in a 'naming class' that is 6366 // related (either the same or derived from) to the class that contains the 6367 // member function that itself contained the implicit member access. 6368 6369 return CurParentClass == NamingClass || 6370 CurParentClass->isDerivedFrom(NamingClass); 6371 } 6372 6373 static void 6374 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6375 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6376 6377 if (!UME) 6378 return; 6379 6380 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6381 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6382 // already been captured, or if this is an implicit member function call (if 6383 // it isn't, an attempt to capture 'this' should already have been made). 6384 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6385 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6386 return; 6387 6388 // Check if the naming class in which the unresolved members were found is 6389 // related (same as or is a base of) to the enclosing class. 6390 6391 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6392 return; 6393 6394 6395 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6396 // If the enclosing function is not dependent, then this lambda is 6397 // capture ready, so if we can capture this, do so. 6398 if (!EnclosingFunctionCtx->isDependentContext()) { 6399 // If the current lambda and all enclosing lambdas can capture 'this' - 6400 // then go ahead and capture 'this' (since our unresolved overload set 6401 // contains at least one non-static member function). 6402 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6403 S.CheckCXXThisCapture(CallLoc); 6404 } else if (S.CurContext->isDependentContext()) { 6405 // ... since this is an implicit member reference, that might potentially 6406 // involve a 'this' capture, mark 'this' for potential capture in 6407 // enclosing lambdas. 6408 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6409 CurLSI->addPotentialThisCapture(CallLoc); 6410 } 6411 } 6412 6413 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6414 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6415 Expr *ExecConfig) { 6416 ExprResult Call = 6417 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6418 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6419 if (Call.isInvalid()) 6420 return Call; 6421 6422 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6423 // language modes. 6424 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6425 if (ULE->hasExplicitTemplateArgs() && 6426 ULE->decls_begin() == ULE->decls_end()) { 6427 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6428 ? diag::warn_cxx17_compat_adl_only_template_id 6429 : diag::ext_adl_only_template_id) 6430 << ULE->getName(); 6431 } 6432 } 6433 6434 if (LangOpts.OpenMP) 6435 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6436 ExecConfig); 6437 6438 return Call; 6439 } 6440 6441 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6442 /// This provides the location of the left/right parens and a list of comma 6443 /// locations. 6444 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6445 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6446 Expr *ExecConfig, bool IsExecConfig, 6447 bool AllowRecovery) { 6448 // Since this might be a postfix expression, get rid of ParenListExprs. 6449 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6450 if (Result.isInvalid()) return ExprError(); 6451 Fn = Result.get(); 6452 6453 if (checkArgsForPlaceholders(*this, ArgExprs)) 6454 return ExprError(); 6455 6456 if (getLangOpts().CPlusPlus) { 6457 // If this is a pseudo-destructor expression, build the call immediately. 6458 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6459 if (!ArgExprs.empty()) { 6460 // Pseudo-destructor calls should not have any arguments. 6461 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6462 << FixItHint::CreateRemoval( 6463 SourceRange(ArgExprs.front()->getBeginLoc(), 6464 ArgExprs.back()->getEndLoc())); 6465 } 6466 6467 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6468 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6469 } 6470 if (Fn->getType() == Context.PseudoObjectTy) { 6471 ExprResult result = CheckPlaceholderExpr(Fn); 6472 if (result.isInvalid()) return ExprError(); 6473 Fn = result.get(); 6474 } 6475 6476 // Determine whether this is a dependent call inside a C++ template, 6477 // in which case we won't do any semantic analysis now. 6478 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6479 if (ExecConfig) { 6480 return CUDAKernelCallExpr::Create(Context, Fn, 6481 cast<CallExpr>(ExecConfig), ArgExprs, 6482 Context.DependentTy, VK_PRValue, 6483 RParenLoc, CurFPFeatureOverrides()); 6484 } else { 6485 6486 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6487 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6488 Fn->getBeginLoc()); 6489 6490 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6491 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6492 } 6493 } 6494 6495 // Determine whether this is a call to an object (C++ [over.call.object]). 6496 if (Fn->getType()->isRecordType()) 6497 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6498 RParenLoc); 6499 6500 if (Fn->getType() == Context.UnknownAnyTy) { 6501 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6502 if (result.isInvalid()) return ExprError(); 6503 Fn = result.get(); 6504 } 6505 6506 if (Fn->getType() == Context.BoundMemberTy) { 6507 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6508 RParenLoc, AllowRecovery); 6509 } 6510 } 6511 6512 // Check for overloaded calls. This can happen even in C due to extensions. 6513 if (Fn->getType() == Context.OverloadTy) { 6514 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6515 6516 // We aren't supposed to apply this logic if there's an '&' involved. 6517 if (!find.HasFormOfMemberPointer) { 6518 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6519 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6520 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6521 OverloadExpr *ovl = find.Expression; 6522 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6523 return BuildOverloadedCallExpr( 6524 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6525 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6526 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6527 RParenLoc, AllowRecovery); 6528 } 6529 } 6530 6531 // If we're directly calling a function, get the appropriate declaration. 6532 if (Fn->getType() == Context.UnknownAnyTy) { 6533 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6534 if (result.isInvalid()) return ExprError(); 6535 Fn = result.get(); 6536 } 6537 6538 Expr *NakedFn = Fn->IgnoreParens(); 6539 6540 bool CallingNDeclIndirectly = false; 6541 NamedDecl *NDecl = nullptr; 6542 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6543 if (UnOp->getOpcode() == UO_AddrOf) { 6544 CallingNDeclIndirectly = true; 6545 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6546 } 6547 } 6548 6549 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6550 NDecl = DRE->getDecl(); 6551 6552 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6553 if (FDecl && FDecl->getBuiltinID()) { 6554 // Rewrite the function decl for this builtin by replacing parameters 6555 // with no explicit address space with the address space of the arguments 6556 // in ArgExprs. 6557 if ((FDecl = 6558 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6559 NDecl = FDecl; 6560 Fn = DeclRefExpr::Create( 6561 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6562 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6563 nullptr, DRE->isNonOdrUse()); 6564 } 6565 } 6566 } else if (isa<MemberExpr>(NakedFn)) 6567 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6568 6569 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6570 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6571 FD, /*Complain=*/true, Fn->getBeginLoc())) 6572 return ExprError(); 6573 6574 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6575 } 6576 6577 if (Context.isDependenceAllowed() && 6578 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6579 assert(!getLangOpts().CPlusPlus); 6580 assert((Fn->containsErrors() || 6581 llvm::any_of(ArgExprs, 6582 [](clang::Expr *E) { return E->containsErrors(); })) && 6583 "should only occur in error-recovery path."); 6584 QualType ReturnType = 6585 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6586 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6587 : Context.DependentTy; 6588 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6589 Expr::getValueKindForType(ReturnType), RParenLoc, 6590 CurFPFeatureOverrides()); 6591 } 6592 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6593 ExecConfig, IsExecConfig); 6594 } 6595 6596 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6597 // with the specified CallArgs 6598 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6599 MultiExprArg CallArgs) { 6600 StringRef Name = Context.BuiltinInfo.getName(Id); 6601 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6602 Sema::LookupOrdinaryName); 6603 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6604 6605 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6606 assert(BuiltInDecl && "failed to find builtin declaration"); 6607 6608 ExprResult DeclRef = 6609 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6610 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6611 6612 ExprResult Call = 6613 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6614 6615 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6616 return Call.get(); 6617 } 6618 6619 /// Parse a __builtin_astype expression. 6620 /// 6621 /// __builtin_astype( value, dst type ) 6622 /// 6623 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6624 SourceLocation BuiltinLoc, 6625 SourceLocation RParenLoc) { 6626 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6627 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6628 } 6629 6630 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6631 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6632 SourceLocation BuiltinLoc, 6633 SourceLocation RParenLoc) { 6634 ExprValueKind VK = VK_PRValue; 6635 ExprObjectKind OK = OK_Ordinary; 6636 QualType SrcTy = E->getType(); 6637 if (!SrcTy->isDependentType() && 6638 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6639 return ExprError( 6640 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6641 << DestTy << SrcTy << E->getSourceRange()); 6642 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6643 } 6644 6645 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6646 /// provided arguments. 6647 /// 6648 /// __builtin_convertvector( value, dst type ) 6649 /// 6650 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6651 SourceLocation BuiltinLoc, 6652 SourceLocation RParenLoc) { 6653 TypeSourceInfo *TInfo; 6654 GetTypeFromParser(ParsedDestTy, &TInfo); 6655 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6656 } 6657 6658 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6659 /// i.e. an expression not of \p OverloadTy. The expression should 6660 /// unary-convert to an expression of function-pointer or 6661 /// block-pointer type. 6662 /// 6663 /// \param NDecl the declaration being called, if available 6664 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6665 SourceLocation LParenLoc, 6666 ArrayRef<Expr *> Args, 6667 SourceLocation RParenLoc, Expr *Config, 6668 bool IsExecConfig, ADLCallKind UsesADL) { 6669 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6670 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6671 6672 // Functions with 'interrupt' attribute cannot be called directly. 6673 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6674 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6675 return ExprError(); 6676 } 6677 6678 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6679 // so there's some risk when calling out to non-interrupt handler functions 6680 // that the callee might not preserve them. This is easy to diagnose here, 6681 // but can be very challenging to debug. 6682 // Likewise, X86 interrupt handlers may only call routines with attribute 6683 // no_caller_saved_registers since there is no efficient way to 6684 // save and restore the non-GPR state. 6685 if (auto *Caller = getCurFunctionDecl()) { 6686 if (Caller->hasAttr<ARMInterruptAttr>()) { 6687 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6688 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6689 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6690 if (FDecl) 6691 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6692 } 6693 } 6694 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6695 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6696 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6697 if (FDecl) 6698 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6699 } 6700 } 6701 6702 // Promote the function operand. 6703 // We special-case function promotion here because we only allow promoting 6704 // builtin functions to function pointers in the callee of a call. 6705 ExprResult Result; 6706 QualType ResultTy; 6707 if (BuiltinID && 6708 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6709 // Extract the return type from the (builtin) function pointer type. 6710 // FIXME Several builtins still have setType in 6711 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6712 // Builtins.def to ensure they are correct before removing setType calls. 6713 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6714 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6715 ResultTy = FDecl->getCallResultType(); 6716 } else { 6717 Result = CallExprUnaryConversions(Fn); 6718 ResultTy = Context.BoolTy; 6719 } 6720 if (Result.isInvalid()) 6721 return ExprError(); 6722 Fn = Result.get(); 6723 6724 // Check for a valid function type, but only if it is not a builtin which 6725 // requires custom type checking. These will be handled by 6726 // CheckBuiltinFunctionCall below just after creation of the call expression. 6727 const FunctionType *FuncT = nullptr; 6728 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6729 retry: 6730 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6731 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6732 // have type pointer to function". 6733 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6734 if (!FuncT) 6735 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6736 << Fn->getType() << Fn->getSourceRange()); 6737 } else if (const BlockPointerType *BPT = 6738 Fn->getType()->getAs<BlockPointerType>()) { 6739 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6740 } else { 6741 // Handle calls to expressions of unknown-any type. 6742 if (Fn->getType() == Context.UnknownAnyTy) { 6743 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6744 if (rewrite.isInvalid()) 6745 return ExprError(); 6746 Fn = rewrite.get(); 6747 goto retry; 6748 } 6749 6750 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6751 << Fn->getType() << Fn->getSourceRange()); 6752 } 6753 } 6754 6755 // Get the number of parameters in the function prototype, if any. 6756 // We will allocate space for max(Args.size(), NumParams) arguments 6757 // in the call expression. 6758 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6759 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6760 6761 CallExpr *TheCall; 6762 if (Config) { 6763 assert(UsesADL == ADLCallKind::NotADL && 6764 "CUDAKernelCallExpr should not use ADL"); 6765 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6766 Args, ResultTy, VK_PRValue, RParenLoc, 6767 CurFPFeatureOverrides(), NumParams); 6768 } else { 6769 TheCall = 6770 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6771 CurFPFeatureOverrides(), NumParams, UsesADL); 6772 } 6773 6774 if (!Context.isDependenceAllowed()) { 6775 // Forget about the nulled arguments since typo correction 6776 // do not handle them well. 6777 TheCall->shrinkNumArgs(Args.size()); 6778 // C cannot always handle TypoExpr nodes in builtin calls and direct 6779 // function calls as their argument checking don't necessarily handle 6780 // dependent types properly, so make sure any TypoExprs have been 6781 // dealt with. 6782 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6783 if (!Result.isUsable()) return ExprError(); 6784 CallExpr *TheOldCall = TheCall; 6785 TheCall = dyn_cast<CallExpr>(Result.get()); 6786 bool CorrectedTypos = TheCall != TheOldCall; 6787 if (!TheCall) return Result; 6788 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6789 6790 // A new call expression node was created if some typos were corrected. 6791 // However it may not have been constructed with enough storage. In this 6792 // case, rebuild the node with enough storage. The waste of space is 6793 // immaterial since this only happens when some typos were corrected. 6794 if (CorrectedTypos && Args.size() < NumParams) { 6795 if (Config) 6796 TheCall = CUDAKernelCallExpr::Create( 6797 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6798 RParenLoc, CurFPFeatureOverrides(), NumParams); 6799 else 6800 TheCall = 6801 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6802 CurFPFeatureOverrides(), NumParams, UsesADL); 6803 } 6804 // We can now handle the nulled arguments for the default arguments. 6805 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6806 } 6807 6808 // Bail out early if calling a builtin with custom type checking. 6809 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6810 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6811 6812 if (getLangOpts().CUDA) { 6813 if (Config) { 6814 // CUDA: Kernel calls must be to global functions 6815 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6816 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6817 << FDecl << Fn->getSourceRange()); 6818 6819 // CUDA: Kernel function must have 'void' return type 6820 if (!FuncT->getReturnType()->isVoidType() && 6821 !FuncT->getReturnType()->getAs<AutoType>() && 6822 !FuncT->getReturnType()->isInstantiationDependentType()) 6823 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6824 << Fn->getType() << Fn->getSourceRange()); 6825 } else { 6826 // CUDA: Calls to global functions must be configured 6827 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6828 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6829 << FDecl << Fn->getSourceRange()); 6830 } 6831 } 6832 6833 // Check for a valid return type 6834 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6835 FDecl)) 6836 return ExprError(); 6837 6838 // We know the result type of the call, set it. 6839 TheCall->setType(FuncT->getCallResultType(Context)); 6840 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6841 6842 if (Proto) { 6843 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6844 IsExecConfig)) 6845 return ExprError(); 6846 } else { 6847 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6848 6849 if (FDecl) { 6850 // Check if we have too few/too many template arguments, based 6851 // on our knowledge of the function definition. 6852 const FunctionDecl *Def = nullptr; 6853 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6854 Proto = Def->getType()->getAs<FunctionProtoType>(); 6855 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6856 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6857 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6858 } 6859 6860 // If the function we're calling isn't a function prototype, but we have 6861 // a function prototype from a prior declaratiom, use that prototype. 6862 if (!FDecl->hasPrototype()) 6863 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6864 } 6865 6866 // Promote the arguments (C99 6.5.2.2p6). 6867 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6868 Expr *Arg = Args[i]; 6869 6870 if (Proto && i < Proto->getNumParams()) { 6871 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6872 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6873 ExprResult ArgE = 6874 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6875 if (ArgE.isInvalid()) 6876 return true; 6877 6878 Arg = ArgE.getAs<Expr>(); 6879 6880 } else { 6881 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6882 6883 if (ArgE.isInvalid()) 6884 return true; 6885 6886 Arg = ArgE.getAs<Expr>(); 6887 } 6888 6889 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6890 diag::err_call_incomplete_argument, Arg)) 6891 return ExprError(); 6892 6893 TheCall->setArg(i, Arg); 6894 } 6895 TheCall->computeDependence(); 6896 } 6897 6898 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6899 if (!Method->isStatic()) 6900 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6901 << Fn->getSourceRange()); 6902 6903 // Check for sentinels 6904 if (NDecl) 6905 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6906 6907 // Warn for unions passing across security boundary (CMSE). 6908 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6909 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6910 if (const auto *RT = 6911 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6912 if (RT->getDecl()->isOrContainsUnion()) 6913 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6914 << 0 << i; 6915 } 6916 } 6917 } 6918 6919 // Do special checking on direct calls to functions. 6920 if (FDecl) { 6921 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6922 return ExprError(); 6923 6924 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6925 6926 if (BuiltinID) 6927 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6928 } else if (NDecl) { 6929 if (CheckPointerCall(NDecl, TheCall, Proto)) 6930 return ExprError(); 6931 } else { 6932 if (CheckOtherCall(TheCall, Proto)) 6933 return ExprError(); 6934 } 6935 6936 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6937 } 6938 6939 ExprResult 6940 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6941 SourceLocation RParenLoc, Expr *InitExpr) { 6942 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6943 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6944 6945 TypeSourceInfo *TInfo; 6946 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6947 if (!TInfo) 6948 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6949 6950 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6951 } 6952 6953 ExprResult 6954 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6955 SourceLocation RParenLoc, Expr *LiteralExpr) { 6956 QualType literalType = TInfo->getType(); 6957 6958 if (literalType->isArrayType()) { 6959 if (RequireCompleteSizedType( 6960 LParenLoc, Context.getBaseElementType(literalType), 6961 diag::err_array_incomplete_or_sizeless_type, 6962 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6963 return ExprError(); 6964 if (literalType->isVariableArrayType()) { 6965 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6966 diag::err_variable_object_no_init)) { 6967 return ExprError(); 6968 } 6969 } 6970 } else if (!literalType->isDependentType() && 6971 RequireCompleteType(LParenLoc, literalType, 6972 diag::err_typecheck_decl_incomplete_type, 6973 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6974 return ExprError(); 6975 6976 InitializedEntity Entity 6977 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6978 InitializationKind Kind 6979 = InitializationKind::CreateCStyleCast(LParenLoc, 6980 SourceRange(LParenLoc, RParenLoc), 6981 /*InitList=*/true); 6982 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6983 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6984 &literalType); 6985 if (Result.isInvalid()) 6986 return ExprError(); 6987 LiteralExpr = Result.get(); 6988 6989 bool isFileScope = !CurContext->isFunctionOrMethod(); 6990 6991 // In C, compound literals are l-values for some reason. 6992 // For GCC compatibility, in C++, file-scope array compound literals with 6993 // constant initializers are also l-values, and compound literals are 6994 // otherwise prvalues. 6995 // 6996 // (GCC also treats C++ list-initialized file-scope array prvalues with 6997 // constant initializers as l-values, but that's non-conforming, so we don't 6998 // follow it there.) 6999 // 7000 // FIXME: It would be better to handle the lvalue cases as materializing and 7001 // lifetime-extending a temporary object, but our materialized temporaries 7002 // representation only supports lifetime extension from a variable, not "out 7003 // of thin air". 7004 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7005 // is bound to the result of applying array-to-pointer decay to the compound 7006 // literal. 7007 // FIXME: GCC supports compound literals of reference type, which should 7008 // obviously have a value kind derived from the kind of reference involved. 7009 ExprValueKind VK = 7010 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7011 ? VK_PRValue 7012 : VK_LValue; 7013 7014 if (isFileScope) 7015 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7016 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7017 Expr *Init = ILE->getInit(i); 7018 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7019 } 7020 7021 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7022 VK, LiteralExpr, isFileScope); 7023 if (isFileScope) { 7024 if (!LiteralExpr->isTypeDependent() && 7025 !LiteralExpr->isValueDependent() && 7026 !literalType->isDependentType()) // C99 6.5.2.5p3 7027 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7028 return ExprError(); 7029 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7030 literalType.getAddressSpace() != LangAS::Default) { 7031 // Embedded-C extensions to C99 6.5.2.5: 7032 // "If the compound literal occurs inside the body of a function, the 7033 // type name shall not be qualified by an address-space qualifier." 7034 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7035 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7036 return ExprError(); 7037 } 7038 7039 if (!isFileScope && !getLangOpts().CPlusPlus) { 7040 // Compound literals that have automatic storage duration are destroyed at 7041 // the end of the scope in C; in C++, they're just temporaries. 7042 7043 // Emit diagnostics if it is or contains a C union type that is non-trivial 7044 // to destruct. 7045 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7046 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7047 NTCUC_CompoundLiteral, NTCUK_Destruct); 7048 7049 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7050 if (literalType.isDestructedType()) { 7051 Cleanup.setExprNeedsCleanups(true); 7052 ExprCleanupObjects.push_back(E); 7053 getCurFunction()->setHasBranchProtectedScope(); 7054 } 7055 } 7056 7057 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7058 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7059 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7060 E->getInitializer()->getExprLoc()); 7061 7062 return MaybeBindToTemporary(E); 7063 } 7064 7065 ExprResult 7066 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7067 SourceLocation RBraceLoc) { 7068 // Only produce each kind of designated initialization diagnostic once. 7069 SourceLocation FirstDesignator; 7070 bool DiagnosedArrayDesignator = false; 7071 bool DiagnosedNestedDesignator = false; 7072 bool DiagnosedMixedDesignator = false; 7073 7074 // Check that any designated initializers are syntactically valid in the 7075 // current language mode. 7076 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7077 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7078 if (FirstDesignator.isInvalid()) 7079 FirstDesignator = DIE->getBeginLoc(); 7080 7081 if (!getLangOpts().CPlusPlus) 7082 break; 7083 7084 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7085 DiagnosedNestedDesignator = true; 7086 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7087 << DIE->getDesignatorsSourceRange(); 7088 } 7089 7090 for (auto &Desig : DIE->designators()) { 7091 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7092 DiagnosedArrayDesignator = true; 7093 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7094 << Desig.getSourceRange(); 7095 } 7096 } 7097 7098 if (!DiagnosedMixedDesignator && 7099 !isa<DesignatedInitExpr>(InitArgList[0])) { 7100 DiagnosedMixedDesignator = true; 7101 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7102 << DIE->getSourceRange(); 7103 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7104 << InitArgList[0]->getSourceRange(); 7105 } 7106 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7107 isa<DesignatedInitExpr>(InitArgList[0])) { 7108 DiagnosedMixedDesignator = true; 7109 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7110 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7111 << DIE->getSourceRange(); 7112 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7113 << InitArgList[I]->getSourceRange(); 7114 } 7115 } 7116 7117 if (FirstDesignator.isValid()) { 7118 // Only diagnose designated initiaization as a C++20 extension if we didn't 7119 // already diagnose use of (non-C++20) C99 designator syntax. 7120 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7121 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7122 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7123 ? diag::warn_cxx17_compat_designated_init 7124 : diag::ext_cxx_designated_init); 7125 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7126 Diag(FirstDesignator, diag::ext_designated_init); 7127 } 7128 } 7129 7130 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7131 } 7132 7133 ExprResult 7134 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7135 SourceLocation RBraceLoc) { 7136 // Semantic analysis for initializers is done by ActOnDeclarator() and 7137 // CheckInitializer() - it requires knowledge of the object being initialized. 7138 7139 // Immediately handle non-overload placeholders. Overloads can be 7140 // resolved contextually, but everything else here can't. 7141 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7142 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7143 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7144 7145 // Ignore failures; dropping the entire initializer list because 7146 // of one failure would be terrible for indexing/etc. 7147 if (result.isInvalid()) continue; 7148 7149 InitArgList[I] = result.get(); 7150 } 7151 } 7152 7153 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7154 RBraceLoc); 7155 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7156 return E; 7157 } 7158 7159 /// Do an explicit extend of the given block pointer if we're in ARC. 7160 void Sema::maybeExtendBlockObject(ExprResult &E) { 7161 assert(E.get()->getType()->isBlockPointerType()); 7162 assert(E.get()->isPRValue()); 7163 7164 // Only do this in an r-value context. 7165 if (!getLangOpts().ObjCAutoRefCount) return; 7166 7167 E = ImplicitCastExpr::Create( 7168 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7169 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7170 Cleanup.setExprNeedsCleanups(true); 7171 } 7172 7173 /// Prepare a conversion of the given expression to an ObjC object 7174 /// pointer type. 7175 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7176 QualType type = E.get()->getType(); 7177 if (type->isObjCObjectPointerType()) { 7178 return CK_BitCast; 7179 } else if (type->isBlockPointerType()) { 7180 maybeExtendBlockObject(E); 7181 return CK_BlockPointerToObjCPointerCast; 7182 } else { 7183 assert(type->isPointerType()); 7184 return CK_CPointerToObjCPointerCast; 7185 } 7186 } 7187 7188 /// Prepares for a scalar cast, performing all the necessary stages 7189 /// except the final cast and returning the kind required. 7190 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7191 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7192 // Also, callers should have filtered out the invalid cases with 7193 // pointers. Everything else should be possible. 7194 7195 QualType SrcTy = Src.get()->getType(); 7196 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7197 return CK_NoOp; 7198 7199 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7200 case Type::STK_MemberPointer: 7201 llvm_unreachable("member pointer type in C"); 7202 7203 case Type::STK_CPointer: 7204 case Type::STK_BlockPointer: 7205 case Type::STK_ObjCObjectPointer: 7206 switch (DestTy->getScalarTypeKind()) { 7207 case Type::STK_CPointer: { 7208 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7209 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7210 if (SrcAS != DestAS) 7211 return CK_AddressSpaceConversion; 7212 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7213 return CK_NoOp; 7214 return CK_BitCast; 7215 } 7216 case Type::STK_BlockPointer: 7217 return (SrcKind == Type::STK_BlockPointer 7218 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7219 case Type::STK_ObjCObjectPointer: 7220 if (SrcKind == Type::STK_ObjCObjectPointer) 7221 return CK_BitCast; 7222 if (SrcKind == Type::STK_CPointer) 7223 return CK_CPointerToObjCPointerCast; 7224 maybeExtendBlockObject(Src); 7225 return CK_BlockPointerToObjCPointerCast; 7226 case Type::STK_Bool: 7227 return CK_PointerToBoolean; 7228 case Type::STK_Integral: 7229 return CK_PointerToIntegral; 7230 case Type::STK_Floating: 7231 case Type::STK_FloatingComplex: 7232 case Type::STK_IntegralComplex: 7233 case Type::STK_MemberPointer: 7234 case Type::STK_FixedPoint: 7235 llvm_unreachable("illegal cast from pointer"); 7236 } 7237 llvm_unreachable("Should have returned before this"); 7238 7239 case Type::STK_FixedPoint: 7240 switch (DestTy->getScalarTypeKind()) { 7241 case Type::STK_FixedPoint: 7242 return CK_FixedPointCast; 7243 case Type::STK_Bool: 7244 return CK_FixedPointToBoolean; 7245 case Type::STK_Integral: 7246 return CK_FixedPointToIntegral; 7247 case Type::STK_Floating: 7248 return CK_FixedPointToFloating; 7249 case Type::STK_IntegralComplex: 7250 case Type::STK_FloatingComplex: 7251 Diag(Src.get()->getExprLoc(), 7252 diag::err_unimplemented_conversion_with_fixed_point_type) 7253 << DestTy; 7254 return CK_IntegralCast; 7255 case Type::STK_CPointer: 7256 case Type::STK_ObjCObjectPointer: 7257 case Type::STK_BlockPointer: 7258 case Type::STK_MemberPointer: 7259 llvm_unreachable("illegal cast to pointer type"); 7260 } 7261 llvm_unreachable("Should have returned before this"); 7262 7263 case Type::STK_Bool: // casting from bool is like casting from an integer 7264 case Type::STK_Integral: 7265 switch (DestTy->getScalarTypeKind()) { 7266 case Type::STK_CPointer: 7267 case Type::STK_ObjCObjectPointer: 7268 case Type::STK_BlockPointer: 7269 if (Src.get()->isNullPointerConstant(Context, 7270 Expr::NPC_ValueDependentIsNull)) 7271 return CK_NullToPointer; 7272 return CK_IntegralToPointer; 7273 case Type::STK_Bool: 7274 return CK_IntegralToBoolean; 7275 case Type::STK_Integral: 7276 return CK_IntegralCast; 7277 case Type::STK_Floating: 7278 return CK_IntegralToFloating; 7279 case Type::STK_IntegralComplex: 7280 Src = ImpCastExprToType(Src.get(), 7281 DestTy->castAs<ComplexType>()->getElementType(), 7282 CK_IntegralCast); 7283 return CK_IntegralRealToComplex; 7284 case Type::STK_FloatingComplex: 7285 Src = ImpCastExprToType(Src.get(), 7286 DestTy->castAs<ComplexType>()->getElementType(), 7287 CK_IntegralToFloating); 7288 return CK_FloatingRealToComplex; 7289 case Type::STK_MemberPointer: 7290 llvm_unreachable("member pointer type in C"); 7291 case Type::STK_FixedPoint: 7292 return CK_IntegralToFixedPoint; 7293 } 7294 llvm_unreachable("Should have returned before this"); 7295 7296 case Type::STK_Floating: 7297 switch (DestTy->getScalarTypeKind()) { 7298 case Type::STK_Floating: 7299 return CK_FloatingCast; 7300 case Type::STK_Bool: 7301 return CK_FloatingToBoolean; 7302 case Type::STK_Integral: 7303 return CK_FloatingToIntegral; 7304 case Type::STK_FloatingComplex: 7305 Src = ImpCastExprToType(Src.get(), 7306 DestTy->castAs<ComplexType>()->getElementType(), 7307 CK_FloatingCast); 7308 return CK_FloatingRealToComplex; 7309 case Type::STK_IntegralComplex: 7310 Src = ImpCastExprToType(Src.get(), 7311 DestTy->castAs<ComplexType>()->getElementType(), 7312 CK_FloatingToIntegral); 7313 return CK_IntegralRealToComplex; 7314 case Type::STK_CPointer: 7315 case Type::STK_ObjCObjectPointer: 7316 case Type::STK_BlockPointer: 7317 llvm_unreachable("valid float->pointer cast?"); 7318 case Type::STK_MemberPointer: 7319 llvm_unreachable("member pointer type in C"); 7320 case Type::STK_FixedPoint: 7321 return CK_FloatingToFixedPoint; 7322 } 7323 llvm_unreachable("Should have returned before this"); 7324 7325 case Type::STK_FloatingComplex: 7326 switch (DestTy->getScalarTypeKind()) { 7327 case Type::STK_FloatingComplex: 7328 return CK_FloatingComplexCast; 7329 case Type::STK_IntegralComplex: 7330 return CK_FloatingComplexToIntegralComplex; 7331 case Type::STK_Floating: { 7332 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7333 if (Context.hasSameType(ET, DestTy)) 7334 return CK_FloatingComplexToReal; 7335 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7336 return CK_FloatingCast; 7337 } 7338 case Type::STK_Bool: 7339 return CK_FloatingComplexToBoolean; 7340 case Type::STK_Integral: 7341 Src = ImpCastExprToType(Src.get(), 7342 SrcTy->castAs<ComplexType>()->getElementType(), 7343 CK_FloatingComplexToReal); 7344 return CK_FloatingToIntegral; 7345 case Type::STK_CPointer: 7346 case Type::STK_ObjCObjectPointer: 7347 case Type::STK_BlockPointer: 7348 llvm_unreachable("valid complex float->pointer cast?"); 7349 case Type::STK_MemberPointer: 7350 llvm_unreachable("member pointer type in C"); 7351 case Type::STK_FixedPoint: 7352 Diag(Src.get()->getExprLoc(), 7353 diag::err_unimplemented_conversion_with_fixed_point_type) 7354 << SrcTy; 7355 return CK_IntegralCast; 7356 } 7357 llvm_unreachable("Should have returned before this"); 7358 7359 case Type::STK_IntegralComplex: 7360 switch (DestTy->getScalarTypeKind()) { 7361 case Type::STK_FloatingComplex: 7362 return CK_IntegralComplexToFloatingComplex; 7363 case Type::STK_IntegralComplex: 7364 return CK_IntegralComplexCast; 7365 case Type::STK_Integral: { 7366 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7367 if (Context.hasSameType(ET, DestTy)) 7368 return CK_IntegralComplexToReal; 7369 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7370 return CK_IntegralCast; 7371 } 7372 case Type::STK_Bool: 7373 return CK_IntegralComplexToBoolean; 7374 case Type::STK_Floating: 7375 Src = ImpCastExprToType(Src.get(), 7376 SrcTy->castAs<ComplexType>()->getElementType(), 7377 CK_IntegralComplexToReal); 7378 return CK_IntegralToFloating; 7379 case Type::STK_CPointer: 7380 case Type::STK_ObjCObjectPointer: 7381 case Type::STK_BlockPointer: 7382 llvm_unreachable("valid complex int->pointer cast?"); 7383 case Type::STK_MemberPointer: 7384 llvm_unreachable("member pointer type in C"); 7385 case Type::STK_FixedPoint: 7386 Diag(Src.get()->getExprLoc(), 7387 diag::err_unimplemented_conversion_with_fixed_point_type) 7388 << SrcTy; 7389 return CK_IntegralCast; 7390 } 7391 llvm_unreachable("Should have returned before this"); 7392 } 7393 7394 llvm_unreachable("Unhandled scalar cast"); 7395 } 7396 7397 static bool breakDownVectorType(QualType type, uint64_t &len, 7398 QualType &eltType) { 7399 // Vectors are simple. 7400 if (const VectorType *vecType = type->getAs<VectorType>()) { 7401 len = vecType->getNumElements(); 7402 eltType = vecType->getElementType(); 7403 assert(eltType->isScalarType()); 7404 return true; 7405 } 7406 7407 // We allow lax conversion to and from non-vector types, but only if 7408 // they're real types (i.e. non-complex, non-pointer scalar types). 7409 if (!type->isRealType()) return false; 7410 7411 len = 1; 7412 eltType = type; 7413 return true; 7414 } 7415 7416 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7417 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7418 /// allowed? 7419 /// 7420 /// This will also return false if the two given types do not make sense from 7421 /// the perspective of SVE bitcasts. 7422 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7423 assert(srcTy->isVectorType() || destTy->isVectorType()); 7424 7425 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7426 if (!FirstType->isSizelessBuiltinType()) 7427 return false; 7428 7429 const auto *VecTy = SecondType->getAs<VectorType>(); 7430 return VecTy && 7431 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7432 }; 7433 7434 return ValidScalableConversion(srcTy, destTy) || 7435 ValidScalableConversion(destTy, srcTy); 7436 } 7437 7438 /// Are the two types matrix types and do they have the same dimensions i.e. 7439 /// do they have the same number of rows and the same number of columns? 7440 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7441 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7442 return false; 7443 7444 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7445 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7446 7447 return matSrcType->getNumRows() == matDestType->getNumRows() && 7448 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7449 } 7450 7451 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7452 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7453 7454 uint64_t SrcLen, DestLen; 7455 QualType SrcEltTy, DestEltTy; 7456 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7457 return false; 7458 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7459 return false; 7460 7461 // ASTContext::getTypeSize will return the size rounded up to a 7462 // power of 2, so instead of using that, we need to use the raw 7463 // element size multiplied by the element count. 7464 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7465 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7466 7467 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7468 } 7469 7470 /// Are the two types lax-compatible vector types? That is, given 7471 /// that one of them is a vector, do they have equal storage sizes, 7472 /// where the storage size is the number of elements times the element 7473 /// size? 7474 /// 7475 /// This will also return false if either of the types is neither a 7476 /// vector nor a real type. 7477 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7478 assert(destTy->isVectorType() || srcTy->isVectorType()); 7479 7480 // Disallow lax conversions between scalars and ExtVectors (these 7481 // conversions are allowed for other vector types because common headers 7482 // depend on them). Most scalar OP ExtVector cases are handled by the 7483 // splat path anyway, which does what we want (convert, not bitcast). 7484 // What this rules out for ExtVectors is crazy things like char4*float. 7485 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7486 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7487 7488 return areVectorTypesSameSize(srcTy, destTy); 7489 } 7490 7491 /// Is this a legal conversion between two types, one of which is 7492 /// known to be a vector type? 7493 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7494 assert(destTy->isVectorType() || srcTy->isVectorType()); 7495 7496 switch (Context.getLangOpts().getLaxVectorConversions()) { 7497 case LangOptions::LaxVectorConversionKind::None: 7498 return false; 7499 7500 case LangOptions::LaxVectorConversionKind::Integer: 7501 if (!srcTy->isIntegralOrEnumerationType()) { 7502 auto *Vec = srcTy->getAs<VectorType>(); 7503 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7504 return false; 7505 } 7506 if (!destTy->isIntegralOrEnumerationType()) { 7507 auto *Vec = destTy->getAs<VectorType>(); 7508 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7509 return false; 7510 } 7511 // OK, integer (vector) -> integer (vector) bitcast. 7512 break; 7513 7514 case LangOptions::LaxVectorConversionKind::All: 7515 break; 7516 } 7517 7518 return areLaxCompatibleVectorTypes(srcTy, destTy); 7519 } 7520 7521 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7522 CastKind &Kind) { 7523 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7524 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7525 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7526 << DestTy << SrcTy << R; 7527 } 7528 } else if (SrcTy->isMatrixType()) { 7529 return Diag(R.getBegin(), 7530 diag::err_invalid_conversion_between_matrix_and_type) 7531 << SrcTy << DestTy << R; 7532 } else if (DestTy->isMatrixType()) { 7533 return Diag(R.getBegin(), 7534 diag::err_invalid_conversion_between_matrix_and_type) 7535 << DestTy << SrcTy << R; 7536 } 7537 7538 Kind = CK_MatrixCast; 7539 return false; 7540 } 7541 7542 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7543 CastKind &Kind) { 7544 assert(VectorTy->isVectorType() && "Not a vector type!"); 7545 7546 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7547 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7548 return Diag(R.getBegin(), 7549 Ty->isVectorType() ? 7550 diag::err_invalid_conversion_between_vectors : 7551 diag::err_invalid_conversion_between_vector_and_integer) 7552 << VectorTy << Ty << R; 7553 } else 7554 return Diag(R.getBegin(), 7555 diag::err_invalid_conversion_between_vector_and_scalar) 7556 << VectorTy << Ty << R; 7557 7558 Kind = CK_BitCast; 7559 return false; 7560 } 7561 7562 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7563 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7564 7565 if (DestElemTy == SplattedExpr->getType()) 7566 return SplattedExpr; 7567 7568 assert(DestElemTy->isFloatingType() || 7569 DestElemTy->isIntegralOrEnumerationType()); 7570 7571 CastKind CK; 7572 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7573 // OpenCL requires that we convert `true` boolean expressions to -1, but 7574 // only when splatting vectors. 7575 if (DestElemTy->isFloatingType()) { 7576 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7577 // in two steps: boolean to signed integral, then to floating. 7578 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7579 CK_BooleanToSignedIntegral); 7580 SplattedExpr = CastExprRes.get(); 7581 CK = CK_IntegralToFloating; 7582 } else { 7583 CK = CK_BooleanToSignedIntegral; 7584 } 7585 } else { 7586 ExprResult CastExprRes = SplattedExpr; 7587 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7588 if (CastExprRes.isInvalid()) 7589 return ExprError(); 7590 SplattedExpr = CastExprRes.get(); 7591 } 7592 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7593 } 7594 7595 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7596 Expr *CastExpr, CastKind &Kind) { 7597 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7598 7599 QualType SrcTy = CastExpr->getType(); 7600 7601 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7602 // an ExtVectorType. 7603 // In OpenCL, casts between vectors of different types are not allowed. 7604 // (See OpenCL 6.2). 7605 if (SrcTy->isVectorType()) { 7606 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7607 (getLangOpts().OpenCL && 7608 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7609 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7610 << DestTy << SrcTy << R; 7611 return ExprError(); 7612 } 7613 Kind = CK_BitCast; 7614 return CastExpr; 7615 } 7616 7617 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7618 // conversion will take place first from scalar to elt type, and then 7619 // splat from elt type to vector. 7620 if (SrcTy->isPointerType()) 7621 return Diag(R.getBegin(), 7622 diag::err_invalid_conversion_between_vector_and_scalar) 7623 << DestTy << SrcTy << R; 7624 7625 Kind = CK_VectorSplat; 7626 return prepareVectorSplat(DestTy, CastExpr); 7627 } 7628 7629 ExprResult 7630 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7631 Declarator &D, ParsedType &Ty, 7632 SourceLocation RParenLoc, Expr *CastExpr) { 7633 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7634 "ActOnCastExpr(): missing type or expr"); 7635 7636 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7637 if (D.isInvalidType()) 7638 return ExprError(); 7639 7640 if (getLangOpts().CPlusPlus) { 7641 // Check that there are no default arguments (C++ only). 7642 CheckExtraCXXDefaultArguments(D); 7643 } else { 7644 // Make sure any TypoExprs have been dealt with. 7645 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7646 if (!Res.isUsable()) 7647 return ExprError(); 7648 CastExpr = Res.get(); 7649 } 7650 7651 checkUnusedDeclAttributes(D); 7652 7653 QualType castType = castTInfo->getType(); 7654 Ty = CreateParsedType(castType, castTInfo); 7655 7656 bool isVectorLiteral = false; 7657 7658 // Check for an altivec or OpenCL literal, 7659 // i.e. all the elements are integer constants. 7660 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7661 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7662 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7663 && castType->isVectorType() && (PE || PLE)) { 7664 if (PLE && PLE->getNumExprs() == 0) { 7665 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7666 return ExprError(); 7667 } 7668 if (PE || PLE->getNumExprs() == 1) { 7669 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7670 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7671 isVectorLiteral = true; 7672 } 7673 else 7674 isVectorLiteral = true; 7675 } 7676 7677 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7678 // then handle it as such. 7679 if (isVectorLiteral) 7680 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7681 7682 // If the Expr being casted is a ParenListExpr, handle it specially. 7683 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7684 // sequence of BinOp comma operators. 7685 if (isa<ParenListExpr>(CastExpr)) { 7686 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7687 if (Result.isInvalid()) return ExprError(); 7688 CastExpr = Result.get(); 7689 } 7690 7691 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7692 !getSourceManager().isInSystemMacro(LParenLoc)) 7693 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7694 7695 CheckTollFreeBridgeCast(castType, CastExpr); 7696 7697 CheckObjCBridgeRelatedCast(castType, CastExpr); 7698 7699 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7700 7701 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7702 } 7703 7704 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7705 SourceLocation RParenLoc, Expr *E, 7706 TypeSourceInfo *TInfo) { 7707 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7708 "Expected paren or paren list expression"); 7709 7710 Expr **exprs; 7711 unsigned numExprs; 7712 Expr *subExpr; 7713 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7714 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7715 LiteralLParenLoc = PE->getLParenLoc(); 7716 LiteralRParenLoc = PE->getRParenLoc(); 7717 exprs = PE->getExprs(); 7718 numExprs = PE->getNumExprs(); 7719 } else { // isa<ParenExpr> by assertion at function entrance 7720 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7721 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7722 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7723 exprs = &subExpr; 7724 numExprs = 1; 7725 } 7726 7727 QualType Ty = TInfo->getType(); 7728 assert(Ty->isVectorType() && "Expected vector type"); 7729 7730 SmallVector<Expr *, 8> initExprs; 7731 const VectorType *VTy = Ty->castAs<VectorType>(); 7732 unsigned numElems = VTy->getNumElements(); 7733 7734 // '(...)' form of vector initialization in AltiVec: the number of 7735 // initializers must be one or must match the size of the vector. 7736 // If a single value is specified in the initializer then it will be 7737 // replicated to all the components of the vector 7738 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7739 VTy->getElementType())) 7740 return ExprError(); 7741 if (ShouldSplatAltivecScalarInCast(VTy)) { 7742 // The number of initializers must be one or must match the size of the 7743 // vector. If a single value is specified in the initializer then it will 7744 // be replicated to all the components of the vector 7745 if (numExprs == 1) { 7746 QualType ElemTy = VTy->getElementType(); 7747 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7748 if (Literal.isInvalid()) 7749 return ExprError(); 7750 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7751 PrepareScalarCast(Literal, ElemTy)); 7752 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7753 } 7754 else if (numExprs < numElems) { 7755 Diag(E->getExprLoc(), 7756 diag::err_incorrect_number_of_vector_initializers); 7757 return ExprError(); 7758 } 7759 else 7760 initExprs.append(exprs, exprs + numExprs); 7761 } 7762 else { 7763 // For OpenCL, when the number of initializers is a single value, 7764 // it will be replicated to all components of the vector. 7765 if (getLangOpts().OpenCL && 7766 VTy->getVectorKind() == VectorType::GenericVector && 7767 numExprs == 1) { 7768 QualType ElemTy = VTy->getElementType(); 7769 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7770 if (Literal.isInvalid()) 7771 return ExprError(); 7772 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7773 PrepareScalarCast(Literal, ElemTy)); 7774 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7775 } 7776 7777 initExprs.append(exprs, exprs + numExprs); 7778 } 7779 // FIXME: This means that pretty-printing the final AST will produce curly 7780 // braces instead of the original commas. 7781 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7782 initExprs, LiteralRParenLoc); 7783 initE->setType(Ty); 7784 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7785 } 7786 7787 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7788 /// the ParenListExpr into a sequence of comma binary operators. 7789 ExprResult 7790 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7791 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7792 if (!E) 7793 return OrigExpr; 7794 7795 ExprResult Result(E->getExpr(0)); 7796 7797 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7798 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7799 E->getExpr(i)); 7800 7801 if (Result.isInvalid()) return ExprError(); 7802 7803 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7804 } 7805 7806 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7807 SourceLocation R, 7808 MultiExprArg Val) { 7809 return ParenListExpr::Create(Context, L, Val, R); 7810 } 7811 7812 /// Emit a specialized diagnostic when one expression is a null pointer 7813 /// constant and the other is not a pointer. Returns true if a diagnostic is 7814 /// emitted. 7815 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7816 SourceLocation QuestionLoc) { 7817 Expr *NullExpr = LHSExpr; 7818 Expr *NonPointerExpr = RHSExpr; 7819 Expr::NullPointerConstantKind NullKind = 7820 NullExpr->isNullPointerConstant(Context, 7821 Expr::NPC_ValueDependentIsNotNull); 7822 7823 if (NullKind == Expr::NPCK_NotNull) { 7824 NullExpr = RHSExpr; 7825 NonPointerExpr = LHSExpr; 7826 NullKind = 7827 NullExpr->isNullPointerConstant(Context, 7828 Expr::NPC_ValueDependentIsNotNull); 7829 } 7830 7831 if (NullKind == Expr::NPCK_NotNull) 7832 return false; 7833 7834 if (NullKind == Expr::NPCK_ZeroExpression) 7835 return false; 7836 7837 if (NullKind == Expr::NPCK_ZeroLiteral) { 7838 // In this case, check to make sure that we got here from a "NULL" 7839 // string in the source code. 7840 NullExpr = NullExpr->IgnoreParenImpCasts(); 7841 SourceLocation loc = NullExpr->getExprLoc(); 7842 if (!findMacroSpelling(loc, "NULL")) 7843 return false; 7844 } 7845 7846 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7847 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7848 << NonPointerExpr->getType() << DiagType 7849 << NonPointerExpr->getSourceRange(); 7850 return true; 7851 } 7852 7853 /// Return false if the condition expression is valid, true otherwise. 7854 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7855 QualType CondTy = Cond->getType(); 7856 7857 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7858 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7859 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7860 << CondTy << Cond->getSourceRange(); 7861 return true; 7862 } 7863 7864 // C99 6.5.15p2 7865 if (CondTy->isScalarType()) return false; 7866 7867 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7868 << CondTy << Cond->getSourceRange(); 7869 return true; 7870 } 7871 7872 /// Handle when one or both operands are void type. 7873 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7874 ExprResult &RHS) { 7875 Expr *LHSExpr = LHS.get(); 7876 Expr *RHSExpr = RHS.get(); 7877 7878 if (!LHSExpr->getType()->isVoidType()) 7879 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7880 << RHSExpr->getSourceRange(); 7881 if (!RHSExpr->getType()->isVoidType()) 7882 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7883 << LHSExpr->getSourceRange(); 7884 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7885 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7886 return S.Context.VoidTy; 7887 } 7888 7889 /// Return false if the NullExpr can be promoted to PointerTy, 7890 /// true otherwise. 7891 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7892 QualType PointerTy) { 7893 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7894 !NullExpr.get()->isNullPointerConstant(S.Context, 7895 Expr::NPC_ValueDependentIsNull)) 7896 return true; 7897 7898 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7899 return false; 7900 } 7901 7902 /// Checks compatibility between two pointers and return the resulting 7903 /// type. 7904 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7905 ExprResult &RHS, 7906 SourceLocation Loc) { 7907 QualType LHSTy = LHS.get()->getType(); 7908 QualType RHSTy = RHS.get()->getType(); 7909 7910 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7911 // Two identical pointers types are always compatible. 7912 return LHSTy; 7913 } 7914 7915 QualType lhptee, rhptee; 7916 7917 // Get the pointee types. 7918 bool IsBlockPointer = false; 7919 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7920 lhptee = LHSBTy->getPointeeType(); 7921 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7922 IsBlockPointer = true; 7923 } else { 7924 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7925 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7926 } 7927 7928 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7929 // differently qualified versions of compatible types, the result type is 7930 // a pointer to an appropriately qualified version of the composite 7931 // type. 7932 7933 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7934 // clause doesn't make sense for our extensions. E.g. address space 2 should 7935 // be incompatible with address space 3: they may live on different devices or 7936 // anything. 7937 Qualifiers lhQual = lhptee.getQualifiers(); 7938 Qualifiers rhQual = rhptee.getQualifiers(); 7939 7940 LangAS ResultAddrSpace = LangAS::Default; 7941 LangAS LAddrSpace = lhQual.getAddressSpace(); 7942 LangAS RAddrSpace = rhQual.getAddressSpace(); 7943 7944 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7945 // spaces is disallowed. 7946 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7947 ResultAddrSpace = LAddrSpace; 7948 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7949 ResultAddrSpace = RAddrSpace; 7950 else { 7951 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7952 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7953 << RHS.get()->getSourceRange(); 7954 return QualType(); 7955 } 7956 7957 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7958 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7959 lhQual.removeCVRQualifiers(); 7960 rhQual.removeCVRQualifiers(); 7961 7962 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7963 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7964 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7965 // qual types are compatible iff 7966 // * corresponded types are compatible 7967 // * CVR qualifiers are equal 7968 // * address spaces are equal 7969 // Thus for conditional operator we merge CVR and address space unqualified 7970 // pointees and if there is a composite type we return a pointer to it with 7971 // merged qualifiers. 7972 LHSCastKind = 7973 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7974 RHSCastKind = 7975 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7976 lhQual.removeAddressSpace(); 7977 rhQual.removeAddressSpace(); 7978 7979 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7980 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7981 7982 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7983 7984 if (CompositeTy.isNull()) { 7985 // In this situation, we assume void* type. No especially good 7986 // reason, but this is what gcc does, and we do have to pick 7987 // to get a consistent AST. 7988 QualType incompatTy; 7989 incompatTy = S.Context.getPointerType( 7990 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7991 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7992 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7993 7994 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7995 // for casts between types with incompatible address space qualifiers. 7996 // For the following code the compiler produces casts between global and 7997 // local address spaces of the corresponded innermost pointees: 7998 // local int *global *a; 7999 // global int *global *b; 8000 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8001 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8002 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8003 << RHS.get()->getSourceRange(); 8004 8005 return incompatTy; 8006 } 8007 8008 // The pointer types are compatible. 8009 // In case of OpenCL ResultTy should have the address space qualifier 8010 // which is a superset of address spaces of both the 2nd and the 3rd 8011 // operands of the conditional operator. 8012 QualType ResultTy = [&, ResultAddrSpace]() { 8013 if (S.getLangOpts().OpenCL) { 8014 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8015 CompositeQuals.setAddressSpace(ResultAddrSpace); 8016 return S.Context 8017 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8018 .withCVRQualifiers(MergedCVRQual); 8019 } 8020 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8021 }(); 8022 if (IsBlockPointer) 8023 ResultTy = S.Context.getBlockPointerType(ResultTy); 8024 else 8025 ResultTy = S.Context.getPointerType(ResultTy); 8026 8027 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8028 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8029 return ResultTy; 8030 } 8031 8032 /// Return the resulting type when the operands are both block pointers. 8033 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8034 ExprResult &LHS, 8035 ExprResult &RHS, 8036 SourceLocation Loc) { 8037 QualType LHSTy = LHS.get()->getType(); 8038 QualType RHSTy = RHS.get()->getType(); 8039 8040 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8041 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8042 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8043 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8044 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8045 return destType; 8046 } 8047 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8048 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8049 << RHS.get()->getSourceRange(); 8050 return QualType(); 8051 } 8052 8053 // We have 2 block pointer types. 8054 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8055 } 8056 8057 /// Return the resulting type when the operands are both pointers. 8058 static QualType 8059 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8060 ExprResult &RHS, 8061 SourceLocation Loc) { 8062 // get the pointer types 8063 QualType LHSTy = LHS.get()->getType(); 8064 QualType RHSTy = RHS.get()->getType(); 8065 8066 // get the "pointed to" types 8067 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8068 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8069 8070 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8071 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8072 // Figure out necessary qualifiers (C99 6.5.15p6) 8073 QualType destPointee 8074 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8075 QualType destType = S.Context.getPointerType(destPointee); 8076 // Add qualifiers if necessary. 8077 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8078 // Promote to void*. 8079 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8080 return destType; 8081 } 8082 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8083 QualType destPointee 8084 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8085 QualType destType = S.Context.getPointerType(destPointee); 8086 // Add qualifiers if necessary. 8087 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8088 // Promote to void*. 8089 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8090 return destType; 8091 } 8092 8093 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8094 } 8095 8096 /// Return false if the first expression is not an integer and the second 8097 /// expression is not a pointer, true otherwise. 8098 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8099 Expr* PointerExpr, SourceLocation Loc, 8100 bool IsIntFirstExpr) { 8101 if (!PointerExpr->getType()->isPointerType() || 8102 !Int.get()->getType()->isIntegerType()) 8103 return false; 8104 8105 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8106 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8107 8108 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8109 << Expr1->getType() << Expr2->getType() 8110 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8111 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8112 CK_IntegralToPointer); 8113 return true; 8114 } 8115 8116 /// Simple conversion between integer and floating point types. 8117 /// 8118 /// Used when handling the OpenCL conditional operator where the 8119 /// condition is a vector while the other operands are scalar. 8120 /// 8121 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8122 /// types are either integer or floating type. Between the two 8123 /// operands, the type with the higher rank is defined as the "result 8124 /// type". The other operand needs to be promoted to the same type. No 8125 /// other type promotion is allowed. We cannot use 8126 /// UsualArithmeticConversions() for this purpose, since it always 8127 /// promotes promotable types. 8128 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8129 ExprResult &RHS, 8130 SourceLocation QuestionLoc) { 8131 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8132 if (LHS.isInvalid()) 8133 return QualType(); 8134 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8135 if (RHS.isInvalid()) 8136 return QualType(); 8137 8138 // For conversion purposes, we ignore any qualifiers. 8139 // For example, "const float" and "float" are equivalent. 8140 QualType LHSType = 8141 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8142 QualType RHSType = 8143 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8144 8145 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8146 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8147 << LHSType << LHS.get()->getSourceRange(); 8148 return QualType(); 8149 } 8150 8151 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8152 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8153 << RHSType << RHS.get()->getSourceRange(); 8154 return QualType(); 8155 } 8156 8157 // If both types are identical, no conversion is needed. 8158 if (LHSType == RHSType) 8159 return LHSType; 8160 8161 // Now handle "real" floating types (i.e. float, double, long double). 8162 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8163 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8164 /*IsCompAssign = */ false); 8165 8166 // Finally, we have two differing integer types. 8167 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8168 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8169 } 8170 8171 /// Convert scalar operands to a vector that matches the 8172 /// condition in length. 8173 /// 8174 /// Used when handling the OpenCL conditional operator where the 8175 /// condition is a vector while the other operands are scalar. 8176 /// 8177 /// We first compute the "result type" for the scalar operands 8178 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8179 /// into a vector of that type where the length matches the condition 8180 /// vector type. s6.11.6 requires that the element types of the result 8181 /// and the condition must have the same number of bits. 8182 static QualType 8183 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8184 QualType CondTy, SourceLocation QuestionLoc) { 8185 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8186 if (ResTy.isNull()) return QualType(); 8187 8188 const VectorType *CV = CondTy->getAs<VectorType>(); 8189 assert(CV); 8190 8191 // Determine the vector result type 8192 unsigned NumElements = CV->getNumElements(); 8193 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8194 8195 // Ensure that all types have the same number of bits 8196 if (S.Context.getTypeSize(CV->getElementType()) 8197 != S.Context.getTypeSize(ResTy)) { 8198 // Since VectorTy is created internally, it does not pretty print 8199 // with an OpenCL name. Instead, we just print a description. 8200 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8201 SmallString<64> Str; 8202 llvm::raw_svector_ostream OS(Str); 8203 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8204 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8205 << CondTy << OS.str(); 8206 return QualType(); 8207 } 8208 8209 // Convert operands to the vector result type 8210 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8211 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8212 8213 return VectorTy; 8214 } 8215 8216 /// Return false if this is a valid OpenCL condition vector 8217 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8218 SourceLocation QuestionLoc) { 8219 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8220 // integral type. 8221 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8222 assert(CondTy); 8223 QualType EleTy = CondTy->getElementType(); 8224 if (EleTy->isIntegerType()) return false; 8225 8226 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8227 << Cond->getType() << Cond->getSourceRange(); 8228 return true; 8229 } 8230 8231 /// Return false if the vector condition type and the vector 8232 /// result type are compatible. 8233 /// 8234 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8235 /// number of elements, and their element types have the same number 8236 /// of bits. 8237 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8238 SourceLocation QuestionLoc) { 8239 const VectorType *CV = CondTy->getAs<VectorType>(); 8240 const VectorType *RV = VecResTy->getAs<VectorType>(); 8241 assert(CV && RV); 8242 8243 if (CV->getNumElements() != RV->getNumElements()) { 8244 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8245 << CondTy << VecResTy; 8246 return true; 8247 } 8248 8249 QualType CVE = CV->getElementType(); 8250 QualType RVE = RV->getElementType(); 8251 8252 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8253 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8254 << CondTy << VecResTy; 8255 return true; 8256 } 8257 8258 return false; 8259 } 8260 8261 /// Return the resulting type for the conditional operator in 8262 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8263 /// s6.3.i) when the condition is a vector type. 8264 static QualType 8265 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8266 ExprResult &LHS, ExprResult &RHS, 8267 SourceLocation QuestionLoc) { 8268 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8269 if (Cond.isInvalid()) 8270 return QualType(); 8271 QualType CondTy = Cond.get()->getType(); 8272 8273 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8274 return QualType(); 8275 8276 // If either operand is a vector then find the vector type of the 8277 // result as specified in OpenCL v1.1 s6.3.i. 8278 if (LHS.get()->getType()->isVectorType() || 8279 RHS.get()->getType()->isVectorType()) { 8280 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8281 /*isCompAssign*/false, 8282 /*AllowBothBool*/true, 8283 /*AllowBoolConversions*/false); 8284 if (VecResTy.isNull()) return QualType(); 8285 // The result type must match the condition type as specified in 8286 // OpenCL v1.1 s6.11.6. 8287 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8288 return QualType(); 8289 return VecResTy; 8290 } 8291 8292 // Both operands are scalar. 8293 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8294 } 8295 8296 /// Return true if the Expr is block type 8297 static bool checkBlockType(Sema &S, const Expr *E) { 8298 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8299 QualType Ty = CE->getCallee()->getType(); 8300 if (Ty->isBlockPointerType()) { 8301 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8302 return true; 8303 } 8304 } 8305 return false; 8306 } 8307 8308 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8309 /// In that case, LHS = cond. 8310 /// C99 6.5.15 8311 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8312 ExprResult &RHS, ExprValueKind &VK, 8313 ExprObjectKind &OK, 8314 SourceLocation QuestionLoc) { 8315 8316 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8317 if (!LHSResult.isUsable()) return QualType(); 8318 LHS = LHSResult; 8319 8320 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8321 if (!RHSResult.isUsable()) return QualType(); 8322 RHS = RHSResult; 8323 8324 // C++ is sufficiently different to merit its own checker. 8325 if (getLangOpts().CPlusPlus) 8326 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8327 8328 VK = VK_PRValue; 8329 OK = OK_Ordinary; 8330 8331 if (Context.isDependenceAllowed() && 8332 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8333 RHS.get()->isTypeDependent())) { 8334 assert(!getLangOpts().CPlusPlus); 8335 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8336 RHS.get()->containsErrors()) && 8337 "should only occur in error-recovery path."); 8338 return Context.DependentTy; 8339 } 8340 8341 // The OpenCL operator with a vector condition is sufficiently 8342 // different to merit its own checker. 8343 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8344 Cond.get()->getType()->isExtVectorType()) 8345 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8346 8347 // First, check the condition. 8348 Cond = UsualUnaryConversions(Cond.get()); 8349 if (Cond.isInvalid()) 8350 return QualType(); 8351 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8352 return QualType(); 8353 8354 // Now check the two expressions. 8355 if (LHS.get()->getType()->isVectorType() || 8356 RHS.get()->getType()->isVectorType()) 8357 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8358 /*AllowBothBool*/true, 8359 /*AllowBoolConversions*/false); 8360 8361 QualType ResTy = 8362 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8363 if (LHS.isInvalid() || RHS.isInvalid()) 8364 return QualType(); 8365 8366 QualType LHSTy = LHS.get()->getType(); 8367 QualType RHSTy = RHS.get()->getType(); 8368 8369 // Diagnose attempts to convert between __float128 and long double where 8370 // such conversions currently can't be handled. 8371 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8372 Diag(QuestionLoc, 8373 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8374 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8375 return QualType(); 8376 } 8377 8378 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8379 // selection operator (?:). 8380 if (getLangOpts().OpenCL && 8381 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8382 return QualType(); 8383 } 8384 8385 // If both operands have arithmetic type, do the usual arithmetic conversions 8386 // to find a common type: C99 6.5.15p3,5. 8387 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8388 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8389 // different sizes, or between ExtInts and other types. 8390 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8391 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8392 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8393 << RHS.get()->getSourceRange(); 8394 return QualType(); 8395 } 8396 8397 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8398 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8399 8400 return ResTy; 8401 } 8402 8403 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8404 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8405 return LHSTy; 8406 } 8407 8408 // If both operands are the same structure or union type, the result is that 8409 // type. 8410 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8411 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8412 if (LHSRT->getDecl() == RHSRT->getDecl()) 8413 // "If both the operands have structure or union type, the result has 8414 // that type." This implies that CV qualifiers are dropped. 8415 return LHSTy.getUnqualifiedType(); 8416 // FIXME: Type of conditional expression must be complete in C mode. 8417 } 8418 8419 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8420 // The following || allows only one side to be void (a GCC-ism). 8421 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8422 return checkConditionalVoidType(*this, LHS, RHS); 8423 } 8424 8425 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8426 // the type of the other operand." 8427 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8428 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8429 8430 // All objective-c pointer type analysis is done here. 8431 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8432 QuestionLoc); 8433 if (LHS.isInvalid() || RHS.isInvalid()) 8434 return QualType(); 8435 if (!compositeType.isNull()) 8436 return compositeType; 8437 8438 8439 // Handle block pointer types. 8440 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8441 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8442 QuestionLoc); 8443 8444 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8445 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8446 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8447 QuestionLoc); 8448 8449 // GCC compatibility: soften pointer/integer mismatch. Note that 8450 // null pointers have been filtered out by this point. 8451 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8452 /*IsIntFirstExpr=*/true)) 8453 return RHSTy; 8454 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8455 /*IsIntFirstExpr=*/false)) 8456 return LHSTy; 8457 8458 // Allow ?: operations in which both operands have the same 8459 // built-in sizeless type. 8460 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8461 return LHSTy; 8462 8463 // Emit a better diagnostic if one of the expressions is a null pointer 8464 // constant and the other is not a pointer type. In this case, the user most 8465 // likely forgot to take the address of the other expression. 8466 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8467 return QualType(); 8468 8469 // Otherwise, the operands are not compatible. 8470 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8471 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8472 << RHS.get()->getSourceRange(); 8473 return QualType(); 8474 } 8475 8476 /// FindCompositeObjCPointerType - Helper method to find composite type of 8477 /// two objective-c pointer types of the two input expressions. 8478 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8479 SourceLocation QuestionLoc) { 8480 QualType LHSTy = LHS.get()->getType(); 8481 QualType RHSTy = RHS.get()->getType(); 8482 8483 // Handle things like Class and struct objc_class*. Here we case the result 8484 // to the pseudo-builtin, because that will be implicitly cast back to the 8485 // redefinition type if an attempt is made to access its fields. 8486 if (LHSTy->isObjCClassType() && 8487 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8488 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8489 return LHSTy; 8490 } 8491 if (RHSTy->isObjCClassType() && 8492 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8493 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8494 return RHSTy; 8495 } 8496 // And the same for struct objc_object* / id 8497 if (LHSTy->isObjCIdType() && 8498 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8499 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8500 return LHSTy; 8501 } 8502 if (RHSTy->isObjCIdType() && 8503 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8504 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8505 return RHSTy; 8506 } 8507 // And the same for struct objc_selector* / SEL 8508 if (Context.isObjCSelType(LHSTy) && 8509 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8510 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8511 return LHSTy; 8512 } 8513 if (Context.isObjCSelType(RHSTy) && 8514 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8515 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8516 return RHSTy; 8517 } 8518 // Check constraints for Objective-C object pointers types. 8519 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8520 8521 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8522 // Two identical object pointer types are always compatible. 8523 return LHSTy; 8524 } 8525 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8526 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8527 QualType compositeType = LHSTy; 8528 8529 // If both operands are interfaces and either operand can be 8530 // assigned to the other, use that type as the composite 8531 // type. This allows 8532 // xxx ? (A*) a : (B*) b 8533 // where B is a subclass of A. 8534 // 8535 // Additionally, as for assignment, if either type is 'id' 8536 // allow silent coercion. Finally, if the types are 8537 // incompatible then make sure to use 'id' as the composite 8538 // type so the result is acceptable for sending messages to. 8539 8540 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8541 // It could return the composite type. 8542 if (!(compositeType = 8543 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8544 // Nothing more to do. 8545 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8546 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8547 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8548 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8549 } else if ((LHSOPT->isObjCQualifiedIdType() || 8550 RHSOPT->isObjCQualifiedIdType()) && 8551 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8552 true)) { 8553 // Need to handle "id<xx>" explicitly. 8554 // GCC allows qualified id and any Objective-C type to devolve to 8555 // id. Currently localizing to here until clear this should be 8556 // part of ObjCQualifiedIdTypesAreCompatible. 8557 compositeType = Context.getObjCIdType(); 8558 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8559 compositeType = Context.getObjCIdType(); 8560 } else { 8561 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8562 << LHSTy << RHSTy 8563 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8564 QualType incompatTy = Context.getObjCIdType(); 8565 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8566 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8567 return incompatTy; 8568 } 8569 // The object pointer types are compatible. 8570 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8571 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8572 return compositeType; 8573 } 8574 // Check Objective-C object pointer types and 'void *' 8575 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8576 if (getLangOpts().ObjCAutoRefCount) { 8577 // ARC forbids the implicit conversion of object pointers to 'void *', 8578 // so these types are not compatible. 8579 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8581 LHS = RHS = true; 8582 return QualType(); 8583 } 8584 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8585 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8586 QualType destPointee 8587 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8588 QualType destType = Context.getPointerType(destPointee); 8589 // Add qualifiers if necessary. 8590 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8591 // Promote to void*. 8592 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8593 return destType; 8594 } 8595 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8596 if (getLangOpts().ObjCAutoRefCount) { 8597 // ARC forbids the implicit conversion of object pointers to 'void *', 8598 // so these types are not compatible. 8599 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8600 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8601 LHS = RHS = true; 8602 return QualType(); 8603 } 8604 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8605 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8606 QualType destPointee 8607 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8608 QualType destType = Context.getPointerType(destPointee); 8609 // Add qualifiers if necessary. 8610 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8611 // Promote to void*. 8612 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8613 return destType; 8614 } 8615 return QualType(); 8616 } 8617 8618 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8619 /// ParenRange in parentheses. 8620 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8621 const PartialDiagnostic &Note, 8622 SourceRange ParenRange) { 8623 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8624 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8625 EndLoc.isValid()) { 8626 Self.Diag(Loc, Note) 8627 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8628 << FixItHint::CreateInsertion(EndLoc, ")"); 8629 } else { 8630 // We can't display the parentheses, so just show the bare note. 8631 Self.Diag(Loc, Note) << ParenRange; 8632 } 8633 } 8634 8635 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8636 return BinaryOperator::isAdditiveOp(Opc) || 8637 BinaryOperator::isMultiplicativeOp(Opc) || 8638 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8639 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8640 // not any of the logical operators. Bitwise-xor is commonly used as a 8641 // logical-xor because there is no logical-xor operator. The logical 8642 // operators, including uses of xor, have a high false positive rate for 8643 // precedence warnings. 8644 } 8645 8646 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8647 /// expression, either using a built-in or overloaded operator, 8648 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8649 /// expression. 8650 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8651 Expr **RHSExprs) { 8652 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8653 E = E->IgnoreImpCasts(); 8654 E = E->IgnoreConversionOperatorSingleStep(); 8655 E = E->IgnoreImpCasts(); 8656 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8657 E = MTE->getSubExpr(); 8658 E = E->IgnoreImpCasts(); 8659 } 8660 8661 // Built-in binary operator. 8662 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8663 if (IsArithmeticOp(OP->getOpcode())) { 8664 *Opcode = OP->getOpcode(); 8665 *RHSExprs = OP->getRHS(); 8666 return true; 8667 } 8668 } 8669 8670 // Overloaded operator. 8671 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8672 if (Call->getNumArgs() != 2) 8673 return false; 8674 8675 // Make sure this is really a binary operator that is safe to pass into 8676 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8677 OverloadedOperatorKind OO = Call->getOperator(); 8678 if (OO < OO_Plus || OO > OO_Arrow || 8679 OO == OO_PlusPlus || OO == OO_MinusMinus) 8680 return false; 8681 8682 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8683 if (IsArithmeticOp(OpKind)) { 8684 *Opcode = OpKind; 8685 *RHSExprs = Call->getArg(1); 8686 return true; 8687 } 8688 } 8689 8690 return false; 8691 } 8692 8693 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8694 /// or is a logical expression such as (x==y) which has int type, but is 8695 /// commonly interpreted as boolean. 8696 static bool ExprLooksBoolean(Expr *E) { 8697 E = E->IgnoreParenImpCasts(); 8698 8699 if (E->getType()->isBooleanType()) 8700 return true; 8701 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8702 return OP->isComparisonOp() || OP->isLogicalOp(); 8703 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8704 return OP->getOpcode() == UO_LNot; 8705 if (E->getType()->isPointerType()) 8706 return true; 8707 // FIXME: What about overloaded operator calls returning "unspecified boolean 8708 // type"s (commonly pointer-to-members)? 8709 8710 return false; 8711 } 8712 8713 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8714 /// and binary operator are mixed in a way that suggests the programmer assumed 8715 /// the conditional operator has higher precedence, for example: 8716 /// "int x = a + someBinaryCondition ? 1 : 2". 8717 static void DiagnoseConditionalPrecedence(Sema &Self, 8718 SourceLocation OpLoc, 8719 Expr *Condition, 8720 Expr *LHSExpr, 8721 Expr *RHSExpr) { 8722 BinaryOperatorKind CondOpcode; 8723 Expr *CondRHS; 8724 8725 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8726 return; 8727 if (!ExprLooksBoolean(CondRHS)) 8728 return; 8729 8730 // The condition is an arithmetic binary expression, with a right- 8731 // hand side that looks boolean, so warn. 8732 8733 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8734 ? diag::warn_precedence_bitwise_conditional 8735 : diag::warn_precedence_conditional; 8736 8737 Self.Diag(OpLoc, DiagID) 8738 << Condition->getSourceRange() 8739 << BinaryOperator::getOpcodeStr(CondOpcode); 8740 8741 SuggestParentheses( 8742 Self, OpLoc, 8743 Self.PDiag(diag::note_precedence_silence) 8744 << BinaryOperator::getOpcodeStr(CondOpcode), 8745 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8746 8747 SuggestParentheses(Self, OpLoc, 8748 Self.PDiag(diag::note_precedence_conditional_first), 8749 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8750 } 8751 8752 /// Compute the nullability of a conditional expression. 8753 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8754 QualType LHSTy, QualType RHSTy, 8755 ASTContext &Ctx) { 8756 if (!ResTy->isAnyPointerType()) 8757 return ResTy; 8758 8759 auto GetNullability = [&Ctx](QualType Ty) { 8760 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8761 if (Kind) { 8762 // For our purposes, treat _Nullable_result as _Nullable. 8763 if (*Kind == NullabilityKind::NullableResult) 8764 return NullabilityKind::Nullable; 8765 return *Kind; 8766 } 8767 return NullabilityKind::Unspecified; 8768 }; 8769 8770 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8771 NullabilityKind MergedKind; 8772 8773 // Compute nullability of a binary conditional expression. 8774 if (IsBin) { 8775 if (LHSKind == NullabilityKind::NonNull) 8776 MergedKind = NullabilityKind::NonNull; 8777 else 8778 MergedKind = RHSKind; 8779 // Compute nullability of a normal conditional expression. 8780 } else { 8781 if (LHSKind == NullabilityKind::Nullable || 8782 RHSKind == NullabilityKind::Nullable) 8783 MergedKind = NullabilityKind::Nullable; 8784 else if (LHSKind == NullabilityKind::NonNull) 8785 MergedKind = RHSKind; 8786 else if (RHSKind == NullabilityKind::NonNull) 8787 MergedKind = LHSKind; 8788 else 8789 MergedKind = NullabilityKind::Unspecified; 8790 } 8791 8792 // Return if ResTy already has the correct nullability. 8793 if (GetNullability(ResTy) == MergedKind) 8794 return ResTy; 8795 8796 // Strip all nullability from ResTy. 8797 while (ResTy->getNullability(Ctx)) 8798 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8799 8800 // Create a new AttributedType with the new nullability kind. 8801 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8802 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8803 } 8804 8805 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8806 /// in the case of a the GNU conditional expr extension. 8807 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8808 SourceLocation ColonLoc, 8809 Expr *CondExpr, Expr *LHSExpr, 8810 Expr *RHSExpr) { 8811 if (!Context.isDependenceAllowed()) { 8812 // C cannot handle TypoExpr nodes in the condition because it 8813 // doesn't handle dependent types properly, so make sure any TypoExprs have 8814 // been dealt with before checking the operands. 8815 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8816 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8817 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8818 8819 if (!CondResult.isUsable()) 8820 return ExprError(); 8821 8822 if (LHSExpr) { 8823 if (!LHSResult.isUsable()) 8824 return ExprError(); 8825 } 8826 8827 if (!RHSResult.isUsable()) 8828 return ExprError(); 8829 8830 CondExpr = CondResult.get(); 8831 LHSExpr = LHSResult.get(); 8832 RHSExpr = RHSResult.get(); 8833 } 8834 8835 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8836 // was the condition. 8837 OpaqueValueExpr *opaqueValue = nullptr; 8838 Expr *commonExpr = nullptr; 8839 if (!LHSExpr) { 8840 commonExpr = CondExpr; 8841 // Lower out placeholder types first. This is important so that we don't 8842 // try to capture a placeholder. This happens in few cases in C++; such 8843 // as Objective-C++'s dictionary subscripting syntax. 8844 if (commonExpr->hasPlaceholderType()) { 8845 ExprResult result = CheckPlaceholderExpr(commonExpr); 8846 if (!result.isUsable()) return ExprError(); 8847 commonExpr = result.get(); 8848 } 8849 // We usually want to apply unary conversions *before* saving, except 8850 // in the special case of a C++ l-value conditional. 8851 if (!(getLangOpts().CPlusPlus 8852 && !commonExpr->isTypeDependent() 8853 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8854 && commonExpr->isGLValue() 8855 && commonExpr->isOrdinaryOrBitFieldObject() 8856 && RHSExpr->isOrdinaryOrBitFieldObject() 8857 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8858 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8859 if (commonRes.isInvalid()) 8860 return ExprError(); 8861 commonExpr = commonRes.get(); 8862 } 8863 8864 // If the common expression is a class or array prvalue, materialize it 8865 // so that we can safely refer to it multiple times. 8866 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8867 commonExpr->getType()->isArrayType())) { 8868 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8869 if (MatExpr.isInvalid()) 8870 return ExprError(); 8871 commonExpr = MatExpr.get(); 8872 } 8873 8874 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8875 commonExpr->getType(), 8876 commonExpr->getValueKind(), 8877 commonExpr->getObjectKind(), 8878 commonExpr); 8879 LHSExpr = CondExpr = opaqueValue; 8880 } 8881 8882 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8883 ExprValueKind VK = VK_PRValue; 8884 ExprObjectKind OK = OK_Ordinary; 8885 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8886 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8887 VK, OK, QuestionLoc); 8888 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8889 RHS.isInvalid()) 8890 return ExprError(); 8891 8892 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8893 RHS.get()); 8894 8895 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8896 8897 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8898 Context); 8899 8900 if (!commonExpr) 8901 return new (Context) 8902 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8903 RHS.get(), result, VK, OK); 8904 8905 return new (Context) BinaryConditionalOperator( 8906 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8907 ColonLoc, result, VK, OK); 8908 } 8909 8910 // Check if we have a conversion between incompatible cmse function pointer 8911 // types, that is, a conversion between a function pointer with the 8912 // cmse_nonsecure_call attribute and one without. 8913 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8914 QualType ToType) { 8915 if (const auto *ToFn = 8916 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8917 if (const auto *FromFn = 8918 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8919 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8920 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8921 8922 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8923 } 8924 } 8925 return false; 8926 } 8927 8928 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8929 // being closely modeled after the C99 spec:-). The odd characteristic of this 8930 // routine is it effectively iqnores the qualifiers on the top level pointee. 8931 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8932 // FIXME: add a couple examples in this comment. 8933 static Sema::AssignConvertType 8934 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8935 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8936 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8937 8938 // get the "pointed to" type (ignoring qualifiers at the top level) 8939 const Type *lhptee, *rhptee; 8940 Qualifiers lhq, rhq; 8941 std::tie(lhptee, lhq) = 8942 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8943 std::tie(rhptee, rhq) = 8944 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8945 8946 Sema::AssignConvertType ConvTy = Sema::Compatible; 8947 8948 // C99 6.5.16.1p1: This following citation is common to constraints 8949 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8950 // qualifiers of the type *pointed to* by the right; 8951 8952 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8953 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8954 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8955 // Ignore lifetime for further calculation. 8956 lhq.removeObjCLifetime(); 8957 rhq.removeObjCLifetime(); 8958 } 8959 8960 if (!lhq.compatiblyIncludes(rhq)) { 8961 // Treat address-space mismatches as fatal. 8962 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8963 return Sema::IncompatiblePointerDiscardsQualifiers; 8964 8965 // It's okay to add or remove GC or lifetime qualifiers when converting to 8966 // and from void*. 8967 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8968 .compatiblyIncludes( 8969 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8970 && (lhptee->isVoidType() || rhptee->isVoidType())) 8971 ; // keep old 8972 8973 // Treat lifetime mismatches as fatal. 8974 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8975 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8976 8977 // For GCC/MS compatibility, other qualifier mismatches are treated 8978 // as still compatible in C. 8979 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8980 } 8981 8982 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8983 // incomplete type and the other is a pointer to a qualified or unqualified 8984 // version of void... 8985 if (lhptee->isVoidType()) { 8986 if (rhptee->isIncompleteOrObjectType()) 8987 return ConvTy; 8988 8989 // As an extension, we allow cast to/from void* to function pointer. 8990 assert(rhptee->isFunctionType()); 8991 return Sema::FunctionVoidPointer; 8992 } 8993 8994 if (rhptee->isVoidType()) { 8995 if (lhptee->isIncompleteOrObjectType()) 8996 return ConvTy; 8997 8998 // As an extension, we allow cast to/from void* to function pointer. 8999 assert(lhptee->isFunctionType()); 9000 return Sema::FunctionVoidPointer; 9001 } 9002 9003 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9004 // unqualified versions of compatible types, ... 9005 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9006 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9007 // Check if the pointee types are compatible ignoring the sign. 9008 // We explicitly check for char so that we catch "char" vs 9009 // "unsigned char" on systems where "char" is unsigned. 9010 if (lhptee->isCharType()) 9011 ltrans = S.Context.UnsignedCharTy; 9012 else if (lhptee->hasSignedIntegerRepresentation()) 9013 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9014 9015 if (rhptee->isCharType()) 9016 rtrans = S.Context.UnsignedCharTy; 9017 else if (rhptee->hasSignedIntegerRepresentation()) 9018 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9019 9020 if (ltrans == rtrans) { 9021 // Types are compatible ignoring the sign. Qualifier incompatibility 9022 // takes priority over sign incompatibility because the sign 9023 // warning can be disabled. 9024 if (ConvTy != Sema::Compatible) 9025 return ConvTy; 9026 9027 return Sema::IncompatiblePointerSign; 9028 } 9029 9030 // If we are a multi-level pointer, it's possible that our issue is simply 9031 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9032 // the eventual target type is the same and the pointers have the same 9033 // level of indirection, this must be the issue. 9034 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9035 do { 9036 std::tie(lhptee, lhq) = 9037 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9038 std::tie(rhptee, rhq) = 9039 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9040 9041 // Inconsistent address spaces at this point is invalid, even if the 9042 // address spaces would be compatible. 9043 // FIXME: This doesn't catch address space mismatches for pointers of 9044 // different nesting levels, like: 9045 // __local int *** a; 9046 // int ** b = a; 9047 // It's not clear how to actually determine when such pointers are 9048 // invalidly incompatible. 9049 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9050 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9051 9052 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9053 9054 if (lhptee == rhptee) 9055 return Sema::IncompatibleNestedPointerQualifiers; 9056 } 9057 9058 // General pointer incompatibility takes priority over qualifiers. 9059 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9060 return Sema::IncompatibleFunctionPointer; 9061 return Sema::IncompatiblePointer; 9062 } 9063 if (!S.getLangOpts().CPlusPlus && 9064 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9065 return Sema::IncompatibleFunctionPointer; 9066 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9067 return Sema::IncompatibleFunctionPointer; 9068 return ConvTy; 9069 } 9070 9071 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9072 /// block pointer types are compatible or whether a block and normal pointer 9073 /// are compatible. It is more restrict than comparing two function pointer 9074 // types. 9075 static Sema::AssignConvertType 9076 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9077 QualType RHSType) { 9078 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9079 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9080 9081 QualType lhptee, rhptee; 9082 9083 // get the "pointed to" type (ignoring qualifiers at the top level) 9084 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9085 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9086 9087 // In C++, the types have to match exactly. 9088 if (S.getLangOpts().CPlusPlus) 9089 return Sema::IncompatibleBlockPointer; 9090 9091 Sema::AssignConvertType ConvTy = Sema::Compatible; 9092 9093 // For blocks we enforce that qualifiers are identical. 9094 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9095 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9096 if (S.getLangOpts().OpenCL) { 9097 LQuals.removeAddressSpace(); 9098 RQuals.removeAddressSpace(); 9099 } 9100 if (LQuals != RQuals) 9101 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9102 9103 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9104 // assignment. 9105 // The current behavior is similar to C++ lambdas. A block might be 9106 // assigned to a variable iff its return type and parameters are compatible 9107 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9108 // an assignment. Presumably it should behave in way that a function pointer 9109 // assignment does in C, so for each parameter and return type: 9110 // * CVR and address space of LHS should be a superset of CVR and address 9111 // space of RHS. 9112 // * unqualified types should be compatible. 9113 if (S.getLangOpts().OpenCL) { 9114 if (!S.Context.typesAreBlockPointerCompatible( 9115 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9116 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9117 return Sema::IncompatibleBlockPointer; 9118 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9119 return Sema::IncompatibleBlockPointer; 9120 9121 return ConvTy; 9122 } 9123 9124 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9125 /// for assignment compatibility. 9126 static Sema::AssignConvertType 9127 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9128 QualType RHSType) { 9129 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9130 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9131 9132 if (LHSType->isObjCBuiltinType()) { 9133 // Class is not compatible with ObjC object pointers. 9134 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9135 !RHSType->isObjCQualifiedClassType()) 9136 return Sema::IncompatiblePointer; 9137 return Sema::Compatible; 9138 } 9139 if (RHSType->isObjCBuiltinType()) { 9140 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9141 !LHSType->isObjCQualifiedClassType()) 9142 return Sema::IncompatiblePointer; 9143 return Sema::Compatible; 9144 } 9145 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9146 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9147 9148 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9149 // make an exception for id<P> 9150 !LHSType->isObjCQualifiedIdType()) 9151 return Sema::CompatiblePointerDiscardsQualifiers; 9152 9153 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9154 return Sema::Compatible; 9155 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9156 return Sema::IncompatibleObjCQualifiedId; 9157 return Sema::IncompatiblePointer; 9158 } 9159 9160 Sema::AssignConvertType 9161 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9162 QualType LHSType, QualType RHSType) { 9163 // Fake up an opaque expression. We don't actually care about what 9164 // cast operations are required, so if CheckAssignmentConstraints 9165 // adds casts to this they'll be wasted, but fortunately that doesn't 9166 // usually happen on valid code. 9167 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9168 ExprResult RHSPtr = &RHSExpr; 9169 CastKind K; 9170 9171 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9172 } 9173 9174 /// This helper function returns true if QT is a vector type that has element 9175 /// type ElementType. 9176 static bool isVector(QualType QT, QualType ElementType) { 9177 if (const VectorType *VT = QT->getAs<VectorType>()) 9178 return VT->getElementType().getCanonicalType() == ElementType; 9179 return false; 9180 } 9181 9182 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9183 /// has code to accommodate several GCC extensions when type checking 9184 /// pointers. Here are some objectionable examples that GCC considers warnings: 9185 /// 9186 /// int a, *pint; 9187 /// short *pshort; 9188 /// struct foo *pfoo; 9189 /// 9190 /// pint = pshort; // warning: assignment from incompatible pointer type 9191 /// a = pint; // warning: assignment makes integer from pointer without a cast 9192 /// pint = a; // warning: assignment makes pointer from integer without a cast 9193 /// pint = pfoo; // warning: assignment from incompatible pointer type 9194 /// 9195 /// As a result, the code for dealing with pointers is more complex than the 9196 /// C99 spec dictates. 9197 /// 9198 /// Sets 'Kind' for any result kind except Incompatible. 9199 Sema::AssignConvertType 9200 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9201 CastKind &Kind, bool ConvertRHS) { 9202 QualType RHSType = RHS.get()->getType(); 9203 QualType OrigLHSType = LHSType; 9204 9205 // Get canonical types. We're not formatting these types, just comparing 9206 // them. 9207 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9208 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9209 9210 // Common case: no conversion required. 9211 if (LHSType == RHSType) { 9212 Kind = CK_NoOp; 9213 return Compatible; 9214 } 9215 9216 // If we have an atomic type, try a non-atomic assignment, then just add an 9217 // atomic qualification step. 9218 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9219 Sema::AssignConvertType result = 9220 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9221 if (result != Compatible) 9222 return result; 9223 if (Kind != CK_NoOp && ConvertRHS) 9224 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9225 Kind = CK_NonAtomicToAtomic; 9226 return Compatible; 9227 } 9228 9229 // If the left-hand side is a reference type, then we are in a 9230 // (rare!) case where we've allowed the use of references in C, 9231 // e.g., as a parameter type in a built-in function. In this case, 9232 // just make sure that the type referenced is compatible with the 9233 // right-hand side type. The caller is responsible for adjusting 9234 // LHSType so that the resulting expression does not have reference 9235 // type. 9236 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9237 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9238 Kind = CK_LValueBitCast; 9239 return Compatible; 9240 } 9241 return Incompatible; 9242 } 9243 9244 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9245 // to the same ExtVector type. 9246 if (LHSType->isExtVectorType()) { 9247 if (RHSType->isExtVectorType()) 9248 return Incompatible; 9249 if (RHSType->isArithmeticType()) { 9250 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9251 if (ConvertRHS) 9252 RHS = prepareVectorSplat(LHSType, RHS.get()); 9253 Kind = CK_VectorSplat; 9254 return Compatible; 9255 } 9256 } 9257 9258 // Conversions to or from vector type. 9259 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9260 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9261 // Allow assignments of an AltiVec vector type to an equivalent GCC 9262 // vector type and vice versa 9263 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9264 Kind = CK_BitCast; 9265 return Compatible; 9266 } 9267 9268 // If we are allowing lax vector conversions, and LHS and RHS are both 9269 // vectors, the total size only needs to be the same. This is a bitcast; 9270 // no bits are changed but the result type is different. 9271 if (isLaxVectorConversion(RHSType, LHSType)) { 9272 Kind = CK_BitCast; 9273 return IncompatibleVectors; 9274 } 9275 } 9276 9277 // When the RHS comes from another lax conversion (e.g. binops between 9278 // scalars and vectors) the result is canonicalized as a vector. When the 9279 // LHS is also a vector, the lax is allowed by the condition above. Handle 9280 // the case where LHS is a scalar. 9281 if (LHSType->isScalarType()) { 9282 const VectorType *VecType = RHSType->getAs<VectorType>(); 9283 if (VecType && VecType->getNumElements() == 1 && 9284 isLaxVectorConversion(RHSType, LHSType)) { 9285 ExprResult *VecExpr = &RHS; 9286 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9287 Kind = CK_BitCast; 9288 return Compatible; 9289 } 9290 } 9291 9292 // Allow assignments between fixed-length and sizeless SVE vectors. 9293 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9294 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9295 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9296 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9297 Kind = CK_BitCast; 9298 return Compatible; 9299 } 9300 9301 return Incompatible; 9302 } 9303 9304 // Diagnose attempts to convert between __float128 and long double where 9305 // such conversions currently can't be handled. 9306 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9307 return Incompatible; 9308 9309 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9310 // discards the imaginary part. 9311 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9312 !LHSType->getAs<ComplexType>()) 9313 return Incompatible; 9314 9315 // Arithmetic conversions. 9316 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9317 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9318 if (ConvertRHS) 9319 Kind = PrepareScalarCast(RHS, LHSType); 9320 return Compatible; 9321 } 9322 9323 // Conversions to normal pointers. 9324 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9325 // U* -> T* 9326 if (isa<PointerType>(RHSType)) { 9327 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9328 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9329 if (AddrSpaceL != AddrSpaceR) 9330 Kind = CK_AddressSpaceConversion; 9331 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9332 Kind = CK_NoOp; 9333 else 9334 Kind = CK_BitCast; 9335 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9336 } 9337 9338 // int -> T* 9339 if (RHSType->isIntegerType()) { 9340 Kind = CK_IntegralToPointer; // FIXME: null? 9341 return IntToPointer; 9342 } 9343 9344 // C pointers are not compatible with ObjC object pointers, 9345 // with two exceptions: 9346 if (isa<ObjCObjectPointerType>(RHSType)) { 9347 // - conversions to void* 9348 if (LHSPointer->getPointeeType()->isVoidType()) { 9349 Kind = CK_BitCast; 9350 return Compatible; 9351 } 9352 9353 // - conversions from 'Class' to the redefinition type 9354 if (RHSType->isObjCClassType() && 9355 Context.hasSameType(LHSType, 9356 Context.getObjCClassRedefinitionType())) { 9357 Kind = CK_BitCast; 9358 return Compatible; 9359 } 9360 9361 Kind = CK_BitCast; 9362 return IncompatiblePointer; 9363 } 9364 9365 // U^ -> void* 9366 if (RHSType->getAs<BlockPointerType>()) { 9367 if (LHSPointer->getPointeeType()->isVoidType()) { 9368 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9369 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9370 ->getPointeeType() 9371 .getAddressSpace(); 9372 Kind = 9373 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9374 return Compatible; 9375 } 9376 } 9377 9378 return Incompatible; 9379 } 9380 9381 // Conversions to block pointers. 9382 if (isa<BlockPointerType>(LHSType)) { 9383 // U^ -> T^ 9384 if (RHSType->isBlockPointerType()) { 9385 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9386 ->getPointeeType() 9387 .getAddressSpace(); 9388 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9389 ->getPointeeType() 9390 .getAddressSpace(); 9391 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9392 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9393 } 9394 9395 // int or null -> T^ 9396 if (RHSType->isIntegerType()) { 9397 Kind = CK_IntegralToPointer; // FIXME: null 9398 return IntToBlockPointer; 9399 } 9400 9401 // id -> T^ 9402 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9403 Kind = CK_AnyPointerToBlockPointerCast; 9404 return Compatible; 9405 } 9406 9407 // void* -> T^ 9408 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9409 if (RHSPT->getPointeeType()->isVoidType()) { 9410 Kind = CK_AnyPointerToBlockPointerCast; 9411 return Compatible; 9412 } 9413 9414 return Incompatible; 9415 } 9416 9417 // Conversions to Objective-C pointers. 9418 if (isa<ObjCObjectPointerType>(LHSType)) { 9419 // A* -> B* 9420 if (RHSType->isObjCObjectPointerType()) { 9421 Kind = CK_BitCast; 9422 Sema::AssignConvertType result = 9423 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9424 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9425 result == Compatible && 9426 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9427 result = IncompatibleObjCWeakRef; 9428 return result; 9429 } 9430 9431 // int or null -> A* 9432 if (RHSType->isIntegerType()) { 9433 Kind = CK_IntegralToPointer; // FIXME: null 9434 return IntToPointer; 9435 } 9436 9437 // In general, C pointers are not compatible with ObjC object pointers, 9438 // with two exceptions: 9439 if (isa<PointerType>(RHSType)) { 9440 Kind = CK_CPointerToObjCPointerCast; 9441 9442 // - conversions from 'void*' 9443 if (RHSType->isVoidPointerType()) { 9444 return Compatible; 9445 } 9446 9447 // - conversions to 'Class' from its redefinition type 9448 if (LHSType->isObjCClassType() && 9449 Context.hasSameType(RHSType, 9450 Context.getObjCClassRedefinitionType())) { 9451 return Compatible; 9452 } 9453 9454 return IncompatiblePointer; 9455 } 9456 9457 // Only under strict condition T^ is compatible with an Objective-C pointer. 9458 if (RHSType->isBlockPointerType() && 9459 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9460 if (ConvertRHS) 9461 maybeExtendBlockObject(RHS); 9462 Kind = CK_BlockPointerToObjCPointerCast; 9463 return Compatible; 9464 } 9465 9466 return Incompatible; 9467 } 9468 9469 // Conversions from pointers that are not covered by the above. 9470 if (isa<PointerType>(RHSType)) { 9471 // T* -> _Bool 9472 if (LHSType == Context.BoolTy) { 9473 Kind = CK_PointerToBoolean; 9474 return Compatible; 9475 } 9476 9477 // T* -> int 9478 if (LHSType->isIntegerType()) { 9479 Kind = CK_PointerToIntegral; 9480 return PointerToInt; 9481 } 9482 9483 return Incompatible; 9484 } 9485 9486 // Conversions from Objective-C pointers that are not covered by the above. 9487 if (isa<ObjCObjectPointerType>(RHSType)) { 9488 // T* -> _Bool 9489 if (LHSType == Context.BoolTy) { 9490 Kind = CK_PointerToBoolean; 9491 return Compatible; 9492 } 9493 9494 // T* -> int 9495 if (LHSType->isIntegerType()) { 9496 Kind = CK_PointerToIntegral; 9497 return PointerToInt; 9498 } 9499 9500 return Incompatible; 9501 } 9502 9503 // struct A -> struct B 9504 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9505 if (Context.typesAreCompatible(LHSType, RHSType)) { 9506 Kind = CK_NoOp; 9507 return Compatible; 9508 } 9509 } 9510 9511 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9512 Kind = CK_IntToOCLSampler; 9513 return Compatible; 9514 } 9515 9516 return Incompatible; 9517 } 9518 9519 /// Constructs a transparent union from an expression that is 9520 /// used to initialize the transparent union. 9521 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9522 ExprResult &EResult, QualType UnionType, 9523 FieldDecl *Field) { 9524 // Build an initializer list that designates the appropriate member 9525 // of the transparent union. 9526 Expr *E = EResult.get(); 9527 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9528 E, SourceLocation()); 9529 Initializer->setType(UnionType); 9530 Initializer->setInitializedFieldInUnion(Field); 9531 9532 // Build a compound literal constructing a value of the transparent 9533 // union type from this initializer list. 9534 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9535 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9536 VK_PRValue, Initializer, false); 9537 } 9538 9539 Sema::AssignConvertType 9540 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9541 ExprResult &RHS) { 9542 QualType RHSType = RHS.get()->getType(); 9543 9544 // If the ArgType is a Union type, we want to handle a potential 9545 // transparent_union GCC extension. 9546 const RecordType *UT = ArgType->getAsUnionType(); 9547 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9548 return Incompatible; 9549 9550 // The field to initialize within the transparent union. 9551 RecordDecl *UD = UT->getDecl(); 9552 FieldDecl *InitField = nullptr; 9553 // It's compatible if the expression matches any of the fields. 9554 for (auto *it : UD->fields()) { 9555 if (it->getType()->isPointerType()) { 9556 // If the transparent union contains a pointer type, we allow: 9557 // 1) void pointer 9558 // 2) null pointer constant 9559 if (RHSType->isPointerType()) 9560 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9561 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9562 InitField = it; 9563 break; 9564 } 9565 9566 if (RHS.get()->isNullPointerConstant(Context, 9567 Expr::NPC_ValueDependentIsNull)) { 9568 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9569 CK_NullToPointer); 9570 InitField = it; 9571 break; 9572 } 9573 } 9574 9575 CastKind Kind; 9576 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9577 == Compatible) { 9578 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9579 InitField = it; 9580 break; 9581 } 9582 } 9583 9584 if (!InitField) 9585 return Incompatible; 9586 9587 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9588 return Compatible; 9589 } 9590 9591 Sema::AssignConvertType 9592 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9593 bool Diagnose, 9594 bool DiagnoseCFAudited, 9595 bool ConvertRHS) { 9596 // We need to be able to tell the caller whether we diagnosed a problem, if 9597 // they ask us to issue diagnostics. 9598 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9599 9600 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9601 // we can't avoid *all* modifications at the moment, so we need some somewhere 9602 // to put the updated value. 9603 ExprResult LocalRHS = CallerRHS; 9604 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9605 9606 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9607 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9608 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9609 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9610 Diag(RHS.get()->getExprLoc(), 9611 diag::warn_noderef_to_dereferenceable_pointer) 9612 << RHS.get()->getSourceRange(); 9613 } 9614 } 9615 } 9616 9617 if (getLangOpts().CPlusPlus) { 9618 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9619 // C++ 5.17p3: If the left operand is not of class type, the 9620 // expression is implicitly converted (C++ 4) to the 9621 // cv-unqualified type of the left operand. 9622 QualType RHSType = RHS.get()->getType(); 9623 if (Diagnose) { 9624 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9625 AA_Assigning); 9626 } else { 9627 ImplicitConversionSequence ICS = 9628 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9629 /*SuppressUserConversions=*/false, 9630 AllowedExplicit::None, 9631 /*InOverloadResolution=*/false, 9632 /*CStyle=*/false, 9633 /*AllowObjCWritebackConversion=*/false); 9634 if (ICS.isFailure()) 9635 return Incompatible; 9636 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9637 ICS, AA_Assigning); 9638 } 9639 if (RHS.isInvalid()) 9640 return Incompatible; 9641 Sema::AssignConvertType result = Compatible; 9642 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9643 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9644 result = IncompatibleObjCWeakRef; 9645 return result; 9646 } 9647 9648 // FIXME: Currently, we fall through and treat C++ classes like C 9649 // structures. 9650 // FIXME: We also fall through for atomics; not sure what should 9651 // happen there, though. 9652 } else if (RHS.get()->getType() == Context.OverloadTy) { 9653 // As a set of extensions to C, we support overloading on functions. These 9654 // functions need to be resolved here. 9655 DeclAccessPair DAP; 9656 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9657 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9658 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9659 else 9660 return Incompatible; 9661 } 9662 9663 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9664 // a null pointer constant. 9665 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9666 LHSType->isBlockPointerType()) && 9667 RHS.get()->isNullPointerConstant(Context, 9668 Expr::NPC_ValueDependentIsNull)) { 9669 if (Diagnose || ConvertRHS) { 9670 CastKind Kind; 9671 CXXCastPath Path; 9672 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9673 /*IgnoreBaseAccess=*/false, Diagnose); 9674 if (ConvertRHS) 9675 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9676 } 9677 return Compatible; 9678 } 9679 9680 // OpenCL queue_t type assignment. 9681 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9682 Context, Expr::NPC_ValueDependentIsNull)) { 9683 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9684 return Compatible; 9685 } 9686 9687 // This check seems unnatural, however it is necessary to ensure the proper 9688 // conversion of functions/arrays. If the conversion were done for all 9689 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9690 // expressions that suppress this implicit conversion (&, sizeof). 9691 // 9692 // Suppress this for references: C++ 8.5.3p5. 9693 if (!LHSType->isReferenceType()) { 9694 // FIXME: We potentially allocate here even if ConvertRHS is false. 9695 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9696 if (RHS.isInvalid()) 9697 return Incompatible; 9698 } 9699 CastKind Kind; 9700 Sema::AssignConvertType result = 9701 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9702 9703 // C99 6.5.16.1p2: The value of the right operand is converted to the 9704 // type of the assignment expression. 9705 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9706 // so that we can use references in built-in functions even in C. 9707 // The getNonReferenceType() call makes sure that the resulting expression 9708 // does not have reference type. 9709 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9710 QualType Ty = LHSType.getNonLValueExprType(Context); 9711 Expr *E = RHS.get(); 9712 9713 // Check for various Objective-C errors. If we are not reporting 9714 // diagnostics and just checking for errors, e.g., during overload 9715 // resolution, return Incompatible to indicate the failure. 9716 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9717 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9718 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9719 if (!Diagnose) 9720 return Incompatible; 9721 } 9722 if (getLangOpts().ObjC && 9723 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9724 E->getType(), E, Diagnose) || 9725 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9726 if (!Diagnose) 9727 return Incompatible; 9728 // Replace the expression with a corrected version and continue so we 9729 // can find further errors. 9730 RHS = E; 9731 return Compatible; 9732 } 9733 9734 if (ConvertRHS) 9735 RHS = ImpCastExprToType(E, Ty, Kind); 9736 } 9737 9738 return result; 9739 } 9740 9741 namespace { 9742 /// The original operand to an operator, prior to the application of the usual 9743 /// arithmetic conversions and converting the arguments of a builtin operator 9744 /// candidate. 9745 struct OriginalOperand { 9746 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9747 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9748 Op = MTE->getSubExpr(); 9749 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9750 Op = BTE->getSubExpr(); 9751 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9752 Orig = ICE->getSubExprAsWritten(); 9753 Conversion = ICE->getConversionFunction(); 9754 } 9755 } 9756 9757 QualType getType() const { return Orig->getType(); } 9758 9759 Expr *Orig; 9760 NamedDecl *Conversion; 9761 }; 9762 } 9763 9764 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9765 ExprResult &RHS) { 9766 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9767 9768 Diag(Loc, diag::err_typecheck_invalid_operands) 9769 << OrigLHS.getType() << OrigRHS.getType() 9770 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9771 9772 // If a user-defined conversion was applied to either of the operands prior 9773 // to applying the built-in operator rules, tell the user about it. 9774 if (OrigLHS.Conversion) { 9775 Diag(OrigLHS.Conversion->getLocation(), 9776 diag::note_typecheck_invalid_operands_converted) 9777 << 0 << LHS.get()->getType(); 9778 } 9779 if (OrigRHS.Conversion) { 9780 Diag(OrigRHS.Conversion->getLocation(), 9781 diag::note_typecheck_invalid_operands_converted) 9782 << 1 << RHS.get()->getType(); 9783 } 9784 9785 return QualType(); 9786 } 9787 9788 // Diagnose cases where a scalar was implicitly converted to a vector and 9789 // diagnose the underlying types. Otherwise, diagnose the error 9790 // as invalid vector logical operands for non-C++ cases. 9791 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9792 ExprResult &RHS) { 9793 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9794 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9795 9796 bool LHSNatVec = LHSType->isVectorType(); 9797 bool RHSNatVec = RHSType->isVectorType(); 9798 9799 if (!(LHSNatVec && RHSNatVec)) { 9800 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9801 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9802 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9803 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9804 << Vector->getSourceRange(); 9805 return QualType(); 9806 } 9807 9808 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9809 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9810 << RHS.get()->getSourceRange(); 9811 9812 return QualType(); 9813 } 9814 9815 /// Try to convert a value of non-vector type to a vector type by converting 9816 /// the type to the element type of the vector and then performing a splat. 9817 /// If the language is OpenCL, we only use conversions that promote scalar 9818 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9819 /// for float->int. 9820 /// 9821 /// OpenCL V2.0 6.2.6.p2: 9822 /// An error shall occur if any scalar operand type has greater rank 9823 /// than the type of the vector element. 9824 /// 9825 /// \param scalar - if non-null, actually perform the conversions 9826 /// \return true if the operation fails (but without diagnosing the failure) 9827 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9828 QualType scalarTy, 9829 QualType vectorEltTy, 9830 QualType vectorTy, 9831 unsigned &DiagID) { 9832 // The conversion to apply to the scalar before splatting it, 9833 // if necessary. 9834 CastKind scalarCast = CK_NoOp; 9835 9836 if (vectorEltTy->isIntegralType(S.Context)) { 9837 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9838 (scalarTy->isIntegerType() && 9839 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9840 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9841 return true; 9842 } 9843 if (!scalarTy->isIntegralType(S.Context)) 9844 return true; 9845 scalarCast = CK_IntegralCast; 9846 } else if (vectorEltTy->isRealFloatingType()) { 9847 if (scalarTy->isRealFloatingType()) { 9848 if (S.getLangOpts().OpenCL && 9849 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9850 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9851 return true; 9852 } 9853 scalarCast = CK_FloatingCast; 9854 } 9855 else if (scalarTy->isIntegralType(S.Context)) 9856 scalarCast = CK_IntegralToFloating; 9857 else 9858 return true; 9859 } else { 9860 return true; 9861 } 9862 9863 // Adjust scalar if desired. 9864 if (scalar) { 9865 if (scalarCast != CK_NoOp) 9866 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9867 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9868 } 9869 return false; 9870 } 9871 9872 /// Convert vector E to a vector with the same number of elements but different 9873 /// element type. 9874 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9875 const auto *VecTy = E->getType()->getAs<VectorType>(); 9876 assert(VecTy && "Expression E must be a vector"); 9877 QualType NewVecTy = S.Context.getVectorType(ElementType, 9878 VecTy->getNumElements(), 9879 VecTy->getVectorKind()); 9880 9881 // Look through the implicit cast. Return the subexpression if its type is 9882 // NewVecTy. 9883 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9884 if (ICE->getSubExpr()->getType() == NewVecTy) 9885 return ICE->getSubExpr(); 9886 9887 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9888 return S.ImpCastExprToType(E, NewVecTy, Cast); 9889 } 9890 9891 /// Test if a (constant) integer Int can be casted to another integer type 9892 /// IntTy without losing precision. 9893 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9894 QualType OtherIntTy) { 9895 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9896 9897 // Reject cases where the value of the Int is unknown as that would 9898 // possibly cause truncation, but accept cases where the scalar can be 9899 // demoted without loss of precision. 9900 Expr::EvalResult EVResult; 9901 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9902 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9903 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9904 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9905 9906 if (CstInt) { 9907 // If the scalar is constant and is of a higher order and has more active 9908 // bits that the vector element type, reject it. 9909 llvm::APSInt Result = EVResult.Val.getInt(); 9910 unsigned NumBits = IntSigned 9911 ? (Result.isNegative() ? Result.getMinSignedBits() 9912 : Result.getActiveBits()) 9913 : Result.getActiveBits(); 9914 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9915 return true; 9916 9917 // If the signedness of the scalar type and the vector element type 9918 // differs and the number of bits is greater than that of the vector 9919 // element reject it. 9920 return (IntSigned != OtherIntSigned && 9921 NumBits > S.Context.getIntWidth(OtherIntTy)); 9922 } 9923 9924 // Reject cases where the value of the scalar is not constant and it's 9925 // order is greater than that of the vector element type. 9926 return (Order < 0); 9927 } 9928 9929 /// Test if a (constant) integer Int can be casted to floating point type 9930 /// FloatTy without losing precision. 9931 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9932 QualType FloatTy) { 9933 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9934 9935 // Determine if the integer constant can be expressed as a floating point 9936 // number of the appropriate type. 9937 Expr::EvalResult EVResult; 9938 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9939 9940 uint64_t Bits = 0; 9941 if (CstInt) { 9942 // Reject constants that would be truncated if they were converted to 9943 // the floating point type. Test by simple to/from conversion. 9944 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9945 // could be avoided if there was a convertFromAPInt method 9946 // which could signal back if implicit truncation occurred. 9947 llvm::APSInt Result = EVResult.Val.getInt(); 9948 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9949 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9950 llvm::APFloat::rmTowardZero); 9951 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9952 !IntTy->hasSignedIntegerRepresentation()); 9953 bool Ignored = false; 9954 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9955 &Ignored); 9956 if (Result != ConvertBack) 9957 return true; 9958 } else { 9959 // Reject types that cannot be fully encoded into the mantissa of 9960 // the float. 9961 Bits = S.Context.getTypeSize(IntTy); 9962 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9963 S.Context.getFloatTypeSemantics(FloatTy)); 9964 if (Bits > FloatPrec) 9965 return true; 9966 } 9967 9968 return false; 9969 } 9970 9971 /// Attempt to convert and splat Scalar into a vector whose types matches 9972 /// Vector following GCC conversion rules. The rule is that implicit 9973 /// conversion can occur when Scalar can be casted to match Vector's element 9974 /// type without causing truncation of Scalar. 9975 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9976 ExprResult *Vector) { 9977 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9978 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9979 const VectorType *VT = VectorTy->getAs<VectorType>(); 9980 9981 assert(!isa<ExtVectorType>(VT) && 9982 "ExtVectorTypes should not be handled here!"); 9983 9984 QualType VectorEltTy = VT->getElementType(); 9985 9986 // Reject cases where the vector element type or the scalar element type are 9987 // not integral or floating point types. 9988 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9989 return true; 9990 9991 // The conversion to apply to the scalar before splatting it, 9992 // if necessary. 9993 CastKind ScalarCast = CK_NoOp; 9994 9995 // Accept cases where the vector elements are integers and the scalar is 9996 // an integer. 9997 // FIXME: Notionally if the scalar was a floating point value with a precise 9998 // integral representation, we could cast it to an appropriate integer 9999 // type and then perform the rest of the checks here. GCC will perform 10000 // this conversion in some cases as determined by the input language. 10001 // We should accept it on a language independent basis. 10002 if (VectorEltTy->isIntegralType(S.Context) && 10003 ScalarTy->isIntegralType(S.Context) && 10004 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10005 10006 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10007 return true; 10008 10009 ScalarCast = CK_IntegralCast; 10010 } else if (VectorEltTy->isIntegralType(S.Context) && 10011 ScalarTy->isRealFloatingType()) { 10012 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10013 ScalarCast = CK_FloatingToIntegral; 10014 else 10015 return true; 10016 } else if (VectorEltTy->isRealFloatingType()) { 10017 if (ScalarTy->isRealFloatingType()) { 10018 10019 // Reject cases where the scalar type is not a constant and has a higher 10020 // Order than the vector element type. 10021 llvm::APFloat Result(0.0); 10022 10023 // Determine whether this is a constant scalar. In the event that the 10024 // value is dependent (and thus cannot be evaluated by the constant 10025 // evaluator), skip the evaluation. This will then diagnose once the 10026 // expression is instantiated. 10027 bool CstScalar = Scalar->get()->isValueDependent() || 10028 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10029 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10030 if (!CstScalar && Order < 0) 10031 return true; 10032 10033 // If the scalar cannot be safely casted to the vector element type, 10034 // reject it. 10035 if (CstScalar) { 10036 bool Truncated = false; 10037 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10038 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10039 if (Truncated) 10040 return true; 10041 } 10042 10043 ScalarCast = CK_FloatingCast; 10044 } else if (ScalarTy->isIntegralType(S.Context)) { 10045 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10046 return true; 10047 10048 ScalarCast = CK_IntegralToFloating; 10049 } else 10050 return true; 10051 } else if (ScalarTy->isEnumeralType()) 10052 return true; 10053 10054 // Adjust scalar if desired. 10055 if (Scalar) { 10056 if (ScalarCast != CK_NoOp) 10057 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10058 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10059 } 10060 return false; 10061 } 10062 10063 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10064 SourceLocation Loc, bool IsCompAssign, 10065 bool AllowBothBool, 10066 bool AllowBoolConversions) { 10067 if (!IsCompAssign) { 10068 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10069 if (LHS.isInvalid()) 10070 return QualType(); 10071 } 10072 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10073 if (RHS.isInvalid()) 10074 return QualType(); 10075 10076 // For conversion purposes, we ignore any qualifiers. 10077 // For example, "const float" and "float" are equivalent. 10078 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10079 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10080 10081 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10082 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10083 assert(LHSVecType || RHSVecType); 10084 10085 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10086 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10087 return InvalidOperands(Loc, LHS, RHS); 10088 10089 // AltiVec-style "vector bool op vector bool" combinations are allowed 10090 // for some operators but not others. 10091 if (!AllowBothBool && 10092 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10093 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10094 return InvalidOperands(Loc, LHS, RHS); 10095 10096 // If the vector types are identical, return. 10097 if (Context.hasSameType(LHSType, RHSType)) 10098 return LHSType; 10099 10100 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10101 if (LHSVecType && RHSVecType && 10102 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10103 if (isa<ExtVectorType>(LHSVecType)) { 10104 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10105 return LHSType; 10106 } 10107 10108 if (!IsCompAssign) 10109 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10110 return RHSType; 10111 } 10112 10113 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10114 // can be mixed, with the result being the non-bool type. The non-bool 10115 // operand must have integer element type. 10116 if (AllowBoolConversions && LHSVecType && RHSVecType && 10117 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10118 (Context.getTypeSize(LHSVecType->getElementType()) == 10119 Context.getTypeSize(RHSVecType->getElementType()))) { 10120 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10121 LHSVecType->getElementType()->isIntegerType() && 10122 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10123 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10124 return LHSType; 10125 } 10126 if (!IsCompAssign && 10127 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10128 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10129 RHSVecType->getElementType()->isIntegerType()) { 10130 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10131 return RHSType; 10132 } 10133 } 10134 10135 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10136 // since the ambiguity can affect the ABI. 10137 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10138 const VectorType *VecType = SecondType->getAs<VectorType>(); 10139 return FirstType->isSizelessBuiltinType() && VecType && 10140 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10141 VecType->getVectorKind() == 10142 VectorType::SveFixedLengthPredicateVector); 10143 }; 10144 10145 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10146 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10147 return QualType(); 10148 } 10149 10150 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10151 // since the ambiguity can affect the ABI. 10152 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10153 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10154 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10155 10156 if (FirstVecType && SecondVecType) 10157 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10158 (SecondVecType->getVectorKind() == 10159 VectorType::SveFixedLengthDataVector || 10160 SecondVecType->getVectorKind() == 10161 VectorType::SveFixedLengthPredicateVector); 10162 10163 return FirstType->isSizelessBuiltinType() && SecondVecType && 10164 SecondVecType->getVectorKind() == VectorType::GenericVector; 10165 }; 10166 10167 if (IsSveGnuConversion(LHSType, RHSType) || 10168 IsSveGnuConversion(RHSType, LHSType)) { 10169 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10170 return QualType(); 10171 } 10172 10173 // If there's a vector type and a scalar, try to convert the scalar to 10174 // the vector element type and splat. 10175 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10176 if (!RHSVecType) { 10177 if (isa<ExtVectorType>(LHSVecType)) { 10178 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10179 LHSVecType->getElementType(), LHSType, 10180 DiagID)) 10181 return LHSType; 10182 } else { 10183 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10184 return LHSType; 10185 } 10186 } 10187 if (!LHSVecType) { 10188 if (isa<ExtVectorType>(RHSVecType)) { 10189 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10190 LHSType, RHSVecType->getElementType(), 10191 RHSType, DiagID)) 10192 return RHSType; 10193 } else { 10194 if (LHS.get()->isLValue() || 10195 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10196 return RHSType; 10197 } 10198 } 10199 10200 // FIXME: The code below also handles conversion between vectors and 10201 // non-scalars, we should break this down into fine grained specific checks 10202 // and emit proper diagnostics. 10203 QualType VecType = LHSVecType ? LHSType : RHSType; 10204 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10205 QualType OtherType = LHSVecType ? RHSType : LHSType; 10206 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10207 if (isLaxVectorConversion(OtherType, VecType)) { 10208 // If we're allowing lax vector conversions, only the total (data) size 10209 // needs to be the same. For non compound assignment, if one of the types is 10210 // scalar, the result is always the vector type. 10211 if (!IsCompAssign) { 10212 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10213 return VecType; 10214 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10215 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10216 // type. Note that this is already done by non-compound assignments in 10217 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10218 // <1 x T> -> T. The result is also a vector type. 10219 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10220 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10221 ExprResult *RHSExpr = &RHS; 10222 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10223 return VecType; 10224 } 10225 } 10226 10227 // Okay, the expression is invalid. 10228 10229 // If there's a non-vector, non-real operand, diagnose that. 10230 if ((!RHSVecType && !RHSType->isRealType()) || 10231 (!LHSVecType && !LHSType->isRealType())) { 10232 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10233 << LHSType << RHSType 10234 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10235 return QualType(); 10236 } 10237 10238 // OpenCL V1.1 6.2.6.p1: 10239 // If the operands are of more than one vector type, then an error shall 10240 // occur. Implicit conversions between vector types are not permitted, per 10241 // section 6.2.1. 10242 if (getLangOpts().OpenCL && 10243 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10244 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10245 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10246 << RHSType; 10247 return QualType(); 10248 } 10249 10250 10251 // If there is a vector type that is not a ExtVector and a scalar, we reach 10252 // this point if scalar could not be converted to the vector's element type 10253 // without truncation. 10254 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10255 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10256 QualType Scalar = LHSVecType ? RHSType : LHSType; 10257 QualType Vector = LHSVecType ? LHSType : RHSType; 10258 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10259 Diag(Loc, 10260 diag::err_typecheck_vector_not_convertable_implict_truncation) 10261 << ScalarOrVector << Scalar << Vector; 10262 10263 return QualType(); 10264 } 10265 10266 // Otherwise, use the generic diagnostic. 10267 Diag(Loc, DiagID) 10268 << LHSType << RHSType 10269 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10270 return QualType(); 10271 } 10272 10273 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10274 // expression. These are mainly cases where the null pointer is used as an 10275 // integer instead of a pointer. 10276 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10277 SourceLocation Loc, bool IsCompare) { 10278 // The canonical way to check for a GNU null is with isNullPointerConstant, 10279 // but we use a bit of a hack here for speed; this is a relatively 10280 // hot path, and isNullPointerConstant is slow. 10281 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10282 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10283 10284 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10285 10286 // Avoid analyzing cases where the result will either be invalid (and 10287 // diagnosed as such) or entirely valid and not something to warn about. 10288 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10289 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10290 return; 10291 10292 // Comparison operations would not make sense with a null pointer no matter 10293 // what the other expression is. 10294 if (!IsCompare) { 10295 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10296 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10297 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10298 return; 10299 } 10300 10301 // The rest of the operations only make sense with a null pointer 10302 // if the other expression is a pointer. 10303 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10304 NonNullType->canDecayToPointerType()) 10305 return; 10306 10307 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10308 << LHSNull /* LHS is NULL */ << NonNullType 10309 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10310 } 10311 10312 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10313 SourceLocation Loc) { 10314 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10315 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10316 if (!LUE || !RUE) 10317 return; 10318 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10319 RUE->getKind() != UETT_SizeOf) 10320 return; 10321 10322 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10323 QualType LHSTy = LHSArg->getType(); 10324 QualType RHSTy; 10325 10326 if (RUE->isArgumentType()) 10327 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10328 else 10329 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10330 10331 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10332 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10333 return; 10334 10335 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10336 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10337 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10338 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10339 << LHSArgDecl; 10340 } 10341 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10342 QualType ArrayElemTy = ArrayTy->getElementType(); 10343 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10344 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10345 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10346 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10347 return; 10348 S.Diag(Loc, diag::warn_division_sizeof_array) 10349 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10350 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10351 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10352 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10353 << LHSArgDecl; 10354 } 10355 10356 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10357 } 10358 } 10359 10360 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10361 ExprResult &RHS, 10362 SourceLocation Loc, bool IsDiv) { 10363 // Check for division/remainder by zero. 10364 Expr::EvalResult RHSValue; 10365 if (!RHS.get()->isValueDependent() && 10366 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10367 RHSValue.Val.getInt() == 0) 10368 S.DiagRuntimeBehavior(Loc, RHS.get(), 10369 S.PDiag(diag::warn_remainder_division_by_zero) 10370 << IsDiv << RHS.get()->getSourceRange()); 10371 } 10372 10373 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10374 SourceLocation Loc, 10375 bool IsCompAssign, bool IsDiv) { 10376 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10377 10378 QualType LHSTy = LHS.get()->getType(); 10379 QualType RHSTy = RHS.get()->getType(); 10380 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10381 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10382 /*AllowBothBool*/getLangOpts().AltiVec, 10383 /*AllowBoolConversions*/false); 10384 if (!IsDiv && 10385 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10386 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10387 // For division, only matrix-by-scalar is supported. Other combinations with 10388 // matrix types are invalid. 10389 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10390 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10391 10392 QualType compType = UsualArithmeticConversions( 10393 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10394 if (LHS.isInvalid() || RHS.isInvalid()) 10395 return QualType(); 10396 10397 10398 if (compType.isNull() || !compType->isArithmeticType()) 10399 return InvalidOperands(Loc, LHS, RHS); 10400 if (IsDiv) { 10401 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10402 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10403 } 10404 return compType; 10405 } 10406 10407 QualType Sema::CheckRemainderOperands( 10408 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10409 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10410 10411 if (LHS.get()->getType()->isVectorType() || 10412 RHS.get()->getType()->isVectorType()) { 10413 if (LHS.get()->getType()->hasIntegerRepresentation() && 10414 RHS.get()->getType()->hasIntegerRepresentation()) 10415 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10416 /*AllowBothBool*/getLangOpts().AltiVec, 10417 /*AllowBoolConversions*/false); 10418 return InvalidOperands(Loc, LHS, RHS); 10419 } 10420 10421 QualType compType = UsualArithmeticConversions( 10422 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10423 if (LHS.isInvalid() || RHS.isInvalid()) 10424 return QualType(); 10425 10426 if (compType.isNull() || !compType->isIntegerType()) 10427 return InvalidOperands(Loc, LHS, RHS); 10428 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10429 return compType; 10430 } 10431 10432 /// Diagnose invalid arithmetic on two void pointers. 10433 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10434 Expr *LHSExpr, Expr *RHSExpr) { 10435 S.Diag(Loc, S.getLangOpts().CPlusPlus 10436 ? diag::err_typecheck_pointer_arith_void_type 10437 : diag::ext_gnu_void_ptr) 10438 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10439 << RHSExpr->getSourceRange(); 10440 } 10441 10442 /// Diagnose invalid arithmetic on a void pointer. 10443 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10444 Expr *Pointer) { 10445 S.Diag(Loc, S.getLangOpts().CPlusPlus 10446 ? diag::err_typecheck_pointer_arith_void_type 10447 : diag::ext_gnu_void_ptr) 10448 << 0 /* one pointer */ << Pointer->getSourceRange(); 10449 } 10450 10451 /// Diagnose invalid arithmetic on a null pointer. 10452 /// 10453 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10454 /// idiom, which we recognize as a GNU extension. 10455 /// 10456 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10457 Expr *Pointer, bool IsGNUIdiom) { 10458 if (IsGNUIdiom) 10459 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10460 << Pointer->getSourceRange(); 10461 else 10462 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10463 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10464 } 10465 10466 /// Diagnose invalid subraction on a null pointer. 10467 /// 10468 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10469 Expr *Pointer, bool BothNull) { 10470 // Null - null is valid in C++ [expr.add]p7 10471 if (BothNull && S.getLangOpts().CPlusPlus) 10472 return; 10473 10474 // Is this s a macro from a system header? 10475 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10476 return; 10477 10478 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10479 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10480 } 10481 10482 /// Diagnose invalid arithmetic on two function pointers. 10483 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10484 Expr *LHS, Expr *RHS) { 10485 assert(LHS->getType()->isAnyPointerType()); 10486 assert(RHS->getType()->isAnyPointerType()); 10487 S.Diag(Loc, S.getLangOpts().CPlusPlus 10488 ? diag::err_typecheck_pointer_arith_function_type 10489 : diag::ext_gnu_ptr_func_arith) 10490 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10491 // We only show the second type if it differs from the first. 10492 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10493 RHS->getType()) 10494 << RHS->getType()->getPointeeType() 10495 << LHS->getSourceRange() << RHS->getSourceRange(); 10496 } 10497 10498 /// Diagnose invalid arithmetic on a function pointer. 10499 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10500 Expr *Pointer) { 10501 assert(Pointer->getType()->isAnyPointerType()); 10502 S.Diag(Loc, S.getLangOpts().CPlusPlus 10503 ? diag::err_typecheck_pointer_arith_function_type 10504 : diag::ext_gnu_ptr_func_arith) 10505 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10506 << 0 /* one pointer, so only one type */ 10507 << Pointer->getSourceRange(); 10508 } 10509 10510 /// Emit error if Operand is incomplete pointer type 10511 /// 10512 /// \returns True if pointer has incomplete type 10513 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10514 Expr *Operand) { 10515 QualType ResType = Operand->getType(); 10516 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10517 ResType = ResAtomicType->getValueType(); 10518 10519 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10520 QualType PointeeTy = ResType->getPointeeType(); 10521 return S.RequireCompleteSizedType( 10522 Loc, PointeeTy, 10523 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10524 Operand->getSourceRange()); 10525 } 10526 10527 /// Check the validity of an arithmetic pointer operand. 10528 /// 10529 /// If the operand has pointer type, this code will check for pointer types 10530 /// which are invalid in arithmetic operations. These will be diagnosed 10531 /// appropriately, including whether or not the use is supported as an 10532 /// extension. 10533 /// 10534 /// \returns True when the operand is valid to use (even if as an extension). 10535 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10536 Expr *Operand) { 10537 QualType ResType = Operand->getType(); 10538 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10539 ResType = ResAtomicType->getValueType(); 10540 10541 if (!ResType->isAnyPointerType()) return true; 10542 10543 QualType PointeeTy = ResType->getPointeeType(); 10544 if (PointeeTy->isVoidType()) { 10545 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10546 return !S.getLangOpts().CPlusPlus; 10547 } 10548 if (PointeeTy->isFunctionType()) { 10549 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10550 return !S.getLangOpts().CPlusPlus; 10551 } 10552 10553 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10554 10555 return true; 10556 } 10557 10558 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10559 /// operands. 10560 /// 10561 /// This routine will diagnose any invalid arithmetic on pointer operands much 10562 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10563 /// for emitting a single diagnostic even for operations where both LHS and RHS 10564 /// are (potentially problematic) pointers. 10565 /// 10566 /// \returns True when the operand is valid to use (even if as an extension). 10567 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10568 Expr *LHSExpr, Expr *RHSExpr) { 10569 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10570 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10571 if (!isLHSPointer && !isRHSPointer) return true; 10572 10573 QualType LHSPointeeTy, RHSPointeeTy; 10574 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10575 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10576 10577 // if both are pointers check if operation is valid wrt address spaces 10578 if (isLHSPointer && isRHSPointer) { 10579 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10580 S.Diag(Loc, 10581 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10582 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10583 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10584 return false; 10585 } 10586 } 10587 10588 // Check for arithmetic on pointers to incomplete types. 10589 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10590 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10591 if (isLHSVoidPtr || isRHSVoidPtr) { 10592 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10593 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10594 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10595 10596 return !S.getLangOpts().CPlusPlus; 10597 } 10598 10599 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10600 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10601 if (isLHSFuncPtr || isRHSFuncPtr) { 10602 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10603 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10604 RHSExpr); 10605 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10606 10607 return !S.getLangOpts().CPlusPlus; 10608 } 10609 10610 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10611 return false; 10612 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10613 return false; 10614 10615 return true; 10616 } 10617 10618 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10619 /// literal. 10620 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10621 Expr *LHSExpr, Expr *RHSExpr) { 10622 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10623 Expr* IndexExpr = RHSExpr; 10624 if (!StrExpr) { 10625 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10626 IndexExpr = LHSExpr; 10627 } 10628 10629 bool IsStringPlusInt = StrExpr && 10630 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10631 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10632 return; 10633 10634 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10635 Self.Diag(OpLoc, diag::warn_string_plus_int) 10636 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10637 10638 // Only print a fixit for "str" + int, not for int + "str". 10639 if (IndexExpr == RHSExpr) { 10640 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10641 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10642 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10643 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10644 << FixItHint::CreateInsertion(EndLoc, "]"); 10645 } else 10646 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10647 } 10648 10649 /// Emit a warning when adding a char literal to a string. 10650 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10651 Expr *LHSExpr, Expr *RHSExpr) { 10652 const Expr *StringRefExpr = LHSExpr; 10653 const CharacterLiteral *CharExpr = 10654 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10655 10656 if (!CharExpr) { 10657 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10658 StringRefExpr = RHSExpr; 10659 } 10660 10661 if (!CharExpr || !StringRefExpr) 10662 return; 10663 10664 const QualType StringType = StringRefExpr->getType(); 10665 10666 // Return if not a PointerType. 10667 if (!StringType->isAnyPointerType()) 10668 return; 10669 10670 // Return if not a CharacterType. 10671 if (!StringType->getPointeeType()->isAnyCharacterType()) 10672 return; 10673 10674 ASTContext &Ctx = Self.getASTContext(); 10675 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10676 10677 const QualType CharType = CharExpr->getType(); 10678 if (!CharType->isAnyCharacterType() && 10679 CharType->isIntegerType() && 10680 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10681 Self.Diag(OpLoc, diag::warn_string_plus_char) 10682 << DiagRange << Ctx.CharTy; 10683 } else { 10684 Self.Diag(OpLoc, diag::warn_string_plus_char) 10685 << DiagRange << CharExpr->getType(); 10686 } 10687 10688 // Only print a fixit for str + char, not for char + str. 10689 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10690 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10691 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10692 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10693 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10694 << FixItHint::CreateInsertion(EndLoc, "]"); 10695 } else { 10696 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10697 } 10698 } 10699 10700 /// Emit error when two pointers are incompatible. 10701 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10702 Expr *LHSExpr, Expr *RHSExpr) { 10703 assert(LHSExpr->getType()->isAnyPointerType()); 10704 assert(RHSExpr->getType()->isAnyPointerType()); 10705 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10706 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10707 << RHSExpr->getSourceRange(); 10708 } 10709 10710 // C99 6.5.6 10711 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10712 SourceLocation Loc, BinaryOperatorKind Opc, 10713 QualType* CompLHSTy) { 10714 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10715 10716 if (LHS.get()->getType()->isVectorType() || 10717 RHS.get()->getType()->isVectorType()) { 10718 QualType compType = CheckVectorOperands( 10719 LHS, RHS, Loc, CompLHSTy, 10720 /*AllowBothBool*/getLangOpts().AltiVec, 10721 /*AllowBoolConversions*/getLangOpts().ZVector); 10722 if (CompLHSTy) *CompLHSTy = compType; 10723 return compType; 10724 } 10725 10726 if (LHS.get()->getType()->isConstantMatrixType() || 10727 RHS.get()->getType()->isConstantMatrixType()) { 10728 QualType compType = 10729 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10730 if (CompLHSTy) 10731 *CompLHSTy = compType; 10732 return compType; 10733 } 10734 10735 QualType compType = UsualArithmeticConversions( 10736 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10737 if (LHS.isInvalid() || RHS.isInvalid()) 10738 return QualType(); 10739 10740 // Diagnose "string literal" '+' int and string '+' "char literal". 10741 if (Opc == BO_Add) { 10742 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10743 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10744 } 10745 10746 // handle the common case first (both operands are arithmetic). 10747 if (!compType.isNull() && compType->isArithmeticType()) { 10748 if (CompLHSTy) *CompLHSTy = compType; 10749 return compType; 10750 } 10751 10752 // Type-checking. Ultimately the pointer's going to be in PExp; 10753 // note that we bias towards the LHS being the pointer. 10754 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10755 10756 bool isObjCPointer; 10757 if (PExp->getType()->isPointerType()) { 10758 isObjCPointer = false; 10759 } else if (PExp->getType()->isObjCObjectPointerType()) { 10760 isObjCPointer = true; 10761 } else { 10762 std::swap(PExp, IExp); 10763 if (PExp->getType()->isPointerType()) { 10764 isObjCPointer = false; 10765 } else if (PExp->getType()->isObjCObjectPointerType()) { 10766 isObjCPointer = true; 10767 } else { 10768 return InvalidOperands(Loc, LHS, RHS); 10769 } 10770 } 10771 assert(PExp->getType()->isAnyPointerType()); 10772 10773 if (!IExp->getType()->isIntegerType()) 10774 return InvalidOperands(Loc, LHS, RHS); 10775 10776 // Adding to a null pointer results in undefined behavior. 10777 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10778 Context, Expr::NPC_ValueDependentIsNotNull)) { 10779 // In C++ adding zero to a null pointer is defined. 10780 Expr::EvalResult KnownVal; 10781 if (!getLangOpts().CPlusPlus || 10782 (!IExp->isValueDependent() && 10783 (!IExp->EvaluateAsInt(KnownVal, Context) || 10784 KnownVal.Val.getInt() != 0))) { 10785 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10786 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10787 Context, BO_Add, PExp, IExp); 10788 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10789 } 10790 } 10791 10792 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10793 return QualType(); 10794 10795 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10796 return QualType(); 10797 10798 // Check array bounds for pointer arithemtic 10799 CheckArrayAccess(PExp, IExp); 10800 10801 if (CompLHSTy) { 10802 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10803 if (LHSTy.isNull()) { 10804 LHSTy = LHS.get()->getType(); 10805 if (LHSTy->isPromotableIntegerType()) 10806 LHSTy = Context.getPromotedIntegerType(LHSTy); 10807 } 10808 *CompLHSTy = LHSTy; 10809 } 10810 10811 return PExp->getType(); 10812 } 10813 10814 // C99 6.5.6 10815 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10816 SourceLocation Loc, 10817 QualType* CompLHSTy) { 10818 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10819 10820 if (LHS.get()->getType()->isVectorType() || 10821 RHS.get()->getType()->isVectorType()) { 10822 QualType compType = CheckVectorOperands( 10823 LHS, RHS, Loc, CompLHSTy, 10824 /*AllowBothBool*/getLangOpts().AltiVec, 10825 /*AllowBoolConversions*/getLangOpts().ZVector); 10826 if (CompLHSTy) *CompLHSTy = compType; 10827 return compType; 10828 } 10829 10830 if (LHS.get()->getType()->isConstantMatrixType() || 10831 RHS.get()->getType()->isConstantMatrixType()) { 10832 QualType compType = 10833 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10834 if (CompLHSTy) 10835 *CompLHSTy = compType; 10836 return compType; 10837 } 10838 10839 QualType compType = UsualArithmeticConversions( 10840 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10841 if (LHS.isInvalid() || RHS.isInvalid()) 10842 return QualType(); 10843 10844 // Enforce type constraints: C99 6.5.6p3. 10845 10846 // Handle the common case first (both operands are arithmetic). 10847 if (!compType.isNull() && compType->isArithmeticType()) { 10848 if (CompLHSTy) *CompLHSTy = compType; 10849 return compType; 10850 } 10851 10852 // Either ptr - int or ptr - ptr. 10853 if (LHS.get()->getType()->isAnyPointerType()) { 10854 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10855 10856 // Diagnose bad cases where we step over interface counts. 10857 if (LHS.get()->getType()->isObjCObjectPointerType() && 10858 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10859 return QualType(); 10860 10861 // The result type of a pointer-int computation is the pointer type. 10862 if (RHS.get()->getType()->isIntegerType()) { 10863 // Subtracting from a null pointer should produce a warning. 10864 // The last argument to the diagnose call says this doesn't match the 10865 // GNU int-to-pointer idiom. 10866 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10867 Expr::NPC_ValueDependentIsNotNull)) { 10868 // In C++ adding zero to a null pointer is defined. 10869 Expr::EvalResult KnownVal; 10870 if (!getLangOpts().CPlusPlus || 10871 (!RHS.get()->isValueDependent() && 10872 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10873 KnownVal.Val.getInt() != 0))) { 10874 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10875 } 10876 } 10877 10878 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10879 return QualType(); 10880 10881 // Check array bounds for pointer arithemtic 10882 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10883 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10884 10885 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10886 return LHS.get()->getType(); 10887 } 10888 10889 // Handle pointer-pointer subtractions. 10890 if (const PointerType *RHSPTy 10891 = RHS.get()->getType()->getAs<PointerType>()) { 10892 QualType rpointee = RHSPTy->getPointeeType(); 10893 10894 if (getLangOpts().CPlusPlus) { 10895 // Pointee types must be the same: C++ [expr.add] 10896 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10897 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10898 } 10899 } else { 10900 // Pointee types must be compatible C99 6.5.6p3 10901 if (!Context.typesAreCompatible( 10902 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10903 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10904 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10905 return QualType(); 10906 } 10907 } 10908 10909 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10910 LHS.get(), RHS.get())) 10911 return QualType(); 10912 10913 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10914 Context, Expr::NPC_ValueDependentIsNotNull); 10915 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10916 Context, Expr::NPC_ValueDependentIsNotNull); 10917 10918 // Subtracting nullptr or from nullptr is suspect 10919 if (LHSIsNullPtr) 10920 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10921 if (RHSIsNullPtr) 10922 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10923 10924 // The pointee type may have zero size. As an extension, a structure or 10925 // union may have zero size or an array may have zero length. In this 10926 // case subtraction does not make sense. 10927 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10928 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10929 if (ElementSize.isZero()) { 10930 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10931 << rpointee.getUnqualifiedType() 10932 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10933 } 10934 } 10935 10936 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10937 return Context.getPointerDiffType(); 10938 } 10939 } 10940 10941 return InvalidOperands(Loc, LHS, RHS); 10942 } 10943 10944 static bool isScopedEnumerationType(QualType T) { 10945 if (const EnumType *ET = T->getAs<EnumType>()) 10946 return ET->getDecl()->isScoped(); 10947 return false; 10948 } 10949 10950 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10951 SourceLocation Loc, BinaryOperatorKind Opc, 10952 QualType LHSType) { 10953 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10954 // so skip remaining warnings as we don't want to modify values within Sema. 10955 if (S.getLangOpts().OpenCL) 10956 return; 10957 10958 // Check right/shifter operand 10959 Expr::EvalResult RHSResult; 10960 if (RHS.get()->isValueDependent() || 10961 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10962 return; 10963 llvm::APSInt Right = RHSResult.Val.getInt(); 10964 10965 if (Right.isNegative()) { 10966 S.DiagRuntimeBehavior(Loc, RHS.get(), 10967 S.PDiag(diag::warn_shift_negative) 10968 << RHS.get()->getSourceRange()); 10969 return; 10970 } 10971 10972 QualType LHSExprType = LHS.get()->getType(); 10973 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10974 if (LHSExprType->isExtIntType()) 10975 LeftSize = S.Context.getIntWidth(LHSExprType); 10976 else if (LHSExprType->isFixedPointType()) { 10977 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10978 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10979 } 10980 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10981 if (Right.uge(LeftBits)) { 10982 S.DiagRuntimeBehavior(Loc, RHS.get(), 10983 S.PDiag(diag::warn_shift_gt_typewidth) 10984 << RHS.get()->getSourceRange()); 10985 return; 10986 } 10987 10988 // FIXME: We probably need to handle fixed point types specially here. 10989 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10990 return; 10991 10992 // When left shifting an ICE which is signed, we can check for overflow which 10993 // according to C++ standards prior to C++2a has undefined behavior 10994 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10995 // more than the maximum value representable in the result type, so never 10996 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10997 // expression is still probably a bug.) 10998 Expr::EvalResult LHSResult; 10999 if (LHS.get()->isValueDependent() || 11000 LHSType->hasUnsignedIntegerRepresentation() || 11001 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11002 return; 11003 llvm::APSInt Left = LHSResult.Val.getInt(); 11004 11005 // If LHS does not have a signed type and non-negative value 11006 // then, the behavior is undefined before C++2a. Warn about it. 11007 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11008 !S.getLangOpts().CPlusPlus20) { 11009 S.DiagRuntimeBehavior(Loc, LHS.get(), 11010 S.PDiag(diag::warn_shift_lhs_negative) 11011 << LHS.get()->getSourceRange()); 11012 return; 11013 } 11014 11015 llvm::APInt ResultBits = 11016 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11017 if (LeftBits.uge(ResultBits)) 11018 return; 11019 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11020 Result = Result.shl(Right); 11021 11022 // Print the bit representation of the signed integer as an unsigned 11023 // hexadecimal number. 11024 SmallString<40> HexResult; 11025 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11026 11027 // If we are only missing a sign bit, this is less likely to result in actual 11028 // bugs -- if the result is cast back to an unsigned type, it will have the 11029 // expected value. Thus we place this behind a different warning that can be 11030 // turned off separately if needed. 11031 if (LeftBits == ResultBits - 1) { 11032 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11033 << HexResult << LHSType 11034 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11035 return; 11036 } 11037 11038 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11039 << HexResult.str() << Result.getMinSignedBits() << LHSType 11040 << Left.getBitWidth() << LHS.get()->getSourceRange() 11041 << RHS.get()->getSourceRange(); 11042 } 11043 11044 /// Return the resulting type when a vector is shifted 11045 /// by a scalar or vector shift amount. 11046 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11047 SourceLocation Loc, bool IsCompAssign) { 11048 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11049 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11050 !LHS.get()->getType()->isVectorType()) { 11051 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11052 << RHS.get()->getType() << LHS.get()->getType() 11053 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11054 return QualType(); 11055 } 11056 11057 if (!IsCompAssign) { 11058 LHS = S.UsualUnaryConversions(LHS.get()); 11059 if (LHS.isInvalid()) return QualType(); 11060 } 11061 11062 RHS = S.UsualUnaryConversions(RHS.get()); 11063 if (RHS.isInvalid()) return QualType(); 11064 11065 QualType LHSType = LHS.get()->getType(); 11066 // Note that LHS might be a scalar because the routine calls not only in 11067 // OpenCL case. 11068 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11069 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11070 11071 // Note that RHS might not be a vector. 11072 QualType RHSType = RHS.get()->getType(); 11073 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11074 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11075 11076 // The operands need to be integers. 11077 if (!LHSEleType->isIntegerType()) { 11078 S.Diag(Loc, diag::err_typecheck_expect_int) 11079 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11080 return QualType(); 11081 } 11082 11083 if (!RHSEleType->isIntegerType()) { 11084 S.Diag(Loc, diag::err_typecheck_expect_int) 11085 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11086 return QualType(); 11087 } 11088 11089 if (!LHSVecTy) { 11090 assert(RHSVecTy); 11091 if (IsCompAssign) 11092 return RHSType; 11093 if (LHSEleType != RHSEleType) { 11094 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11095 LHSEleType = RHSEleType; 11096 } 11097 QualType VecTy = 11098 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11099 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11100 LHSType = VecTy; 11101 } else if (RHSVecTy) { 11102 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11103 // are applied component-wise. So if RHS is a vector, then ensure 11104 // that the number of elements is the same as LHS... 11105 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11106 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11107 << LHS.get()->getType() << RHS.get()->getType() 11108 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11109 return QualType(); 11110 } 11111 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11112 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11113 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11114 if (LHSBT != RHSBT && 11115 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11116 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11117 << LHS.get()->getType() << RHS.get()->getType() 11118 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11119 } 11120 } 11121 } else { 11122 // ...else expand RHS to match the number of elements in LHS. 11123 QualType VecTy = 11124 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11125 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11126 } 11127 11128 return LHSType; 11129 } 11130 11131 // C99 6.5.7 11132 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11133 SourceLocation Loc, BinaryOperatorKind Opc, 11134 bool IsCompAssign) { 11135 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11136 11137 // Vector shifts promote their scalar inputs to vector type. 11138 if (LHS.get()->getType()->isVectorType() || 11139 RHS.get()->getType()->isVectorType()) { 11140 if (LangOpts.ZVector) { 11141 // The shift operators for the z vector extensions work basically 11142 // like general shifts, except that neither the LHS nor the RHS is 11143 // allowed to be a "vector bool". 11144 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11145 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11146 return InvalidOperands(Loc, LHS, RHS); 11147 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11148 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11149 return InvalidOperands(Loc, LHS, RHS); 11150 } 11151 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11152 } 11153 11154 // Shifts don't perform usual arithmetic conversions, they just do integer 11155 // promotions on each operand. C99 6.5.7p3 11156 11157 // For the LHS, do usual unary conversions, but then reset them away 11158 // if this is a compound assignment. 11159 ExprResult OldLHS = LHS; 11160 LHS = UsualUnaryConversions(LHS.get()); 11161 if (LHS.isInvalid()) 11162 return QualType(); 11163 QualType LHSType = LHS.get()->getType(); 11164 if (IsCompAssign) LHS = OldLHS; 11165 11166 // The RHS is simpler. 11167 RHS = UsualUnaryConversions(RHS.get()); 11168 if (RHS.isInvalid()) 11169 return QualType(); 11170 QualType RHSType = RHS.get()->getType(); 11171 11172 // C99 6.5.7p2: Each of the operands shall have integer type. 11173 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11174 if ((!LHSType->isFixedPointOrIntegerType() && 11175 !LHSType->hasIntegerRepresentation()) || 11176 !RHSType->hasIntegerRepresentation()) 11177 return InvalidOperands(Loc, LHS, RHS); 11178 11179 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11180 // hasIntegerRepresentation() above instead of this. 11181 if (isScopedEnumerationType(LHSType) || 11182 isScopedEnumerationType(RHSType)) { 11183 return InvalidOperands(Loc, LHS, RHS); 11184 } 11185 // Sanity-check shift operands 11186 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11187 11188 // "The type of the result is that of the promoted left operand." 11189 return LHSType; 11190 } 11191 11192 /// Diagnose bad pointer comparisons. 11193 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11194 ExprResult &LHS, ExprResult &RHS, 11195 bool IsError) { 11196 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11197 : diag::ext_typecheck_comparison_of_distinct_pointers) 11198 << LHS.get()->getType() << RHS.get()->getType() 11199 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11200 } 11201 11202 /// Returns false if the pointers are converted to a composite type, 11203 /// true otherwise. 11204 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11205 ExprResult &LHS, ExprResult &RHS) { 11206 // C++ [expr.rel]p2: 11207 // [...] Pointer conversions (4.10) and qualification 11208 // conversions (4.4) are performed on pointer operands (or on 11209 // a pointer operand and a null pointer constant) to bring 11210 // them to their composite pointer type. [...] 11211 // 11212 // C++ [expr.eq]p1 uses the same notion for (in)equality 11213 // comparisons of pointers. 11214 11215 QualType LHSType = LHS.get()->getType(); 11216 QualType RHSType = RHS.get()->getType(); 11217 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11218 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11219 11220 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11221 if (T.isNull()) { 11222 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11223 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11224 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11225 else 11226 S.InvalidOperands(Loc, LHS, RHS); 11227 return true; 11228 } 11229 11230 return false; 11231 } 11232 11233 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11234 ExprResult &LHS, 11235 ExprResult &RHS, 11236 bool IsError) { 11237 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11238 : diag::ext_typecheck_comparison_of_fptr_to_void) 11239 << LHS.get()->getType() << RHS.get()->getType() 11240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11241 } 11242 11243 static bool isObjCObjectLiteral(ExprResult &E) { 11244 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11245 case Stmt::ObjCArrayLiteralClass: 11246 case Stmt::ObjCDictionaryLiteralClass: 11247 case Stmt::ObjCStringLiteralClass: 11248 case Stmt::ObjCBoxedExprClass: 11249 return true; 11250 default: 11251 // Note that ObjCBoolLiteral is NOT an object literal! 11252 return false; 11253 } 11254 } 11255 11256 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11257 const ObjCObjectPointerType *Type = 11258 LHS->getType()->getAs<ObjCObjectPointerType>(); 11259 11260 // If this is not actually an Objective-C object, bail out. 11261 if (!Type) 11262 return false; 11263 11264 // Get the LHS object's interface type. 11265 QualType InterfaceType = Type->getPointeeType(); 11266 11267 // If the RHS isn't an Objective-C object, bail out. 11268 if (!RHS->getType()->isObjCObjectPointerType()) 11269 return false; 11270 11271 // Try to find the -isEqual: method. 11272 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11273 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11274 InterfaceType, 11275 /*IsInstance=*/true); 11276 if (!Method) { 11277 if (Type->isObjCIdType()) { 11278 // For 'id', just check the global pool. 11279 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11280 /*receiverId=*/true); 11281 } else { 11282 // Check protocols. 11283 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11284 /*IsInstance=*/true); 11285 } 11286 } 11287 11288 if (!Method) 11289 return false; 11290 11291 QualType T = Method->parameters()[0]->getType(); 11292 if (!T->isObjCObjectPointerType()) 11293 return false; 11294 11295 QualType R = Method->getReturnType(); 11296 if (!R->isScalarType()) 11297 return false; 11298 11299 return true; 11300 } 11301 11302 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11303 FromE = FromE->IgnoreParenImpCasts(); 11304 switch (FromE->getStmtClass()) { 11305 default: 11306 break; 11307 case Stmt::ObjCStringLiteralClass: 11308 // "string literal" 11309 return LK_String; 11310 case Stmt::ObjCArrayLiteralClass: 11311 // "array literal" 11312 return LK_Array; 11313 case Stmt::ObjCDictionaryLiteralClass: 11314 // "dictionary literal" 11315 return LK_Dictionary; 11316 case Stmt::BlockExprClass: 11317 return LK_Block; 11318 case Stmt::ObjCBoxedExprClass: { 11319 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11320 switch (Inner->getStmtClass()) { 11321 case Stmt::IntegerLiteralClass: 11322 case Stmt::FloatingLiteralClass: 11323 case Stmt::CharacterLiteralClass: 11324 case Stmt::ObjCBoolLiteralExprClass: 11325 case Stmt::CXXBoolLiteralExprClass: 11326 // "numeric literal" 11327 return LK_Numeric; 11328 case Stmt::ImplicitCastExprClass: { 11329 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11330 // Boolean literals can be represented by implicit casts. 11331 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11332 return LK_Numeric; 11333 break; 11334 } 11335 default: 11336 break; 11337 } 11338 return LK_Boxed; 11339 } 11340 } 11341 return LK_None; 11342 } 11343 11344 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11345 ExprResult &LHS, ExprResult &RHS, 11346 BinaryOperator::Opcode Opc){ 11347 Expr *Literal; 11348 Expr *Other; 11349 if (isObjCObjectLiteral(LHS)) { 11350 Literal = LHS.get(); 11351 Other = RHS.get(); 11352 } else { 11353 Literal = RHS.get(); 11354 Other = LHS.get(); 11355 } 11356 11357 // Don't warn on comparisons against nil. 11358 Other = Other->IgnoreParenCasts(); 11359 if (Other->isNullPointerConstant(S.getASTContext(), 11360 Expr::NPC_ValueDependentIsNotNull)) 11361 return; 11362 11363 // This should be kept in sync with warn_objc_literal_comparison. 11364 // LK_String should always be after the other literals, since it has its own 11365 // warning flag. 11366 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11367 assert(LiteralKind != Sema::LK_Block); 11368 if (LiteralKind == Sema::LK_None) { 11369 llvm_unreachable("Unknown Objective-C object literal kind"); 11370 } 11371 11372 if (LiteralKind == Sema::LK_String) 11373 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11374 << Literal->getSourceRange(); 11375 else 11376 S.Diag(Loc, diag::warn_objc_literal_comparison) 11377 << LiteralKind << Literal->getSourceRange(); 11378 11379 if (BinaryOperator::isEqualityOp(Opc) && 11380 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11381 SourceLocation Start = LHS.get()->getBeginLoc(); 11382 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11383 CharSourceRange OpRange = 11384 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11385 11386 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11387 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11388 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11389 << FixItHint::CreateInsertion(End, "]"); 11390 } 11391 } 11392 11393 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11394 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11395 ExprResult &RHS, SourceLocation Loc, 11396 BinaryOperatorKind Opc) { 11397 // Check that left hand side is !something. 11398 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11399 if (!UO || UO->getOpcode() != UO_LNot) return; 11400 11401 // Only check if the right hand side is non-bool arithmetic type. 11402 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11403 11404 // Make sure that the something in !something is not bool. 11405 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11406 if (SubExpr->isKnownToHaveBooleanValue()) return; 11407 11408 // Emit warning. 11409 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11410 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11411 << Loc << IsBitwiseOp; 11412 11413 // First note suggest !(x < y) 11414 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11415 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11416 FirstClose = S.getLocForEndOfToken(FirstClose); 11417 if (FirstClose.isInvalid()) 11418 FirstOpen = SourceLocation(); 11419 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11420 << IsBitwiseOp 11421 << FixItHint::CreateInsertion(FirstOpen, "(") 11422 << FixItHint::CreateInsertion(FirstClose, ")"); 11423 11424 // Second note suggests (!x) < y 11425 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11426 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11427 SecondClose = S.getLocForEndOfToken(SecondClose); 11428 if (SecondClose.isInvalid()) 11429 SecondOpen = SourceLocation(); 11430 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11431 << FixItHint::CreateInsertion(SecondOpen, "(") 11432 << FixItHint::CreateInsertion(SecondClose, ")"); 11433 } 11434 11435 // Returns true if E refers to a non-weak array. 11436 static bool checkForArray(const Expr *E) { 11437 const ValueDecl *D = nullptr; 11438 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11439 D = DR->getDecl(); 11440 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11441 if (Mem->isImplicitAccess()) 11442 D = Mem->getMemberDecl(); 11443 } 11444 if (!D) 11445 return false; 11446 return D->getType()->isArrayType() && !D->isWeak(); 11447 } 11448 11449 /// Diagnose some forms of syntactically-obvious tautological comparison. 11450 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11451 Expr *LHS, Expr *RHS, 11452 BinaryOperatorKind Opc) { 11453 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11454 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11455 11456 QualType LHSType = LHS->getType(); 11457 QualType RHSType = RHS->getType(); 11458 if (LHSType->hasFloatingRepresentation() || 11459 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11460 S.inTemplateInstantiation()) 11461 return; 11462 11463 // Comparisons between two array types are ill-formed for operator<=>, so 11464 // we shouldn't emit any additional warnings about it. 11465 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11466 return; 11467 11468 // For non-floating point types, check for self-comparisons of the form 11469 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11470 // often indicate logic errors in the program. 11471 // 11472 // NOTE: Don't warn about comparison expressions resulting from macro 11473 // expansion. Also don't warn about comparisons which are only self 11474 // comparisons within a template instantiation. The warnings should catch 11475 // obvious cases in the definition of the template anyways. The idea is to 11476 // warn when the typed comparison operator will always evaluate to the same 11477 // result. 11478 11479 // Used for indexing into %select in warn_comparison_always 11480 enum { 11481 AlwaysConstant, 11482 AlwaysTrue, 11483 AlwaysFalse, 11484 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11485 }; 11486 11487 // C++2a [depr.array.comp]: 11488 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11489 // operands of array type are deprecated. 11490 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11491 RHSStripped->getType()->isArrayType()) { 11492 S.Diag(Loc, diag::warn_depr_array_comparison) 11493 << LHS->getSourceRange() << RHS->getSourceRange() 11494 << LHSStripped->getType() << RHSStripped->getType(); 11495 // Carry on to produce the tautological comparison warning, if this 11496 // expression is potentially-evaluated, we can resolve the array to a 11497 // non-weak declaration, and so on. 11498 } 11499 11500 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11501 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11502 unsigned Result; 11503 switch (Opc) { 11504 case BO_EQ: 11505 case BO_LE: 11506 case BO_GE: 11507 Result = AlwaysTrue; 11508 break; 11509 case BO_NE: 11510 case BO_LT: 11511 case BO_GT: 11512 Result = AlwaysFalse; 11513 break; 11514 case BO_Cmp: 11515 Result = AlwaysEqual; 11516 break; 11517 default: 11518 Result = AlwaysConstant; 11519 break; 11520 } 11521 S.DiagRuntimeBehavior(Loc, nullptr, 11522 S.PDiag(diag::warn_comparison_always) 11523 << 0 /*self-comparison*/ 11524 << Result); 11525 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11526 // What is it always going to evaluate to? 11527 unsigned Result; 11528 switch (Opc) { 11529 case BO_EQ: // e.g. array1 == array2 11530 Result = AlwaysFalse; 11531 break; 11532 case BO_NE: // e.g. array1 != array2 11533 Result = AlwaysTrue; 11534 break; 11535 default: // e.g. array1 <= array2 11536 // The best we can say is 'a constant' 11537 Result = AlwaysConstant; 11538 break; 11539 } 11540 S.DiagRuntimeBehavior(Loc, nullptr, 11541 S.PDiag(diag::warn_comparison_always) 11542 << 1 /*array comparison*/ 11543 << Result); 11544 } 11545 } 11546 11547 if (isa<CastExpr>(LHSStripped)) 11548 LHSStripped = LHSStripped->IgnoreParenCasts(); 11549 if (isa<CastExpr>(RHSStripped)) 11550 RHSStripped = RHSStripped->IgnoreParenCasts(); 11551 11552 // Warn about comparisons against a string constant (unless the other 11553 // operand is null); the user probably wants string comparison function. 11554 Expr *LiteralString = nullptr; 11555 Expr *LiteralStringStripped = nullptr; 11556 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11557 !RHSStripped->isNullPointerConstant(S.Context, 11558 Expr::NPC_ValueDependentIsNull)) { 11559 LiteralString = LHS; 11560 LiteralStringStripped = LHSStripped; 11561 } else if ((isa<StringLiteral>(RHSStripped) || 11562 isa<ObjCEncodeExpr>(RHSStripped)) && 11563 !LHSStripped->isNullPointerConstant(S.Context, 11564 Expr::NPC_ValueDependentIsNull)) { 11565 LiteralString = RHS; 11566 LiteralStringStripped = RHSStripped; 11567 } 11568 11569 if (LiteralString) { 11570 S.DiagRuntimeBehavior(Loc, nullptr, 11571 S.PDiag(diag::warn_stringcompare) 11572 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11573 << LiteralString->getSourceRange()); 11574 } 11575 } 11576 11577 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11578 switch (CK) { 11579 default: { 11580 #ifndef NDEBUG 11581 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11582 << "\n"; 11583 #endif 11584 llvm_unreachable("unhandled cast kind"); 11585 } 11586 case CK_UserDefinedConversion: 11587 return ICK_Identity; 11588 case CK_LValueToRValue: 11589 return ICK_Lvalue_To_Rvalue; 11590 case CK_ArrayToPointerDecay: 11591 return ICK_Array_To_Pointer; 11592 case CK_FunctionToPointerDecay: 11593 return ICK_Function_To_Pointer; 11594 case CK_IntegralCast: 11595 return ICK_Integral_Conversion; 11596 case CK_FloatingCast: 11597 return ICK_Floating_Conversion; 11598 case CK_IntegralToFloating: 11599 case CK_FloatingToIntegral: 11600 return ICK_Floating_Integral; 11601 case CK_IntegralComplexCast: 11602 case CK_FloatingComplexCast: 11603 case CK_FloatingComplexToIntegralComplex: 11604 case CK_IntegralComplexToFloatingComplex: 11605 return ICK_Complex_Conversion; 11606 case CK_FloatingComplexToReal: 11607 case CK_FloatingRealToComplex: 11608 case CK_IntegralComplexToReal: 11609 case CK_IntegralRealToComplex: 11610 return ICK_Complex_Real; 11611 } 11612 } 11613 11614 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11615 QualType FromType, 11616 SourceLocation Loc) { 11617 // Check for a narrowing implicit conversion. 11618 StandardConversionSequence SCS; 11619 SCS.setAsIdentityConversion(); 11620 SCS.setToType(0, FromType); 11621 SCS.setToType(1, ToType); 11622 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11623 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11624 11625 APValue PreNarrowingValue; 11626 QualType PreNarrowingType; 11627 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11628 PreNarrowingType, 11629 /*IgnoreFloatToIntegralConversion*/ true)) { 11630 case NK_Dependent_Narrowing: 11631 // Implicit conversion to a narrower type, but the expression is 11632 // value-dependent so we can't tell whether it's actually narrowing. 11633 case NK_Not_Narrowing: 11634 return false; 11635 11636 case NK_Constant_Narrowing: 11637 // Implicit conversion to a narrower type, and the value is not a constant 11638 // expression. 11639 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11640 << /*Constant*/ 1 11641 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11642 return true; 11643 11644 case NK_Variable_Narrowing: 11645 // Implicit conversion to a narrower type, and the value is not a constant 11646 // expression. 11647 case NK_Type_Narrowing: 11648 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11649 << /*Constant*/ 0 << FromType << ToType; 11650 // TODO: It's not a constant expression, but what if the user intended it 11651 // to be? Can we produce notes to help them figure out why it isn't? 11652 return true; 11653 } 11654 llvm_unreachable("unhandled case in switch"); 11655 } 11656 11657 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11658 ExprResult &LHS, 11659 ExprResult &RHS, 11660 SourceLocation Loc) { 11661 QualType LHSType = LHS.get()->getType(); 11662 QualType RHSType = RHS.get()->getType(); 11663 // Dig out the original argument type and expression before implicit casts 11664 // were applied. These are the types/expressions we need to check the 11665 // [expr.spaceship] requirements against. 11666 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11667 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11668 QualType LHSStrippedType = LHSStripped.get()->getType(); 11669 QualType RHSStrippedType = RHSStripped.get()->getType(); 11670 11671 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11672 // other is not, the program is ill-formed. 11673 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11674 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11675 return QualType(); 11676 } 11677 11678 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11679 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11680 RHSStrippedType->isEnumeralType(); 11681 if (NumEnumArgs == 1) { 11682 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11683 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11684 if (OtherTy->hasFloatingRepresentation()) { 11685 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11686 return QualType(); 11687 } 11688 } 11689 if (NumEnumArgs == 2) { 11690 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11691 // type E, the operator yields the result of converting the operands 11692 // to the underlying type of E and applying <=> to the converted operands. 11693 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11694 S.InvalidOperands(Loc, LHS, RHS); 11695 return QualType(); 11696 } 11697 QualType IntType = 11698 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11699 assert(IntType->isArithmeticType()); 11700 11701 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11702 // promote the boolean type, and all other promotable integer types, to 11703 // avoid this. 11704 if (IntType->isPromotableIntegerType()) 11705 IntType = S.Context.getPromotedIntegerType(IntType); 11706 11707 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11708 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11709 LHSType = RHSType = IntType; 11710 } 11711 11712 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11713 // usual arithmetic conversions are applied to the operands. 11714 QualType Type = 11715 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11716 if (LHS.isInvalid() || RHS.isInvalid()) 11717 return QualType(); 11718 if (Type.isNull()) 11719 return S.InvalidOperands(Loc, LHS, RHS); 11720 11721 Optional<ComparisonCategoryType> CCT = 11722 getComparisonCategoryForBuiltinCmp(Type); 11723 if (!CCT) 11724 return S.InvalidOperands(Loc, LHS, RHS); 11725 11726 bool HasNarrowing = checkThreeWayNarrowingConversion( 11727 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11728 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11729 RHS.get()->getBeginLoc()); 11730 if (HasNarrowing) 11731 return QualType(); 11732 11733 assert(!Type.isNull() && "composite type for <=> has not been set"); 11734 11735 return S.CheckComparisonCategoryType( 11736 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11737 } 11738 11739 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11740 ExprResult &RHS, 11741 SourceLocation Loc, 11742 BinaryOperatorKind Opc) { 11743 if (Opc == BO_Cmp) 11744 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11745 11746 // C99 6.5.8p3 / C99 6.5.9p4 11747 QualType Type = 11748 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11749 if (LHS.isInvalid() || RHS.isInvalid()) 11750 return QualType(); 11751 if (Type.isNull()) 11752 return S.InvalidOperands(Loc, LHS, RHS); 11753 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11754 11755 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11756 return S.InvalidOperands(Loc, LHS, RHS); 11757 11758 // Check for comparisons of floating point operands using != and ==. 11759 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11760 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11761 11762 // The result of comparisons is 'bool' in C++, 'int' in C. 11763 return S.Context.getLogicalOperationType(); 11764 } 11765 11766 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11767 if (!NullE.get()->getType()->isAnyPointerType()) 11768 return; 11769 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11770 if (!E.get()->getType()->isAnyPointerType() && 11771 E.get()->isNullPointerConstant(Context, 11772 Expr::NPC_ValueDependentIsNotNull) == 11773 Expr::NPCK_ZeroExpression) { 11774 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11775 if (CL->getValue() == 0) 11776 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11777 << NullValue 11778 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11779 NullValue ? "NULL" : "(void *)0"); 11780 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11781 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11782 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11783 if (T == Context.CharTy) 11784 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11785 << NullValue 11786 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11787 NullValue ? "NULL" : "(void *)0"); 11788 } 11789 } 11790 } 11791 11792 // C99 6.5.8, C++ [expr.rel] 11793 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11794 SourceLocation Loc, 11795 BinaryOperatorKind Opc) { 11796 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11797 bool IsThreeWay = Opc == BO_Cmp; 11798 bool IsOrdered = IsRelational || IsThreeWay; 11799 auto IsAnyPointerType = [](ExprResult E) { 11800 QualType Ty = E.get()->getType(); 11801 return Ty->isPointerType() || Ty->isMemberPointerType(); 11802 }; 11803 11804 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11805 // type, array-to-pointer, ..., conversions are performed on both operands to 11806 // bring them to their composite type. 11807 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11808 // any type-related checks. 11809 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11810 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11811 if (LHS.isInvalid()) 11812 return QualType(); 11813 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11814 if (RHS.isInvalid()) 11815 return QualType(); 11816 } else { 11817 LHS = DefaultLvalueConversion(LHS.get()); 11818 if (LHS.isInvalid()) 11819 return QualType(); 11820 RHS = DefaultLvalueConversion(RHS.get()); 11821 if (RHS.isInvalid()) 11822 return QualType(); 11823 } 11824 11825 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11826 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11827 CheckPtrComparisonWithNullChar(LHS, RHS); 11828 CheckPtrComparisonWithNullChar(RHS, LHS); 11829 } 11830 11831 // Handle vector comparisons separately. 11832 if (LHS.get()->getType()->isVectorType() || 11833 RHS.get()->getType()->isVectorType()) 11834 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11835 11836 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11837 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11838 11839 QualType LHSType = LHS.get()->getType(); 11840 QualType RHSType = RHS.get()->getType(); 11841 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11842 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11843 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11844 11845 const Expr::NullPointerConstantKind LHSNullKind = 11846 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11847 const Expr::NullPointerConstantKind RHSNullKind = 11848 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11849 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11850 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11851 11852 auto computeResultTy = [&]() { 11853 if (Opc != BO_Cmp) 11854 return Context.getLogicalOperationType(); 11855 assert(getLangOpts().CPlusPlus); 11856 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11857 11858 QualType CompositeTy = LHS.get()->getType(); 11859 assert(!CompositeTy->isReferenceType()); 11860 11861 Optional<ComparisonCategoryType> CCT = 11862 getComparisonCategoryForBuiltinCmp(CompositeTy); 11863 if (!CCT) 11864 return InvalidOperands(Loc, LHS, RHS); 11865 11866 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11867 // P0946R0: Comparisons between a null pointer constant and an object 11868 // pointer result in std::strong_equality, which is ill-formed under 11869 // P1959R0. 11870 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11871 << (LHSIsNull ? LHS.get()->getSourceRange() 11872 : RHS.get()->getSourceRange()); 11873 return QualType(); 11874 } 11875 11876 return CheckComparisonCategoryType( 11877 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11878 }; 11879 11880 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11881 bool IsEquality = Opc == BO_EQ; 11882 if (RHSIsNull) 11883 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11884 RHS.get()->getSourceRange()); 11885 else 11886 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11887 LHS.get()->getSourceRange()); 11888 } 11889 11890 if (IsOrdered && LHSType->isFunctionPointerType() && 11891 RHSType->isFunctionPointerType()) { 11892 // Valid unless a relational comparison of function pointers 11893 bool IsError = Opc == BO_Cmp; 11894 auto DiagID = 11895 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11896 : getLangOpts().CPlusPlus 11897 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11898 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11899 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11900 << RHS.get()->getSourceRange(); 11901 if (IsError) 11902 return QualType(); 11903 } 11904 11905 if ((LHSType->isIntegerType() && !LHSIsNull) || 11906 (RHSType->isIntegerType() && !RHSIsNull)) { 11907 // Skip normal pointer conversion checks in this case; we have better 11908 // diagnostics for this below. 11909 } else if (getLangOpts().CPlusPlus) { 11910 // Equality comparison of a function pointer to a void pointer is invalid, 11911 // but we allow it as an extension. 11912 // FIXME: If we really want to allow this, should it be part of composite 11913 // pointer type computation so it works in conditionals too? 11914 if (!IsOrdered && 11915 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11916 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11917 // This is a gcc extension compatibility comparison. 11918 // In a SFINAE context, we treat this as a hard error to maintain 11919 // conformance with the C++ standard. 11920 diagnoseFunctionPointerToVoidComparison( 11921 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11922 11923 if (isSFINAEContext()) 11924 return QualType(); 11925 11926 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11927 return computeResultTy(); 11928 } 11929 11930 // C++ [expr.eq]p2: 11931 // If at least one operand is a pointer [...] bring them to their 11932 // composite pointer type. 11933 // C++ [expr.spaceship]p6 11934 // If at least one of the operands is of pointer type, [...] bring them 11935 // to their composite pointer type. 11936 // C++ [expr.rel]p2: 11937 // If both operands are pointers, [...] bring them to their composite 11938 // pointer type. 11939 // For <=>, the only valid non-pointer types are arrays and functions, and 11940 // we already decayed those, so this is really the same as the relational 11941 // comparison rule. 11942 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11943 (IsOrdered ? 2 : 1) && 11944 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11945 RHSType->isObjCObjectPointerType()))) { 11946 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11947 return QualType(); 11948 return computeResultTy(); 11949 } 11950 } else if (LHSType->isPointerType() && 11951 RHSType->isPointerType()) { // C99 6.5.8p2 11952 // All of the following pointer-related warnings are GCC extensions, except 11953 // when handling null pointer constants. 11954 QualType LCanPointeeTy = 11955 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11956 QualType RCanPointeeTy = 11957 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11958 11959 // C99 6.5.9p2 and C99 6.5.8p2 11960 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11961 RCanPointeeTy.getUnqualifiedType())) { 11962 if (IsRelational) { 11963 // Pointers both need to point to complete or incomplete types 11964 if ((LCanPointeeTy->isIncompleteType() != 11965 RCanPointeeTy->isIncompleteType()) && 11966 !getLangOpts().C11) { 11967 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11968 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11969 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11970 << RCanPointeeTy->isIncompleteType(); 11971 } 11972 } 11973 } else if (!IsRelational && 11974 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11975 // Valid unless comparison between non-null pointer and function pointer 11976 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11977 && !LHSIsNull && !RHSIsNull) 11978 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11979 /*isError*/false); 11980 } else { 11981 // Invalid 11982 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11983 } 11984 if (LCanPointeeTy != RCanPointeeTy) { 11985 // Treat NULL constant as a special case in OpenCL. 11986 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11987 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11988 Diag(Loc, 11989 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11990 << LHSType << RHSType << 0 /* comparison */ 11991 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11992 } 11993 } 11994 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11995 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11996 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11997 : CK_BitCast; 11998 if (LHSIsNull && !RHSIsNull) 11999 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12000 else 12001 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12002 } 12003 return computeResultTy(); 12004 } 12005 12006 if (getLangOpts().CPlusPlus) { 12007 // C++ [expr.eq]p4: 12008 // Two operands of type std::nullptr_t or one operand of type 12009 // std::nullptr_t and the other a null pointer constant compare equal. 12010 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12011 if (LHSType->isNullPtrType()) { 12012 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12013 return computeResultTy(); 12014 } 12015 if (RHSType->isNullPtrType()) { 12016 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12017 return computeResultTy(); 12018 } 12019 } 12020 12021 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12022 // These aren't covered by the composite pointer type rules. 12023 if (!IsOrdered && RHSType->isNullPtrType() && 12024 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12025 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12026 return computeResultTy(); 12027 } 12028 if (!IsOrdered && LHSType->isNullPtrType() && 12029 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12030 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12031 return computeResultTy(); 12032 } 12033 12034 if (IsRelational && 12035 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12036 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12037 // HACK: Relational comparison of nullptr_t against a pointer type is 12038 // invalid per DR583, but we allow it within std::less<> and friends, 12039 // since otherwise common uses of it break. 12040 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12041 // friends to have std::nullptr_t overload candidates. 12042 DeclContext *DC = CurContext; 12043 if (isa<FunctionDecl>(DC)) 12044 DC = DC->getParent(); 12045 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12046 if (CTSD->isInStdNamespace() && 12047 llvm::StringSwitch<bool>(CTSD->getName()) 12048 .Cases("less", "less_equal", "greater", "greater_equal", true) 12049 .Default(false)) { 12050 if (RHSType->isNullPtrType()) 12051 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12052 else 12053 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12054 return computeResultTy(); 12055 } 12056 } 12057 } 12058 12059 // C++ [expr.eq]p2: 12060 // If at least one operand is a pointer to member, [...] bring them to 12061 // their composite pointer type. 12062 if (!IsOrdered && 12063 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12064 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12065 return QualType(); 12066 else 12067 return computeResultTy(); 12068 } 12069 } 12070 12071 // Handle block pointer types. 12072 if (!IsOrdered && LHSType->isBlockPointerType() && 12073 RHSType->isBlockPointerType()) { 12074 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12075 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12076 12077 if (!LHSIsNull && !RHSIsNull && 12078 !Context.typesAreCompatible(lpointee, rpointee)) { 12079 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12080 << LHSType << RHSType << LHS.get()->getSourceRange() 12081 << RHS.get()->getSourceRange(); 12082 } 12083 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12084 return computeResultTy(); 12085 } 12086 12087 // Allow block pointers to be compared with null pointer constants. 12088 if (!IsOrdered 12089 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12090 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12091 if (!LHSIsNull && !RHSIsNull) { 12092 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12093 ->getPointeeType()->isVoidType()) 12094 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12095 ->getPointeeType()->isVoidType()))) 12096 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12097 << LHSType << RHSType << LHS.get()->getSourceRange() 12098 << RHS.get()->getSourceRange(); 12099 } 12100 if (LHSIsNull && !RHSIsNull) 12101 LHS = ImpCastExprToType(LHS.get(), RHSType, 12102 RHSType->isPointerType() ? CK_BitCast 12103 : CK_AnyPointerToBlockPointerCast); 12104 else 12105 RHS = ImpCastExprToType(RHS.get(), LHSType, 12106 LHSType->isPointerType() ? CK_BitCast 12107 : CK_AnyPointerToBlockPointerCast); 12108 return computeResultTy(); 12109 } 12110 12111 if (LHSType->isObjCObjectPointerType() || 12112 RHSType->isObjCObjectPointerType()) { 12113 const PointerType *LPT = LHSType->getAs<PointerType>(); 12114 const PointerType *RPT = RHSType->getAs<PointerType>(); 12115 if (LPT || RPT) { 12116 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12117 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12118 12119 if (!LPtrToVoid && !RPtrToVoid && 12120 !Context.typesAreCompatible(LHSType, RHSType)) { 12121 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12122 /*isError*/false); 12123 } 12124 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12125 // the RHS, but we have test coverage for this behavior. 12126 // FIXME: Consider using convertPointersToCompositeType in C++. 12127 if (LHSIsNull && !RHSIsNull) { 12128 Expr *E = LHS.get(); 12129 if (getLangOpts().ObjCAutoRefCount) 12130 CheckObjCConversion(SourceRange(), RHSType, E, 12131 CCK_ImplicitConversion); 12132 LHS = ImpCastExprToType(E, RHSType, 12133 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12134 } 12135 else { 12136 Expr *E = RHS.get(); 12137 if (getLangOpts().ObjCAutoRefCount) 12138 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12139 /*Diagnose=*/true, 12140 /*DiagnoseCFAudited=*/false, Opc); 12141 RHS = ImpCastExprToType(E, LHSType, 12142 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12143 } 12144 return computeResultTy(); 12145 } 12146 if (LHSType->isObjCObjectPointerType() && 12147 RHSType->isObjCObjectPointerType()) { 12148 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12149 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12150 /*isError*/false); 12151 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12152 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12153 12154 if (LHSIsNull && !RHSIsNull) 12155 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12156 else 12157 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12158 return computeResultTy(); 12159 } 12160 12161 if (!IsOrdered && LHSType->isBlockPointerType() && 12162 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12163 LHS = ImpCastExprToType(LHS.get(), RHSType, 12164 CK_BlockPointerToObjCPointerCast); 12165 return computeResultTy(); 12166 } else if (!IsOrdered && 12167 LHSType->isBlockCompatibleObjCPointerType(Context) && 12168 RHSType->isBlockPointerType()) { 12169 RHS = ImpCastExprToType(RHS.get(), LHSType, 12170 CK_BlockPointerToObjCPointerCast); 12171 return computeResultTy(); 12172 } 12173 } 12174 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12175 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12176 unsigned DiagID = 0; 12177 bool isError = false; 12178 if (LangOpts.DebuggerSupport) { 12179 // Under a debugger, allow the comparison of pointers to integers, 12180 // since users tend to want to compare addresses. 12181 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12182 (RHSIsNull && RHSType->isIntegerType())) { 12183 if (IsOrdered) { 12184 isError = getLangOpts().CPlusPlus; 12185 DiagID = 12186 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12187 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12188 } 12189 } else if (getLangOpts().CPlusPlus) { 12190 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12191 isError = true; 12192 } else if (IsOrdered) 12193 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12194 else 12195 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12196 12197 if (DiagID) { 12198 Diag(Loc, DiagID) 12199 << LHSType << RHSType << LHS.get()->getSourceRange() 12200 << RHS.get()->getSourceRange(); 12201 if (isError) 12202 return QualType(); 12203 } 12204 12205 if (LHSType->isIntegerType()) 12206 LHS = ImpCastExprToType(LHS.get(), RHSType, 12207 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12208 else 12209 RHS = ImpCastExprToType(RHS.get(), LHSType, 12210 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12211 return computeResultTy(); 12212 } 12213 12214 // Handle block pointers. 12215 if (!IsOrdered && RHSIsNull 12216 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12217 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12218 return computeResultTy(); 12219 } 12220 if (!IsOrdered && LHSIsNull 12221 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12222 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12223 return computeResultTy(); 12224 } 12225 12226 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12227 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12228 return computeResultTy(); 12229 } 12230 12231 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12232 return computeResultTy(); 12233 } 12234 12235 if (LHSIsNull && RHSType->isQueueT()) { 12236 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12237 return computeResultTy(); 12238 } 12239 12240 if (LHSType->isQueueT() && RHSIsNull) { 12241 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12242 return computeResultTy(); 12243 } 12244 } 12245 12246 return InvalidOperands(Loc, LHS, RHS); 12247 } 12248 12249 // Return a signed ext_vector_type that is of identical size and number of 12250 // elements. For floating point vectors, return an integer type of identical 12251 // size and number of elements. In the non ext_vector_type case, search from 12252 // the largest type to the smallest type to avoid cases where long long == long, 12253 // where long gets picked over long long. 12254 QualType Sema::GetSignedVectorType(QualType V) { 12255 const VectorType *VTy = V->castAs<VectorType>(); 12256 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12257 12258 if (isa<ExtVectorType>(VTy)) { 12259 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12260 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12261 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12262 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12263 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12264 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12265 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12266 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12267 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12268 "Unhandled vector element size in vector compare"); 12269 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12270 } 12271 12272 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12273 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12274 VectorType::GenericVector); 12275 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12276 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12277 VectorType::GenericVector); 12278 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12279 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12280 VectorType::GenericVector); 12281 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12282 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12283 VectorType::GenericVector); 12284 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12285 "Unhandled vector element size in vector compare"); 12286 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12287 VectorType::GenericVector); 12288 } 12289 12290 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12291 /// operates on extended vector types. Instead of producing an IntTy result, 12292 /// like a scalar comparison, a vector comparison produces a vector of integer 12293 /// types. 12294 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12295 SourceLocation Loc, 12296 BinaryOperatorKind Opc) { 12297 if (Opc == BO_Cmp) { 12298 Diag(Loc, diag::err_three_way_vector_comparison); 12299 return QualType(); 12300 } 12301 12302 // Check to make sure we're operating on vectors of the same type and width, 12303 // Allowing one side to be a scalar of element type. 12304 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12305 /*AllowBothBool*/true, 12306 /*AllowBoolConversions*/getLangOpts().ZVector); 12307 if (vType.isNull()) 12308 return vType; 12309 12310 QualType LHSType = LHS.get()->getType(); 12311 12312 // Determine the return type of a vector compare. By default clang will return 12313 // a scalar for all vector compares except vector bool and vector pixel. 12314 // With the gcc compiler we will always return a vector type and with the xl 12315 // compiler we will always return a scalar type. This switch allows choosing 12316 // which behavior is prefered. 12317 if (getLangOpts().AltiVec) { 12318 switch (getLangOpts().getAltivecSrcCompat()) { 12319 case LangOptions::AltivecSrcCompatKind::Mixed: 12320 // If AltiVec, the comparison results in a numeric type, i.e. 12321 // bool for C++, int for C 12322 if (vType->castAs<VectorType>()->getVectorKind() == 12323 VectorType::AltiVecVector) 12324 return Context.getLogicalOperationType(); 12325 else 12326 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12327 break; 12328 case LangOptions::AltivecSrcCompatKind::GCC: 12329 // For GCC we always return the vector type. 12330 break; 12331 case LangOptions::AltivecSrcCompatKind::XL: 12332 return Context.getLogicalOperationType(); 12333 break; 12334 } 12335 } 12336 12337 // For non-floating point types, check for self-comparisons of the form 12338 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12339 // often indicate logic errors in the program. 12340 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12341 12342 // Check for comparisons of floating point operands using != and ==. 12343 if (BinaryOperator::isEqualityOp(Opc) && 12344 LHSType->hasFloatingRepresentation()) { 12345 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12346 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12347 } 12348 12349 // Return a signed type for the vector. 12350 return GetSignedVectorType(vType); 12351 } 12352 12353 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12354 const ExprResult &XorRHS, 12355 const SourceLocation Loc) { 12356 // Do not diagnose macros. 12357 if (Loc.isMacroID()) 12358 return; 12359 12360 // Do not diagnose if both LHS and RHS are macros. 12361 if (XorLHS.get()->getExprLoc().isMacroID() && 12362 XorRHS.get()->getExprLoc().isMacroID()) 12363 return; 12364 12365 bool Negative = false; 12366 bool ExplicitPlus = false; 12367 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12368 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12369 12370 if (!LHSInt) 12371 return; 12372 if (!RHSInt) { 12373 // Check negative literals. 12374 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12375 UnaryOperatorKind Opc = UO->getOpcode(); 12376 if (Opc != UO_Minus && Opc != UO_Plus) 12377 return; 12378 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12379 if (!RHSInt) 12380 return; 12381 Negative = (Opc == UO_Minus); 12382 ExplicitPlus = !Negative; 12383 } else { 12384 return; 12385 } 12386 } 12387 12388 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12389 llvm::APInt RightSideValue = RHSInt->getValue(); 12390 if (LeftSideValue != 2 && LeftSideValue != 10) 12391 return; 12392 12393 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12394 return; 12395 12396 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12397 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12398 llvm::StringRef ExprStr = 12399 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12400 12401 CharSourceRange XorRange = 12402 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12403 llvm::StringRef XorStr = 12404 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12405 // Do not diagnose if xor keyword/macro is used. 12406 if (XorStr == "xor") 12407 return; 12408 12409 std::string LHSStr = std::string(Lexer::getSourceText( 12410 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12411 S.getSourceManager(), S.getLangOpts())); 12412 std::string RHSStr = std::string(Lexer::getSourceText( 12413 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12414 S.getSourceManager(), S.getLangOpts())); 12415 12416 if (Negative) { 12417 RightSideValue = -RightSideValue; 12418 RHSStr = "-" + RHSStr; 12419 } else if (ExplicitPlus) { 12420 RHSStr = "+" + RHSStr; 12421 } 12422 12423 StringRef LHSStrRef = LHSStr; 12424 StringRef RHSStrRef = RHSStr; 12425 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12426 // literals. 12427 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12428 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12429 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12430 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12431 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12432 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12433 LHSStrRef.find('\'') != StringRef::npos || 12434 RHSStrRef.find('\'') != StringRef::npos) 12435 return; 12436 12437 bool SuggestXor = 12438 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12439 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12440 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12441 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12442 std::string SuggestedExpr = "1 << " + RHSStr; 12443 bool Overflow = false; 12444 llvm::APInt One = (LeftSideValue - 1); 12445 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12446 if (Overflow) { 12447 if (RightSideIntValue < 64) 12448 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12449 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12450 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12451 else if (RightSideIntValue == 64) 12452 S.Diag(Loc, diag::warn_xor_used_as_pow) 12453 << ExprStr << toString(XorValue, 10, true); 12454 else 12455 return; 12456 } else { 12457 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12458 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12459 << toString(PowValue, 10, true) 12460 << FixItHint::CreateReplacement( 12461 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12462 } 12463 12464 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12465 << ("0x2 ^ " + RHSStr) << SuggestXor; 12466 } else if (LeftSideValue == 10) { 12467 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12468 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12469 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12470 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12471 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12472 << ("0xA ^ " + RHSStr) << SuggestXor; 12473 } 12474 } 12475 12476 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12477 SourceLocation Loc) { 12478 // Ensure that either both operands are of the same vector type, or 12479 // one operand is of a vector type and the other is of its element type. 12480 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12481 /*AllowBothBool*/true, 12482 /*AllowBoolConversions*/false); 12483 if (vType.isNull()) 12484 return InvalidOperands(Loc, LHS, RHS); 12485 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12486 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12487 return InvalidOperands(Loc, LHS, RHS); 12488 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12489 // usage of the logical operators && and || with vectors in C. This 12490 // check could be notionally dropped. 12491 if (!getLangOpts().CPlusPlus && 12492 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12493 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12494 12495 return GetSignedVectorType(LHS.get()->getType()); 12496 } 12497 12498 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12499 SourceLocation Loc, 12500 bool IsCompAssign) { 12501 if (!IsCompAssign) { 12502 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12503 if (LHS.isInvalid()) 12504 return QualType(); 12505 } 12506 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12507 if (RHS.isInvalid()) 12508 return QualType(); 12509 12510 // For conversion purposes, we ignore any qualifiers. 12511 // For example, "const float" and "float" are equivalent. 12512 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12513 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12514 12515 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12516 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12517 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12518 12519 if (Context.hasSameType(LHSType, RHSType)) 12520 return LHSType; 12521 12522 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12523 // case we have to return InvalidOperands. 12524 ExprResult OriginalLHS = LHS; 12525 ExprResult OriginalRHS = RHS; 12526 if (LHSMatType && !RHSMatType) { 12527 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12528 if (!RHS.isInvalid()) 12529 return LHSType; 12530 12531 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12532 } 12533 12534 if (!LHSMatType && RHSMatType) { 12535 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12536 if (!LHS.isInvalid()) 12537 return RHSType; 12538 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12539 } 12540 12541 return InvalidOperands(Loc, LHS, RHS); 12542 } 12543 12544 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12545 SourceLocation Loc, 12546 bool IsCompAssign) { 12547 if (!IsCompAssign) { 12548 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12549 if (LHS.isInvalid()) 12550 return QualType(); 12551 } 12552 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12553 if (RHS.isInvalid()) 12554 return QualType(); 12555 12556 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12557 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12558 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12559 12560 if (LHSMatType && RHSMatType) { 12561 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12562 return InvalidOperands(Loc, LHS, RHS); 12563 12564 if (!Context.hasSameType(LHSMatType->getElementType(), 12565 RHSMatType->getElementType())) 12566 return InvalidOperands(Loc, LHS, RHS); 12567 12568 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12569 LHSMatType->getNumRows(), 12570 RHSMatType->getNumColumns()); 12571 } 12572 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12573 } 12574 12575 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12576 SourceLocation Loc, 12577 BinaryOperatorKind Opc) { 12578 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12579 12580 bool IsCompAssign = 12581 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12582 12583 if (LHS.get()->getType()->isVectorType() || 12584 RHS.get()->getType()->isVectorType()) { 12585 if (LHS.get()->getType()->hasIntegerRepresentation() && 12586 RHS.get()->getType()->hasIntegerRepresentation()) 12587 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12588 /*AllowBothBool*/true, 12589 /*AllowBoolConversions*/getLangOpts().ZVector); 12590 return InvalidOperands(Loc, LHS, RHS); 12591 } 12592 12593 if (Opc == BO_And) 12594 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12595 12596 if (LHS.get()->getType()->hasFloatingRepresentation() || 12597 RHS.get()->getType()->hasFloatingRepresentation()) 12598 return InvalidOperands(Loc, LHS, RHS); 12599 12600 ExprResult LHSResult = LHS, RHSResult = RHS; 12601 QualType compType = UsualArithmeticConversions( 12602 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12603 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12604 return QualType(); 12605 LHS = LHSResult.get(); 12606 RHS = RHSResult.get(); 12607 12608 if (Opc == BO_Xor) 12609 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12610 12611 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12612 return compType; 12613 return InvalidOperands(Loc, LHS, RHS); 12614 } 12615 12616 // C99 6.5.[13,14] 12617 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12618 SourceLocation Loc, 12619 BinaryOperatorKind Opc) { 12620 // Check vector operands differently. 12621 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12622 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12623 12624 bool EnumConstantInBoolContext = false; 12625 for (const ExprResult &HS : {LHS, RHS}) { 12626 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12627 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12628 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12629 EnumConstantInBoolContext = true; 12630 } 12631 } 12632 12633 if (EnumConstantInBoolContext) 12634 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12635 12636 // Diagnose cases where the user write a logical and/or but probably meant a 12637 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12638 // is a constant. 12639 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12640 !LHS.get()->getType()->isBooleanType() && 12641 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12642 // Don't warn in macros or template instantiations. 12643 !Loc.isMacroID() && !inTemplateInstantiation()) { 12644 // If the RHS can be constant folded, and if it constant folds to something 12645 // that isn't 0 or 1 (which indicate a potential logical operation that 12646 // happened to fold to true/false) then warn. 12647 // Parens on the RHS are ignored. 12648 Expr::EvalResult EVResult; 12649 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12650 llvm::APSInt Result = EVResult.Val.getInt(); 12651 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12652 !RHS.get()->getExprLoc().isMacroID()) || 12653 (Result != 0 && Result != 1)) { 12654 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12655 << RHS.get()->getSourceRange() 12656 << (Opc == BO_LAnd ? "&&" : "||"); 12657 // Suggest replacing the logical operator with the bitwise version 12658 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12659 << (Opc == BO_LAnd ? "&" : "|") 12660 << FixItHint::CreateReplacement(SourceRange( 12661 Loc, getLocForEndOfToken(Loc)), 12662 Opc == BO_LAnd ? "&" : "|"); 12663 if (Opc == BO_LAnd) 12664 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12665 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12666 << FixItHint::CreateRemoval( 12667 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12668 RHS.get()->getEndLoc())); 12669 } 12670 } 12671 } 12672 12673 if (!Context.getLangOpts().CPlusPlus) { 12674 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12675 // not operate on the built-in scalar and vector float types. 12676 if (Context.getLangOpts().OpenCL && 12677 Context.getLangOpts().OpenCLVersion < 120) { 12678 if (LHS.get()->getType()->isFloatingType() || 12679 RHS.get()->getType()->isFloatingType()) 12680 return InvalidOperands(Loc, LHS, RHS); 12681 } 12682 12683 LHS = UsualUnaryConversions(LHS.get()); 12684 if (LHS.isInvalid()) 12685 return QualType(); 12686 12687 RHS = UsualUnaryConversions(RHS.get()); 12688 if (RHS.isInvalid()) 12689 return QualType(); 12690 12691 if (!LHS.get()->getType()->isScalarType() || 12692 !RHS.get()->getType()->isScalarType()) 12693 return InvalidOperands(Loc, LHS, RHS); 12694 12695 return Context.IntTy; 12696 } 12697 12698 // The following is safe because we only use this method for 12699 // non-overloadable operands. 12700 12701 // C++ [expr.log.and]p1 12702 // C++ [expr.log.or]p1 12703 // The operands are both contextually converted to type bool. 12704 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12705 if (LHSRes.isInvalid()) 12706 return InvalidOperands(Loc, LHS, RHS); 12707 LHS = LHSRes; 12708 12709 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12710 if (RHSRes.isInvalid()) 12711 return InvalidOperands(Loc, LHS, RHS); 12712 RHS = RHSRes; 12713 12714 // C++ [expr.log.and]p2 12715 // C++ [expr.log.or]p2 12716 // The result is a bool. 12717 return Context.BoolTy; 12718 } 12719 12720 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12721 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12722 if (!ME) return false; 12723 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12724 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12725 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12726 if (!Base) return false; 12727 return Base->getMethodDecl() != nullptr; 12728 } 12729 12730 /// Is the given expression (which must be 'const') a reference to a 12731 /// variable which was originally non-const, but which has become 12732 /// 'const' due to being captured within a block? 12733 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12734 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12735 assert(E->isLValue() && E->getType().isConstQualified()); 12736 E = E->IgnoreParens(); 12737 12738 // Must be a reference to a declaration from an enclosing scope. 12739 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12740 if (!DRE) return NCCK_None; 12741 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12742 12743 // The declaration must be a variable which is not declared 'const'. 12744 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12745 if (!var) return NCCK_None; 12746 if (var->getType().isConstQualified()) return NCCK_None; 12747 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12748 12749 // Decide whether the first capture was for a block or a lambda. 12750 DeclContext *DC = S.CurContext, *Prev = nullptr; 12751 // Decide whether the first capture was for a block or a lambda. 12752 while (DC) { 12753 // For init-capture, it is possible that the variable belongs to the 12754 // template pattern of the current context. 12755 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12756 if (var->isInitCapture() && 12757 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12758 break; 12759 if (DC == var->getDeclContext()) 12760 break; 12761 Prev = DC; 12762 DC = DC->getParent(); 12763 } 12764 // Unless we have an init-capture, we've gone one step too far. 12765 if (!var->isInitCapture()) 12766 DC = Prev; 12767 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12768 } 12769 12770 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12771 Ty = Ty.getNonReferenceType(); 12772 if (IsDereference && Ty->isPointerType()) 12773 Ty = Ty->getPointeeType(); 12774 return !Ty.isConstQualified(); 12775 } 12776 12777 // Update err_typecheck_assign_const and note_typecheck_assign_const 12778 // when this enum is changed. 12779 enum { 12780 ConstFunction, 12781 ConstVariable, 12782 ConstMember, 12783 ConstMethod, 12784 NestedConstMember, 12785 ConstUnknown, // Keep as last element 12786 }; 12787 12788 /// Emit the "read-only variable not assignable" error and print notes to give 12789 /// more information about why the variable is not assignable, such as pointing 12790 /// to the declaration of a const variable, showing that a method is const, or 12791 /// that the function is returning a const reference. 12792 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12793 SourceLocation Loc) { 12794 SourceRange ExprRange = E->getSourceRange(); 12795 12796 // Only emit one error on the first const found. All other consts will emit 12797 // a note to the error. 12798 bool DiagnosticEmitted = false; 12799 12800 // Track if the current expression is the result of a dereference, and if the 12801 // next checked expression is the result of a dereference. 12802 bool IsDereference = false; 12803 bool NextIsDereference = false; 12804 12805 // Loop to process MemberExpr chains. 12806 while (true) { 12807 IsDereference = NextIsDereference; 12808 12809 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12810 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12811 NextIsDereference = ME->isArrow(); 12812 const ValueDecl *VD = ME->getMemberDecl(); 12813 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12814 // Mutable fields can be modified even if the class is const. 12815 if (Field->isMutable()) { 12816 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12817 break; 12818 } 12819 12820 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12821 if (!DiagnosticEmitted) { 12822 S.Diag(Loc, diag::err_typecheck_assign_const) 12823 << ExprRange << ConstMember << false /*static*/ << Field 12824 << Field->getType(); 12825 DiagnosticEmitted = true; 12826 } 12827 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12828 << ConstMember << false /*static*/ << Field << Field->getType() 12829 << Field->getSourceRange(); 12830 } 12831 E = ME->getBase(); 12832 continue; 12833 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12834 if (VDecl->getType().isConstQualified()) { 12835 if (!DiagnosticEmitted) { 12836 S.Diag(Loc, diag::err_typecheck_assign_const) 12837 << ExprRange << ConstMember << true /*static*/ << VDecl 12838 << VDecl->getType(); 12839 DiagnosticEmitted = true; 12840 } 12841 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12842 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12843 << VDecl->getSourceRange(); 12844 } 12845 // Static fields do not inherit constness from parents. 12846 break; 12847 } 12848 break; // End MemberExpr 12849 } else if (const ArraySubscriptExpr *ASE = 12850 dyn_cast<ArraySubscriptExpr>(E)) { 12851 E = ASE->getBase()->IgnoreParenImpCasts(); 12852 continue; 12853 } else if (const ExtVectorElementExpr *EVE = 12854 dyn_cast<ExtVectorElementExpr>(E)) { 12855 E = EVE->getBase()->IgnoreParenImpCasts(); 12856 continue; 12857 } 12858 break; 12859 } 12860 12861 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12862 // Function calls 12863 const FunctionDecl *FD = CE->getDirectCallee(); 12864 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12865 if (!DiagnosticEmitted) { 12866 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12867 << ConstFunction << FD; 12868 DiagnosticEmitted = true; 12869 } 12870 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12871 diag::note_typecheck_assign_const) 12872 << ConstFunction << FD << FD->getReturnType() 12873 << FD->getReturnTypeSourceRange(); 12874 } 12875 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12876 // Point to variable declaration. 12877 if (const ValueDecl *VD = DRE->getDecl()) { 12878 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12879 if (!DiagnosticEmitted) { 12880 S.Diag(Loc, diag::err_typecheck_assign_const) 12881 << ExprRange << ConstVariable << VD << VD->getType(); 12882 DiagnosticEmitted = true; 12883 } 12884 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12885 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12886 } 12887 } 12888 } else if (isa<CXXThisExpr>(E)) { 12889 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12890 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12891 if (MD->isConst()) { 12892 if (!DiagnosticEmitted) { 12893 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12894 << ConstMethod << MD; 12895 DiagnosticEmitted = true; 12896 } 12897 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12898 << ConstMethod << MD << MD->getSourceRange(); 12899 } 12900 } 12901 } 12902 } 12903 12904 if (DiagnosticEmitted) 12905 return; 12906 12907 // Can't determine a more specific message, so display the generic error. 12908 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12909 } 12910 12911 enum OriginalExprKind { 12912 OEK_Variable, 12913 OEK_Member, 12914 OEK_LValue 12915 }; 12916 12917 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12918 const RecordType *Ty, 12919 SourceLocation Loc, SourceRange Range, 12920 OriginalExprKind OEK, 12921 bool &DiagnosticEmitted) { 12922 std::vector<const RecordType *> RecordTypeList; 12923 RecordTypeList.push_back(Ty); 12924 unsigned NextToCheckIndex = 0; 12925 // We walk the record hierarchy breadth-first to ensure that we print 12926 // diagnostics in field nesting order. 12927 while (RecordTypeList.size() > NextToCheckIndex) { 12928 bool IsNested = NextToCheckIndex > 0; 12929 for (const FieldDecl *Field : 12930 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12931 // First, check every field for constness. 12932 QualType FieldTy = Field->getType(); 12933 if (FieldTy.isConstQualified()) { 12934 if (!DiagnosticEmitted) { 12935 S.Diag(Loc, diag::err_typecheck_assign_const) 12936 << Range << NestedConstMember << OEK << VD 12937 << IsNested << Field; 12938 DiagnosticEmitted = true; 12939 } 12940 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12941 << NestedConstMember << IsNested << Field 12942 << FieldTy << Field->getSourceRange(); 12943 } 12944 12945 // Then we append it to the list to check next in order. 12946 FieldTy = FieldTy.getCanonicalType(); 12947 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12948 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12949 RecordTypeList.push_back(FieldRecTy); 12950 } 12951 } 12952 ++NextToCheckIndex; 12953 } 12954 } 12955 12956 /// Emit an error for the case where a record we are trying to assign to has a 12957 /// const-qualified field somewhere in its hierarchy. 12958 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12959 SourceLocation Loc) { 12960 QualType Ty = E->getType(); 12961 assert(Ty->isRecordType() && "lvalue was not record?"); 12962 SourceRange Range = E->getSourceRange(); 12963 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12964 bool DiagEmitted = false; 12965 12966 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12967 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12968 Range, OEK_Member, DiagEmitted); 12969 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12970 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12971 Range, OEK_Variable, DiagEmitted); 12972 else 12973 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12974 Range, OEK_LValue, DiagEmitted); 12975 if (!DiagEmitted) 12976 DiagnoseConstAssignment(S, E, Loc); 12977 } 12978 12979 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12980 /// emit an error and return true. If so, return false. 12981 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12982 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12983 12984 S.CheckShadowingDeclModification(E, Loc); 12985 12986 SourceLocation OrigLoc = Loc; 12987 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12988 &Loc); 12989 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12990 IsLV = Expr::MLV_InvalidMessageExpression; 12991 if (IsLV == Expr::MLV_Valid) 12992 return false; 12993 12994 unsigned DiagID = 0; 12995 bool NeedType = false; 12996 switch (IsLV) { // C99 6.5.16p2 12997 case Expr::MLV_ConstQualified: 12998 // Use a specialized diagnostic when we're assigning to an object 12999 // from an enclosing function or block. 13000 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13001 if (NCCK == NCCK_Block) 13002 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13003 else 13004 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13005 break; 13006 } 13007 13008 // In ARC, use some specialized diagnostics for occasions where we 13009 // infer 'const'. These are always pseudo-strong variables. 13010 if (S.getLangOpts().ObjCAutoRefCount) { 13011 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13012 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13013 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13014 13015 // Use the normal diagnostic if it's pseudo-__strong but the 13016 // user actually wrote 'const'. 13017 if (var->isARCPseudoStrong() && 13018 (!var->getTypeSourceInfo() || 13019 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13020 // There are three pseudo-strong cases: 13021 // - self 13022 ObjCMethodDecl *method = S.getCurMethodDecl(); 13023 if (method && var == method->getSelfDecl()) { 13024 DiagID = method->isClassMethod() 13025 ? diag::err_typecheck_arc_assign_self_class_method 13026 : diag::err_typecheck_arc_assign_self; 13027 13028 // - Objective-C externally_retained attribute. 13029 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13030 isa<ParmVarDecl>(var)) { 13031 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13032 13033 // - fast enumeration variables 13034 } else { 13035 DiagID = diag::err_typecheck_arr_assign_enumeration; 13036 } 13037 13038 SourceRange Assign; 13039 if (Loc != OrigLoc) 13040 Assign = SourceRange(OrigLoc, OrigLoc); 13041 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13042 // We need to preserve the AST regardless, so migration tool 13043 // can do its job. 13044 return false; 13045 } 13046 } 13047 } 13048 13049 // If none of the special cases above are triggered, then this is a 13050 // simple const assignment. 13051 if (DiagID == 0) { 13052 DiagnoseConstAssignment(S, E, Loc); 13053 return true; 13054 } 13055 13056 break; 13057 case Expr::MLV_ConstAddrSpace: 13058 DiagnoseConstAssignment(S, E, Loc); 13059 return true; 13060 case Expr::MLV_ConstQualifiedField: 13061 DiagnoseRecursiveConstFields(S, E, Loc); 13062 return true; 13063 case Expr::MLV_ArrayType: 13064 case Expr::MLV_ArrayTemporary: 13065 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13066 NeedType = true; 13067 break; 13068 case Expr::MLV_NotObjectType: 13069 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13070 NeedType = true; 13071 break; 13072 case Expr::MLV_LValueCast: 13073 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13074 break; 13075 case Expr::MLV_Valid: 13076 llvm_unreachable("did not take early return for MLV_Valid"); 13077 case Expr::MLV_InvalidExpression: 13078 case Expr::MLV_MemberFunction: 13079 case Expr::MLV_ClassTemporary: 13080 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13081 break; 13082 case Expr::MLV_IncompleteType: 13083 case Expr::MLV_IncompleteVoidType: 13084 return S.RequireCompleteType(Loc, E->getType(), 13085 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13086 case Expr::MLV_DuplicateVectorComponents: 13087 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13088 break; 13089 case Expr::MLV_NoSetterProperty: 13090 llvm_unreachable("readonly properties should be processed differently"); 13091 case Expr::MLV_InvalidMessageExpression: 13092 DiagID = diag::err_readonly_message_assignment; 13093 break; 13094 case Expr::MLV_SubObjCPropertySetting: 13095 DiagID = diag::err_no_subobject_property_setting; 13096 break; 13097 } 13098 13099 SourceRange Assign; 13100 if (Loc != OrigLoc) 13101 Assign = SourceRange(OrigLoc, OrigLoc); 13102 if (NeedType) 13103 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13104 else 13105 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13106 return true; 13107 } 13108 13109 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13110 SourceLocation Loc, 13111 Sema &Sema) { 13112 if (Sema.inTemplateInstantiation()) 13113 return; 13114 if (Sema.isUnevaluatedContext()) 13115 return; 13116 if (Loc.isInvalid() || Loc.isMacroID()) 13117 return; 13118 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13119 return; 13120 13121 // C / C++ fields 13122 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13123 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13124 if (ML && MR) { 13125 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13126 return; 13127 const ValueDecl *LHSDecl = 13128 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13129 const ValueDecl *RHSDecl = 13130 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13131 if (LHSDecl != RHSDecl) 13132 return; 13133 if (LHSDecl->getType().isVolatileQualified()) 13134 return; 13135 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13136 if (RefTy->getPointeeType().isVolatileQualified()) 13137 return; 13138 13139 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13140 } 13141 13142 // Objective-C instance variables 13143 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13144 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13145 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13146 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13147 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13148 if (RL && RR && RL->getDecl() == RR->getDecl()) 13149 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13150 } 13151 } 13152 13153 // C99 6.5.16.1 13154 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13155 SourceLocation Loc, 13156 QualType CompoundType) { 13157 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13158 13159 // Verify that LHS is a modifiable lvalue, and emit error if not. 13160 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13161 return QualType(); 13162 13163 QualType LHSType = LHSExpr->getType(); 13164 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13165 CompoundType; 13166 // OpenCL v1.2 s6.1.1.1 p2: 13167 // The half data type can only be used to declare a pointer to a buffer that 13168 // contains half values 13169 if (getLangOpts().OpenCL && 13170 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13171 LHSType->isHalfType()) { 13172 Diag(Loc, diag::err_opencl_half_load_store) << 1 13173 << LHSType.getUnqualifiedType(); 13174 return QualType(); 13175 } 13176 13177 AssignConvertType ConvTy; 13178 if (CompoundType.isNull()) { 13179 Expr *RHSCheck = RHS.get(); 13180 13181 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13182 13183 QualType LHSTy(LHSType); 13184 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13185 if (RHS.isInvalid()) 13186 return QualType(); 13187 // Special case of NSObject attributes on c-style pointer types. 13188 if (ConvTy == IncompatiblePointer && 13189 ((Context.isObjCNSObjectType(LHSType) && 13190 RHSType->isObjCObjectPointerType()) || 13191 (Context.isObjCNSObjectType(RHSType) && 13192 LHSType->isObjCObjectPointerType()))) 13193 ConvTy = Compatible; 13194 13195 if (ConvTy == Compatible && 13196 LHSType->isObjCObjectType()) 13197 Diag(Loc, diag::err_objc_object_assignment) 13198 << LHSType; 13199 13200 // If the RHS is a unary plus or minus, check to see if they = and + are 13201 // right next to each other. If so, the user may have typo'd "x =+ 4" 13202 // instead of "x += 4". 13203 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13204 RHSCheck = ICE->getSubExpr(); 13205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13206 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13207 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13208 // Only if the two operators are exactly adjacent. 13209 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13210 // And there is a space or other character before the subexpr of the 13211 // unary +/-. We don't want to warn on "x=-1". 13212 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13213 UO->getSubExpr()->getBeginLoc().isFileID()) { 13214 Diag(Loc, diag::warn_not_compound_assign) 13215 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13216 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13217 } 13218 } 13219 13220 if (ConvTy == Compatible) { 13221 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13222 // Warn about retain cycles where a block captures the LHS, but 13223 // not if the LHS is a simple variable into which the block is 13224 // being stored...unless that variable can be captured by reference! 13225 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13226 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13227 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13228 checkRetainCycles(LHSExpr, RHS.get()); 13229 } 13230 13231 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13232 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13233 // It is safe to assign a weak reference into a strong variable. 13234 // Although this code can still have problems: 13235 // id x = self.weakProp; 13236 // id y = self.weakProp; 13237 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13238 // paths through the function. This should be revisited if 13239 // -Wrepeated-use-of-weak is made flow-sensitive. 13240 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13241 // variable, which will be valid for the current autorelease scope. 13242 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13243 RHS.get()->getBeginLoc())) 13244 getCurFunction()->markSafeWeakUse(RHS.get()); 13245 13246 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13247 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13248 } 13249 } 13250 } else { 13251 // Compound assignment "x += y" 13252 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13253 } 13254 13255 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13256 RHS.get(), AA_Assigning)) 13257 return QualType(); 13258 13259 CheckForNullPointerDereference(*this, LHSExpr); 13260 13261 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13262 if (CompoundType.isNull()) { 13263 // C++2a [expr.ass]p5: 13264 // A simple-assignment whose left operand is of a volatile-qualified 13265 // type is deprecated unless the assignment is either a discarded-value 13266 // expression or an unevaluated operand 13267 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13268 } else { 13269 // C++2a [expr.ass]p6: 13270 // [Compound-assignment] expressions are deprecated if E1 has 13271 // volatile-qualified type 13272 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13273 } 13274 } 13275 13276 // C99 6.5.16p3: The type of an assignment expression is the type of the 13277 // left operand unless the left operand has qualified type, in which case 13278 // it is the unqualified version of the type of the left operand. 13279 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13280 // is converted to the type of the assignment expression (above). 13281 // C++ 5.17p1: the type of the assignment expression is that of its left 13282 // operand. 13283 return (getLangOpts().CPlusPlus 13284 ? LHSType : LHSType.getUnqualifiedType()); 13285 } 13286 13287 // Only ignore explicit casts to void. 13288 static bool IgnoreCommaOperand(const Expr *E) { 13289 E = E->IgnoreParens(); 13290 13291 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13292 if (CE->getCastKind() == CK_ToVoid) { 13293 return true; 13294 } 13295 13296 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13297 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13298 CE->getSubExpr()->getType()->isDependentType()) { 13299 return true; 13300 } 13301 } 13302 13303 return false; 13304 } 13305 13306 // Look for instances where it is likely the comma operator is confused with 13307 // another operator. There is an explicit list of acceptable expressions for 13308 // the left hand side of the comma operator, otherwise emit a warning. 13309 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13310 // No warnings in macros 13311 if (Loc.isMacroID()) 13312 return; 13313 13314 // Don't warn in template instantiations. 13315 if (inTemplateInstantiation()) 13316 return; 13317 13318 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13319 // instead, skip more than needed, then call back into here with the 13320 // CommaVisitor in SemaStmt.cpp. 13321 // The listed locations are the initialization and increment portions 13322 // of a for loop. The additional checks are on the condition of 13323 // if statements, do/while loops, and for loops. 13324 // Differences in scope flags for C89 mode requires the extra logic. 13325 const unsigned ForIncrementFlags = 13326 getLangOpts().C99 || getLangOpts().CPlusPlus 13327 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13328 : Scope::ContinueScope | Scope::BreakScope; 13329 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13330 const unsigned ScopeFlags = getCurScope()->getFlags(); 13331 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13332 (ScopeFlags & ForInitFlags) == ForInitFlags) 13333 return; 13334 13335 // If there are multiple comma operators used together, get the RHS of the 13336 // of the comma operator as the LHS. 13337 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13338 if (BO->getOpcode() != BO_Comma) 13339 break; 13340 LHS = BO->getRHS(); 13341 } 13342 13343 // Only allow some expressions on LHS to not warn. 13344 if (IgnoreCommaOperand(LHS)) 13345 return; 13346 13347 Diag(Loc, diag::warn_comma_operator); 13348 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13349 << LHS->getSourceRange() 13350 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13351 LangOpts.CPlusPlus ? "static_cast<void>(" 13352 : "(void)(") 13353 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13354 ")"); 13355 } 13356 13357 // C99 6.5.17 13358 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13359 SourceLocation Loc) { 13360 LHS = S.CheckPlaceholderExpr(LHS.get()); 13361 RHS = S.CheckPlaceholderExpr(RHS.get()); 13362 if (LHS.isInvalid() || RHS.isInvalid()) 13363 return QualType(); 13364 13365 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13366 // operands, but not unary promotions. 13367 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13368 13369 // So we treat the LHS as a ignored value, and in C++ we allow the 13370 // containing site to determine what should be done with the RHS. 13371 LHS = S.IgnoredValueConversions(LHS.get()); 13372 if (LHS.isInvalid()) 13373 return QualType(); 13374 13375 S.DiagnoseUnusedExprResult(LHS.get()); 13376 13377 if (!S.getLangOpts().CPlusPlus) { 13378 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13379 if (RHS.isInvalid()) 13380 return QualType(); 13381 if (!RHS.get()->getType()->isVoidType()) 13382 S.RequireCompleteType(Loc, RHS.get()->getType(), 13383 diag::err_incomplete_type); 13384 } 13385 13386 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13387 S.DiagnoseCommaOperator(LHS.get(), Loc); 13388 13389 return RHS.get()->getType(); 13390 } 13391 13392 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13393 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13394 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13395 ExprValueKind &VK, 13396 ExprObjectKind &OK, 13397 SourceLocation OpLoc, 13398 bool IsInc, bool IsPrefix) { 13399 if (Op->isTypeDependent()) 13400 return S.Context.DependentTy; 13401 13402 QualType ResType = Op->getType(); 13403 // Atomic types can be used for increment / decrement where the non-atomic 13404 // versions can, so ignore the _Atomic() specifier for the purpose of 13405 // checking. 13406 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13407 ResType = ResAtomicType->getValueType(); 13408 13409 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13410 13411 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13412 // Decrement of bool is not allowed. 13413 if (!IsInc) { 13414 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13415 return QualType(); 13416 } 13417 // Increment of bool sets it to true, but is deprecated. 13418 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13419 : diag::warn_increment_bool) 13420 << Op->getSourceRange(); 13421 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13422 // Error on enum increments and decrements in C++ mode 13423 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13424 return QualType(); 13425 } else if (ResType->isRealType()) { 13426 // OK! 13427 } else if (ResType->isPointerType()) { 13428 // C99 6.5.2.4p2, 6.5.6p2 13429 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13430 return QualType(); 13431 } else if (ResType->isObjCObjectPointerType()) { 13432 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13433 // Otherwise, we just need a complete type. 13434 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13435 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13436 return QualType(); 13437 } else if (ResType->isAnyComplexType()) { 13438 // C99 does not support ++/-- on complex types, we allow as an extension. 13439 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13440 << ResType << Op->getSourceRange(); 13441 } else if (ResType->isPlaceholderType()) { 13442 ExprResult PR = S.CheckPlaceholderExpr(Op); 13443 if (PR.isInvalid()) return QualType(); 13444 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13445 IsInc, IsPrefix); 13446 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13447 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13448 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13449 (ResType->castAs<VectorType>()->getVectorKind() != 13450 VectorType::AltiVecBool)) { 13451 // The z vector extensions allow ++ and -- for non-bool vectors. 13452 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13453 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13454 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13455 } else { 13456 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13457 << ResType << int(IsInc) << Op->getSourceRange(); 13458 return QualType(); 13459 } 13460 // At this point, we know we have a real, complex or pointer type. 13461 // Now make sure the operand is a modifiable lvalue. 13462 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13463 return QualType(); 13464 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13465 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13466 // An operand with volatile-qualified type is deprecated 13467 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13468 << IsInc << ResType; 13469 } 13470 // In C++, a prefix increment is the same type as the operand. Otherwise 13471 // (in C or with postfix), the increment is the unqualified type of the 13472 // operand. 13473 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13474 VK = VK_LValue; 13475 OK = Op->getObjectKind(); 13476 return ResType; 13477 } else { 13478 VK = VK_PRValue; 13479 return ResType.getUnqualifiedType(); 13480 } 13481 } 13482 13483 13484 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13485 /// This routine allows us to typecheck complex/recursive expressions 13486 /// where the declaration is needed for type checking. We only need to 13487 /// handle cases when the expression references a function designator 13488 /// or is an lvalue. Here are some examples: 13489 /// - &(x) => x 13490 /// - &*****f => f for f a function designator. 13491 /// - &s.xx => s 13492 /// - &s.zz[1].yy -> s, if zz is an array 13493 /// - *(x + 1) -> x, if x is an array 13494 /// - &"123"[2] -> 0 13495 /// - & __real__ x -> x 13496 /// 13497 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13498 /// members. 13499 static ValueDecl *getPrimaryDecl(Expr *E) { 13500 switch (E->getStmtClass()) { 13501 case Stmt::DeclRefExprClass: 13502 return cast<DeclRefExpr>(E)->getDecl(); 13503 case Stmt::MemberExprClass: 13504 // If this is an arrow operator, the address is an offset from 13505 // the base's value, so the object the base refers to is 13506 // irrelevant. 13507 if (cast<MemberExpr>(E)->isArrow()) 13508 return nullptr; 13509 // Otherwise, the expression refers to a part of the base 13510 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13511 case Stmt::ArraySubscriptExprClass: { 13512 // FIXME: This code shouldn't be necessary! We should catch the implicit 13513 // promotion of register arrays earlier. 13514 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13515 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13516 if (ICE->getSubExpr()->getType()->isArrayType()) 13517 return getPrimaryDecl(ICE->getSubExpr()); 13518 } 13519 return nullptr; 13520 } 13521 case Stmt::UnaryOperatorClass: { 13522 UnaryOperator *UO = cast<UnaryOperator>(E); 13523 13524 switch(UO->getOpcode()) { 13525 case UO_Real: 13526 case UO_Imag: 13527 case UO_Extension: 13528 return getPrimaryDecl(UO->getSubExpr()); 13529 default: 13530 return nullptr; 13531 } 13532 } 13533 case Stmt::ParenExprClass: 13534 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13535 case Stmt::ImplicitCastExprClass: 13536 // If the result of an implicit cast is an l-value, we care about 13537 // the sub-expression; otherwise, the result here doesn't matter. 13538 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13539 case Stmt::CXXUuidofExprClass: 13540 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13541 default: 13542 return nullptr; 13543 } 13544 } 13545 13546 namespace { 13547 enum { 13548 AO_Bit_Field = 0, 13549 AO_Vector_Element = 1, 13550 AO_Property_Expansion = 2, 13551 AO_Register_Variable = 3, 13552 AO_Matrix_Element = 4, 13553 AO_No_Error = 5 13554 }; 13555 } 13556 /// Diagnose invalid operand for address of operations. 13557 /// 13558 /// \param Type The type of operand which cannot have its address taken. 13559 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13560 Expr *E, unsigned Type) { 13561 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13562 } 13563 13564 /// CheckAddressOfOperand - The operand of & must be either a function 13565 /// designator or an lvalue designating an object. If it is an lvalue, the 13566 /// object cannot be declared with storage class register or be a bit field. 13567 /// Note: The usual conversions are *not* applied to the operand of the & 13568 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13569 /// In C++, the operand might be an overloaded function name, in which case 13570 /// we allow the '&' but retain the overloaded-function type. 13571 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13572 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13573 if (PTy->getKind() == BuiltinType::Overload) { 13574 Expr *E = OrigOp.get()->IgnoreParens(); 13575 if (!isa<OverloadExpr>(E)) { 13576 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13577 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13578 << OrigOp.get()->getSourceRange(); 13579 return QualType(); 13580 } 13581 13582 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13583 if (isa<UnresolvedMemberExpr>(Ovl)) 13584 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13585 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13586 << OrigOp.get()->getSourceRange(); 13587 return QualType(); 13588 } 13589 13590 return Context.OverloadTy; 13591 } 13592 13593 if (PTy->getKind() == BuiltinType::UnknownAny) 13594 return Context.UnknownAnyTy; 13595 13596 if (PTy->getKind() == BuiltinType::BoundMember) { 13597 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13598 << OrigOp.get()->getSourceRange(); 13599 return QualType(); 13600 } 13601 13602 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13603 if (OrigOp.isInvalid()) return QualType(); 13604 } 13605 13606 if (OrigOp.get()->isTypeDependent()) 13607 return Context.DependentTy; 13608 13609 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13610 13611 // Make sure to ignore parentheses in subsequent checks 13612 Expr *op = OrigOp.get()->IgnoreParens(); 13613 13614 // In OpenCL captures for blocks called as lambda functions 13615 // are located in the private address space. Blocks used in 13616 // enqueue_kernel can be located in a different address space 13617 // depending on a vendor implementation. Thus preventing 13618 // taking an address of the capture to avoid invalid AS casts. 13619 if (LangOpts.OpenCL) { 13620 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13621 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13622 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13623 return QualType(); 13624 } 13625 } 13626 13627 if (getLangOpts().C99) { 13628 // Implement C99-only parts of addressof rules. 13629 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13630 if (uOp->getOpcode() == UO_Deref) 13631 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13632 // (assuming the deref expression is valid). 13633 return uOp->getSubExpr()->getType(); 13634 } 13635 // Technically, there should be a check for array subscript 13636 // expressions here, but the result of one is always an lvalue anyway. 13637 } 13638 ValueDecl *dcl = getPrimaryDecl(op); 13639 13640 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13641 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13642 op->getBeginLoc())) 13643 return QualType(); 13644 13645 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13646 unsigned AddressOfError = AO_No_Error; 13647 13648 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13649 bool sfinae = (bool)isSFINAEContext(); 13650 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13651 : diag::ext_typecheck_addrof_temporary) 13652 << op->getType() << op->getSourceRange(); 13653 if (sfinae) 13654 return QualType(); 13655 // Materialize the temporary as an lvalue so that we can take its address. 13656 OrigOp = op = 13657 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13658 } else if (isa<ObjCSelectorExpr>(op)) { 13659 return Context.getPointerType(op->getType()); 13660 } else if (lval == Expr::LV_MemberFunction) { 13661 // If it's an instance method, make a member pointer. 13662 // The expression must have exactly the form &A::foo. 13663 13664 // If the underlying expression isn't a decl ref, give up. 13665 if (!isa<DeclRefExpr>(op)) { 13666 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13667 << OrigOp.get()->getSourceRange(); 13668 return QualType(); 13669 } 13670 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13671 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13672 13673 // The id-expression was parenthesized. 13674 if (OrigOp.get() != DRE) { 13675 Diag(OpLoc, diag::err_parens_pointer_member_function) 13676 << OrigOp.get()->getSourceRange(); 13677 13678 // The method was named without a qualifier. 13679 } else if (!DRE->getQualifier()) { 13680 if (MD->getParent()->getName().empty()) 13681 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13682 << op->getSourceRange(); 13683 else { 13684 SmallString<32> Str; 13685 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13686 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13687 << op->getSourceRange() 13688 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13689 } 13690 } 13691 13692 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13693 if (isa<CXXDestructorDecl>(MD)) 13694 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13695 13696 QualType MPTy = Context.getMemberPointerType( 13697 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13698 // Under the MS ABI, lock down the inheritance model now. 13699 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13700 (void)isCompleteType(OpLoc, MPTy); 13701 return MPTy; 13702 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13703 // C99 6.5.3.2p1 13704 // The operand must be either an l-value or a function designator 13705 if (!op->getType()->isFunctionType()) { 13706 // Use a special diagnostic for loads from property references. 13707 if (isa<PseudoObjectExpr>(op)) { 13708 AddressOfError = AO_Property_Expansion; 13709 } else { 13710 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13711 << op->getType() << op->getSourceRange(); 13712 return QualType(); 13713 } 13714 } 13715 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13716 // The operand cannot be a bit-field 13717 AddressOfError = AO_Bit_Field; 13718 } else if (op->getObjectKind() == OK_VectorComponent) { 13719 // The operand cannot be an element of a vector 13720 AddressOfError = AO_Vector_Element; 13721 } else if (op->getObjectKind() == OK_MatrixComponent) { 13722 // The operand cannot be an element of a matrix. 13723 AddressOfError = AO_Matrix_Element; 13724 } else if (dcl) { // C99 6.5.3.2p1 13725 // We have an lvalue with a decl. Make sure the decl is not declared 13726 // with the register storage-class specifier. 13727 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13728 // in C++ it is not error to take address of a register 13729 // variable (c++03 7.1.1P3) 13730 if (vd->getStorageClass() == SC_Register && 13731 !getLangOpts().CPlusPlus) { 13732 AddressOfError = AO_Register_Variable; 13733 } 13734 } else if (isa<MSPropertyDecl>(dcl)) { 13735 AddressOfError = AO_Property_Expansion; 13736 } else if (isa<FunctionTemplateDecl>(dcl)) { 13737 return Context.OverloadTy; 13738 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13739 // Okay: we can take the address of a field. 13740 // Could be a pointer to member, though, if there is an explicit 13741 // scope qualifier for the class. 13742 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13743 DeclContext *Ctx = dcl->getDeclContext(); 13744 if (Ctx && Ctx->isRecord()) { 13745 if (dcl->getType()->isReferenceType()) { 13746 Diag(OpLoc, 13747 diag::err_cannot_form_pointer_to_member_of_reference_type) 13748 << dcl->getDeclName() << dcl->getType(); 13749 return QualType(); 13750 } 13751 13752 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13753 Ctx = Ctx->getParent(); 13754 13755 QualType MPTy = Context.getMemberPointerType( 13756 op->getType(), 13757 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13758 // Under the MS ABI, lock down the inheritance model now. 13759 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13760 (void)isCompleteType(OpLoc, MPTy); 13761 return MPTy; 13762 } 13763 } 13764 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13765 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13766 llvm_unreachable("Unknown/unexpected decl type"); 13767 } 13768 13769 if (AddressOfError != AO_No_Error) { 13770 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13771 return QualType(); 13772 } 13773 13774 if (lval == Expr::LV_IncompleteVoidType) { 13775 // Taking the address of a void variable is technically illegal, but we 13776 // allow it in cases which are otherwise valid. 13777 // Example: "extern void x; void* y = &x;". 13778 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13779 } 13780 13781 // If the operand has type "type", the result has type "pointer to type". 13782 if (op->getType()->isObjCObjectType()) 13783 return Context.getObjCObjectPointerType(op->getType()); 13784 13785 CheckAddressOfPackedMember(op); 13786 13787 return Context.getPointerType(op->getType()); 13788 } 13789 13790 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13791 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13792 if (!DRE) 13793 return; 13794 const Decl *D = DRE->getDecl(); 13795 if (!D) 13796 return; 13797 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13798 if (!Param) 13799 return; 13800 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13801 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13802 return; 13803 if (FunctionScopeInfo *FD = S.getCurFunction()) 13804 if (!FD->ModifiedNonNullParams.count(Param)) 13805 FD->ModifiedNonNullParams.insert(Param); 13806 } 13807 13808 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13809 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13810 SourceLocation OpLoc) { 13811 if (Op->isTypeDependent()) 13812 return S.Context.DependentTy; 13813 13814 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13815 if (ConvResult.isInvalid()) 13816 return QualType(); 13817 Op = ConvResult.get(); 13818 QualType OpTy = Op->getType(); 13819 QualType Result; 13820 13821 if (isa<CXXReinterpretCastExpr>(Op)) { 13822 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13823 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13824 Op->getSourceRange()); 13825 } 13826 13827 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13828 { 13829 Result = PT->getPointeeType(); 13830 } 13831 else if (const ObjCObjectPointerType *OPT = 13832 OpTy->getAs<ObjCObjectPointerType>()) 13833 Result = OPT->getPointeeType(); 13834 else { 13835 ExprResult PR = S.CheckPlaceholderExpr(Op); 13836 if (PR.isInvalid()) return QualType(); 13837 if (PR.get() != Op) 13838 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13839 } 13840 13841 if (Result.isNull()) { 13842 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13843 << OpTy << Op->getSourceRange(); 13844 return QualType(); 13845 } 13846 13847 // Note that per both C89 and C99, indirection is always legal, even if Result 13848 // is an incomplete type or void. It would be possible to warn about 13849 // dereferencing a void pointer, but it's completely well-defined, and such a 13850 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13851 // for pointers to 'void' but is fine for any other pointer type: 13852 // 13853 // C++ [expr.unary.op]p1: 13854 // [...] the expression to which [the unary * operator] is applied shall 13855 // be a pointer to an object type, or a pointer to a function type 13856 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13857 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13858 << OpTy << Op->getSourceRange(); 13859 13860 // Dereferences are usually l-values... 13861 VK = VK_LValue; 13862 13863 // ...except that certain expressions are never l-values in C. 13864 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13865 VK = VK_PRValue; 13866 13867 return Result; 13868 } 13869 13870 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13871 BinaryOperatorKind Opc; 13872 switch (Kind) { 13873 default: llvm_unreachable("Unknown binop!"); 13874 case tok::periodstar: Opc = BO_PtrMemD; break; 13875 case tok::arrowstar: Opc = BO_PtrMemI; break; 13876 case tok::star: Opc = BO_Mul; break; 13877 case tok::slash: Opc = BO_Div; break; 13878 case tok::percent: Opc = BO_Rem; break; 13879 case tok::plus: Opc = BO_Add; break; 13880 case tok::minus: Opc = BO_Sub; break; 13881 case tok::lessless: Opc = BO_Shl; break; 13882 case tok::greatergreater: Opc = BO_Shr; break; 13883 case tok::lessequal: Opc = BO_LE; break; 13884 case tok::less: Opc = BO_LT; break; 13885 case tok::greaterequal: Opc = BO_GE; break; 13886 case tok::greater: Opc = BO_GT; break; 13887 case tok::exclaimequal: Opc = BO_NE; break; 13888 case tok::equalequal: Opc = BO_EQ; break; 13889 case tok::spaceship: Opc = BO_Cmp; break; 13890 case tok::amp: Opc = BO_And; break; 13891 case tok::caret: Opc = BO_Xor; break; 13892 case tok::pipe: Opc = BO_Or; break; 13893 case tok::ampamp: Opc = BO_LAnd; break; 13894 case tok::pipepipe: Opc = BO_LOr; break; 13895 case tok::equal: Opc = BO_Assign; break; 13896 case tok::starequal: Opc = BO_MulAssign; break; 13897 case tok::slashequal: Opc = BO_DivAssign; break; 13898 case tok::percentequal: Opc = BO_RemAssign; break; 13899 case tok::plusequal: Opc = BO_AddAssign; break; 13900 case tok::minusequal: Opc = BO_SubAssign; break; 13901 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13902 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13903 case tok::ampequal: Opc = BO_AndAssign; break; 13904 case tok::caretequal: Opc = BO_XorAssign; break; 13905 case tok::pipeequal: Opc = BO_OrAssign; break; 13906 case tok::comma: Opc = BO_Comma; break; 13907 } 13908 return Opc; 13909 } 13910 13911 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13912 tok::TokenKind Kind) { 13913 UnaryOperatorKind Opc; 13914 switch (Kind) { 13915 default: llvm_unreachable("Unknown unary op!"); 13916 case tok::plusplus: Opc = UO_PreInc; break; 13917 case tok::minusminus: Opc = UO_PreDec; break; 13918 case tok::amp: Opc = UO_AddrOf; break; 13919 case tok::star: Opc = UO_Deref; break; 13920 case tok::plus: Opc = UO_Plus; break; 13921 case tok::minus: Opc = UO_Minus; break; 13922 case tok::tilde: Opc = UO_Not; break; 13923 case tok::exclaim: Opc = UO_LNot; break; 13924 case tok::kw___real: Opc = UO_Real; break; 13925 case tok::kw___imag: Opc = UO_Imag; break; 13926 case tok::kw___extension__: Opc = UO_Extension; break; 13927 } 13928 return Opc; 13929 } 13930 13931 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13932 /// This warning suppressed in the event of macro expansions. 13933 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13934 SourceLocation OpLoc, bool IsBuiltin) { 13935 if (S.inTemplateInstantiation()) 13936 return; 13937 if (S.isUnevaluatedContext()) 13938 return; 13939 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13940 return; 13941 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13942 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13943 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13944 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13945 if (!LHSDeclRef || !RHSDeclRef || 13946 LHSDeclRef->getLocation().isMacroID() || 13947 RHSDeclRef->getLocation().isMacroID()) 13948 return; 13949 const ValueDecl *LHSDecl = 13950 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13951 const ValueDecl *RHSDecl = 13952 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13953 if (LHSDecl != RHSDecl) 13954 return; 13955 if (LHSDecl->getType().isVolatileQualified()) 13956 return; 13957 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13958 if (RefTy->getPointeeType().isVolatileQualified()) 13959 return; 13960 13961 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13962 : diag::warn_self_assignment_overloaded) 13963 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13964 << RHSExpr->getSourceRange(); 13965 } 13966 13967 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13968 /// is usually indicative of introspection within the Objective-C pointer. 13969 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13970 SourceLocation OpLoc) { 13971 if (!S.getLangOpts().ObjC) 13972 return; 13973 13974 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13975 const Expr *LHS = L.get(); 13976 const Expr *RHS = R.get(); 13977 13978 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13979 ObjCPointerExpr = LHS; 13980 OtherExpr = RHS; 13981 } 13982 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13983 ObjCPointerExpr = RHS; 13984 OtherExpr = LHS; 13985 } 13986 13987 // This warning is deliberately made very specific to reduce false 13988 // positives with logic that uses '&' for hashing. This logic mainly 13989 // looks for code trying to introspect into tagged pointers, which 13990 // code should generally never do. 13991 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13992 unsigned Diag = diag::warn_objc_pointer_masking; 13993 // Determine if we are introspecting the result of performSelectorXXX. 13994 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13995 // Special case messages to -performSelector and friends, which 13996 // can return non-pointer values boxed in a pointer value. 13997 // Some clients may wish to silence warnings in this subcase. 13998 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13999 Selector S = ME->getSelector(); 14000 StringRef SelArg0 = S.getNameForSlot(0); 14001 if (SelArg0.startswith("performSelector")) 14002 Diag = diag::warn_objc_pointer_masking_performSelector; 14003 } 14004 14005 S.Diag(OpLoc, Diag) 14006 << ObjCPointerExpr->getSourceRange(); 14007 } 14008 } 14009 14010 static NamedDecl *getDeclFromExpr(Expr *E) { 14011 if (!E) 14012 return nullptr; 14013 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14014 return DRE->getDecl(); 14015 if (auto *ME = dyn_cast<MemberExpr>(E)) 14016 return ME->getMemberDecl(); 14017 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14018 return IRE->getDecl(); 14019 return nullptr; 14020 } 14021 14022 // This helper function promotes a binary operator's operands (which are of a 14023 // half vector type) to a vector of floats and then truncates the result to 14024 // a vector of either half or short. 14025 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14026 BinaryOperatorKind Opc, QualType ResultTy, 14027 ExprValueKind VK, ExprObjectKind OK, 14028 bool IsCompAssign, SourceLocation OpLoc, 14029 FPOptionsOverride FPFeatures) { 14030 auto &Context = S.getASTContext(); 14031 assert((isVector(ResultTy, Context.HalfTy) || 14032 isVector(ResultTy, Context.ShortTy)) && 14033 "Result must be a vector of half or short"); 14034 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14035 isVector(RHS.get()->getType(), Context.HalfTy) && 14036 "both operands expected to be a half vector"); 14037 14038 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14039 QualType BinOpResTy = RHS.get()->getType(); 14040 14041 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14042 // change BinOpResTy to a vector of ints. 14043 if (isVector(ResultTy, Context.ShortTy)) 14044 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14045 14046 if (IsCompAssign) 14047 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14048 ResultTy, VK, OK, OpLoc, FPFeatures, 14049 BinOpResTy, BinOpResTy); 14050 14051 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14052 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14053 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14054 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14055 } 14056 14057 static std::pair<ExprResult, ExprResult> 14058 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14059 Expr *RHSExpr) { 14060 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14061 if (!S.Context.isDependenceAllowed()) { 14062 // C cannot handle TypoExpr nodes on either side of a binop because it 14063 // doesn't handle dependent types properly, so make sure any TypoExprs have 14064 // been dealt with before checking the operands. 14065 LHS = S.CorrectDelayedTyposInExpr(LHS); 14066 RHS = S.CorrectDelayedTyposInExpr( 14067 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14068 [Opc, LHS](Expr *E) { 14069 if (Opc != BO_Assign) 14070 return ExprResult(E); 14071 // Avoid correcting the RHS to the same Expr as the LHS. 14072 Decl *D = getDeclFromExpr(E); 14073 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14074 }); 14075 } 14076 return std::make_pair(LHS, RHS); 14077 } 14078 14079 /// Returns true if conversion between vectors of halfs and vectors of floats 14080 /// is needed. 14081 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14082 Expr *E0, Expr *E1 = nullptr) { 14083 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14084 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14085 return false; 14086 14087 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14088 QualType Ty = E->IgnoreImplicit()->getType(); 14089 14090 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14091 // to vectors of floats. Although the element type of the vectors is __fp16, 14092 // the vectors shouldn't be treated as storage-only types. See the 14093 // discussion here: https://reviews.llvm.org/rG825235c140e7 14094 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14095 if (VT->getVectorKind() == VectorType::NeonVector) 14096 return false; 14097 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14098 } 14099 return false; 14100 }; 14101 14102 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14103 } 14104 14105 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14106 /// operator @p Opc at location @c TokLoc. This routine only supports 14107 /// built-in operations; ActOnBinOp handles overloaded operators. 14108 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14109 BinaryOperatorKind Opc, 14110 Expr *LHSExpr, Expr *RHSExpr) { 14111 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14112 // The syntax only allows initializer lists on the RHS of assignment, 14113 // so we don't need to worry about accepting invalid code for 14114 // non-assignment operators. 14115 // C++11 5.17p9: 14116 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14117 // of x = {} is x = T(). 14118 InitializationKind Kind = InitializationKind::CreateDirectList( 14119 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14120 InitializedEntity Entity = 14121 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14122 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14123 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14124 if (Init.isInvalid()) 14125 return Init; 14126 RHSExpr = Init.get(); 14127 } 14128 14129 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14130 QualType ResultTy; // Result type of the binary operator. 14131 // The following two variables are used for compound assignment operators 14132 QualType CompLHSTy; // Type of LHS after promotions for computation 14133 QualType CompResultTy; // Type of computation result 14134 ExprValueKind VK = VK_PRValue; 14135 ExprObjectKind OK = OK_Ordinary; 14136 bool ConvertHalfVec = false; 14137 14138 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14139 if (!LHS.isUsable() || !RHS.isUsable()) 14140 return ExprError(); 14141 14142 if (getLangOpts().OpenCL) { 14143 QualType LHSTy = LHSExpr->getType(); 14144 QualType RHSTy = RHSExpr->getType(); 14145 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14146 // the ATOMIC_VAR_INIT macro. 14147 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14148 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14149 if (BO_Assign == Opc) 14150 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14151 else 14152 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14153 return ExprError(); 14154 } 14155 14156 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14157 // only with a builtin functions and therefore should be disallowed here. 14158 if (LHSTy->isImageType() || RHSTy->isImageType() || 14159 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14160 LHSTy->isPipeType() || RHSTy->isPipeType() || 14161 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14162 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14163 return ExprError(); 14164 } 14165 } 14166 14167 switch (Opc) { 14168 case BO_Assign: 14169 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14170 if (getLangOpts().CPlusPlus && 14171 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14172 VK = LHS.get()->getValueKind(); 14173 OK = LHS.get()->getObjectKind(); 14174 } 14175 if (!ResultTy.isNull()) { 14176 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14177 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14178 14179 // Avoid copying a block to the heap if the block is assigned to a local 14180 // auto variable that is declared in the same scope as the block. This 14181 // optimization is unsafe if the local variable is declared in an outer 14182 // scope. For example: 14183 // 14184 // BlockTy b; 14185 // { 14186 // b = ^{...}; 14187 // } 14188 // // It is unsafe to invoke the block here if it wasn't copied to the 14189 // // heap. 14190 // b(); 14191 14192 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14193 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14194 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14195 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14196 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14197 14198 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14199 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14200 NTCUC_Assignment, NTCUK_Copy); 14201 } 14202 RecordModifiableNonNullParam(*this, LHS.get()); 14203 break; 14204 case BO_PtrMemD: 14205 case BO_PtrMemI: 14206 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14207 Opc == BO_PtrMemI); 14208 break; 14209 case BO_Mul: 14210 case BO_Div: 14211 ConvertHalfVec = true; 14212 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14213 Opc == BO_Div); 14214 break; 14215 case BO_Rem: 14216 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14217 break; 14218 case BO_Add: 14219 ConvertHalfVec = true; 14220 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14221 break; 14222 case BO_Sub: 14223 ConvertHalfVec = true; 14224 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14225 break; 14226 case BO_Shl: 14227 case BO_Shr: 14228 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14229 break; 14230 case BO_LE: 14231 case BO_LT: 14232 case BO_GE: 14233 case BO_GT: 14234 ConvertHalfVec = true; 14235 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14236 break; 14237 case BO_EQ: 14238 case BO_NE: 14239 ConvertHalfVec = true; 14240 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14241 break; 14242 case BO_Cmp: 14243 ConvertHalfVec = true; 14244 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14245 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14246 break; 14247 case BO_And: 14248 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14249 LLVM_FALLTHROUGH; 14250 case BO_Xor: 14251 case BO_Or: 14252 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14253 break; 14254 case BO_LAnd: 14255 case BO_LOr: 14256 ConvertHalfVec = true; 14257 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14258 break; 14259 case BO_MulAssign: 14260 case BO_DivAssign: 14261 ConvertHalfVec = true; 14262 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14263 Opc == BO_DivAssign); 14264 CompLHSTy = CompResultTy; 14265 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14266 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14267 break; 14268 case BO_RemAssign: 14269 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14270 CompLHSTy = CompResultTy; 14271 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14272 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14273 break; 14274 case BO_AddAssign: 14275 ConvertHalfVec = true; 14276 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14277 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14278 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14279 break; 14280 case BO_SubAssign: 14281 ConvertHalfVec = true; 14282 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14283 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14284 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14285 break; 14286 case BO_ShlAssign: 14287 case BO_ShrAssign: 14288 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14289 CompLHSTy = CompResultTy; 14290 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14291 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14292 break; 14293 case BO_AndAssign: 14294 case BO_OrAssign: // fallthrough 14295 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14296 LLVM_FALLTHROUGH; 14297 case BO_XorAssign: 14298 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14299 CompLHSTy = CompResultTy; 14300 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14301 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14302 break; 14303 case BO_Comma: 14304 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14305 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14306 VK = RHS.get()->getValueKind(); 14307 OK = RHS.get()->getObjectKind(); 14308 } 14309 break; 14310 } 14311 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14312 return ExprError(); 14313 14314 // Some of the binary operations require promoting operands of half vector to 14315 // float vectors and truncating the result back to half vector. For now, we do 14316 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14317 // arm64). 14318 assert( 14319 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14320 isVector(LHS.get()->getType(), Context.HalfTy)) && 14321 "both sides are half vectors or neither sides are"); 14322 ConvertHalfVec = 14323 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14324 14325 // Check for array bounds violations for both sides of the BinaryOperator 14326 CheckArrayAccess(LHS.get()); 14327 CheckArrayAccess(RHS.get()); 14328 14329 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14330 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14331 &Context.Idents.get("object_setClass"), 14332 SourceLocation(), LookupOrdinaryName); 14333 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14334 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14335 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14336 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14337 "object_setClass(") 14338 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14339 ",") 14340 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14341 } 14342 else 14343 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14344 } 14345 else if (const ObjCIvarRefExpr *OIRE = 14346 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14347 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14348 14349 // Opc is not a compound assignment if CompResultTy is null. 14350 if (CompResultTy.isNull()) { 14351 if (ConvertHalfVec) 14352 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14353 OpLoc, CurFPFeatureOverrides()); 14354 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14355 VK, OK, OpLoc, CurFPFeatureOverrides()); 14356 } 14357 14358 // Handle compound assignments. 14359 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14360 OK_ObjCProperty) { 14361 VK = VK_LValue; 14362 OK = LHS.get()->getObjectKind(); 14363 } 14364 14365 // The LHS is not converted to the result type for fixed-point compound 14366 // assignment as the common type is computed on demand. Reset the CompLHSTy 14367 // to the LHS type we would have gotten after unary conversions. 14368 if (CompResultTy->isFixedPointType()) 14369 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14370 14371 if (ConvertHalfVec) 14372 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14373 OpLoc, CurFPFeatureOverrides()); 14374 14375 return CompoundAssignOperator::Create( 14376 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14377 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14378 } 14379 14380 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14381 /// operators are mixed in a way that suggests that the programmer forgot that 14382 /// comparison operators have higher precedence. The most typical example of 14383 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14384 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14385 SourceLocation OpLoc, Expr *LHSExpr, 14386 Expr *RHSExpr) { 14387 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14388 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14389 14390 // Check that one of the sides is a comparison operator and the other isn't. 14391 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14392 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14393 if (isLeftComp == isRightComp) 14394 return; 14395 14396 // Bitwise operations are sometimes used as eager logical ops. 14397 // Don't diagnose this. 14398 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14399 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14400 if (isLeftBitwise || isRightBitwise) 14401 return; 14402 14403 SourceRange DiagRange = isLeftComp 14404 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14405 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14406 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14407 SourceRange ParensRange = 14408 isLeftComp 14409 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14410 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14411 14412 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14413 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14414 SuggestParentheses(Self, OpLoc, 14415 Self.PDiag(diag::note_precedence_silence) << OpStr, 14416 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14417 SuggestParentheses(Self, OpLoc, 14418 Self.PDiag(diag::note_precedence_bitwise_first) 14419 << BinaryOperator::getOpcodeStr(Opc), 14420 ParensRange); 14421 } 14422 14423 /// It accepts a '&&' expr that is inside a '||' one. 14424 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14425 /// in parentheses. 14426 static void 14427 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14428 BinaryOperator *Bop) { 14429 assert(Bop->getOpcode() == BO_LAnd); 14430 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14431 << Bop->getSourceRange() << OpLoc; 14432 SuggestParentheses(Self, Bop->getOperatorLoc(), 14433 Self.PDiag(diag::note_precedence_silence) 14434 << Bop->getOpcodeStr(), 14435 Bop->getSourceRange()); 14436 } 14437 14438 /// Returns true if the given expression can be evaluated as a constant 14439 /// 'true'. 14440 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14441 bool Res; 14442 return !E->isValueDependent() && 14443 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14444 } 14445 14446 /// Returns true if the given expression can be evaluated as a constant 14447 /// 'false'. 14448 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14449 bool Res; 14450 return !E->isValueDependent() && 14451 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14452 } 14453 14454 /// Look for '&&' in the left hand of a '||' expr. 14455 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14456 Expr *LHSExpr, Expr *RHSExpr) { 14457 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14458 if (Bop->getOpcode() == BO_LAnd) { 14459 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14460 if (EvaluatesAsFalse(S, RHSExpr)) 14461 return; 14462 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14463 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14464 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14465 } else if (Bop->getOpcode() == BO_LOr) { 14466 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14467 // If it's "a || b && 1 || c" we didn't warn earlier for 14468 // "a || b && 1", but warn now. 14469 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14470 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14471 } 14472 } 14473 } 14474 } 14475 14476 /// Look for '&&' in the right hand of a '||' expr. 14477 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14478 Expr *LHSExpr, Expr *RHSExpr) { 14479 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14480 if (Bop->getOpcode() == BO_LAnd) { 14481 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14482 if (EvaluatesAsFalse(S, LHSExpr)) 14483 return; 14484 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14485 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14486 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14487 } 14488 } 14489 } 14490 14491 /// Look for bitwise op in the left or right hand of a bitwise op with 14492 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14493 /// the '&' expression in parentheses. 14494 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14495 SourceLocation OpLoc, Expr *SubExpr) { 14496 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14497 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14498 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14499 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14500 << Bop->getSourceRange() << OpLoc; 14501 SuggestParentheses(S, Bop->getOperatorLoc(), 14502 S.PDiag(diag::note_precedence_silence) 14503 << Bop->getOpcodeStr(), 14504 Bop->getSourceRange()); 14505 } 14506 } 14507 } 14508 14509 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14510 Expr *SubExpr, StringRef Shift) { 14511 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14512 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14513 StringRef Op = Bop->getOpcodeStr(); 14514 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14515 << Bop->getSourceRange() << OpLoc << Shift << Op; 14516 SuggestParentheses(S, Bop->getOperatorLoc(), 14517 S.PDiag(diag::note_precedence_silence) << Op, 14518 Bop->getSourceRange()); 14519 } 14520 } 14521 } 14522 14523 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14524 Expr *LHSExpr, Expr *RHSExpr) { 14525 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14526 if (!OCE) 14527 return; 14528 14529 FunctionDecl *FD = OCE->getDirectCallee(); 14530 if (!FD || !FD->isOverloadedOperator()) 14531 return; 14532 14533 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14534 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14535 return; 14536 14537 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14538 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14539 << (Kind == OO_LessLess); 14540 SuggestParentheses(S, OCE->getOperatorLoc(), 14541 S.PDiag(diag::note_precedence_silence) 14542 << (Kind == OO_LessLess ? "<<" : ">>"), 14543 OCE->getSourceRange()); 14544 SuggestParentheses( 14545 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14546 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14547 } 14548 14549 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14550 /// precedence. 14551 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14552 SourceLocation OpLoc, Expr *LHSExpr, 14553 Expr *RHSExpr){ 14554 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14555 if (BinaryOperator::isBitwiseOp(Opc)) 14556 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14557 14558 // Diagnose "arg1 & arg2 | arg3" 14559 if ((Opc == BO_Or || Opc == BO_Xor) && 14560 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14561 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14562 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14563 } 14564 14565 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14566 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14567 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14568 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14569 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14570 } 14571 14572 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14573 || Opc == BO_Shr) { 14574 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14575 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14576 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14577 } 14578 14579 // Warn on overloaded shift operators and comparisons, such as: 14580 // cout << 5 == 4; 14581 if (BinaryOperator::isComparisonOp(Opc)) 14582 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14583 } 14584 14585 // Binary Operators. 'Tok' is the token for the operator. 14586 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14587 tok::TokenKind Kind, 14588 Expr *LHSExpr, Expr *RHSExpr) { 14589 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14590 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14591 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14592 14593 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14594 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14595 14596 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14597 } 14598 14599 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14600 UnresolvedSetImpl &Functions) { 14601 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14602 if (OverOp != OO_None && OverOp != OO_Equal) 14603 LookupOverloadedOperatorName(OverOp, S, Functions); 14604 14605 // In C++20 onwards, we may have a second operator to look up. 14606 if (getLangOpts().CPlusPlus20) { 14607 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14608 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14609 } 14610 } 14611 14612 /// Build an overloaded binary operator expression in the given scope. 14613 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14614 BinaryOperatorKind Opc, 14615 Expr *LHS, Expr *RHS) { 14616 switch (Opc) { 14617 case BO_Assign: 14618 case BO_DivAssign: 14619 case BO_RemAssign: 14620 case BO_SubAssign: 14621 case BO_AndAssign: 14622 case BO_OrAssign: 14623 case BO_XorAssign: 14624 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14625 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14626 break; 14627 default: 14628 break; 14629 } 14630 14631 // Find all of the overloaded operators visible from this point. 14632 UnresolvedSet<16> Functions; 14633 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14634 14635 // Build the (potentially-overloaded, potentially-dependent) 14636 // binary operation. 14637 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14638 } 14639 14640 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14641 BinaryOperatorKind Opc, 14642 Expr *LHSExpr, Expr *RHSExpr) { 14643 ExprResult LHS, RHS; 14644 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14645 if (!LHS.isUsable() || !RHS.isUsable()) 14646 return ExprError(); 14647 LHSExpr = LHS.get(); 14648 RHSExpr = RHS.get(); 14649 14650 // We want to end up calling one of checkPseudoObjectAssignment 14651 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14652 // both expressions are overloadable or either is type-dependent), 14653 // or CreateBuiltinBinOp (in any other case). We also want to get 14654 // any placeholder types out of the way. 14655 14656 // Handle pseudo-objects in the LHS. 14657 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14658 // Assignments with a pseudo-object l-value need special analysis. 14659 if (pty->getKind() == BuiltinType::PseudoObject && 14660 BinaryOperator::isAssignmentOp(Opc)) 14661 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14662 14663 // Don't resolve overloads if the other type is overloadable. 14664 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14665 // We can't actually test that if we still have a placeholder, 14666 // though. Fortunately, none of the exceptions we see in that 14667 // code below are valid when the LHS is an overload set. Note 14668 // that an overload set can be dependently-typed, but it never 14669 // instantiates to having an overloadable type. 14670 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14671 if (resolvedRHS.isInvalid()) return ExprError(); 14672 RHSExpr = resolvedRHS.get(); 14673 14674 if (RHSExpr->isTypeDependent() || 14675 RHSExpr->getType()->isOverloadableType()) 14676 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14677 } 14678 14679 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14680 // template, diagnose the missing 'template' keyword instead of diagnosing 14681 // an invalid use of a bound member function. 14682 // 14683 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14684 // to C++1z [over.over]/1.4, but we already checked for that case above. 14685 if (Opc == BO_LT && inTemplateInstantiation() && 14686 (pty->getKind() == BuiltinType::BoundMember || 14687 pty->getKind() == BuiltinType::Overload)) { 14688 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14689 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14690 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14691 return isa<FunctionTemplateDecl>(ND); 14692 })) { 14693 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14694 : OE->getNameLoc(), 14695 diag::err_template_kw_missing) 14696 << OE->getName().getAsString() << ""; 14697 return ExprError(); 14698 } 14699 } 14700 14701 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14702 if (LHS.isInvalid()) return ExprError(); 14703 LHSExpr = LHS.get(); 14704 } 14705 14706 // Handle pseudo-objects in the RHS. 14707 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14708 // An overload in the RHS can potentially be resolved by the type 14709 // being assigned to. 14710 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14711 if (getLangOpts().CPlusPlus && 14712 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14713 LHSExpr->getType()->isOverloadableType())) 14714 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14715 14716 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14717 } 14718 14719 // Don't resolve overloads if the other type is overloadable. 14720 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14721 LHSExpr->getType()->isOverloadableType()) 14722 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14723 14724 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14725 if (!resolvedRHS.isUsable()) return ExprError(); 14726 RHSExpr = resolvedRHS.get(); 14727 } 14728 14729 if (getLangOpts().CPlusPlus) { 14730 // If either expression is type-dependent, always build an 14731 // overloaded op. 14732 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14733 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14734 14735 // Otherwise, build an overloaded op if either expression has an 14736 // overloadable type. 14737 if (LHSExpr->getType()->isOverloadableType() || 14738 RHSExpr->getType()->isOverloadableType()) 14739 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14740 } 14741 14742 if (getLangOpts().RecoveryAST && 14743 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14744 assert(!getLangOpts().CPlusPlus); 14745 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14746 "Should only occur in error-recovery path."); 14747 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14748 // C [6.15.16] p3: 14749 // An assignment expression has the value of the left operand after the 14750 // assignment, but is not an lvalue. 14751 return CompoundAssignOperator::Create( 14752 Context, LHSExpr, RHSExpr, Opc, 14753 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14754 OpLoc, CurFPFeatureOverrides()); 14755 QualType ResultType; 14756 switch (Opc) { 14757 case BO_Assign: 14758 ResultType = LHSExpr->getType().getUnqualifiedType(); 14759 break; 14760 case BO_LT: 14761 case BO_GT: 14762 case BO_LE: 14763 case BO_GE: 14764 case BO_EQ: 14765 case BO_NE: 14766 case BO_LAnd: 14767 case BO_LOr: 14768 // These operators have a fixed result type regardless of operands. 14769 ResultType = Context.IntTy; 14770 break; 14771 case BO_Comma: 14772 ResultType = RHSExpr->getType(); 14773 break; 14774 default: 14775 ResultType = Context.DependentTy; 14776 break; 14777 } 14778 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14779 VK_PRValue, OK_Ordinary, OpLoc, 14780 CurFPFeatureOverrides()); 14781 } 14782 14783 // Build a built-in binary operation. 14784 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14785 } 14786 14787 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14788 if (T.isNull() || T->isDependentType()) 14789 return false; 14790 14791 if (!T->isPromotableIntegerType()) 14792 return true; 14793 14794 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14795 } 14796 14797 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14798 UnaryOperatorKind Opc, 14799 Expr *InputExpr) { 14800 ExprResult Input = InputExpr; 14801 ExprValueKind VK = VK_PRValue; 14802 ExprObjectKind OK = OK_Ordinary; 14803 QualType resultType; 14804 bool CanOverflow = false; 14805 14806 bool ConvertHalfVec = false; 14807 if (getLangOpts().OpenCL) { 14808 QualType Ty = InputExpr->getType(); 14809 // The only legal unary operation for atomics is '&'. 14810 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14811 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14812 // only with a builtin functions and therefore should be disallowed here. 14813 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14814 || Ty->isBlockPointerType())) { 14815 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14816 << InputExpr->getType() 14817 << Input.get()->getSourceRange()); 14818 } 14819 } 14820 14821 switch (Opc) { 14822 case UO_PreInc: 14823 case UO_PreDec: 14824 case UO_PostInc: 14825 case UO_PostDec: 14826 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14827 OpLoc, 14828 Opc == UO_PreInc || 14829 Opc == UO_PostInc, 14830 Opc == UO_PreInc || 14831 Opc == UO_PreDec); 14832 CanOverflow = isOverflowingIntegerType(Context, resultType); 14833 break; 14834 case UO_AddrOf: 14835 resultType = CheckAddressOfOperand(Input, OpLoc); 14836 CheckAddressOfNoDeref(InputExpr); 14837 RecordModifiableNonNullParam(*this, InputExpr); 14838 break; 14839 case UO_Deref: { 14840 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14841 if (Input.isInvalid()) return ExprError(); 14842 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14843 break; 14844 } 14845 case UO_Plus: 14846 case UO_Minus: 14847 CanOverflow = Opc == UO_Minus && 14848 isOverflowingIntegerType(Context, Input.get()->getType()); 14849 Input = UsualUnaryConversions(Input.get()); 14850 if (Input.isInvalid()) return ExprError(); 14851 // Unary plus and minus require promoting an operand of half vector to a 14852 // float vector and truncating the result back to a half vector. For now, we 14853 // do this only when HalfArgsAndReturns is set (that is, when the target is 14854 // arm or arm64). 14855 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14856 14857 // If the operand is a half vector, promote it to a float vector. 14858 if (ConvertHalfVec) 14859 Input = convertVector(Input.get(), Context.FloatTy, *this); 14860 resultType = Input.get()->getType(); 14861 if (resultType->isDependentType()) 14862 break; 14863 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14864 break; 14865 else if (resultType->isVectorType() && 14866 // The z vector extensions don't allow + or - with bool vectors. 14867 (!Context.getLangOpts().ZVector || 14868 resultType->castAs<VectorType>()->getVectorKind() != 14869 VectorType::AltiVecBool)) 14870 break; 14871 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14872 Opc == UO_Plus && 14873 resultType->isPointerType()) 14874 break; 14875 14876 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14877 << resultType << Input.get()->getSourceRange()); 14878 14879 case UO_Not: // bitwise complement 14880 Input = UsualUnaryConversions(Input.get()); 14881 if (Input.isInvalid()) 14882 return ExprError(); 14883 resultType = Input.get()->getType(); 14884 if (resultType->isDependentType()) 14885 break; 14886 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14887 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14888 // C99 does not support '~' for complex conjugation. 14889 Diag(OpLoc, diag::ext_integer_complement_complex) 14890 << resultType << Input.get()->getSourceRange(); 14891 else if (resultType->hasIntegerRepresentation()) 14892 break; 14893 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14894 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14895 // on vector float types. 14896 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14897 if (!T->isIntegerType()) 14898 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14899 << resultType << Input.get()->getSourceRange()); 14900 } else { 14901 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14902 << resultType << Input.get()->getSourceRange()); 14903 } 14904 break; 14905 14906 case UO_LNot: // logical negation 14907 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14908 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14909 if (Input.isInvalid()) return ExprError(); 14910 resultType = Input.get()->getType(); 14911 14912 // Though we still have to promote half FP to float... 14913 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14914 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14915 resultType = Context.FloatTy; 14916 } 14917 14918 if (resultType->isDependentType()) 14919 break; 14920 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14921 // C99 6.5.3.3p1: ok, fallthrough; 14922 if (Context.getLangOpts().CPlusPlus) { 14923 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14924 // operand contextually converted to bool. 14925 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14926 ScalarTypeToBooleanCastKind(resultType)); 14927 } else if (Context.getLangOpts().OpenCL && 14928 Context.getLangOpts().OpenCLVersion < 120) { 14929 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14930 // operate on scalar float types. 14931 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14932 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14933 << resultType << Input.get()->getSourceRange()); 14934 } 14935 } else if (resultType->isExtVectorType()) { 14936 if (Context.getLangOpts().OpenCL && 14937 Context.getLangOpts().OpenCLVersion < 120 && 14938 !Context.getLangOpts().OpenCLCPlusPlus) { 14939 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14940 // operate on vector float types. 14941 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14942 if (!T->isIntegerType()) 14943 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14944 << resultType << Input.get()->getSourceRange()); 14945 } 14946 // Vector logical not returns the signed variant of the operand type. 14947 resultType = GetSignedVectorType(resultType); 14948 break; 14949 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14950 const VectorType *VTy = resultType->castAs<VectorType>(); 14951 if (VTy->getVectorKind() != VectorType::GenericVector) 14952 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14953 << resultType << Input.get()->getSourceRange()); 14954 14955 // Vector logical not returns the signed variant of the operand type. 14956 resultType = GetSignedVectorType(resultType); 14957 break; 14958 } else { 14959 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14960 << resultType << Input.get()->getSourceRange()); 14961 } 14962 14963 // LNot always has type int. C99 6.5.3.3p5. 14964 // In C++, it's bool. C++ 5.3.1p8 14965 resultType = Context.getLogicalOperationType(); 14966 break; 14967 case UO_Real: 14968 case UO_Imag: 14969 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14970 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14971 // complex l-values to ordinary l-values and all other values to r-values. 14972 if (Input.isInvalid()) return ExprError(); 14973 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14974 if (Input.get()->isGLValue() && 14975 Input.get()->getObjectKind() == OK_Ordinary) 14976 VK = Input.get()->getValueKind(); 14977 } else if (!getLangOpts().CPlusPlus) { 14978 // In C, a volatile scalar is read by __imag. In C++, it is not. 14979 Input = DefaultLvalueConversion(Input.get()); 14980 } 14981 break; 14982 case UO_Extension: 14983 resultType = Input.get()->getType(); 14984 VK = Input.get()->getValueKind(); 14985 OK = Input.get()->getObjectKind(); 14986 break; 14987 case UO_Coawait: 14988 // It's unnecessary to represent the pass-through operator co_await in the 14989 // AST; just return the input expression instead. 14990 assert(!Input.get()->getType()->isDependentType() && 14991 "the co_await expression must be non-dependant before " 14992 "building operator co_await"); 14993 return Input; 14994 } 14995 if (resultType.isNull() || Input.isInvalid()) 14996 return ExprError(); 14997 14998 // Check for array bounds violations in the operand of the UnaryOperator, 14999 // except for the '*' and '&' operators that have to be handled specially 15000 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15001 // that are explicitly defined as valid by the standard). 15002 if (Opc != UO_AddrOf && Opc != UO_Deref) 15003 CheckArrayAccess(Input.get()); 15004 15005 auto *UO = 15006 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15007 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15008 15009 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15010 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15011 !isUnevaluatedContext()) 15012 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15013 15014 // Convert the result back to a half vector. 15015 if (ConvertHalfVec) 15016 return convertVector(UO, Context.HalfTy, *this); 15017 return UO; 15018 } 15019 15020 /// Determine whether the given expression is a qualified member 15021 /// access expression, of a form that could be turned into a pointer to member 15022 /// with the address-of operator. 15023 bool Sema::isQualifiedMemberAccess(Expr *E) { 15024 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15025 if (!DRE->getQualifier()) 15026 return false; 15027 15028 ValueDecl *VD = DRE->getDecl(); 15029 if (!VD->isCXXClassMember()) 15030 return false; 15031 15032 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15033 return true; 15034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15035 return Method->isInstance(); 15036 15037 return false; 15038 } 15039 15040 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15041 if (!ULE->getQualifier()) 15042 return false; 15043 15044 for (NamedDecl *D : ULE->decls()) { 15045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15046 if (Method->isInstance()) 15047 return true; 15048 } else { 15049 // Overload set does not contain methods. 15050 break; 15051 } 15052 } 15053 15054 return false; 15055 } 15056 15057 return false; 15058 } 15059 15060 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15061 UnaryOperatorKind Opc, Expr *Input) { 15062 // First things first: handle placeholders so that the 15063 // overloaded-operator check considers the right type. 15064 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15065 // Increment and decrement of pseudo-object references. 15066 if (pty->getKind() == BuiltinType::PseudoObject && 15067 UnaryOperator::isIncrementDecrementOp(Opc)) 15068 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15069 15070 // extension is always a builtin operator. 15071 if (Opc == UO_Extension) 15072 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15073 15074 // & gets special logic for several kinds of placeholder. 15075 // The builtin code knows what to do. 15076 if (Opc == UO_AddrOf && 15077 (pty->getKind() == BuiltinType::Overload || 15078 pty->getKind() == BuiltinType::UnknownAny || 15079 pty->getKind() == BuiltinType::BoundMember)) 15080 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15081 15082 // Anything else needs to be handled now. 15083 ExprResult Result = CheckPlaceholderExpr(Input); 15084 if (Result.isInvalid()) return ExprError(); 15085 Input = Result.get(); 15086 } 15087 15088 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15089 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15090 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15091 // Find all of the overloaded operators visible from this point. 15092 UnresolvedSet<16> Functions; 15093 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15094 if (S && OverOp != OO_None) 15095 LookupOverloadedOperatorName(OverOp, S, Functions); 15096 15097 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15098 } 15099 15100 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15101 } 15102 15103 // Unary Operators. 'Tok' is the token for the operator. 15104 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15105 tok::TokenKind Op, Expr *Input) { 15106 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15107 } 15108 15109 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15110 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15111 LabelDecl *TheDecl) { 15112 TheDecl->markUsed(Context); 15113 // Create the AST node. The address of a label always has type 'void*'. 15114 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15115 Context.getPointerType(Context.VoidTy)); 15116 } 15117 15118 void Sema::ActOnStartStmtExpr() { 15119 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15120 } 15121 15122 void Sema::ActOnStmtExprError() { 15123 // Note that function is also called by TreeTransform when leaving a 15124 // StmtExpr scope without rebuilding anything. 15125 15126 DiscardCleanupsInEvaluationContext(); 15127 PopExpressionEvaluationContext(); 15128 } 15129 15130 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15131 SourceLocation RPLoc) { 15132 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15133 } 15134 15135 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15136 SourceLocation RPLoc, unsigned TemplateDepth) { 15137 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15138 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15139 15140 if (hasAnyUnrecoverableErrorsInThisFunction()) 15141 DiscardCleanupsInEvaluationContext(); 15142 assert(!Cleanup.exprNeedsCleanups() && 15143 "cleanups within StmtExpr not correctly bound!"); 15144 PopExpressionEvaluationContext(); 15145 15146 // FIXME: there are a variety of strange constraints to enforce here, for 15147 // example, it is not possible to goto into a stmt expression apparently. 15148 // More semantic analysis is needed. 15149 15150 // If there are sub-stmts in the compound stmt, take the type of the last one 15151 // as the type of the stmtexpr. 15152 QualType Ty = Context.VoidTy; 15153 bool StmtExprMayBindToTemp = false; 15154 if (!Compound->body_empty()) { 15155 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15156 if (const auto *LastStmt = 15157 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15158 if (const Expr *Value = LastStmt->getExprStmt()) { 15159 StmtExprMayBindToTemp = true; 15160 Ty = Value->getType(); 15161 } 15162 } 15163 } 15164 15165 // FIXME: Check that expression type is complete/non-abstract; statement 15166 // expressions are not lvalues. 15167 Expr *ResStmtExpr = 15168 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15169 if (StmtExprMayBindToTemp) 15170 return MaybeBindToTemporary(ResStmtExpr); 15171 return ResStmtExpr; 15172 } 15173 15174 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15175 if (ER.isInvalid()) 15176 return ExprError(); 15177 15178 // Do function/array conversion on the last expression, but not 15179 // lvalue-to-rvalue. However, initialize an unqualified type. 15180 ER = DefaultFunctionArrayConversion(ER.get()); 15181 if (ER.isInvalid()) 15182 return ExprError(); 15183 Expr *E = ER.get(); 15184 15185 if (E->isTypeDependent()) 15186 return E; 15187 15188 // In ARC, if the final expression ends in a consume, splice 15189 // the consume out and bind it later. In the alternate case 15190 // (when dealing with a retainable type), the result 15191 // initialization will create a produce. In both cases the 15192 // result will be +1, and we'll need to balance that out with 15193 // a bind. 15194 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15195 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15196 return Cast->getSubExpr(); 15197 15198 // FIXME: Provide a better location for the initialization. 15199 return PerformCopyInitialization( 15200 InitializedEntity::InitializeStmtExprResult( 15201 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15202 SourceLocation(), E); 15203 } 15204 15205 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15206 TypeSourceInfo *TInfo, 15207 ArrayRef<OffsetOfComponent> Components, 15208 SourceLocation RParenLoc) { 15209 QualType ArgTy = TInfo->getType(); 15210 bool Dependent = ArgTy->isDependentType(); 15211 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15212 15213 // We must have at least one component that refers to the type, and the first 15214 // one is known to be a field designator. Verify that the ArgTy represents 15215 // a struct/union/class. 15216 if (!Dependent && !ArgTy->isRecordType()) 15217 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15218 << ArgTy << TypeRange); 15219 15220 // Type must be complete per C99 7.17p3 because a declaring a variable 15221 // with an incomplete type would be ill-formed. 15222 if (!Dependent 15223 && RequireCompleteType(BuiltinLoc, ArgTy, 15224 diag::err_offsetof_incomplete_type, TypeRange)) 15225 return ExprError(); 15226 15227 bool DidWarnAboutNonPOD = false; 15228 QualType CurrentType = ArgTy; 15229 SmallVector<OffsetOfNode, 4> Comps; 15230 SmallVector<Expr*, 4> Exprs; 15231 for (const OffsetOfComponent &OC : Components) { 15232 if (OC.isBrackets) { 15233 // Offset of an array sub-field. TODO: Should we allow vector elements? 15234 if (!CurrentType->isDependentType()) { 15235 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15236 if(!AT) 15237 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15238 << CurrentType); 15239 CurrentType = AT->getElementType(); 15240 } else 15241 CurrentType = Context.DependentTy; 15242 15243 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15244 if (IdxRval.isInvalid()) 15245 return ExprError(); 15246 Expr *Idx = IdxRval.get(); 15247 15248 // The expression must be an integral expression. 15249 // FIXME: An integral constant expression? 15250 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15251 !Idx->getType()->isIntegerType()) 15252 return ExprError( 15253 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15254 << Idx->getSourceRange()); 15255 15256 // Record this array index. 15257 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15258 Exprs.push_back(Idx); 15259 continue; 15260 } 15261 15262 // Offset of a field. 15263 if (CurrentType->isDependentType()) { 15264 // We have the offset of a field, but we can't look into the dependent 15265 // type. Just record the identifier of the field. 15266 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15267 CurrentType = Context.DependentTy; 15268 continue; 15269 } 15270 15271 // We need to have a complete type to look into. 15272 if (RequireCompleteType(OC.LocStart, CurrentType, 15273 diag::err_offsetof_incomplete_type)) 15274 return ExprError(); 15275 15276 // Look for the designated field. 15277 const RecordType *RC = CurrentType->getAs<RecordType>(); 15278 if (!RC) 15279 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15280 << CurrentType); 15281 RecordDecl *RD = RC->getDecl(); 15282 15283 // C++ [lib.support.types]p5: 15284 // The macro offsetof accepts a restricted set of type arguments in this 15285 // International Standard. type shall be a POD structure or a POD union 15286 // (clause 9). 15287 // C++11 [support.types]p4: 15288 // If type is not a standard-layout class (Clause 9), the results are 15289 // undefined. 15290 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15291 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15292 unsigned DiagID = 15293 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15294 : diag::ext_offsetof_non_pod_type; 15295 15296 if (!IsSafe && !DidWarnAboutNonPOD && 15297 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15298 PDiag(DiagID) 15299 << SourceRange(Components[0].LocStart, OC.LocEnd) 15300 << CurrentType)) 15301 DidWarnAboutNonPOD = true; 15302 } 15303 15304 // Look for the field. 15305 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15306 LookupQualifiedName(R, RD); 15307 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15308 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15309 if (!MemberDecl) { 15310 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15311 MemberDecl = IndirectMemberDecl->getAnonField(); 15312 } 15313 15314 if (!MemberDecl) 15315 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15316 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15317 OC.LocEnd)); 15318 15319 // C99 7.17p3: 15320 // (If the specified member is a bit-field, the behavior is undefined.) 15321 // 15322 // We diagnose this as an error. 15323 if (MemberDecl->isBitField()) { 15324 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15325 << MemberDecl->getDeclName() 15326 << SourceRange(BuiltinLoc, RParenLoc); 15327 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15328 return ExprError(); 15329 } 15330 15331 RecordDecl *Parent = MemberDecl->getParent(); 15332 if (IndirectMemberDecl) 15333 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15334 15335 // If the member was found in a base class, introduce OffsetOfNodes for 15336 // the base class indirections. 15337 CXXBasePaths Paths; 15338 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15339 Paths)) { 15340 if (Paths.getDetectedVirtual()) { 15341 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15342 << MemberDecl->getDeclName() 15343 << SourceRange(BuiltinLoc, RParenLoc); 15344 return ExprError(); 15345 } 15346 15347 CXXBasePath &Path = Paths.front(); 15348 for (const CXXBasePathElement &B : Path) 15349 Comps.push_back(OffsetOfNode(B.Base)); 15350 } 15351 15352 if (IndirectMemberDecl) { 15353 for (auto *FI : IndirectMemberDecl->chain()) { 15354 assert(isa<FieldDecl>(FI)); 15355 Comps.push_back(OffsetOfNode(OC.LocStart, 15356 cast<FieldDecl>(FI), OC.LocEnd)); 15357 } 15358 } else 15359 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15360 15361 CurrentType = MemberDecl->getType().getNonReferenceType(); 15362 } 15363 15364 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15365 Comps, Exprs, RParenLoc); 15366 } 15367 15368 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15369 SourceLocation BuiltinLoc, 15370 SourceLocation TypeLoc, 15371 ParsedType ParsedArgTy, 15372 ArrayRef<OffsetOfComponent> Components, 15373 SourceLocation RParenLoc) { 15374 15375 TypeSourceInfo *ArgTInfo; 15376 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15377 if (ArgTy.isNull()) 15378 return ExprError(); 15379 15380 if (!ArgTInfo) 15381 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15382 15383 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15384 } 15385 15386 15387 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15388 Expr *CondExpr, 15389 Expr *LHSExpr, Expr *RHSExpr, 15390 SourceLocation RPLoc) { 15391 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15392 15393 ExprValueKind VK = VK_PRValue; 15394 ExprObjectKind OK = OK_Ordinary; 15395 QualType resType; 15396 bool CondIsTrue = false; 15397 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15398 resType = Context.DependentTy; 15399 } else { 15400 // The conditional expression is required to be a constant expression. 15401 llvm::APSInt condEval(32); 15402 ExprResult CondICE = VerifyIntegerConstantExpression( 15403 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15404 if (CondICE.isInvalid()) 15405 return ExprError(); 15406 CondExpr = CondICE.get(); 15407 CondIsTrue = condEval.getZExtValue(); 15408 15409 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15410 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15411 15412 resType = ActiveExpr->getType(); 15413 VK = ActiveExpr->getValueKind(); 15414 OK = ActiveExpr->getObjectKind(); 15415 } 15416 15417 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15418 resType, VK, OK, RPLoc, CondIsTrue); 15419 } 15420 15421 //===----------------------------------------------------------------------===// 15422 // Clang Extensions. 15423 //===----------------------------------------------------------------------===// 15424 15425 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15426 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15427 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15428 15429 if (LangOpts.CPlusPlus) { 15430 MangleNumberingContext *MCtx; 15431 Decl *ManglingContextDecl; 15432 std::tie(MCtx, ManglingContextDecl) = 15433 getCurrentMangleNumberContext(Block->getDeclContext()); 15434 if (MCtx) { 15435 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15436 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15437 } 15438 } 15439 15440 PushBlockScope(CurScope, Block); 15441 CurContext->addDecl(Block); 15442 if (CurScope) 15443 PushDeclContext(CurScope, Block); 15444 else 15445 CurContext = Block; 15446 15447 getCurBlock()->HasImplicitReturnType = true; 15448 15449 // Enter a new evaluation context to insulate the block from any 15450 // cleanups from the enclosing full-expression. 15451 PushExpressionEvaluationContext( 15452 ExpressionEvaluationContext::PotentiallyEvaluated); 15453 } 15454 15455 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15456 Scope *CurScope) { 15457 assert(ParamInfo.getIdentifier() == nullptr && 15458 "block-id should have no identifier!"); 15459 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15460 BlockScopeInfo *CurBlock = getCurBlock(); 15461 15462 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15463 QualType T = Sig->getType(); 15464 15465 // FIXME: We should allow unexpanded parameter packs here, but that would, 15466 // in turn, make the block expression contain unexpanded parameter packs. 15467 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15468 // Drop the parameters. 15469 FunctionProtoType::ExtProtoInfo EPI; 15470 EPI.HasTrailingReturn = false; 15471 EPI.TypeQuals.addConst(); 15472 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15473 Sig = Context.getTrivialTypeSourceInfo(T); 15474 } 15475 15476 // GetTypeForDeclarator always produces a function type for a block 15477 // literal signature. Furthermore, it is always a FunctionProtoType 15478 // unless the function was written with a typedef. 15479 assert(T->isFunctionType() && 15480 "GetTypeForDeclarator made a non-function block signature"); 15481 15482 // Look for an explicit signature in that function type. 15483 FunctionProtoTypeLoc ExplicitSignature; 15484 15485 if ((ExplicitSignature = Sig->getTypeLoc() 15486 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15487 15488 // Check whether that explicit signature was synthesized by 15489 // GetTypeForDeclarator. If so, don't save that as part of the 15490 // written signature. 15491 if (ExplicitSignature.getLocalRangeBegin() == 15492 ExplicitSignature.getLocalRangeEnd()) { 15493 // This would be much cheaper if we stored TypeLocs instead of 15494 // TypeSourceInfos. 15495 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15496 unsigned Size = Result.getFullDataSize(); 15497 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15498 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15499 15500 ExplicitSignature = FunctionProtoTypeLoc(); 15501 } 15502 } 15503 15504 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15505 CurBlock->FunctionType = T; 15506 15507 const auto *Fn = T->castAs<FunctionType>(); 15508 QualType RetTy = Fn->getReturnType(); 15509 bool isVariadic = 15510 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15511 15512 CurBlock->TheDecl->setIsVariadic(isVariadic); 15513 15514 // Context.DependentTy is used as a placeholder for a missing block 15515 // return type. TODO: what should we do with declarators like: 15516 // ^ * { ... } 15517 // If the answer is "apply template argument deduction".... 15518 if (RetTy != Context.DependentTy) { 15519 CurBlock->ReturnType = RetTy; 15520 CurBlock->TheDecl->setBlockMissingReturnType(false); 15521 CurBlock->HasImplicitReturnType = false; 15522 } 15523 15524 // Push block parameters from the declarator if we had them. 15525 SmallVector<ParmVarDecl*, 8> Params; 15526 if (ExplicitSignature) { 15527 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15528 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15529 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15530 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15531 // Diagnose this as an extension in C17 and earlier. 15532 if (!getLangOpts().C2x) 15533 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15534 } 15535 Params.push_back(Param); 15536 } 15537 15538 // Fake up parameter variables if we have a typedef, like 15539 // ^ fntype { ... } 15540 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15541 for (const auto &I : Fn->param_types()) { 15542 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15543 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15544 Params.push_back(Param); 15545 } 15546 } 15547 15548 // Set the parameters on the block decl. 15549 if (!Params.empty()) { 15550 CurBlock->TheDecl->setParams(Params); 15551 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15552 /*CheckParameterNames=*/false); 15553 } 15554 15555 // Finally we can process decl attributes. 15556 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15557 15558 // Put the parameter variables in scope. 15559 for (auto AI : CurBlock->TheDecl->parameters()) { 15560 AI->setOwningFunction(CurBlock->TheDecl); 15561 15562 // If this has an identifier, add it to the scope stack. 15563 if (AI->getIdentifier()) { 15564 CheckShadow(CurBlock->TheScope, AI); 15565 15566 PushOnScopeChains(AI, CurBlock->TheScope); 15567 } 15568 } 15569 } 15570 15571 /// ActOnBlockError - If there is an error parsing a block, this callback 15572 /// is invoked to pop the information about the block from the action impl. 15573 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15574 // Leave the expression-evaluation context. 15575 DiscardCleanupsInEvaluationContext(); 15576 PopExpressionEvaluationContext(); 15577 15578 // Pop off CurBlock, handle nested blocks. 15579 PopDeclContext(); 15580 PopFunctionScopeInfo(); 15581 } 15582 15583 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15584 /// literal was successfully completed. ^(int x){...} 15585 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15586 Stmt *Body, Scope *CurScope) { 15587 // If blocks are disabled, emit an error. 15588 if (!LangOpts.Blocks) 15589 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15590 15591 // Leave the expression-evaluation context. 15592 if (hasAnyUnrecoverableErrorsInThisFunction()) 15593 DiscardCleanupsInEvaluationContext(); 15594 assert(!Cleanup.exprNeedsCleanups() && 15595 "cleanups within block not correctly bound!"); 15596 PopExpressionEvaluationContext(); 15597 15598 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15599 BlockDecl *BD = BSI->TheDecl; 15600 15601 if (BSI->HasImplicitReturnType) 15602 deduceClosureReturnType(*BSI); 15603 15604 QualType RetTy = Context.VoidTy; 15605 if (!BSI->ReturnType.isNull()) 15606 RetTy = BSI->ReturnType; 15607 15608 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15609 QualType BlockTy; 15610 15611 // If the user wrote a function type in some form, try to use that. 15612 if (!BSI->FunctionType.isNull()) { 15613 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15614 15615 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15616 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15617 15618 // Turn protoless block types into nullary block types. 15619 if (isa<FunctionNoProtoType>(FTy)) { 15620 FunctionProtoType::ExtProtoInfo EPI; 15621 EPI.ExtInfo = Ext; 15622 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15623 15624 // Otherwise, if we don't need to change anything about the function type, 15625 // preserve its sugar structure. 15626 } else if (FTy->getReturnType() == RetTy && 15627 (!NoReturn || FTy->getNoReturnAttr())) { 15628 BlockTy = BSI->FunctionType; 15629 15630 // Otherwise, make the minimal modifications to the function type. 15631 } else { 15632 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15633 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15634 EPI.TypeQuals = Qualifiers(); 15635 EPI.ExtInfo = Ext; 15636 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15637 } 15638 15639 // If we don't have a function type, just build one from nothing. 15640 } else { 15641 FunctionProtoType::ExtProtoInfo EPI; 15642 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15643 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15644 } 15645 15646 DiagnoseUnusedParameters(BD->parameters()); 15647 BlockTy = Context.getBlockPointerType(BlockTy); 15648 15649 // If needed, diagnose invalid gotos and switches in the block. 15650 if (getCurFunction()->NeedsScopeChecking() && 15651 !PP.isCodeCompletionEnabled()) 15652 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15653 15654 BD->setBody(cast<CompoundStmt>(Body)); 15655 15656 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15657 DiagnoseUnguardedAvailabilityViolations(BD); 15658 15659 // Try to apply the named return value optimization. We have to check again 15660 // if we can do this, though, because blocks keep return statements around 15661 // to deduce an implicit return type. 15662 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15663 !BD->isDependentContext()) 15664 computeNRVO(Body, BSI); 15665 15666 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15667 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15668 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15669 NTCUK_Destruct|NTCUK_Copy); 15670 15671 PopDeclContext(); 15672 15673 // Set the captured variables on the block. 15674 SmallVector<BlockDecl::Capture, 4> Captures; 15675 for (Capture &Cap : BSI->Captures) { 15676 if (Cap.isInvalid() || Cap.isThisCapture()) 15677 continue; 15678 15679 VarDecl *Var = Cap.getVariable(); 15680 Expr *CopyExpr = nullptr; 15681 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15682 if (const RecordType *Record = 15683 Cap.getCaptureType()->getAs<RecordType>()) { 15684 // The capture logic needs the destructor, so make sure we mark it. 15685 // Usually this is unnecessary because most local variables have 15686 // their destructors marked at declaration time, but parameters are 15687 // an exception because it's technically only the call site that 15688 // actually requires the destructor. 15689 if (isa<ParmVarDecl>(Var)) 15690 FinalizeVarWithDestructor(Var, Record); 15691 15692 // Enter a separate potentially-evaluated context while building block 15693 // initializers to isolate their cleanups from those of the block 15694 // itself. 15695 // FIXME: Is this appropriate even when the block itself occurs in an 15696 // unevaluated operand? 15697 EnterExpressionEvaluationContext EvalContext( 15698 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15699 15700 SourceLocation Loc = Cap.getLocation(); 15701 15702 ExprResult Result = BuildDeclarationNameExpr( 15703 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15704 15705 // According to the blocks spec, the capture of a variable from 15706 // the stack requires a const copy constructor. This is not true 15707 // of the copy/move done to move a __block variable to the heap. 15708 if (!Result.isInvalid() && 15709 !Result.get()->getType().isConstQualified()) { 15710 Result = ImpCastExprToType(Result.get(), 15711 Result.get()->getType().withConst(), 15712 CK_NoOp, VK_LValue); 15713 } 15714 15715 if (!Result.isInvalid()) { 15716 Result = PerformCopyInitialization( 15717 InitializedEntity::InitializeBlock(Var->getLocation(), 15718 Cap.getCaptureType(), false), 15719 Loc, Result.get()); 15720 } 15721 15722 // Build a full-expression copy expression if initialization 15723 // succeeded and used a non-trivial constructor. Recover from 15724 // errors by pretending that the copy isn't necessary. 15725 if (!Result.isInvalid() && 15726 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15727 ->isTrivial()) { 15728 Result = MaybeCreateExprWithCleanups(Result); 15729 CopyExpr = Result.get(); 15730 } 15731 } 15732 } 15733 15734 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15735 CopyExpr); 15736 Captures.push_back(NewCap); 15737 } 15738 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15739 15740 // Pop the block scope now but keep it alive to the end of this function. 15741 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15742 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15743 15744 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15745 15746 // If the block isn't obviously global, i.e. it captures anything at 15747 // all, then we need to do a few things in the surrounding context: 15748 if (Result->getBlockDecl()->hasCaptures()) { 15749 // First, this expression has a new cleanup object. 15750 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15751 Cleanup.setExprNeedsCleanups(true); 15752 15753 // It also gets a branch-protected scope if any of the captured 15754 // variables needs destruction. 15755 for (const auto &CI : Result->getBlockDecl()->captures()) { 15756 const VarDecl *var = CI.getVariable(); 15757 if (var->getType().isDestructedType() != QualType::DK_none) { 15758 setFunctionHasBranchProtectedScope(); 15759 break; 15760 } 15761 } 15762 } 15763 15764 if (getCurFunction()) 15765 getCurFunction()->addBlock(BD); 15766 15767 return Result; 15768 } 15769 15770 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15771 SourceLocation RPLoc) { 15772 TypeSourceInfo *TInfo; 15773 GetTypeFromParser(Ty, &TInfo); 15774 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15775 } 15776 15777 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15778 Expr *E, TypeSourceInfo *TInfo, 15779 SourceLocation RPLoc) { 15780 Expr *OrigExpr = E; 15781 bool IsMS = false; 15782 15783 // CUDA device code does not support varargs. 15784 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15785 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15786 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15787 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15788 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15789 } 15790 } 15791 15792 // NVPTX does not support va_arg expression. 15793 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15794 Context.getTargetInfo().getTriple().isNVPTX()) 15795 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15796 15797 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15798 // as Microsoft ABI on an actual Microsoft platform, where 15799 // __builtin_ms_va_list and __builtin_va_list are the same.) 15800 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15801 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15802 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15803 if (Context.hasSameType(MSVaListType, E->getType())) { 15804 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15805 return ExprError(); 15806 IsMS = true; 15807 } 15808 } 15809 15810 // Get the va_list type 15811 QualType VaListType = Context.getBuiltinVaListType(); 15812 if (!IsMS) { 15813 if (VaListType->isArrayType()) { 15814 // Deal with implicit array decay; for example, on x86-64, 15815 // va_list is an array, but it's supposed to decay to 15816 // a pointer for va_arg. 15817 VaListType = Context.getArrayDecayedType(VaListType); 15818 // Make sure the input expression also decays appropriately. 15819 ExprResult Result = UsualUnaryConversions(E); 15820 if (Result.isInvalid()) 15821 return ExprError(); 15822 E = Result.get(); 15823 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15824 // If va_list is a record type and we are compiling in C++ mode, 15825 // check the argument using reference binding. 15826 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15827 Context, Context.getLValueReferenceType(VaListType), false); 15828 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15829 if (Init.isInvalid()) 15830 return ExprError(); 15831 E = Init.getAs<Expr>(); 15832 } else { 15833 // Otherwise, the va_list argument must be an l-value because 15834 // it is modified by va_arg. 15835 if (!E->isTypeDependent() && 15836 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15837 return ExprError(); 15838 } 15839 } 15840 15841 if (!IsMS && !E->isTypeDependent() && 15842 !Context.hasSameType(VaListType, E->getType())) 15843 return ExprError( 15844 Diag(E->getBeginLoc(), 15845 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15846 << OrigExpr->getType() << E->getSourceRange()); 15847 15848 if (!TInfo->getType()->isDependentType()) { 15849 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15850 diag::err_second_parameter_to_va_arg_incomplete, 15851 TInfo->getTypeLoc())) 15852 return ExprError(); 15853 15854 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15855 TInfo->getType(), 15856 diag::err_second_parameter_to_va_arg_abstract, 15857 TInfo->getTypeLoc())) 15858 return ExprError(); 15859 15860 if (!TInfo->getType().isPODType(Context)) { 15861 Diag(TInfo->getTypeLoc().getBeginLoc(), 15862 TInfo->getType()->isObjCLifetimeType() 15863 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15864 : diag::warn_second_parameter_to_va_arg_not_pod) 15865 << TInfo->getType() 15866 << TInfo->getTypeLoc().getSourceRange(); 15867 } 15868 15869 // Check for va_arg where arguments of the given type will be promoted 15870 // (i.e. this va_arg is guaranteed to have undefined behavior). 15871 QualType PromoteType; 15872 if (TInfo->getType()->isPromotableIntegerType()) { 15873 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15874 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15875 // and C2x 7.16.1.1p2 says, in part: 15876 // If type is not compatible with the type of the actual next argument 15877 // (as promoted according to the default argument promotions), the 15878 // behavior is undefined, except for the following cases: 15879 // - both types are pointers to qualified or unqualified versions of 15880 // compatible types; 15881 // - one type is a signed integer type, the other type is the 15882 // corresponding unsigned integer type, and the value is 15883 // representable in both types; 15884 // - one type is pointer to qualified or unqualified void and the 15885 // other is a pointer to a qualified or unqualified character type. 15886 // Given that type compatibility is the primary requirement (ignoring 15887 // qualifications), you would think we could call typesAreCompatible() 15888 // directly to test this. However, in C++, that checks for *same type*, 15889 // which causes false positives when passing an enumeration type to 15890 // va_arg. Instead, get the underlying type of the enumeration and pass 15891 // that. 15892 QualType UnderlyingType = TInfo->getType(); 15893 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15894 UnderlyingType = ET->getDecl()->getIntegerType(); 15895 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15896 /*CompareUnqualified*/ true)) 15897 PromoteType = QualType(); 15898 15899 // If the types are still not compatible, we need to test whether the 15900 // promoted type and the underlying type are the same except for 15901 // signedness. Ask the AST for the correctly corresponding type and see 15902 // if that's compatible. 15903 if (!PromoteType.isNull() && 15904 PromoteType->isUnsignedIntegerType() != 15905 UnderlyingType->isUnsignedIntegerType()) { 15906 UnderlyingType = 15907 UnderlyingType->isUnsignedIntegerType() 15908 ? Context.getCorrespondingSignedType(UnderlyingType) 15909 : Context.getCorrespondingUnsignedType(UnderlyingType); 15910 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15911 /*CompareUnqualified*/ true)) 15912 PromoteType = QualType(); 15913 } 15914 } 15915 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15916 PromoteType = Context.DoubleTy; 15917 if (!PromoteType.isNull()) 15918 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15919 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15920 << TInfo->getType() 15921 << PromoteType 15922 << TInfo->getTypeLoc().getSourceRange()); 15923 } 15924 15925 QualType T = TInfo->getType().getNonLValueExprType(Context); 15926 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15927 } 15928 15929 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15930 // The type of __null will be int or long, depending on the size of 15931 // pointers on the target. 15932 QualType Ty; 15933 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15934 if (pw == Context.getTargetInfo().getIntWidth()) 15935 Ty = Context.IntTy; 15936 else if (pw == Context.getTargetInfo().getLongWidth()) 15937 Ty = Context.LongTy; 15938 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15939 Ty = Context.LongLongTy; 15940 else { 15941 llvm_unreachable("I don't know size of pointer!"); 15942 } 15943 15944 return new (Context) GNUNullExpr(Ty, TokenLoc); 15945 } 15946 15947 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15948 SourceLocation BuiltinLoc, 15949 SourceLocation RPLoc) { 15950 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15951 } 15952 15953 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15954 SourceLocation BuiltinLoc, 15955 SourceLocation RPLoc, 15956 DeclContext *ParentContext) { 15957 return new (Context) 15958 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15959 } 15960 15961 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15962 bool Diagnose) { 15963 if (!getLangOpts().ObjC) 15964 return false; 15965 15966 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15967 if (!PT) 15968 return false; 15969 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15970 15971 // Ignore any parens, implicit casts (should only be 15972 // array-to-pointer decays), and not-so-opaque values. The last is 15973 // important for making this trigger for property assignments. 15974 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15975 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15976 if (OV->getSourceExpr()) 15977 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15978 15979 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15980 if (!PT->isObjCIdType() && 15981 !(ID && ID->getIdentifier()->isStr("NSString"))) 15982 return false; 15983 if (!SL->isAscii()) 15984 return false; 15985 15986 if (Diagnose) { 15987 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15988 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15989 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15990 } 15991 return true; 15992 } 15993 15994 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15995 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15996 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15997 !SrcExpr->isNullPointerConstant( 15998 getASTContext(), Expr::NPC_NeverValueDependent)) { 15999 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16000 return false; 16001 if (Diagnose) { 16002 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16003 << /*number*/1 16004 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16005 Expr *NumLit = 16006 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16007 if (NumLit) 16008 Exp = NumLit; 16009 } 16010 return true; 16011 } 16012 16013 return false; 16014 } 16015 16016 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16017 const Expr *SrcExpr) { 16018 if (!DstType->isFunctionPointerType() || 16019 !SrcExpr->getType()->isFunctionType()) 16020 return false; 16021 16022 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16023 if (!DRE) 16024 return false; 16025 16026 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16027 if (!FD) 16028 return false; 16029 16030 return !S.checkAddressOfFunctionIsAvailable(FD, 16031 /*Complain=*/true, 16032 SrcExpr->getBeginLoc()); 16033 } 16034 16035 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16036 SourceLocation Loc, 16037 QualType DstType, QualType SrcType, 16038 Expr *SrcExpr, AssignmentAction Action, 16039 bool *Complained) { 16040 if (Complained) 16041 *Complained = false; 16042 16043 // Decode the result (notice that AST's are still created for extensions). 16044 bool CheckInferredResultType = false; 16045 bool isInvalid = false; 16046 unsigned DiagKind = 0; 16047 ConversionFixItGenerator ConvHints; 16048 bool MayHaveConvFixit = false; 16049 bool MayHaveFunctionDiff = false; 16050 const ObjCInterfaceDecl *IFace = nullptr; 16051 const ObjCProtocolDecl *PDecl = nullptr; 16052 16053 switch (ConvTy) { 16054 case Compatible: 16055 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16056 return false; 16057 16058 case PointerToInt: 16059 if (getLangOpts().CPlusPlus) { 16060 DiagKind = diag::err_typecheck_convert_pointer_int; 16061 isInvalid = true; 16062 } else { 16063 DiagKind = diag::ext_typecheck_convert_pointer_int; 16064 } 16065 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16066 MayHaveConvFixit = true; 16067 break; 16068 case IntToPointer: 16069 if (getLangOpts().CPlusPlus) { 16070 DiagKind = diag::err_typecheck_convert_int_pointer; 16071 isInvalid = true; 16072 } else { 16073 DiagKind = diag::ext_typecheck_convert_int_pointer; 16074 } 16075 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16076 MayHaveConvFixit = true; 16077 break; 16078 case IncompatibleFunctionPointer: 16079 if (getLangOpts().CPlusPlus) { 16080 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16081 isInvalid = true; 16082 } else { 16083 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16084 } 16085 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16086 MayHaveConvFixit = true; 16087 break; 16088 case IncompatiblePointer: 16089 if (Action == AA_Passing_CFAudited) { 16090 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16091 } else if (getLangOpts().CPlusPlus) { 16092 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16093 isInvalid = true; 16094 } else { 16095 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16096 } 16097 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16098 SrcType->isObjCObjectPointerType(); 16099 if (!CheckInferredResultType) { 16100 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16101 } else if (CheckInferredResultType) { 16102 SrcType = SrcType.getUnqualifiedType(); 16103 DstType = DstType.getUnqualifiedType(); 16104 } 16105 MayHaveConvFixit = true; 16106 break; 16107 case IncompatiblePointerSign: 16108 if (getLangOpts().CPlusPlus) { 16109 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16110 isInvalid = true; 16111 } else { 16112 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16113 } 16114 break; 16115 case FunctionVoidPointer: 16116 if (getLangOpts().CPlusPlus) { 16117 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16118 isInvalid = true; 16119 } else { 16120 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16121 } 16122 break; 16123 case IncompatiblePointerDiscardsQualifiers: { 16124 // Perform array-to-pointer decay if necessary. 16125 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16126 16127 isInvalid = true; 16128 16129 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16130 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16131 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16132 DiagKind = diag::err_typecheck_incompatible_address_space; 16133 break; 16134 16135 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16136 DiagKind = diag::err_typecheck_incompatible_ownership; 16137 break; 16138 } 16139 16140 llvm_unreachable("unknown error case for discarding qualifiers!"); 16141 // fallthrough 16142 } 16143 case CompatiblePointerDiscardsQualifiers: 16144 // If the qualifiers lost were because we were applying the 16145 // (deprecated) C++ conversion from a string literal to a char* 16146 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16147 // Ideally, this check would be performed in 16148 // checkPointerTypesForAssignment. However, that would require a 16149 // bit of refactoring (so that the second argument is an 16150 // expression, rather than a type), which should be done as part 16151 // of a larger effort to fix checkPointerTypesForAssignment for 16152 // C++ semantics. 16153 if (getLangOpts().CPlusPlus && 16154 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16155 return false; 16156 if (getLangOpts().CPlusPlus) { 16157 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16158 isInvalid = true; 16159 } else { 16160 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16161 } 16162 16163 break; 16164 case IncompatibleNestedPointerQualifiers: 16165 if (getLangOpts().CPlusPlus) { 16166 isInvalid = true; 16167 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16168 } else { 16169 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16170 } 16171 break; 16172 case IncompatibleNestedPointerAddressSpaceMismatch: 16173 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16174 isInvalid = true; 16175 break; 16176 case IntToBlockPointer: 16177 DiagKind = diag::err_int_to_block_pointer; 16178 isInvalid = true; 16179 break; 16180 case IncompatibleBlockPointer: 16181 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16182 isInvalid = true; 16183 break; 16184 case IncompatibleObjCQualifiedId: { 16185 if (SrcType->isObjCQualifiedIdType()) { 16186 const ObjCObjectPointerType *srcOPT = 16187 SrcType->castAs<ObjCObjectPointerType>(); 16188 for (auto *srcProto : srcOPT->quals()) { 16189 PDecl = srcProto; 16190 break; 16191 } 16192 if (const ObjCInterfaceType *IFaceT = 16193 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16194 IFace = IFaceT->getDecl(); 16195 } 16196 else if (DstType->isObjCQualifiedIdType()) { 16197 const ObjCObjectPointerType *dstOPT = 16198 DstType->castAs<ObjCObjectPointerType>(); 16199 for (auto *dstProto : dstOPT->quals()) { 16200 PDecl = dstProto; 16201 break; 16202 } 16203 if (const ObjCInterfaceType *IFaceT = 16204 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16205 IFace = IFaceT->getDecl(); 16206 } 16207 if (getLangOpts().CPlusPlus) { 16208 DiagKind = diag::err_incompatible_qualified_id; 16209 isInvalid = true; 16210 } else { 16211 DiagKind = diag::warn_incompatible_qualified_id; 16212 } 16213 break; 16214 } 16215 case IncompatibleVectors: 16216 if (getLangOpts().CPlusPlus) { 16217 DiagKind = diag::err_incompatible_vectors; 16218 isInvalid = true; 16219 } else { 16220 DiagKind = diag::warn_incompatible_vectors; 16221 } 16222 break; 16223 case IncompatibleObjCWeakRef: 16224 DiagKind = diag::err_arc_weak_unavailable_assign; 16225 isInvalid = true; 16226 break; 16227 case Incompatible: 16228 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16229 if (Complained) 16230 *Complained = true; 16231 return true; 16232 } 16233 16234 DiagKind = diag::err_typecheck_convert_incompatible; 16235 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16236 MayHaveConvFixit = true; 16237 isInvalid = true; 16238 MayHaveFunctionDiff = true; 16239 break; 16240 } 16241 16242 QualType FirstType, SecondType; 16243 switch (Action) { 16244 case AA_Assigning: 16245 case AA_Initializing: 16246 // The destination type comes first. 16247 FirstType = DstType; 16248 SecondType = SrcType; 16249 break; 16250 16251 case AA_Returning: 16252 case AA_Passing: 16253 case AA_Passing_CFAudited: 16254 case AA_Converting: 16255 case AA_Sending: 16256 case AA_Casting: 16257 // The source type comes first. 16258 FirstType = SrcType; 16259 SecondType = DstType; 16260 break; 16261 } 16262 16263 PartialDiagnostic FDiag = PDiag(DiagKind); 16264 if (Action == AA_Passing_CFAudited) 16265 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16266 else 16267 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16268 16269 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16270 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16271 auto isPlainChar = [](const clang::Type *Type) { 16272 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16273 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16274 }; 16275 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16276 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16277 } 16278 16279 // If we can fix the conversion, suggest the FixIts. 16280 if (!ConvHints.isNull()) { 16281 for (FixItHint &H : ConvHints.Hints) 16282 FDiag << H; 16283 } 16284 16285 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16286 16287 if (MayHaveFunctionDiff) 16288 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16289 16290 Diag(Loc, FDiag); 16291 if ((DiagKind == diag::warn_incompatible_qualified_id || 16292 DiagKind == diag::err_incompatible_qualified_id) && 16293 PDecl && IFace && !IFace->hasDefinition()) 16294 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16295 << IFace << PDecl; 16296 16297 if (SecondType == Context.OverloadTy) 16298 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16299 FirstType, /*TakingAddress=*/true); 16300 16301 if (CheckInferredResultType) 16302 EmitRelatedResultTypeNote(SrcExpr); 16303 16304 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16305 EmitRelatedResultTypeNoteForReturn(DstType); 16306 16307 if (Complained) 16308 *Complained = true; 16309 return isInvalid; 16310 } 16311 16312 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16313 llvm::APSInt *Result, 16314 AllowFoldKind CanFold) { 16315 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16316 public: 16317 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16318 QualType T) override { 16319 return S.Diag(Loc, diag::err_ice_not_integral) 16320 << T << S.LangOpts.CPlusPlus; 16321 } 16322 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16323 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16324 } 16325 } Diagnoser; 16326 16327 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16328 } 16329 16330 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16331 llvm::APSInt *Result, 16332 unsigned DiagID, 16333 AllowFoldKind CanFold) { 16334 class IDDiagnoser : public VerifyICEDiagnoser { 16335 unsigned DiagID; 16336 16337 public: 16338 IDDiagnoser(unsigned DiagID) 16339 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16340 16341 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16342 return S.Diag(Loc, DiagID); 16343 } 16344 } Diagnoser(DiagID); 16345 16346 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16347 } 16348 16349 Sema::SemaDiagnosticBuilder 16350 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16351 QualType T) { 16352 return diagnoseNotICE(S, Loc); 16353 } 16354 16355 Sema::SemaDiagnosticBuilder 16356 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16357 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16358 } 16359 16360 ExprResult 16361 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16362 VerifyICEDiagnoser &Diagnoser, 16363 AllowFoldKind CanFold) { 16364 SourceLocation DiagLoc = E->getBeginLoc(); 16365 16366 if (getLangOpts().CPlusPlus11) { 16367 // C++11 [expr.const]p5: 16368 // If an expression of literal class type is used in a context where an 16369 // integral constant expression is required, then that class type shall 16370 // have a single non-explicit conversion function to an integral or 16371 // unscoped enumeration type 16372 ExprResult Converted; 16373 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16374 VerifyICEDiagnoser &BaseDiagnoser; 16375 public: 16376 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16377 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16378 BaseDiagnoser.Suppress, true), 16379 BaseDiagnoser(BaseDiagnoser) {} 16380 16381 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16382 QualType T) override { 16383 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16384 } 16385 16386 SemaDiagnosticBuilder diagnoseIncomplete( 16387 Sema &S, SourceLocation Loc, QualType T) override { 16388 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16389 } 16390 16391 SemaDiagnosticBuilder diagnoseExplicitConv( 16392 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16393 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16394 } 16395 16396 SemaDiagnosticBuilder noteExplicitConv( 16397 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16398 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16399 << ConvTy->isEnumeralType() << ConvTy; 16400 } 16401 16402 SemaDiagnosticBuilder diagnoseAmbiguous( 16403 Sema &S, SourceLocation Loc, QualType T) override { 16404 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16405 } 16406 16407 SemaDiagnosticBuilder noteAmbiguous( 16408 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16409 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16410 << ConvTy->isEnumeralType() << ConvTy; 16411 } 16412 16413 SemaDiagnosticBuilder diagnoseConversion( 16414 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16415 llvm_unreachable("conversion functions are permitted"); 16416 } 16417 } ConvertDiagnoser(Diagnoser); 16418 16419 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16420 ConvertDiagnoser); 16421 if (Converted.isInvalid()) 16422 return Converted; 16423 E = Converted.get(); 16424 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16425 return ExprError(); 16426 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16427 // An ICE must be of integral or unscoped enumeration type. 16428 if (!Diagnoser.Suppress) 16429 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16430 << E->getSourceRange(); 16431 return ExprError(); 16432 } 16433 16434 ExprResult RValueExpr = DefaultLvalueConversion(E); 16435 if (RValueExpr.isInvalid()) 16436 return ExprError(); 16437 16438 E = RValueExpr.get(); 16439 16440 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16441 // in the non-ICE case. 16442 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16443 if (Result) 16444 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16445 if (!isa<ConstantExpr>(E)) 16446 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16447 : ConstantExpr::Create(Context, E); 16448 return E; 16449 } 16450 16451 Expr::EvalResult EvalResult; 16452 SmallVector<PartialDiagnosticAt, 8> Notes; 16453 EvalResult.Diag = &Notes; 16454 16455 // Try to evaluate the expression, and produce diagnostics explaining why it's 16456 // not a constant expression as a side-effect. 16457 bool Folded = 16458 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16459 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16460 16461 if (!isa<ConstantExpr>(E)) 16462 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16463 16464 // In C++11, we can rely on diagnostics being produced for any expression 16465 // which is not a constant expression. If no diagnostics were produced, then 16466 // this is a constant expression. 16467 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16468 if (Result) 16469 *Result = EvalResult.Val.getInt(); 16470 return E; 16471 } 16472 16473 // If our only note is the usual "invalid subexpression" note, just point 16474 // the caret at its location rather than producing an essentially 16475 // redundant note. 16476 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16477 diag::note_invalid_subexpr_in_const_expr) { 16478 DiagLoc = Notes[0].first; 16479 Notes.clear(); 16480 } 16481 16482 if (!Folded || !CanFold) { 16483 if (!Diagnoser.Suppress) { 16484 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16485 for (const PartialDiagnosticAt &Note : Notes) 16486 Diag(Note.first, Note.second); 16487 } 16488 16489 return ExprError(); 16490 } 16491 16492 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16493 for (const PartialDiagnosticAt &Note : Notes) 16494 Diag(Note.first, Note.second); 16495 16496 if (Result) 16497 *Result = EvalResult.Val.getInt(); 16498 return E; 16499 } 16500 16501 namespace { 16502 // Handle the case where we conclude a expression which we speculatively 16503 // considered to be unevaluated is actually evaluated. 16504 class TransformToPE : public TreeTransform<TransformToPE> { 16505 typedef TreeTransform<TransformToPE> BaseTransform; 16506 16507 public: 16508 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16509 16510 // Make sure we redo semantic analysis 16511 bool AlwaysRebuild() { return true; } 16512 bool ReplacingOriginal() { return true; } 16513 16514 // We need to special-case DeclRefExprs referring to FieldDecls which 16515 // are not part of a member pointer formation; normal TreeTransforming 16516 // doesn't catch this case because of the way we represent them in the AST. 16517 // FIXME: This is a bit ugly; is it really the best way to handle this 16518 // case? 16519 // 16520 // Error on DeclRefExprs referring to FieldDecls. 16521 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16522 if (isa<FieldDecl>(E->getDecl()) && 16523 !SemaRef.isUnevaluatedContext()) 16524 return SemaRef.Diag(E->getLocation(), 16525 diag::err_invalid_non_static_member_use) 16526 << E->getDecl() << E->getSourceRange(); 16527 16528 return BaseTransform::TransformDeclRefExpr(E); 16529 } 16530 16531 // Exception: filter out member pointer formation 16532 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16533 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16534 return E; 16535 16536 return BaseTransform::TransformUnaryOperator(E); 16537 } 16538 16539 // The body of a lambda-expression is in a separate expression evaluation 16540 // context so never needs to be transformed. 16541 // FIXME: Ideally we wouldn't transform the closure type either, and would 16542 // just recreate the capture expressions and lambda expression. 16543 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16544 return SkipLambdaBody(E, Body); 16545 } 16546 }; 16547 } 16548 16549 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16550 assert(isUnevaluatedContext() && 16551 "Should only transform unevaluated expressions"); 16552 ExprEvalContexts.back().Context = 16553 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16554 if (isUnevaluatedContext()) 16555 return E; 16556 return TransformToPE(*this).TransformExpr(E); 16557 } 16558 16559 void 16560 Sema::PushExpressionEvaluationContext( 16561 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16562 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16563 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16564 LambdaContextDecl, ExprContext); 16565 Cleanup.reset(); 16566 if (!MaybeODRUseExprs.empty()) 16567 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16568 } 16569 16570 void 16571 Sema::PushExpressionEvaluationContext( 16572 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16573 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16574 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16575 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16576 } 16577 16578 namespace { 16579 16580 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16581 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16582 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16583 if (E->getOpcode() == UO_Deref) 16584 return CheckPossibleDeref(S, E->getSubExpr()); 16585 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16586 return CheckPossibleDeref(S, E->getBase()); 16587 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16588 return CheckPossibleDeref(S, E->getBase()); 16589 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16590 QualType Inner; 16591 QualType Ty = E->getType(); 16592 if (const auto *Ptr = Ty->getAs<PointerType>()) 16593 Inner = Ptr->getPointeeType(); 16594 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16595 Inner = Arr->getElementType(); 16596 else 16597 return nullptr; 16598 16599 if (Inner->hasAttr(attr::NoDeref)) 16600 return E; 16601 } 16602 return nullptr; 16603 } 16604 16605 } // namespace 16606 16607 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16608 for (const Expr *E : Rec.PossibleDerefs) { 16609 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16610 if (DeclRef) { 16611 const ValueDecl *Decl = DeclRef->getDecl(); 16612 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16613 << Decl->getName() << E->getSourceRange(); 16614 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16615 } else { 16616 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16617 << E->getSourceRange(); 16618 } 16619 } 16620 Rec.PossibleDerefs.clear(); 16621 } 16622 16623 /// Check whether E, which is either a discarded-value expression or an 16624 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16625 /// and if so, remove it from the list of volatile-qualified assignments that 16626 /// we are going to warn are deprecated. 16627 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16628 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16629 return; 16630 16631 // Note: ignoring parens here is not justified by the standard rules, but 16632 // ignoring parentheses seems like a more reasonable approach, and this only 16633 // drives a deprecation warning so doesn't affect conformance. 16634 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16635 if (BO->getOpcode() == BO_Assign) { 16636 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16637 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16638 LHSs.end()); 16639 } 16640 } 16641 } 16642 16643 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16644 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16645 RebuildingImmediateInvocation) 16646 return E; 16647 16648 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16649 /// It's OK if this fails; we'll also remove this in 16650 /// HandleImmediateInvocations, but catching it here allows us to avoid 16651 /// walking the AST looking for it in simple cases. 16652 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16653 if (auto *DeclRef = 16654 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16655 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16656 16657 E = MaybeCreateExprWithCleanups(E); 16658 16659 ConstantExpr *Res = ConstantExpr::Create( 16660 getASTContext(), E.get(), 16661 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16662 getASTContext()), 16663 /*IsImmediateInvocation*/ true); 16664 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16665 return Res; 16666 } 16667 16668 static void EvaluateAndDiagnoseImmediateInvocation( 16669 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16670 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16671 Expr::EvalResult Eval; 16672 Eval.Diag = &Notes; 16673 ConstantExpr *CE = Candidate.getPointer(); 16674 bool Result = CE->EvaluateAsConstantExpr( 16675 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16676 if (!Result || !Notes.empty()) { 16677 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16678 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16679 InnerExpr = FunctionalCast->getSubExpr(); 16680 FunctionDecl *FD = nullptr; 16681 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16682 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16683 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16684 FD = Call->getConstructor(); 16685 else 16686 llvm_unreachable("unhandled decl kind"); 16687 assert(FD->isConsteval()); 16688 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16689 for (auto &Note : Notes) 16690 SemaRef.Diag(Note.first, Note.second); 16691 return; 16692 } 16693 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16694 } 16695 16696 static void RemoveNestedImmediateInvocation( 16697 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16698 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16699 struct ComplexRemove : TreeTransform<ComplexRemove> { 16700 using Base = TreeTransform<ComplexRemove>; 16701 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16702 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16703 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16704 CurrentII; 16705 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16706 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16707 SmallVector<Sema::ImmediateInvocationCandidate, 16708 4>::reverse_iterator Current) 16709 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16710 void RemoveImmediateInvocation(ConstantExpr* E) { 16711 auto It = std::find_if(CurrentII, IISet.rend(), 16712 [E](Sema::ImmediateInvocationCandidate Elem) { 16713 return Elem.getPointer() == E; 16714 }); 16715 assert(It != IISet.rend() && 16716 "ConstantExpr marked IsImmediateInvocation should " 16717 "be present"); 16718 It->setInt(1); // Mark as deleted 16719 } 16720 ExprResult TransformConstantExpr(ConstantExpr *E) { 16721 if (!E->isImmediateInvocation()) 16722 return Base::TransformConstantExpr(E); 16723 RemoveImmediateInvocation(E); 16724 return Base::TransformExpr(E->getSubExpr()); 16725 } 16726 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16727 /// we need to remove its DeclRefExpr from the DRSet. 16728 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16729 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16730 return Base::TransformCXXOperatorCallExpr(E); 16731 } 16732 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16733 /// here. 16734 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16735 if (!Init) 16736 return Init; 16737 /// ConstantExpr are the first layer of implicit node to be removed so if 16738 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16739 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16740 if (CE->isImmediateInvocation()) 16741 RemoveImmediateInvocation(CE); 16742 return Base::TransformInitializer(Init, NotCopyInit); 16743 } 16744 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16745 DRSet.erase(E); 16746 return E; 16747 } 16748 bool AlwaysRebuild() { return false; } 16749 bool ReplacingOriginal() { return true; } 16750 bool AllowSkippingCXXConstructExpr() { 16751 bool Res = AllowSkippingFirstCXXConstructExpr; 16752 AllowSkippingFirstCXXConstructExpr = true; 16753 return Res; 16754 } 16755 bool AllowSkippingFirstCXXConstructExpr = true; 16756 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16757 Rec.ImmediateInvocationCandidates, It); 16758 16759 /// CXXConstructExpr with a single argument are getting skipped by 16760 /// TreeTransform in some situtation because they could be implicit. This 16761 /// can only occur for the top-level CXXConstructExpr because it is used 16762 /// nowhere in the expression being transformed therefore will not be rebuilt. 16763 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16764 /// skipping the first CXXConstructExpr. 16765 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16766 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16767 16768 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16769 assert(Res.isUsable()); 16770 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16771 It->getPointer()->setSubExpr(Res.get()); 16772 } 16773 16774 static void 16775 HandleImmediateInvocations(Sema &SemaRef, 16776 Sema::ExpressionEvaluationContextRecord &Rec) { 16777 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16778 Rec.ReferenceToConsteval.size() == 0) || 16779 SemaRef.RebuildingImmediateInvocation) 16780 return; 16781 16782 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16783 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16784 /// need to remove ReferenceToConsteval in the immediate invocation. 16785 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16786 16787 /// Prevent sema calls during the tree transform from adding pointers that 16788 /// are already in the sets. 16789 llvm::SaveAndRestore<bool> DisableIITracking( 16790 SemaRef.RebuildingImmediateInvocation, true); 16791 16792 /// Prevent diagnostic during tree transfrom as they are duplicates 16793 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16794 16795 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16796 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16797 if (!It->getInt()) 16798 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16799 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16800 Rec.ReferenceToConsteval.size()) { 16801 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16802 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16803 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16804 bool VisitDeclRefExpr(DeclRefExpr *E) { 16805 DRSet.erase(E); 16806 return DRSet.size(); 16807 } 16808 } Visitor(Rec.ReferenceToConsteval); 16809 Visitor.TraverseStmt( 16810 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16811 } 16812 for (auto CE : Rec.ImmediateInvocationCandidates) 16813 if (!CE.getInt()) 16814 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16815 for (auto DR : Rec.ReferenceToConsteval) { 16816 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16817 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16818 << FD; 16819 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16820 } 16821 } 16822 16823 void Sema::PopExpressionEvaluationContext() { 16824 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16825 unsigned NumTypos = Rec.NumTypos; 16826 16827 if (!Rec.Lambdas.empty()) { 16828 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16829 if (!getLangOpts().CPlusPlus20 && 16830 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16831 Rec.isUnevaluated() || 16832 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16833 unsigned D; 16834 if (Rec.isUnevaluated()) { 16835 // C++11 [expr.prim.lambda]p2: 16836 // A lambda-expression shall not appear in an unevaluated operand 16837 // (Clause 5). 16838 D = diag::err_lambda_unevaluated_operand; 16839 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16840 // C++1y [expr.const]p2: 16841 // A conditional-expression e is a core constant expression unless the 16842 // evaluation of e, following the rules of the abstract machine, would 16843 // evaluate [...] a lambda-expression. 16844 D = diag::err_lambda_in_constant_expression; 16845 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16846 // C++17 [expr.prim.lamda]p2: 16847 // A lambda-expression shall not appear [...] in a template-argument. 16848 D = diag::err_lambda_in_invalid_context; 16849 } else 16850 llvm_unreachable("Couldn't infer lambda error message."); 16851 16852 for (const auto *L : Rec.Lambdas) 16853 Diag(L->getBeginLoc(), D); 16854 } 16855 } 16856 16857 WarnOnPendingNoDerefs(Rec); 16858 HandleImmediateInvocations(*this, Rec); 16859 16860 // Warn on any volatile-qualified simple-assignments that are not discarded- 16861 // value expressions nor unevaluated operands (those cases get removed from 16862 // this list by CheckUnusedVolatileAssignment). 16863 for (auto *BO : Rec.VolatileAssignmentLHSs) 16864 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16865 << BO->getType(); 16866 16867 // When are coming out of an unevaluated context, clear out any 16868 // temporaries that we may have created as part of the evaluation of 16869 // the expression in that context: they aren't relevant because they 16870 // will never be constructed. 16871 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16872 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16873 ExprCleanupObjects.end()); 16874 Cleanup = Rec.ParentCleanup; 16875 CleanupVarDeclMarking(); 16876 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16877 // Otherwise, merge the contexts together. 16878 } else { 16879 Cleanup.mergeFrom(Rec.ParentCleanup); 16880 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16881 Rec.SavedMaybeODRUseExprs.end()); 16882 } 16883 16884 // Pop the current expression evaluation context off the stack. 16885 ExprEvalContexts.pop_back(); 16886 16887 // The global expression evaluation context record is never popped. 16888 ExprEvalContexts.back().NumTypos += NumTypos; 16889 } 16890 16891 void Sema::DiscardCleanupsInEvaluationContext() { 16892 ExprCleanupObjects.erase( 16893 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16894 ExprCleanupObjects.end()); 16895 Cleanup.reset(); 16896 MaybeODRUseExprs.clear(); 16897 } 16898 16899 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16900 ExprResult Result = CheckPlaceholderExpr(E); 16901 if (Result.isInvalid()) 16902 return ExprError(); 16903 E = Result.get(); 16904 if (!E->getType()->isVariablyModifiedType()) 16905 return E; 16906 return TransformToPotentiallyEvaluated(E); 16907 } 16908 16909 /// Are we in a context that is potentially constant evaluated per C++20 16910 /// [expr.const]p12? 16911 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16912 /// C++2a [expr.const]p12: 16913 // An expression or conversion is potentially constant evaluated if it is 16914 switch (SemaRef.ExprEvalContexts.back().Context) { 16915 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16916 // -- a manifestly constant-evaluated expression, 16917 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16918 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16919 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16920 // -- a potentially-evaluated expression, 16921 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16922 // -- an immediate subexpression of a braced-init-list, 16923 16924 // -- [FIXME] an expression of the form & cast-expression that occurs 16925 // within a templated entity 16926 // -- a subexpression of one of the above that is not a subexpression of 16927 // a nested unevaluated operand. 16928 return true; 16929 16930 case Sema::ExpressionEvaluationContext::Unevaluated: 16931 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16932 // Expressions in this context are never evaluated. 16933 return false; 16934 } 16935 llvm_unreachable("Invalid context"); 16936 } 16937 16938 /// Return true if this function has a calling convention that requires mangling 16939 /// in the size of the parameter pack. 16940 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16941 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16942 // we don't need parameter type sizes. 16943 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16944 if (!TT.isOSWindows() || !TT.isX86()) 16945 return false; 16946 16947 // If this is C++ and this isn't an extern "C" function, parameters do not 16948 // need to be complete. In this case, C++ mangling will apply, which doesn't 16949 // use the size of the parameters. 16950 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16951 return false; 16952 16953 // Stdcall, fastcall, and vectorcall need this special treatment. 16954 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16955 switch (CC) { 16956 case CC_X86StdCall: 16957 case CC_X86FastCall: 16958 case CC_X86VectorCall: 16959 return true; 16960 default: 16961 break; 16962 } 16963 return false; 16964 } 16965 16966 /// Require that all of the parameter types of function be complete. Normally, 16967 /// parameter types are only required to be complete when a function is called 16968 /// or defined, but to mangle functions with certain calling conventions, the 16969 /// mangler needs to know the size of the parameter list. In this situation, 16970 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16971 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16972 /// result in a linker error. Clang doesn't implement this behavior, and instead 16973 /// attempts to error at compile time. 16974 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16975 SourceLocation Loc) { 16976 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16977 FunctionDecl *FD; 16978 ParmVarDecl *Param; 16979 16980 public: 16981 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16982 : FD(FD), Param(Param) {} 16983 16984 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16985 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16986 StringRef CCName; 16987 switch (CC) { 16988 case CC_X86StdCall: 16989 CCName = "stdcall"; 16990 break; 16991 case CC_X86FastCall: 16992 CCName = "fastcall"; 16993 break; 16994 case CC_X86VectorCall: 16995 CCName = "vectorcall"; 16996 break; 16997 default: 16998 llvm_unreachable("CC does not need mangling"); 16999 } 17000 17001 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17002 << Param->getDeclName() << FD->getDeclName() << CCName; 17003 } 17004 }; 17005 17006 for (ParmVarDecl *Param : FD->parameters()) { 17007 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17008 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17009 } 17010 } 17011 17012 namespace { 17013 enum class OdrUseContext { 17014 /// Declarations in this context are not odr-used. 17015 None, 17016 /// Declarations in this context are formally odr-used, but this is a 17017 /// dependent context. 17018 Dependent, 17019 /// Declarations in this context are odr-used but not actually used (yet). 17020 FormallyOdrUsed, 17021 /// Declarations in this context are used. 17022 Used 17023 }; 17024 } 17025 17026 /// Are we within a context in which references to resolved functions or to 17027 /// variables result in odr-use? 17028 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17029 OdrUseContext Result; 17030 17031 switch (SemaRef.ExprEvalContexts.back().Context) { 17032 case Sema::ExpressionEvaluationContext::Unevaluated: 17033 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17034 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17035 return OdrUseContext::None; 17036 17037 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17038 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17039 Result = OdrUseContext::Used; 17040 break; 17041 17042 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17043 Result = OdrUseContext::FormallyOdrUsed; 17044 break; 17045 17046 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17047 // A default argument formally results in odr-use, but doesn't actually 17048 // result in a use in any real sense until it itself is used. 17049 Result = OdrUseContext::FormallyOdrUsed; 17050 break; 17051 } 17052 17053 if (SemaRef.CurContext->isDependentContext()) 17054 return OdrUseContext::Dependent; 17055 17056 return Result; 17057 } 17058 17059 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17060 if (!Func->isConstexpr()) 17061 return false; 17062 17063 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17064 return true; 17065 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17066 return CCD && CCD->getInheritedConstructor(); 17067 } 17068 17069 /// Mark a function referenced, and check whether it is odr-used 17070 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17071 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17072 bool MightBeOdrUse) { 17073 assert(Func && "No function?"); 17074 17075 Func->setReferenced(); 17076 17077 // Recursive functions aren't really used until they're used from some other 17078 // context. 17079 bool IsRecursiveCall = CurContext == Func; 17080 17081 // C++11 [basic.def.odr]p3: 17082 // A function whose name appears as a potentially-evaluated expression is 17083 // odr-used if it is the unique lookup result or the selected member of a 17084 // set of overloaded functions [...]. 17085 // 17086 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17087 // can just check that here. 17088 OdrUseContext OdrUse = 17089 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17090 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17091 OdrUse = OdrUseContext::FormallyOdrUsed; 17092 17093 // Trivial default constructors and destructors are never actually used. 17094 // FIXME: What about other special members? 17095 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17096 OdrUse == OdrUseContext::Used) { 17097 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17098 if (Constructor->isDefaultConstructor()) 17099 OdrUse = OdrUseContext::FormallyOdrUsed; 17100 if (isa<CXXDestructorDecl>(Func)) 17101 OdrUse = OdrUseContext::FormallyOdrUsed; 17102 } 17103 17104 // C++20 [expr.const]p12: 17105 // A function [...] is needed for constant evaluation if it is [...] a 17106 // constexpr function that is named by an expression that is potentially 17107 // constant evaluated 17108 bool NeededForConstantEvaluation = 17109 isPotentiallyConstantEvaluatedContext(*this) && 17110 isImplicitlyDefinableConstexprFunction(Func); 17111 17112 // Determine whether we require a function definition to exist, per 17113 // C++11 [temp.inst]p3: 17114 // Unless a function template specialization has been explicitly 17115 // instantiated or explicitly specialized, the function template 17116 // specialization is implicitly instantiated when the specialization is 17117 // referenced in a context that requires a function definition to exist. 17118 // C++20 [temp.inst]p7: 17119 // The existence of a definition of a [...] function is considered to 17120 // affect the semantics of the program if the [...] function is needed for 17121 // constant evaluation by an expression 17122 // C++20 [basic.def.odr]p10: 17123 // Every program shall contain exactly one definition of every non-inline 17124 // function or variable that is odr-used in that program outside of a 17125 // discarded statement 17126 // C++20 [special]p1: 17127 // The implementation will implicitly define [defaulted special members] 17128 // if they are odr-used or needed for constant evaluation. 17129 // 17130 // Note that we skip the implicit instantiation of templates that are only 17131 // used in unused default arguments or by recursive calls to themselves. 17132 // This is formally non-conforming, but seems reasonable in practice. 17133 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17134 NeededForConstantEvaluation); 17135 17136 // C++14 [temp.expl.spec]p6: 17137 // If a template [...] is explicitly specialized then that specialization 17138 // shall be declared before the first use of that specialization that would 17139 // cause an implicit instantiation to take place, in every translation unit 17140 // in which such a use occurs 17141 if (NeedDefinition && 17142 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17143 Func->getMemberSpecializationInfo())) 17144 checkSpecializationVisibility(Loc, Func); 17145 17146 if (getLangOpts().CUDA) 17147 CheckCUDACall(Loc, Func); 17148 17149 if (getLangOpts().SYCLIsDevice) 17150 checkSYCLDeviceFunction(Loc, Func); 17151 17152 // If we need a definition, try to create one. 17153 if (NeedDefinition && !Func->getBody()) { 17154 runWithSufficientStackSpace(Loc, [&] { 17155 if (CXXConstructorDecl *Constructor = 17156 dyn_cast<CXXConstructorDecl>(Func)) { 17157 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17158 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17159 if (Constructor->isDefaultConstructor()) { 17160 if (Constructor->isTrivial() && 17161 !Constructor->hasAttr<DLLExportAttr>()) 17162 return; 17163 DefineImplicitDefaultConstructor(Loc, Constructor); 17164 } else if (Constructor->isCopyConstructor()) { 17165 DefineImplicitCopyConstructor(Loc, Constructor); 17166 } else if (Constructor->isMoveConstructor()) { 17167 DefineImplicitMoveConstructor(Loc, Constructor); 17168 } 17169 } else if (Constructor->getInheritedConstructor()) { 17170 DefineInheritingConstructor(Loc, Constructor); 17171 } 17172 } else if (CXXDestructorDecl *Destructor = 17173 dyn_cast<CXXDestructorDecl>(Func)) { 17174 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17175 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17176 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17177 return; 17178 DefineImplicitDestructor(Loc, Destructor); 17179 } 17180 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17181 MarkVTableUsed(Loc, Destructor->getParent()); 17182 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17183 if (MethodDecl->isOverloadedOperator() && 17184 MethodDecl->getOverloadedOperator() == OO_Equal) { 17185 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17186 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17187 if (MethodDecl->isCopyAssignmentOperator()) 17188 DefineImplicitCopyAssignment(Loc, MethodDecl); 17189 else if (MethodDecl->isMoveAssignmentOperator()) 17190 DefineImplicitMoveAssignment(Loc, MethodDecl); 17191 } 17192 } else if (isa<CXXConversionDecl>(MethodDecl) && 17193 MethodDecl->getParent()->isLambda()) { 17194 CXXConversionDecl *Conversion = 17195 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17196 if (Conversion->isLambdaToBlockPointerConversion()) 17197 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17198 else 17199 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17200 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17201 MarkVTableUsed(Loc, MethodDecl->getParent()); 17202 } 17203 17204 if (Func->isDefaulted() && !Func->isDeleted()) { 17205 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17206 if (DCK != DefaultedComparisonKind::None) 17207 DefineDefaultedComparison(Loc, Func, DCK); 17208 } 17209 17210 // Implicit instantiation of function templates and member functions of 17211 // class templates. 17212 if (Func->isImplicitlyInstantiable()) { 17213 TemplateSpecializationKind TSK = 17214 Func->getTemplateSpecializationKindForInstantiation(); 17215 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17216 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17217 if (FirstInstantiation) { 17218 PointOfInstantiation = Loc; 17219 if (auto *MSI = Func->getMemberSpecializationInfo()) 17220 MSI->setPointOfInstantiation(Loc); 17221 // FIXME: Notify listener. 17222 else 17223 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17224 } else if (TSK != TSK_ImplicitInstantiation) { 17225 // Use the point of use as the point of instantiation, instead of the 17226 // point of explicit instantiation (which we track as the actual point 17227 // of instantiation). This gives better backtraces in diagnostics. 17228 PointOfInstantiation = Loc; 17229 } 17230 17231 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17232 Func->isConstexpr()) { 17233 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17234 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17235 CodeSynthesisContexts.size()) 17236 PendingLocalImplicitInstantiations.push_back( 17237 std::make_pair(Func, PointOfInstantiation)); 17238 else if (Func->isConstexpr()) 17239 // Do not defer instantiations of constexpr functions, to avoid the 17240 // expression evaluator needing to call back into Sema if it sees a 17241 // call to such a function. 17242 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17243 else { 17244 Func->setInstantiationIsPending(true); 17245 PendingInstantiations.push_back( 17246 std::make_pair(Func, PointOfInstantiation)); 17247 // Notify the consumer that a function was implicitly instantiated. 17248 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17249 } 17250 } 17251 } else { 17252 // Walk redefinitions, as some of them may be instantiable. 17253 for (auto i : Func->redecls()) { 17254 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17255 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17256 } 17257 } 17258 }); 17259 } 17260 17261 // C++14 [except.spec]p17: 17262 // An exception-specification is considered to be needed when: 17263 // - the function is odr-used or, if it appears in an unevaluated operand, 17264 // would be odr-used if the expression were potentially-evaluated; 17265 // 17266 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17267 // function is a pure virtual function we're calling, and in that case the 17268 // function was selected by overload resolution and we need to resolve its 17269 // exception specification for a different reason. 17270 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17271 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17272 ResolveExceptionSpec(Loc, FPT); 17273 17274 // If this is the first "real" use, act on that. 17275 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17276 // Keep track of used but undefined functions. 17277 if (!Func->isDefined()) { 17278 if (mightHaveNonExternalLinkage(Func)) 17279 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17280 else if (Func->getMostRecentDecl()->isInlined() && 17281 !LangOpts.GNUInline && 17282 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17283 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17284 else if (isExternalWithNoLinkageType(Func)) 17285 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17286 } 17287 17288 // Some x86 Windows calling conventions mangle the size of the parameter 17289 // pack into the name. Computing the size of the parameters requires the 17290 // parameter types to be complete. Check that now. 17291 if (funcHasParameterSizeMangling(*this, Func)) 17292 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17293 17294 // In the MS C++ ABI, the compiler emits destructor variants where they are 17295 // used. If the destructor is used here but defined elsewhere, mark the 17296 // virtual base destructors referenced. If those virtual base destructors 17297 // are inline, this will ensure they are defined when emitting the complete 17298 // destructor variant. This checking may be redundant if the destructor is 17299 // provided later in this TU. 17300 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17301 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17302 CXXRecordDecl *Parent = Dtor->getParent(); 17303 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17304 CheckCompleteDestructorVariant(Loc, Dtor); 17305 } 17306 } 17307 17308 Func->markUsed(Context); 17309 } 17310 } 17311 17312 /// Directly mark a variable odr-used. Given a choice, prefer to use 17313 /// MarkVariableReferenced since it does additional checks and then 17314 /// calls MarkVarDeclODRUsed. 17315 /// If the variable must be captured: 17316 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17317 /// - else capture it in the DeclContext that maps to the 17318 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17319 static void 17320 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17321 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17322 // Keep track of used but undefined variables. 17323 // FIXME: We shouldn't suppress this warning for static data members. 17324 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17325 (!Var->isExternallyVisible() || Var->isInline() || 17326 SemaRef.isExternalWithNoLinkageType(Var)) && 17327 !(Var->isStaticDataMember() && Var->hasInit())) { 17328 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17329 if (old.isInvalid()) 17330 old = Loc; 17331 } 17332 QualType CaptureType, DeclRefType; 17333 if (SemaRef.LangOpts.OpenMP) 17334 SemaRef.tryCaptureOpenMPLambdas(Var); 17335 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17336 /*EllipsisLoc*/ SourceLocation(), 17337 /*BuildAndDiagnose*/ true, 17338 CaptureType, DeclRefType, 17339 FunctionScopeIndexToStopAt); 17340 17341 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17342 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17343 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17344 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17345 if (VarTarget == Sema::CVT_Host && 17346 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17347 UserTarget == Sema::CFT_Global)) { 17348 // Diagnose ODR-use of host global variables in device functions. 17349 // Reference of device global variables in host functions is allowed 17350 // through shadow variables therefore it is not diagnosed. 17351 if (SemaRef.LangOpts.CUDAIsDevice) { 17352 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17353 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17354 SemaRef.targetDiag(Var->getLocation(), 17355 Var->getType().isConstQualified() 17356 ? diag::note_cuda_const_var_unpromoted 17357 : diag::note_cuda_host_var); 17358 } 17359 } else if (VarTarget == Sema::CVT_Device && 17360 (UserTarget == Sema::CFT_Host || 17361 UserTarget == Sema::CFT_HostDevice) && 17362 !Var->hasExternalStorage()) { 17363 // Record a CUDA/HIP device side variable if it is ODR-used 17364 // by host code. This is done conservatively, when the variable is 17365 // referenced in any of the following contexts: 17366 // - a non-function context 17367 // - a host function 17368 // - a host device function 17369 // This makes the ODR-use of the device side variable by host code to 17370 // be visible in the device compilation for the compiler to be able to 17371 // emit template variables instantiated by host code only and to 17372 // externalize the static device side variable ODR-used by host code. 17373 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17374 } 17375 } 17376 17377 Var->markUsed(SemaRef.Context); 17378 } 17379 17380 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17381 SourceLocation Loc, 17382 unsigned CapturingScopeIndex) { 17383 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17384 } 17385 17386 static void 17387 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17388 ValueDecl *var, DeclContext *DC) { 17389 DeclContext *VarDC = var->getDeclContext(); 17390 17391 // If the parameter still belongs to the translation unit, then 17392 // we're actually just using one parameter in the declaration of 17393 // the next. 17394 if (isa<ParmVarDecl>(var) && 17395 isa<TranslationUnitDecl>(VarDC)) 17396 return; 17397 17398 // For C code, don't diagnose about capture if we're not actually in code 17399 // right now; it's impossible to write a non-constant expression outside of 17400 // function context, so we'll get other (more useful) diagnostics later. 17401 // 17402 // For C++, things get a bit more nasty... it would be nice to suppress this 17403 // diagnostic for certain cases like using a local variable in an array bound 17404 // for a member of a local class, but the correct predicate is not obvious. 17405 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17406 return; 17407 17408 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17409 unsigned ContextKind = 3; // unknown 17410 if (isa<CXXMethodDecl>(VarDC) && 17411 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17412 ContextKind = 2; 17413 } else if (isa<FunctionDecl>(VarDC)) { 17414 ContextKind = 0; 17415 } else if (isa<BlockDecl>(VarDC)) { 17416 ContextKind = 1; 17417 } 17418 17419 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17420 << var << ValueKind << ContextKind << VarDC; 17421 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17422 << var; 17423 17424 // FIXME: Add additional diagnostic info about class etc. which prevents 17425 // capture. 17426 } 17427 17428 17429 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17430 bool &SubCapturesAreNested, 17431 QualType &CaptureType, 17432 QualType &DeclRefType) { 17433 // Check whether we've already captured it. 17434 if (CSI->CaptureMap.count(Var)) { 17435 // If we found a capture, any subcaptures are nested. 17436 SubCapturesAreNested = true; 17437 17438 // Retrieve the capture type for this variable. 17439 CaptureType = CSI->getCapture(Var).getCaptureType(); 17440 17441 // Compute the type of an expression that refers to this variable. 17442 DeclRefType = CaptureType.getNonReferenceType(); 17443 17444 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17445 // are mutable in the sense that user can change their value - they are 17446 // private instances of the captured declarations. 17447 const Capture &Cap = CSI->getCapture(Var); 17448 if (Cap.isCopyCapture() && 17449 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17450 !(isa<CapturedRegionScopeInfo>(CSI) && 17451 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17452 DeclRefType.addConst(); 17453 return true; 17454 } 17455 return false; 17456 } 17457 17458 // Only block literals, captured statements, and lambda expressions can 17459 // capture; other scopes don't work. 17460 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17461 SourceLocation Loc, 17462 const bool Diagnose, Sema &S) { 17463 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17464 return getLambdaAwareParentOfDeclContext(DC); 17465 else if (Var->hasLocalStorage()) { 17466 if (Diagnose) 17467 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17468 } 17469 return nullptr; 17470 } 17471 17472 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17473 // certain types of variables (unnamed, variably modified types etc.) 17474 // so check for eligibility. 17475 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17476 SourceLocation Loc, 17477 const bool Diagnose, Sema &S) { 17478 17479 bool IsBlock = isa<BlockScopeInfo>(CSI); 17480 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17481 17482 // Lambdas are not allowed to capture unnamed variables 17483 // (e.g. anonymous unions). 17484 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17485 // assuming that's the intent. 17486 if (IsLambda && !Var->getDeclName()) { 17487 if (Diagnose) { 17488 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17489 S.Diag(Var->getLocation(), diag::note_declared_at); 17490 } 17491 return false; 17492 } 17493 17494 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17495 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17496 if (Diagnose) { 17497 S.Diag(Loc, diag::err_ref_vm_type); 17498 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17499 } 17500 return false; 17501 } 17502 // Prohibit structs with flexible array members too. 17503 // We cannot capture what is in the tail end of the struct. 17504 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17505 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17506 if (Diagnose) { 17507 if (IsBlock) 17508 S.Diag(Loc, diag::err_ref_flexarray_type); 17509 else 17510 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17511 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17512 } 17513 return false; 17514 } 17515 } 17516 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17517 // Lambdas and captured statements are not allowed to capture __block 17518 // variables; they don't support the expected semantics. 17519 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17520 if (Diagnose) { 17521 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17522 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17523 } 17524 return false; 17525 } 17526 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17527 if (S.getLangOpts().OpenCL && IsBlock && 17528 Var->getType()->isBlockPointerType()) { 17529 if (Diagnose) 17530 S.Diag(Loc, diag::err_opencl_block_ref_block); 17531 return false; 17532 } 17533 17534 return true; 17535 } 17536 17537 // Returns true if the capture by block was successful. 17538 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17539 SourceLocation Loc, 17540 const bool BuildAndDiagnose, 17541 QualType &CaptureType, 17542 QualType &DeclRefType, 17543 const bool Nested, 17544 Sema &S, bool Invalid) { 17545 bool ByRef = false; 17546 17547 // Blocks are not allowed to capture arrays, excepting OpenCL. 17548 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17549 // (decayed to pointers). 17550 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17551 if (BuildAndDiagnose) { 17552 S.Diag(Loc, diag::err_ref_array_type); 17553 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17554 Invalid = true; 17555 } else { 17556 return false; 17557 } 17558 } 17559 17560 // Forbid the block-capture of autoreleasing variables. 17561 if (!Invalid && 17562 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17563 if (BuildAndDiagnose) { 17564 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17565 << /*block*/ 0; 17566 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17567 Invalid = true; 17568 } else { 17569 return false; 17570 } 17571 } 17572 17573 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17574 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17575 QualType PointeeTy = PT->getPointeeType(); 17576 17577 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17578 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17579 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17580 if (BuildAndDiagnose) { 17581 SourceLocation VarLoc = Var->getLocation(); 17582 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17583 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17584 } 17585 } 17586 } 17587 17588 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17589 if (HasBlocksAttr || CaptureType->isReferenceType() || 17590 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17591 // Block capture by reference does not change the capture or 17592 // declaration reference types. 17593 ByRef = true; 17594 } else { 17595 // Block capture by copy introduces 'const'. 17596 CaptureType = CaptureType.getNonReferenceType().withConst(); 17597 DeclRefType = CaptureType; 17598 } 17599 17600 // Actually capture the variable. 17601 if (BuildAndDiagnose) 17602 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17603 CaptureType, Invalid); 17604 17605 return !Invalid; 17606 } 17607 17608 17609 /// Capture the given variable in the captured region. 17610 static bool captureInCapturedRegion( 17611 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17612 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17613 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17614 bool IsTopScope, Sema &S, bool Invalid) { 17615 // By default, capture variables by reference. 17616 bool ByRef = true; 17617 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17618 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17619 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17620 // Using an LValue reference type is consistent with Lambdas (see below). 17621 if (S.isOpenMPCapturedDecl(Var)) { 17622 bool HasConst = DeclRefType.isConstQualified(); 17623 DeclRefType = DeclRefType.getUnqualifiedType(); 17624 // Don't lose diagnostics about assignments to const. 17625 if (HasConst) 17626 DeclRefType.addConst(); 17627 } 17628 // Do not capture firstprivates in tasks. 17629 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17630 OMPC_unknown) 17631 return true; 17632 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17633 RSI->OpenMPCaptureLevel); 17634 } 17635 17636 if (ByRef) 17637 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17638 else 17639 CaptureType = DeclRefType; 17640 17641 // Actually capture the variable. 17642 if (BuildAndDiagnose) 17643 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17644 Loc, SourceLocation(), CaptureType, Invalid); 17645 17646 return !Invalid; 17647 } 17648 17649 /// Capture the given variable in the lambda. 17650 static bool captureInLambda(LambdaScopeInfo *LSI, 17651 VarDecl *Var, 17652 SourceLocation Loc, 17653 const bool BuildAndDiagnose, 17654 QualType &CaptureType, 17655 QualType &DeclRefType, 17656 const bool RefersToCapturedVariable, 17657 const Sema::TryCaptureKind Kind, 17658 SourceLocation EllipsisLoc, 17659 const bool IsTopScope, 17660 Sema &S, bool Invalid) { 17661 // Determine whether we are capturing by reference or by value. 17662 bool ByRef = false; 17663 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17664 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17665 } else { 17666 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17667 } 17668 17669 // Compute the type of the field that will capture this variable. 17670 if (ByRef) { 17671 // C++11 [expr.prim.lambda]p15: 17672 // An entity is captured by reference if it is implicitly or 17673 // explicitly captured but not captured by copy. It is 17674 // unspecified whether additional unnamed non-static data 17675 // members are declared in the closure type for entities 17676 // captured by reference. 17677 // 17678 // FIXME: It is not clear whether we want to build an lvalue reference 17679 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17680 // to do the former, while EDG does the latter. Core issue 1249 will 17681 // clarify, but for now we follow GCC because it's a more permissive and 17682 // easily defensible position. 17683 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17684 } else { 17685 // C++11 [expr.prim.lambda]p14: 17686 // For each entity captured by copy, an unnamed non-static 17687 // data member is declared in the closure type. The 17688 // declaration order of these members is unspecified. The type 17689 // of such a data member is the type of the corresponding 17690 // captured entity if the entity is not a reference to an 17691 // object, or the referenced type otherwise. [Note: If the 17692 // captured entity is a reference to a function, the 17693 // corresponding data member is also a reference to a 17694 // function. - end note ] 17695 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17696 if (!RefType->getPointeeType()->isFunctionType()) 17697 CaptureType = RefType->getPointeeType(); 17698 } 17699 17700 // Forbid the lambda copy-capture of autoreleasing variables. 17701 if (!Invalid && 17702 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17703 if (BuildAndDiagnose) { 17704 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17705 S.Diag(Var->getLocation(), diag::note_previous_decl) 17706 << Var->getDeclName(); 17707 Invalid = true; 17708 } else { 17709 return false; 17710 } 17711 } 17712 17713 // Make sure that by-copy captures are of a complete and non-abstract type. 17714 if (!Invalid && BuildAndDiagnose) { 17715 if (!CaptureType->isDependentType() && 17716 S.RequireCompleteSizedType( 17717 Loc, CaptureType, 17718 diag::err_capture_of_incomplete_or_sizeless_type, 17719 Var->getDeclName())) 17720 Invalid = true; 17721 else if (S.RequireNonAbstractType(Loc, CaptureType, 17722 diag::err_capture_of_abstract_type)) 17723 Invalid = true; 17724 } 17725 } 17726 17727 // Compute the type of a reference to this captured variable. 17728 if (ByRef) 17729 DeclRefType = CaptureType.getNonReferenceType(); 17730 else { 17731 // C++ [expr.prim.lambda]p5: 17732 // The closure type for a lambda-expression has a public inline 17733 // function call operator [...]. This function call operator is 17734 // declared const (9.3.1) if and only if the lambda-expression's 17735 // parameter-declaration-clause is not followed by mutable. 17736 DeclRefType = CaptureType.getNonReferenceType(); 17737 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17738 DeclRefType.addConst(); 17739 } 17740 17741 // Add the capture. 17742 if (BuildAndDiagnose) 17743 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17744 Loc, EllipsisLoc, CaptureType, Invalid); 17745 17746 return !Invalid; 17747 } 17748 17749 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17750 // Offer a Copy fix even if the type is dependent. 17751 if (Var->getType()->isDependentType()) 17752 return true; 17753 QualType T = Var->getType().getNonReferenceType(); 17754 if (T.isTriviallyCopyableType(Context)) 17755 return true; 17756 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17757 17758 if (!(RD = RD->getDefinition())) 17759 return false; 17760 if (RD->hasSimpleCopyConstructor()) 17761 return true; 17762 if (RD->hasUserDeclaredCopyConstructor()) 17763 for (CXXConstructorDecl *Ctor : RD->ctors()) 17764 if (Ctor->isCopyConstructor()) 17765 return !Ctor->isDeleted(); 17766 } 17767 return false; 17768 } 17769 17770 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17771 /// default capture. Fixes may be omitted if they aren't allowed by the 17772 /// standard, for example we can't emit a default copy capture fix-it if we 17773 /// already explicitly copy capture capture another variable. 17774 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17775 VarDecl *Var) { 17776 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17777 // Don't offer Capture by copy of default capture by copy fixes if Var is 17778 // known not to be copy constructible. 17779 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17780 17781 SmallString<32> FixBuffer; 17782 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17783 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17784 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17785 if (ShouldOfferCopyFix) { 17786 // Offer fixes to insert an explicit capture for the variable. 17787 // [] -> [VarName] 17788 // [OtherCapture] -> [OtherCapture, VarName] 17789 FixBuffer.assign({Separator, Var->getName()}); 17790 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17791 << Var << /*value*/ 0 17792 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17793 } 17794 // As above but capture by reference. 17795 FixBuffer.assign({Separator, "&", Var->getName()}); 17796 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17797 << Var << /*reference*/ 1 17798 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17799 } 17800 17801 // Only try to offer default capture if there are no captures excluding this 17802 // and init captures. 17803 // [this]: OK. 17804 // [X = Y]: OK. 17805 // [&A, &B]: Don't offer. 17806 // [A, B]: Don't offer. 17807 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17808 return !C.isThisCapture() && !C.isInitCapture(); 17809 })) 17810 return; 17811 17812 // The default capture specifiers, '=' or '&', must appear first in the 17813 // capture body. 17814 SourceLocation DefaultInsertLoc = 17815 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17816 17817 if (ShouldOfferCopyFix) { 17818 bool CanDefaultCopyCapture = true; 17819 // [=, *this] OK since c++17 17820 // [=, this] OK since c++20 17821 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17822 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17823 ? LSI->getCXXThisCapture().isCopyCapture() 17824 : false; 17825 // We can't use default capture by copy if any captures already specified 17826 // capture by copy. 17827 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17828 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17829 })) { 17830 FixBuffer.assign({"=", Separator}); 17831 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17832 << /*value*/ 0 17833 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17834 } 17835 } 17836 17837 // We can't use default capture by reference if any captures already specified 17838 // capture by reference. 17839 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17840 return !C.isInitCapture() && C.isReferenceCapture() && 17841 !C.isThisCapture(); 17842 })) { 17843 FixBuffer.assign({"&", Separator}); 17844 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17845 << /*reference*/ 1 17846 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17847 } 17848 } 17849 17850 bool Sema::tryCaptureVariable( 17851 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17852 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17853 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17854 // An init-capture is notionally from the context surrounding its 17855 // declaration, but its parent DC is the lambda class. 17856 DeclContext *VarDC = Var->getDeclContext(); 17857 if (Var->isInitCapture()) 17858 VarDC = VarDC->getParent(); 17859 17860 DeclContext *DC = CurContext; 17861 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17862 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17863 // We need to sync up the Declaration Context with the 17864 // FunctionScopeIndexToStopAt 17865 if (FunctionScopeIndexToStopAt) { 17866 unsigned FSIndex = FunctionScopes.size() - 1; 17867 while (FSIndex != MaxFunctionScopesIndex) { 17868 DC = getLambdaAwareParentOfDeclContext(DC); 17869 --FSIndex; 17870 } 17871 } 17872 17873 17874 // If the variable is declared in the current context, there is no need to 17875 // capture it. 17876 if (VarDC == DC) return true; 17877 17878 // Capture global variables if it is required to use private copy of this 17879 // variable. 17880 bool IsGlobal = !Var->hasLocalStorage(); 17881 if (IsGlobal && 17882 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17883 MaxFunctionScopesIndex))) 17884 return true; 17885 Var = Var->getCanonicalDecl(); 17886 17887 // Walk up the stack to determine whether we can capture the variable, 17888 // performing the "simple" checks that don't depend on type. We stop when 17889 // we've either hit the declared scope of the variable or find an existing 17890 // capture of that variable. We start from the innermost capturing-entity 17891 // (the DC) and ensure that all intervening capturing-entities 17892 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17893 // declcontext can either capture the variable or have already captured 17894 // the variable. 17895 CaptureType = Var->getType(); 17896 DeclRefType = CaptureType.getNonReferenceType(); 17897 bool Nested = false; 17898 bool Explicit = (Kind != TryCapture_Implicit); 17899 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17900 do { 17901 // Only block literals, captured statements, and lambda expressions can 17902 // capture; other scopes don't work. 17903 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17904 ExprLoc, 17905 BuildAndDiagnose, 17906 *this); 17907 // We need to check for the parent *first* because, if we *have* 17908 // private-captured a global variable, we need to recursively capture it in 17909 // intermediate blocks, lambdas, etc. 17910 if (!ParentDC) { 17911 if (IsGlobal) { 17912 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17913 break; 17914 } 17915 return true; 17916 } 17917 17918 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17919 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17920 17921 17922 // Check whether we've already captured it. 17923 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17924 DeclRefType)) { 17925 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17926 break; 17927 } 17928 // If we are instantiating a generic lambda call operator body, 17929 // we do not want to capture new variables. What was captured 17930 // during either a lambdas transformation or initial parsing 17931 // should be used. 17932 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17933 if (BuildAndDiagnose) { 17934 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17935 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17936 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17937 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17938 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17939 buildLambdaCaptureFixit(*this, LSI, Var); 17940 } else 17941 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17942 } 17943 return true; 17944 } 17945 17946 // Try to capture variable-length arrays types. 17947 if (Var->getType()->isVariablyModifiedType()) { 17948 // We're going to walk down into the type and look for VLA 17949 // expressions. 17950 QualType QTy = Var->getType(); 17951 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17952 QTy = PVD->getOriginalType(); 17953 captureVariablyModifiedType(Context, QTy, CSI); 17954 } 17955 17956 if (getLangOpts().OpenMP) { 17957 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17958 // OpenMP private variables should not be captured in outer scope, so 17959 // just break here. Similarly, global variables that are captured in a 17960 // target region should not be captured outside the scope of the region. 17961 if (RSI->CapRegionKind == CR_OpenMP) { 17962 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17963 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17964 // If the variable is private (i.e. not captured) and has variably 17965 // modified type, we still need to capture the type for correct 17966 // codegen in all regions, associated with the construct. Currently, 17967 // it is captured in the innermost captured region only. 17968 if (IsOpenMPPrivateDecl != OMPC_unknown && 17969 Var->getType()->isVariablyModifiedType()) { 17970 QualType QTy = Var->getType(); 17971 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17972 QTy = PVD->getOriginalType(); 17973 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17974 I < E; ++I) { 17975 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17976 FunctionScopes[FunctionScopesIndex - I]); 17977 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17978 "Wrong number of captured regions associated with the " 17979 "OpenMP construct."); 17980 captureVariablyModifiedType(Context, QTy, OuterRSI); 17981 } 17982 } 17983 bool IsTargetCap = 17984 IsOpenMPPrivateDecl != OMPC_private && 17985 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17986 RSI->OpenMPCaptureLevel); 17987 // Do not capture global if it is not privatized in outer regions. 17988 bool IsGlobalCap = 17989 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17990 RSI->OpenMPCaptureLevel); 17991 17992 // When we detect target captures we are looking from inside the 17993 // target region, therefore we need to propagate the capture from the 17994 // enclosing region. Therefore, the capture is not initially nested. 17995 if (IsTargetCap) 17996 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17997 17998 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17999 (IsGlobal && !IsGlobalCap)) { 18000 Nested = !IsTargetCap; 18001 bool HasConst = DeclRefType.isConstQualified(); 18002 DeclRefType = DeclRefType.getUnqualifiedType(); 18003 // Don't lose diagnostics about assignments to const. 18004 if (HasConst) 18005 DeclRefType.addConst(); 18006 CaptureType = Context.getLValueReferenceType(DeclRefType); 18007 break; 18008 } 18009 } 18010 } 18011 } 18012 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18013 // No capture-default, and this is not an explicit capture 18014 // so cannot capture this variable. 18015 if (BuildAndDiagnose) { 18016 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18017 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18018 auto *LSI = cast<LambdaScopeInfo>(CSI); 18019 if (LSI->Lambda) { 18020 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18021 buildLambdaCaptureFixit(*this, LSI, Var); 18022 } 18023 // FIXME: If we error out because an outer lambda can not implicitly 18024 // capture a variable that an inner lambda explicitly captures, we 18025 // should have the inner lambda do the explicit capture - because 18026 // it makes for cleaner diagnostics later. This would purely be done 18027 // so that the diagnostic does not misleadingly claim that a variable 18028 // can not be captured by a lambda implicitly even though it is captured 18029 // explicitly. Suggestion: 18030 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18031 // at the function head 18032 // - cache the StartingDeclContext - this must be a lambda 18033 // - captureInLambda in the innermost lambda the variable. 18034 } 18035 return true; 18036 } 18037 18038 FunctionScopesIndex--; 18039 DC = ParentDC; 18040 Explicit = false; 18041 } while (!VarDC->Equals(DC)); 18042 18043 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18044 // computing the type of the capture at each step, checking type-specific 18045 // requirements, and adding captures if requested. 18046 // If the variable had already been captured previously, we start capturing 18047 // at the lambda nested within that one. 18048 bool Invalid = false; 18049 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18050 ++I) { 18051 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18052 18053 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18054 // certain types of variables (unnamed, variably modified types etc.) 18055 // so check for eligibility. 18056 if (!Invalid) 18057 Invalid = 18058 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18059 18060 // After encountering an error, if we're actually supposed to capture, keep 18061 // capturing in nested contexts to suppress any follow-on diagnostics. 18062 if (Invalid && !BuildAndDiagnose) 18063 return true; 18064 18065 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18066 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18067 DeclRefType, Nested, *this, Invalid); 18068 Nested = true; 18069 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18070 Invalid = !captureInCapturedRegion( 18071 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18072 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18073 Nested = true; 18074 } else { 18075 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18076 Invalid = 18077 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18078 DeclRefType, Nested, Kind, EllipsisLoc, 18079 /*IsTopScope*/ I == N - 1, *this, Invalid); 18080 Nested = true; 18081 } 18082 18083 if (Invalid && !BuildAndDiagnose) 18084 return true; 18085 } 18086 return Invalid; 18087 } 18088 18089 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18090 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18091 QualType CaptureType; 18092 QualType DeclRefType; 18093 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18094 /*BuildAndDiagnose=*/true, CaptureType, 18095 DeclRefType, nullptr); 18096 } 18097 18098 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18099 QualType CaptureType; 18100 QualType DeclRefType; 18101 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18102 /*BuildAndDiagnose=*/false, CaptureType, 18103 DeclRefType, nullptr); 18104 } 18105 18106 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18107 QualType CaptureType; 18108 QualType DeclRefType; 18109 18110 // Determine whether we can capture this variable. 18111 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18112 /*BuildAndDiagnose=*/false, CaptureType, 18113 DeclRefType, nullptr)) 18114 return QualType(); 18115 18116 return DeclRefType; 18117 } 18118 18119 namespace { 18120 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18121 // The produced TemplateArgumentListInfo* points to data stored within this 18122 // object, so should only be used in contexts where the pointer will not be 18123 // used after the CopiedTemplateArgs object is destroyed. 18124 class CopiedTemplateArgs { 18125 bool HasArgs; 18126 TemplateArgumentListInfo TemplateArgStorage; 18127 public: 18128 template<typename RefExpr> 18129 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18130 if (HasArgs) 18131 E->copyTemplateArgumentsInto(TemplateArgStorage); 18132 } 18133 operator TemplateArgumentListInfo*() 18134 #ifdef __has_cpp_attribute 18135 #if __has_cpp_attribute(clang::lifetimebound) 18136 [[clang::lifetimebound]] 18137 #endif 18138 #endif 18139 { 18140 return HasArgs ? &TemplateArgStorage : nullptr; 18141 } 18142 }; 18143 } 18144 18145 /// Walk the set of potential results of an expression and mark them all as 18146 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18147 /// 18148 /// \return A new expression if we found any potential results, ExprEmpty() if 18149 /// not, and ExprError() if we diagnosed an error. 18150 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18151 NonOdrUseReason NOUR) { 18152 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18153 // an object that satisfies the requirements for appearing in a 18154 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18155 // is immediately applied." This function handles the lvalue-to-rvalue 18156 // conversion part. 18157 // 18158 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18159 // transform it into the relevant kind of non-odr-use node and rebuild the 18160 // tree of nodes leading to it. 18161 // 18162 // This is a mini-TreeTransform that only transforms a restricted subset of 18163 // nodes (and only certain operands of them). 18164 18165 // Rebuild a subexpression. 18166 auto Rebuild = [&](Expr *Sub) { 18167 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18168 }; 18169 18170 // Check whether a potential result satisfies the requirements of NOUR. 18171 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18172 // Any entity other than a VarDecl is always odr-used whenever it's named 18173 // in a potentially-evaluated expression. 18174 auto *VD = dyn_cast<VarDecl>(D); 18175 if (!VD) 18176 return true; 18177 18178 // C++2a [basic.def.odr]p4: 18179 // A variable x whose name appears as a potentially-evalauted expression 18180 // e is odr-used by e unless 18181 // -- x is a reference that is usable in constant expressions, or 18182 // -- x is a variable of non-reference type that is usable in constant 18183 // expressions and has no mutable subobjects, and e is an element of 18184 // the set of potential results of an expression of 18185 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18186 // conversion is applied, or 18187 // -- x is a variable of non-reference type, and e is an element of the 18188 // set of potential results of a discarded-value expression to which 18189 // the lvalue-to-rvalue conversion is not applied 18190 // 18191 // We check the first bullet and the "potentially-evaluated" condition in 18192 // BuildDeclRefExpr. We check the type requirements in the second bullet 18193 // in CheckLValueToRValueConversionOperand below. 18194 switch (NOUR) { 18195 case NOUR_None: 18196 case NOUR_Unevaluated: 18197 llvm_unreachable("unexpected non-odr-use-reason"); 18198 18199 case NOUR_Constant: 18200 // Constant references were handled when they were built. 18201 if (VD->getType()->isReferenceType()) 18202 return true; 18203 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18204 if (RD->hasMutableFields()) 18205 return true; 18206 if (!VD->isUsableInConstantExpressions(S.Context)) 18207 return true; 18208 break; 18209 18210 case NOUR_Discarded: 18211 if (VD->getType()->isReferenceType()) 18212 return true; 18213 break; 18214 } 18215 return false; 18216 }; 18217 18218 // Mark that this expression does not constitute an odr-use. 18219 auto MarkNotOdrUsed = [&] { 18220 S.MaybeODRUseExprs.remove(E); 18221 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18222 LSI->markVariableExprAsNonODRUsed(E); 18223 }; 18224 18225 // C++2a [basic.def.odr]p2: 18226 // The set of potential results of an expression e is defined as follows: 18227 switch (E->getStmtClass()) { 18228 // -- If e is an id-expression, ... 18229 case Expr::DeclRefExprClass: { 18230 auto *DRE = cast<DeclRefExpr>(E); 18231 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18232 break; 18233 18234 // Rebuild as a non-odr-use DeclRefExpr. 18235 MarkNotOdrUsed(); 18236 return DeclRefExpr::Create( 18237 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18238 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18239 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18240 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18241 } 18242 18243 case Expr::FunctionParmPackExprClass: { 18244 auto *FPPE = cast<FunctionParmPackExpr>(E); 18245 // If any of the declarations in the pack is odr-used, then the expression 18246 // as a whole constitutes an odr-use. 18247 for (VarDecl *D : *FPPE) 18248 if (IsPotentialResultOdrUsed(D)) 18249 return ExprEmpty(); 18250 18251 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18252 // nothing cares about whether we marked this as an odr-use, but it might 18253 // be useful for non-compiler tools. 18254 MarkNotOdrUsed(); 18255 break; 18256 } 18257 18258 // -- If e is a subscripting operation with an array operand... 18259 case Expr::ArraySubscriptExprClass: { 18260 auto *ASE = cast<ArraySubscriptExpr>(E); 18261 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18262 if (!OldBase->getType()->isArrayType()) 18263 break; 18264 ExprResult Base = Rebuild(OldBase); 18265 if (!Base.isUsable()) 18266 return Base; 18267 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18268 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18269 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18270 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18271 ASE->getRBracketLoc()); 18272 } 18273 18274 case Expr::MemberExprClass: { 18275 auto *ME = cast<MemberExpr>(E); 18276 // -- If e is a class member access expression [...] naming a non-static 18277 // data member... 18278 if (isa<FieldDecl>(ME->getMemberDecl())) { 18279 ExprResult Base = Rebuild(ME->getBase()); 18280 if (!Base.isUsable()) 18281 return Base; 18282 return MemberExpr::Create( 18283 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18284 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18285 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18286 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18287 ME->getObjectKind(), ME->isNonOdrUse()); 18288 } 18289 18290 if (ME->getMemberDecl()->isCXXInstanceMember()) 18291 break; 18292 18293 // -- If e is a class member access expression naming a static data member, 18294 // ... 18295 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18296 break; 18297 18298 // Rebuild as a non-odr-use MemberExpr. 18299 MarkNotOdrUsed(); 18300 return MemberExpr::Create( 18301 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18302 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18303 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18304 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18305 return ExprEmpty(); 18306 } 18307 18308 case Expr::BinaryOperatorClass: { 18309 auto *BO = cast<BinaryOperator>(E); 18310 Expr *LHS = BO->getLHS(); 18311 Expr *RHS = BO->getRHS(); 18312 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18313 if (BO->getOpcode() == BO_PtrMemD) { 18314 ExprResult Sub = Rebuild(LHS); 18315 if (!Sub.isUsable()) 18316 return Sub; 18317 LHS = Sub.get(); 18318 // -- If e is a comma expression, ... 18319 } else if (BO->getOpcode() == BO_Comma) { 18320 ExprResult Sub = Rebuild(RHS); 18321 if (!Sub.isUsable()) 18322 return Sub; 18323 RHS = Sub.get(); 18324 } else { 18325 break; 18326 } 18327 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18328 LHS, RHS); 18329 } 18330 18331 // -- If e has the form (e1)... 18332 case Expr::ParenExprClass: { 18333 auto *PE = cast<ParenExpr>(E); 18334 ExprResult Sub = Rebuild(PE->getSubExpr()); 18335 if (!Sub.isUsable()) 18336 return Sub; 18337 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18338 } 18339 18340 // -- If e is a glvalue conditional expression, ... 18341 // We don't apply this to a binary conditional operator. FIXME: Should we? 18342 case Expr::ConditionalOperatorClass: { 18343 auto *CO = cast<ConditionalOperator>(E); 18344 ExprResult LHS = Rebuild(CO->getLHS()); 18345 if (LHS.isInvalid()) 18346 return ExprError(); 18347 ExprResult RHS = Rebuild(CO->getRHS()); 18348 if (RHS.isInvalid()) 18349 return ExprError(); 18350 if (!LHS.isUsable() && !RHS.isUsable()) 18351 return ExprEmpty(); 18352 if (!LHS.isUsable()) 18353 LHS = CO->getLHS(); 18354 if (!RHS.isUsable()) 18355 RHS = CO->getRHS(); 18356 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18357 CO->getCond(), LHS.get(), RHS.get()); 18358 } 18359 18360 // [Clang extension] 18361 // -- If e has the form __extension__ e1... 18362 case Expr::UnaryOperatorClass: { 18363 auto *UO = cast<UnaryOperator>(E); 18364 if (UO->getOpcode() != UO_Extension) 18365 break; 18366 ExprResult Sub = Rebuild(UO->getSubExpr()); 18367 if (!Sub.isUsable()) 18368 return Sub; 18369 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18370 Sub.get()); 18371 } 18372 18373 // [Clang extension] 18374 // -- If e has the form _Generic(...), the set of potential results is the 18375 // union of the sets of potential results of the associated expressions. 18376 case Expr::GenericSelectionExprClass: { 18377 auto *GSE = cast<GenericSelectionExpr>(E); 18378 18379 SmallVector<Expr *, 4> AssocExprs; 18380 bool AnyChanged = false; 18381 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18382 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18383 if (AssocExpr.isInvalid()) 18384 return ExprError(); 18385 if (AssocExpr.isUsable()) { 18386 AssocExprs.push_back(AssocExpr.get()); 18387 AnyChanged = true; 18388 } else { 18389 AssocExprs.push_back(OrigAssocExpr); 18390 } 18391 } 18392 18393 return AnyChanged ? S.CreateGenericSelectionExpr( 18394 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18395 GSE->getRParenLoc(), GSE->getControllingExpr(), 18396 GSE->getAssocTypeSourceInfos(), AssocExprs) 18397 : ExprEmpty(); 18398 } 18399 18400 // [Clang extension] 18401 // -- If e has the form __builtin_choose_expr(...), the set of potential 18402 // results is the union of the sets of potential results of the 18403 // second and third subexpressions. 18404 case Expr::ChooseExprClass: { 18405 auto *CE = cast<ChooseExpr>(E); 18406 18407 ExprResult LHS = Rebuild(CE->getLHS()); 18408 if (LHS.isInvalid()) 18409 return ExprError(); 18410 18411 ExprResult RHS = Rebuild(CE->getLHS()); 18412 if (RHS.isInvalid()) 18413 return ExprError(); 18414 18415 if (!LHS.get() && !RHS.get()) 18416 return ExprEmpty(); 18417 if (!LHS.isUsable()) 18418 LHS = CE->getLHS(); 18419 if (!RHS.isUsable()) 18420 RHS = CE->getRHS(); 18421 18422 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18423 RHS.get(), CE->getRParenLoc()); 18424 } 18425 18426 // Step through non-syntactic nodes. 18427 case Expr::ConstantExprClass: { 18428 auto *CE = cast<ConstantExpr>(E); 18429 ExprResult Sub = Rebuild(CE->getSubExpr()); 18430 if (!Sub.isUsable()) 18431 return Sub; 18432 return ConstantExpr::Create(S.Context, Sub.get()); 18433 } 18434 18435 // We could mostly rely on the recursive rebuilding to rebuild implicit 18436 // casts, but not at the top level, so rebuild them here. 18437 case Expr::ImplicitCastExprClass: { 18438 auto *ICE = cast<ImplicitCastExpr>(E); 18439 // Only step through the narrow set of cast kinds we expect to encounter. 18440 // Anything else suggests we've left the region in which potential results 18441 // can be found. 18442 switch (ICE->getCastKind()) { 18443 case CK_NoOp: 18444 case CK_DerivedToBase: 18445 case CK_UncheckedDerivedToBase: { 18446 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18447 if (!Sub.isUsable()) 18448 return Sub; 18449 CXXCastPath Path(ICE->path()); 18450 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18451 ICE->getValueKind(), &Path); 18452 } 18453 18454 default: 18455 break; 18456 } 18457 break; 18458 } 18459 18460 default: 18461 break; 18462 } 18463 18464 // Can't traverse through this node. Nothing to do. 18465 return ExprEmpty(); 18466 } 18467 18468 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18469 // Check whether the operand is or contains an object of non-trivial C union 18470 // type. 18471 if (E->getType().isVolatileQualified() && 18472 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18473 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18474 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18475 Sema::NTCUC_LValueToRValueVolatile, 18476 NTCUK_Destruct|NTCUK_Copy); 18477 18478 // C++2a [basic.def.odr]p4: 18479 // [...] an expression of non-volatile-qualified non-class type to which 18480 // the lvalue-to-rvalue conversion is applied [...] 18481 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18482 return E; 18483 18484 ExprResult Result = 18485 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18486 if (Result.isInvalid()) 18487 return ExprError(); 18488 return Result.get() ? Result : E; 18489 } 18490 18491 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18492 Res = CorrectDelayedTyposInExpr(Res); 18493 18494 if (!Res.isUsable()) 18495 return Res; 18496 18497 // If a constant-expression is a reference to a variable where we delay 18498 // deciding whether it is an odr-use, just assume we will apply the 18499 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18500 // (a non-type template argument), we have special handling anyway. 18501 return CheckLValueToRValueConversionOperand(Res.get()); 18502 } 18503 18504 void Sema::CleanupVarDeclMarking() { 18505 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18506 // call. 18507 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18508 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18509 18510 for (Expr *E : LocalMaybeODRUseExprs) { 18511 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18512 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18513 DRE->getLocation(), *this); 18514 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18515 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18516 *this); 18517 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18518 for (VarDecl *VD : *FP) 18519 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18520 } else { 18521 llvm_unreachable("Unexpected expression"); 18522 } 18523 } 18524 18525 assert(MaybeODRUseExprs.empty() && 18526 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18527 } 18528 18529 static void DoMarkVarDeclReferenced( 18530 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18531 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18532 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18533 isa<FunctionParmPackExpr>(E)) && 18534 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18535 Var->setReferenced(); 18536 18537 if (Var->isInvalidDecl()) 18538 return; 18539 18540 auto *MSI = Var->getMemberSpecializationInfo(); 18541 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18542 : Var->getTemplateSpecializationKind(); 18543 18544 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18545 bool UsableInConstantExpr = 18546 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18547 18548 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18549 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18550 } 18551 18552 // C++20 [expr.const]p12: 18553 // A variable [...] is needed for constant evaluation if it is [...] a 18554 // variable whose name appears as a potentially constant evaluated 18555 // expression that is either a contexpr variable or is of non-volatile 18556 // const-qualified integral type or of reference type 18557 bool NeededForConstantEvaluation = 18558 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18559 18560 bool NeedDefinition = 18561 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18562 18563 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18564 "Can't instantiate a partial template specialization."); 18565 18566 // If this might be a member specialization of a static data member, check 18567 // the specialization is visible. We already did the checks for variable 18568 // template specializations when we created them. 18569 if (NeedDefinition && TSK != TSK_Undeclared && 18570 !isa<VarTemplateSpecializationDecl>(Var)) 18571 SemaRef.checkSpecializationVisibility(Loc, Var); 18572 18573 // Perform implicit instantiation of static data members, static data member 18574 // templates of class templates, and variable template specializations. Delay 18575 // instantiations of variable templates, except for those that could be used 18576 // in a constant expression. 18577 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18578 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18579 // instantiation declaration if a variable is usable in a constant 18580 // expression (among other cases). 18581 bool TryInstantiating = 18582 TSK == TSK_ImplicitInstantiation || 18583 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18584 18585 if (TryInstantiating) { 18586 SourceLocation PointOfInstantiation = 18587 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18588 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18589 if (FirstInstantiation) { 18590 PointOfInstantiation = Loc; 18591 if (MSI) 18592 MSI->setPointOfInstantiation(PointOfInstantiation); 18593 // FIXME: Notify listener. 18594 else 18595 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18596 } 18597 18598 if (UsableInConstantExpr) { 18599 // Do not defer instantiations of variables that could be used in a 18600 // constant expression. 18601 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18602 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18603 }); 18604 18605 // Re-set the member to trigger a recomputation of the dependence bits 18606 // for the expression. 18607 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18608 DRE->setDecl(DRE->getDecl()); 18609 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18610 ME->setMemberDecl(ME->getMemberDecl()); 18611 } else if (FirstInstantiation || 18612 isa<VarTemplateSpecializationDecl>(Var)) { 18613 // FIXME: For a specialization of a variable template, we don't 18614 // distinguish between "declaration and type implicitly instantiated" 18615 // and "implicit instantiation of definition requested", so we have 18616 // no direct way to avoid enqueueing the pending instantiation 18617 // multiple times. 18618 SemaRef.PendingInstantiations 18619 .push_back(std::make_pair(Var, PointOfInstantiation)); 18620 } 18621 } 18622 } 18623 18624 // C++2a [basic.def.odr]p4: 18625 // A variable x whose name appears as a potentially-evaluated expression e 18626 // is odr-used by e unless 18627 // -- x is a reference that is usable in constant expressions 18628 // -- x is a variable of non-reference type that is usable in constant 18629 // expressions and has no mutable subobjects [FIXME], and e is an 18630 // element of the set of potential results of an expression of 18631 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18632 // conversion is applied 18633 // -- x is a variable of non-reference type, and e is an element of the set 18634 // of potential results of a discarded-value expression to which the 18635 // lvalue-to-rvalue conversion is not applied [FIXME] 18636 // 18637 // We check the first part of the second bullet here, and 18638 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18639 // FIXME: To get the third bullet right, we need to delay this even for 18640 // variables that are not usable in constant expressions. 18641 18642 // If we already know this isn't an odr-use, there's nothing more to do. 18643 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18644 if (DRE->isNonOdrUse()) 18645 return; 18646 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18647 if (ME->isNonOdrUse()) 18648 return; 18649 18650 switch (OdrUse) { 18651 case OdrUseContext::None: 18652 assert((!E || isa<FunctionParmPackExpr>(E)) && 18653 "missing non-odr-use marking for unevaluated decl ref"); 18654 break; 18655 18656 case OdrUseContext::FormallyOdrUsed: 18657 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18658 // behavior. 18659 break; 18660 18661 case OdrUseContext::Used: 18662 // If we might later find that this expression isn't actually an odr-use, 18663 // delay the marking. 18664 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18665 SemaRef.MaybeODRUseExprs.insert(E); 18666 else 18667 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18668 break; 18669 18670 case OdrUseContext::Dependent: 18671 // If this is a dependent context, we don't need to mark variables as 18672 // odr-used, but we may still need to track them for lambda capture. 18673 // FIXME: Do we also need to do this inside dependent typeid expressions 18674 // (which are modeled as unevaluated at this point)? 18675 const bool RefersToEnclosingScope = 18676 (SemaRef.CurContext != Var->getDeclContext() && 18677 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18678 if (RefersToEnclosingScope) { 18679 LambdaScopeInfo *const LSI = 18680 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18681 if (LSI && (!LSI->CallOperator || 18682 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18683 // If a variable could potentially be odr-used, defer marking it so 18684 // until we finish analyzing the full expression for any 18685 // lvalue-to-rvalue 18686 // or discarded value conversions that would obviate odr-use. 18687 // Add it to the list of potential captures that will be analyzed 18688 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18689 // unless the variable is a reference that was initialized by a constant 18690 // expression (this will never need to be captured or odr-used). 18691 // 18692 // FIXME: We can simplify this a lot after implementing P0588R1. 18693 assert(E && "Capture variable should be used in an expression."); 18694 if (!Var->getType()->isReferenceType() || 18695 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18696 LSI->addPotentialCapture(E->IgnoreParens()); 18697 } 18698 } 18699 break; 18700 } 18701 } 18702 18703 /// Mark a variable referenced, and check whether it is odr-used 18704 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18705 /// used directly for normal expressions referring to VarDecl. 18706 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18707 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18708 } 18709 18710 static void 18711 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18712 bool MightBeOdrUse, 18713 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18714 if (SemaRef.isInOpenMPDeclareTargetContext()) 18715 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18716 18717 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18718 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18719 return; 18720 } 18721 18722 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18723 18724 // If this is a call to a method via a cast, also mark the method in the 18725 // derived class used in case codegen can devirtualize the call. 18726 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18727 if (!ME) 18728 return; 18729 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18730 if (!MD) 18731 return; 18732 // Only attempt to devirtualize if this is truly a virtual call. 18733 bool IsVirtualCall = MD->isVirtual() && 18734 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18735 if (!IsVirtualCall) 18736 return; 18737 18738 // If it's possible to devirtualize the call, mark the called function 18739 // referenced. 18740 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18741 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18742 if (DM) 18743 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18744 } 18745 18746 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18747 /// 18748 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18749 /// handled with care if the DeclRefExpr is not newly-created. 18750 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18751 // TODO: update this with DR# once a defect report is filed. 18752 // C++11 defect. The address of a pure member should not be an ODR use, even 18753 // if it's a qualified reference. 18754 bool OdrUse = true; 18755 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18756 if (Method->isVirtual() && 18757 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18758 OdrUse = false; 18759 18760 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18761 if (!isConstantEvaluated() && FD->isConsteval() && 18762 !RebuildingImmediateInvocation) 18763 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18764 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18765 RefsMinusAssignments); 18766 } 18767 18768 /// Perform reference-marking and odr-use handling for a MemberExpr. 18769 void Sema::MarkMemberReferenced(MemberExpr *E) { 18770 // C++11 [basic.def.odr]p2: 18771 // A non-overloaded function whose name appears as a potentially-evaluated 18772 // expression or a member of a set of candidate functions, if selected by 18773 // overload resolution when referred to from a potentially-evaluated 18774 // expression, is odr-used, unless it is a pure virtual function and its 18775 // name is not explicitly qualified. 18776 bool MightBeOdrUse = true; 18777 if (E->performsVirtualDispatch(getLangOpts())) { 18778 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18779 if (Method->isPure()) 18780 MightBeOdrUse = false; 18781 } 18782 SourceLocation Loc = 18783 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18784 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18785 RefsMinusAssignments); 18786 } 18787 18788 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18789 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18790 for (VarDecl *VD : *E) 18791 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18792 RefsMinusAssignments); 18793 } 18794 18795 /// Perform marking for a reference to an arbitrary declaration. It 18796 /// marks the declaration referenced, and performs odr-use checking for 18797 /// functions and variables. This method should not be used when building a 18798 /// normal expression which refers to a variable. 18799 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18800 bool MightBeOdrUse) { 18801 if (MightBeOdrUse) { 18802 if (auto *VD = dyn_cast<VarDecl>(D)) { 18803 MarkVariableReferenced(Loc, VD); 18804 return; 18805 } 18806 } 18807 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18808 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18809 return; 18810 } 18811 D->setReferenced(); 18812 } 18813 18814 namespace { 18815 // Mark all of the declarations used by a type as referenced. 18816 // FIXME: Not fully implemented yet! We need to have a better understanding 18817 // of when we're entering a context we should not recurse into. 18818 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18819 // TreeTransforms rebuilding the type in a new context. Rather than 18820 // duplicating the TreeTransform logic, we should consider reusing it here. 18821 // Currently that causes problems when rebuilding LambdaExprs. 18822 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18823 Sema &S; 18824 SourceLocation Loc; 18825 18826 public: 18827 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18828 18829 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18830 18831 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18832 }; 18833 } 18834 18835 bool MarkReferencedDecls::TraverseTemplateArgument( 18836 const TemplateArgument &Arg) { 18837 { 18838 // A non-type template argument is a constant-evaluated context. 18839 EnterExpressionEvaluationContext Evaluated( 18840 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18841 if (Arg.getKind() == TemplateArgument::Declaration) { 18842 if (Decl *D = Arg.getAsDecl()) 18843 S.MarkAnyDeclReferenced(Loc, D, true); 18844 } else if (Arg.getKind() == TemplateArgument::Expression) { 18845 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18846 } 18847 } 18848 18849 return Inherited::TraverseTemplateArgument(Arg); 18850 } 18851 18852 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18853 MarkReferencedDecls Marker(*this, Loc); 18854 Marker.TraverseType(T); 18855 } 18856 18857 namespace { 18858 /// Helper class that marks all of the declarations referenced by 18859 /// potentially-evaluated subexpressions as "referenced". 18860 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18861 public: 18862 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18863 bool SkipLocalVariables; 18864 18865 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18866 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18867 18868 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18869 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18870 } 18871 18872 void VisitDeclRefExpr(DeclRefExpr *E) { 18873 // If we were asked not to visit local variables, don't. 18874 if (SkipLocalVariables) { 18875 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18876 if (VD->hasLocalStorage()) 18877 return; 18878 } 18879 18880 // FIXME: This can trigger the instantiation of the initializer of a 18881 // variable, which can cause the expression to become value-dependent 18882 // or error-dependent. Do we need to propagate the new dependence bits? 18883 S.MarkDeclRefReferenced(E); 18884 } 18885 18886 void VisitMemberExpr(MemberExpr *E) { 18887 S.MarkMemberReferenced(E); 18888 Visit(E->getBase()); 18889 } 18890 }; 18891 } // namespace 18892 18893 /// Mark any declarations that appear within this expression or any 18894 /// potentially-evaluated subexpressions as "referenced". 18895 /// 18896 /// \param SkipLocalVariables If true, don't mark local variables as 18897 /// 'referenced'. 18898 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18899 bool SkipLocalVariables) { 18900 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18901 } 18902 18903 /// Emit a diagnostic that describes an effect on the run-time behavior 18904 /// of the program being compiled. 18905 /// 18906 /// This routine emits the given diagnostic when the code currently being 18907 /// type-checked is "potentially evaluated", meaning that there is a 18908 /// possibility that the code will actually be executable. Code in sizeof() 18909 /// expressions, code used only during overload resolution, etc., are not 18910 /// potentially evaluated. This routine will suppress such diagnostics or, 18911 /// in the absolutely nutty case of potentially potentially evaluated 18912 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18913 /// later. 18914 /// 18915 /// This routine should be used for all diagnostics that describe the run-time 18916 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18917 /// Failure to do so will likely result in spurious diagnostics or failures 18918 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18919 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18920 const PartialDiagnostic &PD) { 18921 switch (ExprEvalContexts.back().Context) { 18922 case ExpressionEvaluationContext::Unevaluated: 18923 case ExpressionEvaluationContext::UnevaluatedList: 18924 case ExpressionEvaluationContext::UnevaluatedAbstract: 18925 case ExpressionEvaluationContext::DiscardedStatement: 18926 // The argument will never be evaluated, so don't complain. 18927 break; 18928 18929 case ExpressionEvaluationContext::ConstantEvaluated: 18930 // Relevant diagnostics should be produced by constant evaluation. 18931 break; 18932 18933 case ExpressionEvaluationContext::PotentiallyEvaluated: 18934 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18935 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18936 FunctionScopes.back()->PossiblyUnreachableDiags. 18937 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18938 return true; 18939 } 18940 18941 // The initializer of a constexpr variable or of the first declaration of a 18942 // static data member is not syntactically a constant evaluated constant, 18943 // but nonetheless is always required to be a constant expression, so we 18944 // can skip diagnosing. 18945 // FIXME: Using the mangling context here is a hack. 18946 if (auto *VD = dyn_cast_or_null<VarDecl>( 18947 ExprEvalContexts.back().ManglingContextDecl)) { 18948 if (VD->isConstexpr() || 18949 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18950 break; 18951 // FIXME: For any other kind of variable, we should build a CFG for its 18952 // initializer and check whether the context in question is reachable. 18953 } 18954 18955 Diag(Loc, PD); 18956 return true; 18957 } 18958 18959 return false; 18960 } 18961 18962 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18963 const PartialDiagnostic &PD) { 18964 return DiagRuntimeBehavior( 18965 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18966 } 18967 18968 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18969 CallExpr *CE, FunctionDecl *FD) { 18970 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18971 return false; 18972 18973 // If we're inside a decltype's expression, don't check for a valid return 18974 // type or construct temporaries until we know whether this is the last call. 18975 if (ExprEvalContexts.back().ExprContext == 18976 ExpressionEvaluationContextRecord::EK_Decltype) { 18977 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18978 return false; 18979 } 18980 18981 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18982 FunctionDecl *FD; 18983 CallExpr *CE; 18984 18985 public: 18986 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18987 : FD(FD), CE(CE) { } 18988 18989 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18990 if (!FD) { 18991 S.Diag(Loc, diag::err_call_incomplete_return) 18992 << T << CE->getSourceRange(); 18993 return; 18994 } 18995 18996 S.Diag(Loc, diag::err_call_function_incomplete_return) 18997 << CE->getSourceRange() << FD << T; 18998 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18999 << FD->getDeclName(); 19000 } 19001 } Diagnoser(FD, CE); 19002 19003 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19004 return true; 19005 19006 return false; 19007 } 19008 19009 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19010 // will prevent this condition from triggering, which is what we want. 19011 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19012 SourceLocation Loc; 19013 19014 unsigned diagnostic = diag::warn_condition_is_assignment; 19015 bool IsOrAssign = false; 19016 19017 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19018 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19019 return; 19020 19021 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19022 19023 // Greylist some idioms by putting them into a warning subcategory. 19024 if (ObjCMessageExpr *ME 19025 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19026 Selector Sel = ME->getSelector(); 19027 19028 // self = [<foo> init...] 19029 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19030 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19031 19032 // <foo> = [<bar> nextObject] 19033 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19034 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19035 } 19036 19037 Loc = Op->getOperatorLoc(); 19038 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19039 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19040 return; 19041 19042 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19043 Loc = Op->getOperatorLoc(); 19044 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19045 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19046 else { 19047 // Not an assignment. 19048 return; 19049 } 19050 19051 Diag(Loc, diagnostic) << E->getSourceRange(); 19052 19053 SourceLocation Open = E->getBeginLoc(); 19054 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19055 Diag(Loc, diag::note_condition_assign_silence) 19056 << FixItHint::CreateInsertion(Open, "(") 19057 << FixItHint::CreateInsertion(Close, ")"); 19058 19059 if (IsOrAssign) 19060 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19061 << FixItHint::CreateReplacement(Loc, "!="); 19062 else 19063 Diag(Loc, diag::note_condition_assign_to_comparison) 19064 << FixItHint::CreateReplacement(Loc, "=="); 19065 } 19066 19067 /// Redundant parentheses over an equality comparison can indicate 19068 /// that the user intended an assignment used as condition. 19069 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19070 // Don't warn if the parens came from a macro. 19071 SourceLocation parenLoc = ParenE->getBeginLoc(); 19072 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19073 return; 19074 // Don't warn for dependent expressions. 19075 if (ParenE->isTypeDependent()) 19076 return; 19077 19078 Expr *E = ParenE->IgnoreParens(); 19079 19080 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19081 if (opE->getOpcode() == BO_EQ && 19082 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19083 == Expr::MLV_Valid) { 19084 SourceLocation Loc = opE->getOperatorLoc(); 19085 19086 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19087 SourceRange ParenERange = ParenE->getSourceRange(); 19088 Diag(Loc, diag::note_equality_comparison_silence) 19089 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19090 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19091 Diag(Loc, diag::note_equality_comparison_to_assign) 19092 << FixItHint::CreateReplacement(Loc, "="); 19093 } 19094 } 19095 19096 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19097 bool IsConstexpr) { 19098 DiagnoseAssignmentAsCondition(E); 19099 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19100 DiagnoseEqualityWithExtraParens(parenE); 19101 19102 ExprResult result = CheckPlaceholderExpr(E); 19103 if (result.isInvalid()) return ExprError(); 19104 E = result.get(); 19105 19106 if (!E->isTypeDependent()) { 19107 if (getLangOpts().CPlusPlus) 19108 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19109 19110 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19111 if (ERes.isInvalid()) 19112 return ExprError(); 19113 E = ERes.get(); 19114 19115 QualType T = E->getType(); 19116 if (!T->isScalarType()) { // C99 6.8.4.1p1 19117 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19118 << T << E->getSourceRange(); 19119 return ExprError(); 19120 } 19121 CheckBoolLikeConversion(E, Loc); 19122 } 19123 19124 return E; 19125 } 19126 19127 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19128 Expr *SubExpr, ConditionKind CK) { 19129 // Empty conditions are valid in for-statements. 19130 if (!SubExpr) 19131 return ConditionResult(); 19132 19133 ExprResult Cond; 19134 switch (CK) { 19135 case ConditionKind::Boolean: 19136 Cond = CheckBooleanCondition(Loc, SubExpr); 19137 break; 19138 19139 case ConditionKind::ConstexprIf: 19140 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19141 break; 19142 19143 case ConditionKind::Switch: 19144 Cond = CheckSwitchCondition(Loc, SubExpr); 19145 break; 19146 } 19147 if (Cond.isInvalid()) { 19148 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19149 {SubExpr}); 19150 if (!Cond.get()) 19151 return ConditionError(); 19152 } 19153 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19154 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19155 if (!FullExpr.get()) 19156 return ConditionError(); 19157 19158 return ConditionResult(*this, nullptr, FullExpr, 19159 CK == ConditionKind::ConstexprIf); 19160 } 19161 19162 namespace { 19163 /// A visitor for rebuilding a call to an __unknown_any expression 19164 /// to have an appropriate type. 19165 struct RebuildUnknownAnyFunction 19166 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19167 19168 Sema &S; 19169 19170 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19171 19172 ExprResult VisitStmt(Stmt *S) { 19173 llvm_unreachable("unexpected statement!"); 19174 } 19175 19176 ExprResult VisitExpr(Expr *E) { 19177 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19178 << E->getSourceRange(); 19179 return ExprError(); 19180 } 19181 19182 /// Rebuild an expression which simply semantically wraps another 19183 /// expression which it shares the type and value kind of. 19184 template <class T> ExprResult rebuildSugarExpr(T *E) { 19185 ExprResult SubResult = Visit(E->getSubExpr()); 19186 if (SubResult.isInvalid()) return ExprError(); 19187 19188 Expr *SubExpr = SubResult.get(); 19189 E->setSubExpr(SubExpr); 19190 E->setType(SubExpr->getType()); 19191 E->setValueKind(SubExpr->getValueKind()); 19192 assert(E->getObjectKind() == OK_Ordinary); 19193 return E; 19194 } 19195 19196 ExprResult VisitParenExpr(ParenExpr *E) { 19197 return rebuildSugarExpr(E); 19198 } 19199 19200 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19201 return rebuildSugarExpr(E); 19202 } 19203 19204 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19205 ExprResult SubResult = Visit(E->getSubExpr()); 19206 if (SubResult.isInvalid()) return ExprError(); 19207 19208 Expr *SubExpr = SubResult.get(); 19209 E->setSubExpr(SubExpr); 19210 E->setType(S.Context.getPointerType(SubExpr->getType())); 19211 assert(E->isPRValue()); 19212 assert(E->getObjectKind() == OK_Ordinary); 19213 return E; 19214 } 19215 19216 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19217 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19218 19219 E->setType(VD->getType()); 19220 19221 assert(E->isPRValue()); 19222 if (S.getLangOpts().CPlusPlus && 19223 !(isa<CXXMethodDecl>(VD) && 19224 cast<CXXMethodDecl>(VD)->isInstance())) 19225 E->setValueKind(VK_LValue); 19226 19227 return E; 19228 } 19229 19230 ExprResult VisitMemberExpr(MemberExpr *E) { 19231 return resolveDecl(E, E->getMemberDecl()); 19232 } 19233 19234 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19235 return resolveDecl(E, E->getDecl()); 19236 } 19237 }; 19238 } 19239 19240 /// Given a function expression of unknown-any type, try to rebuild it 19241 /// to have a function type. 19242 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19243 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19244 if (Result.isInvalid()) return ExprError(); 19245 return S.DefaultFunctionArrayConversion(Result.get()); 19246 } 19247 19248 namespace { 19249 /// A visitor for rebuilding an expression of type __unknown_anytype 19250 /// into one which resolves the type directly on the referring 19251 /// expression. Strict preservation of the original source 19252 /// structure is not a goal. 19253 struct RebuildUnknownAnyExpr 19254 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19255 19256 Sema &S; 19257 19258 /// The current destination type. 19259 QualType DestType; 19260 19261 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19262 : S(S), DestType(CastType) {} 19263 19264 ExprResult VisitStmt(Stmt *S) { 19265 llvm_unreachable("unexpected statement!"); 19266 } 19267 19268 ExprResult VisitExpr(Expr *E) { 19269 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19270 << E->getSourceRange(); 19271 return ExprError(); 19272 } 19273 19274 ExprResult VisitCallExpr(CallExpr *E); 19275 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19276 19277 /// Rebuild an expression which simply semantically wraps another 19278 /// expression which it shares the type and value kind of. 19279 template <class T> ExprResult rebuildSugarExpr(T *E) { 19280 ExprResult SubResult = Visit(E->getSubExpr()); 19281 if (SubResult.isInvalid()) return ExprError(); 19282 Expr *SubExpr = SubResult.get(); 19283 E->setSubExpr(SubExpr); 19284 E->setType(SubExpr->getType()); 19285 E->setValueKind(SubExpr->getValueKind()); 19286 assert(E->getObjectKind() == OK_Ordinary); 19287 return E; 19288 } 19289 19290 ExprResult VisitParenExpr(ParenExpr *E) { 19291 return rebuildSugarExpr(E); 19292 } 19293 19294 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19295 return rebuildSugarExpr(E); 19296 } 19297 19298 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19299 const PointerType *Ptr = DestType->getAs<PointerType>(); 19300 if (!Ptr) { 19301 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19302 << E->getSourceRange(); 19303 return ExprError(); 19304 } 19305 19306 if (isa<CallExpr>(E->getSubExpr())) { 19307 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19308 << E->getSourceRange(); 19309 return ExprError(); 19310 } 19311 19312 assert(E->isPRValue()); 19313 assert(E->getObjectKind() == OK_Ordinary); 19314 E->setType(DestType); 19315 19316 // Build the sub-expression as if it were an object of the pointee type. 19317 DestType = Ptr->getPointeeType(); 19318 ExprResult SubResult = Visit(E->getSubExpr()); 19319 if (SubResult.isInvalid()) return ExprError(); 19320 E->setSubExpr(SubResult.get()); 19321 return E; 19322 } 19323 19324 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19325 19326 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19327 19328 ExprResult VisitMemberExpr(MemberExpr *E) { 19329 return resolveDecl(E, E->getMemberDecl()); 19330 } 19331 19332 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19333 return resolveDecl(E, E->getDecl()); 19334 } 19335 }; 19336 } 19337 19338 /// Rebuilds a call expression which yielded __unknown_anytype. 19339 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19340 Expr *CalleeExpr = E->getCallee(); 19341 19342 enum FnKind { 19343 FK_MemberFunction, 19344 FK_FunctionPointer, 19345 FK_BlockPointer 19346 }; 19347 19348 FnKind Kind; 19349 QualType CalleeType = CalleeExpr->getType(); 19350 if (CalleeType == S.Context.BoundMemberTy) { 19351 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19352 Kind = FK_MemberFunction; 19353 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19354 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19355 CalleeType = Ptr->getPointeeType(); 19356 Kind = FK_FunctionPointer; 19357 } else { 19358 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19359 Kind = FK_BlockPointer; 19360 } 19361 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19362 19363 // Verify that this is a legal result type of a function. 19364 if (DestType->isArrayType() || DestType->isFunctionType()) { 19365 unsigned diagID = diag::err_func_returning_array_function; 19366 if (Kind == FK_BlockPointer) 19367 diagID = diag::err_block_returning_array_function; 19368 19369 S.Diag(E->getExprLoc(), diagID) 19370 << DestType->isFunctionType() << DestType; 19371 return ExprError(); 19372 } 19373 19374 // Otherwise, go ahead and set DestType as the call's result. 19375 E->setType(DestType.getNonLValueExprType(S.Context)); 19376 E->setValueKind(Expr::getValueKindForType(DestType)); 19377 assert(E->getObjectKind() == OK_Ordinary); 19378 19379 // Rebuild the function type, replacing the result type with DestType. 19380 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19381 if (Proto) { 19382 // __unknown_anytype(...) is a special case used by the debugger when 19383 // it has no idea what a function's signature is. 19384 // 19385 // We want to build this call essentially under the K&R 19386 // unprototyped rules, but making a FunctionNoProtoType in C++ 19387 // would foul up all sorts of assumptions. However, we cannot 19388 // simply pass all arguments as variadic arguments, nor can we 19389 // portably just call the function under a non-variadic type; see 19390 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19391 // However, it turns out that in practice it is generally safe to 19392 // call a function declared as "A foo(B,C,D);" under the prototype 19393 // "A foo(B,C,D,...);". The only known exception is with the 19394 // Windows ABI, where any variadic function is implicitly cdecl 19395 // regardless of its normal CC. Therefore we change the parameter 19396 // types to match the types of the arguments. 19397 // 19398 // This is a hack, but it is far superior to moving the 19399 // corresponding target-specific code from IR-gen to Sema/AST. 19400 19401 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19402 SmallVector<QualType, 8> ArgTypes; 19403 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19404 ArgTypes.reserve(E->getNumArgs()); 19405 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19406 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19407 } 19408 ParamTypes = ArgTypes; 19409 } 19410 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19411 Proto->getExtProtoInfo()); 19412 } else { 19413 DestType = S.Context.getFunctionNoProtoType(DestType, 19414 FnType->getExtInfo()); 19415 } 19416 19417 // Rebuild the appropriate pointer-to-function type. 19418 switch (Kind) { 19419 case FK_MemberFunction: 19420 // Nothing to do. 19421 break; 19422 19423 case FK_FunctionPointer: 19424 DestType = S.Context.getPointerType(DestType); 19425 break; 19426 19427 case FK_BlockPointer: 19428 DestType = S.Context.getBlockPointerType(DestType); 19429 break; 19430 } 19431 19432 // Finally, we can recurse. 19433 ExprResult CalleeResult = Visit(CalleeExpr); 19434 if (!CalleeResult.isUsable()) return ExprError(); 19435 E->setCallee(CalleeResult.get()); 19436 19437 // Bind a temporary if necessary. 19438 return S.MaybeBindToTemporary(E); 19439 } 19440 19441 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19442 // Verify that this is a legal result type of a call. 19443 if (DestType->isArrayType() || DestType->isFunctionType()) { 19444 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19445 << DestType->isFunctionType() << DestType; 19446 return ExprError(); 19447 } 19448 19449 // Rewrite the method result type if available. 19450 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19451 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19452 Method->setReturnType(DestType); 19453 } 19454 19455 // Change the type of the message. 19456 E->setType(DestType.getNonReferenceType()); 19457 E->setValueKind(Expr::getValueKindForType(DestType)); 19458 19459 return S.MaybeBindToTemporary(E); 19460 } 19461 19462 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19463 // The only case we should ever see here is a function-to-pointer decay. 19464 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19465 assert(E->isPRValue()); 19466 assert(E->getObjectKind() == OK_Ordinary); 19467 19468 E->setType(DestType); 19469 19470 // Rebuild the sub-expression as the pointee (function) type. 19471 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19472 19473 ExprResult Result = Visit(E->getSubExpr()); 19474 if (!Result.isUsable()) return ExprError(); 19475 19476 E->setSubExpr(Result.get()); 19477 return E; 19478 } else if (E->getCastKind() == CK_LValueToRValue) { 19479 assert(E->isPRValue()); 19480 assert(E->getObjectKind() == OK_Ordinary); 19481 19482 assert(isa<BlockPointerType>(E->getType())); 19483 19484 E->setType(DestType); 19485 19486 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19487 DestType = S.Context.getLValueReferenceType(DestType); 19488 19489 ExprResult Result = Visit(E->getSubExpr()); 19490 if (!Result.isUsable()) return ExprError(); 19491 19492 E->setSubExpr(Result.get()); 19493 return E; 19494 } else { 19495 llvm_unreachable("Unhandled cast type!"); 19496 } 19497 } 19498 19499 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19500 ExprValueKind ValueKind = VK_LValue; 19501 QualType Type = DestType; 19502 19503 // We know how to make this work for certain kinds of decls: 19504 19505 // - functions 19506 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19507 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19508 DestType = Ptr->getPointeeType(); 19509 ExprResult Result = resolveDecl(E, VD); 19510 if (Result.isInvalid()) return ExprError(); 19511 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19512 VK_PRValue); 19513 } 19514 19515 if (!Type->isFunctionType()) { 19516 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19517 << VD << E->getSourceRange(); 19518 return ExprError(); 19519 } 19520 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19521 // We must match the FunctionDecl's type to the hack introduced in 19522 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19523 // type. See the lengthy commentary in that routine. 19524 QualType FDT = FD->getType(); 19525 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19526 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19527 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19528 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19529 SourceLocation Loc = FD->getLocation(); 19530 FunctionDecl *NewFD = FunctionDecl::Create( 19531 S.Context, FD->getDeclContext(), Loc, Loc, 19532 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19533 SC_None, S.getCurFPFeatures().isFPConstrained(), 19534 false /*isInlineSpecified*/, FD->hasPrototype(), 19535 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19536 19537 if (FD->getQualifier()) 19538 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19539 19540 SmallVector<ParmVarDecl*, 16> Params; 19541 for (const auto &AI : FT->param_types()) { 19542 ParmVarDecl *Param = 19543 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19544 Param->setScopeInfo(0, Params.size()); 19545 Params.push_back(Param); 19546 } 19547 NewFD->setParams(Params); 19548 DRE->setDecl(NewFD); 19549 VD = DRE->getDecl(); 19550 } 19551 } 19552 19553 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19554 if (MD->isInstance()) { 19555 ValueKind = VK_PRValue; 19556 Type = S.Context.BoundMemberTy; 19557 } 19558 19559 // Function references aren't l-values in C. 19560 if (!S.getLangOpts().CPlusPlus) 19561 ValueKind = VK_PRValue; 19562 19563 // - variables 19564 } else if (isa<VarDecl>(VD)) { 19565 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19566 Type = RefTy->getPointeeType(); 19567 } else if (Type->isFunctionType()) { 19568 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19569 << VD << E->getSourceRange(); 19570 return ExprError(); 19571 } 19572 19573 // - nothing else 19574 } else { 19575 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19576 << VD << E->getSourceRange(); 19577 return ExprError(); 19578 } 19579 19580 // Modifying the declaration like this is friendly to IR-gen but 19581 // also really dangerous. 19582 VD->setType(DestType); 19583 E->setType(Type); 19584 E->setValueKind(ValueKind); 19585 return E; 19586 } 19587 19588 /// Check a cast of an unknown-any type. We intentionally only 19589 /// trigger this for C-style casts. 19590 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19591 Expr *CastExpr, CastKind &CastKind, 19592 ExprValueKind &VK, CXXCastPath &Path) { 19593 // The type we're casting to must be either void or complete. 19594 if (!CastType->isVoidType() && 19595 RequireCompleteType(TypeRange.getBegin(), CastType, 19596 diag::err_typecheck_cast_to_incomplete)) 19597 return ExprError(); 19598 19599 // Rewrite the casted expression from scratch. 19600 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19601 if (!result.isUsable()) return ExprError(); 19602 19603 CastExpr = result.get(); 19604 VK = CastExpr->getValueKind(); 19605 CastKind = CK_NoOp; 19606 19607 return CastExpr; 19608 } 19609 19610 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19611 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19612 } 19613 19614 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19615 Expr *arg, QualType ¶mType) { 19616 // If the syntactic form of the argument is not an explicit cast of 19617 // any sort, just do default argument promotion. 19618 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19619 if (!castArg) { 19620 ExprResult result = DefaultArgumentPromotion(arg); 19621 if (result.isInvalid()) return ExprError(); 19622 paramType = result.get()->getType(); 19623 return result; 19624 } 19625 19626 // Otherwise, use the type that was written in the explicit cast. 19627 assert(!arg->hasPlaceholderType()); 19628 paramType = castArg->getTypeAsWritten(); 19629 19630 // Copy-initialize a parameter of that type. 19631 InitializedEntity entity = 19632 InitializedEntity::InitializeParameter(Context, paramType, 19633 /*consumed*/ false); 19634 return PerformCopyInitialization(entity, callLoc, arg); 19635 } 19636 19637 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19638 Expr *orig = E; 19639 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19640 while (true) { 19641 E = E->IgnoreParenImpCasts(); 19642 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19643 E = call->getCallee(); 19644 diagID = diag::err_uncasted_call_of_unknown_any; 19645 } else { 19646 break; 19647 } 19648 } 19649 19650 SourceLocation loc; 19651 NamedDecl *d; 19652 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19653 loc = ref->getLocation(); 19654 d = ref->getDecl(); 19655 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19656 loc = mem->getMemberLoc(); 19657 d = mem->getMemberDecl(); 19658 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19659 diagID = diag::err_uncasted_call_of_unknown_any; 19660 loc = msg->getSelectorStartLoc(); 19661 d = msg->getMethodDecl(); 19662 if (!d) { 19663 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19664 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19665 << orig->getSourceRange(); 19666 return ExprError(); 19667 } 19668 } else { 19669 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19670 << E->getSourceRange(); 19671 return ExprError(); 19672 } 19673 19674 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19675 19676 // Never recoverable. 19677 return ExprError(); 19678 } 19679 19680 /// Check for operands with placeholder types and complain if found. 19681 /// Returns ExprError() if there was an error and no recovery was possible. 19682 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19683 if (!Context.isDependenceAllowed()) { 19684 // C cannot handle TypoExpr nodes on either side of a binop because it 19685 // doesn't handle dependent types properly, so make sure any TypoExprs have 19686 // been dealt with before checking the operands. 19687 ExprResult Result = CorrectDelayedTyposInExpr(E); 19688 if (!Result.isUsable()) return ExprError(); 19689 E = Result.get(); 19690 } 19691 19692 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19693 if (!placeholderType) return E; 19694 19695 switch (placeholderType->getKind()) { 19696 19697 // Overloaded expressions. 19698 case BuiltinType::Overload: { 19699 // Try to resolve a single function template specialization. 19700 // This is obligatory. 19701 ExprResult Result = E; 19702 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19703 return Result; 19704 19705 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19706 // leaves Result unchanged on failure. 19707 Result = E; 19708 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19709 return Result; 19710 19711 // If that failed, try to recover with a call. 19712 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19713 /*complain*/ true); 19714 return Result; 19715 } 19716 19717 // Bound member functions. 19718 case BuiltinType::BoundMember: { 19719 ExprResult result = E; 19720 const Expr *BME = E->IgnoreParens(); 19721 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19722 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19723 if (isa<CXXPseudoDestructorExpr>(BME)) { 19724 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19725 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19726 if (ME->getMemberNameInfo().getName().getNameKind() == 19727 DeclarationName::CXXDestructorName) 19728 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19729 } 19730 tryToRecoverWithCall(result, PD, 19731 /*complain*/ true); 19732 return result; 19733 } 19734 19735 // ARC unbridged casts. 19736 case BuiltinType::ARCUnbridgedCast: { 19737 Expr *realCast = stripARCUnbridgedCast(E); 19738 diagnoseARCUnbridgedCast(realCast); 19739 return realCast; 19740 } 19741 19742 // Expressions of unknown type. 19743 case BuiltinType::UnknownAny: 19744 return diagnoseUnknownAnyExpr(*this, E); 19745 19746 // Pseudo-objects. 19747 case BuiltinType::PseudoObject: 19748 return checkPseudoObjectRValue(E); 19749 19750 case BuiltinType::BuiltinFn: { 19751 // Accept __noop without parens by implicitly converting it to a call expr. 19752 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19753 if (DRE) { 19754 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19755 if (FD->getBuiltinID() == Builtin::BI__noop) { 19756 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19757 CK_BuiltinFnToFnPtr) 19758 .get(); 19759 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19760 VK_PRValue, SourceLocation(), 19761 FPOptionsOverride()); 19762 } 19763 } 19764 19765 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19766 return ExprError(); 19767 } 19768 19769 case BuiltinType::IncompleteMatrixIdx: 19770 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19771 ->getRowIdx() 19772 ->getBeginLoc(), 19773 diag::err_matrix_incomplete_index); 19774 return ExprError(); 19775 19776 // Expressions of unknown type. 19777 case BuiltinType::OMPArraySection: 19778 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19779 return ExprError(); 19780 19781 // Expressions of unknown type. 19782 case BuiltinType::OMPArrayShaping: 19783 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19784 19785 case BuiltinType::OMPIterator: 19786 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19787 19788 // Everything else should be impossible. 19789 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19790 case BuiltinType::Id: 19791 #include "clang/Basic/OpenCLImageTypes.def" 19792 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19793 case BuiltinType::Id: 19794 #include "clang/Basic/OpenCLExtensionTypes.def" 19795 #define SVE_TYPE(Name, Id, SingletonId) \ 19796 case BuiltinType::Id: 19797 #include "clang/Basic/AArch64SVEACLETypes.def" 19798 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19799 case BuiltinType::Id: 19800 #include "clang/Basic/PPCTypes.def" 19801 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19802 #include "clang/Basic/RISCVVTypes.def" 19803 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19804 #define PLACEHOLDER_TYPE(Id, SingletonId) 19805 #include "clang/AST/BuiltinTypes.def" 19806 break; 19807 } 19808 19809 llvm_unreachable("invalid placeholder type!"); 19810 } 19811 19812 bool Sema::CheckCaseExpression(Expr *E) { 19813 if (E->isTypeDependent()) 19814 return true; 19815 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19816 return E->getType()->isIntegralOrEnumerationType(); 19817 return false; 19818 } 19819 19820 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19821 ExprResult 19822 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19823 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19824 "Unknown Objective-C Boolean value!"); 19825 QualType BoolT = Context.ObjCBuiltinBoolTy; 19826 if (!Context.getBOOLDecl()) { 19827 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19828 Sema::LookupOrdinaryName); 19829 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19830 NamedDecl *ND = Result.getFoundDecl(); 19831 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19832 Context.setBOOLDecl(TD); 19833 } 19834 } 19835 if (Context.getBOOLDecl()) 19836 BoolT = Context.getBOOLType(); 19837 return new (Context) 19838 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19839 } 19840 19841 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19842 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19843 SourceLocation RParen) { 19844 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19845 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19846 return Spec.getPlatform() == Platform; 19847 }); 19848 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19849 // for "maccatalyst" if "maccatalyst" is not specified. 19850 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19851 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19852 return Spec.getPlatform() == "ios"; 19853 }); 19854 } 19855 if (Spec == AvailSpecs.end()) 19856 return None; 19857 return Spec->getVersion(); 19858 }; 19859 19860 VersionTuple Version; 19861 if (auto MaybeVersion = 19862 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19863 Version = *MaybeVersion; 19864 19865 // The use of `@available` in the enclosing context should be analyzed to 19866 // warn when it's used inappropriately (i.e. not if(@available)). 19867 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19868 Context->HasPotentialAvailabilityViolations = true; 19869 19870 return new (Context) 19871 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19872 } 19873 19874 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19875 ArrayRef<Expr *> SubExprs, QualType T) { 19876 if (!Context.getLangOpts().RecoveryAST) 19877 return ExprError(); 19878 19879 if (isSFINAEContext()) 19880 return ExprError(); 19881 19882 if (T.isNull() || T->isUndeducedType() || 19883 !Context.getLangOpts().RecoveryASTType) 19884 // We don't know the concrete type, fallback to dependent type. 19885 T = Context.DependentTy; 19886 19887 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19888 } 19889