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/Support/ConvertUTF.h" 51 #include "llvm/Support/SaveAndRestore.h" 52 using namespace clang; 53 using namespace sema; 54 using llvm::RoundingMode; 55 56 /// Determine whether the use of this declaration is valid, without 57 /// emitting diagnostics. 58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 59 // See if this is an auto-typed variable whose initializer we are parsing. 60 if (ParsingInitForAutoVars.count(D)) 61 return false; 62 63 // See if this is a deleted function. 64 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 65 if (FD->isDeleted()) 66 return false; 67 68 // If the function has a deduced return type, and we can't deduce it, 69 // then we can't use it either. 70 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 71 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 72 return false; 73 74 // See if this is an aligned allocation/deallocation function that is 75 // unavailable. 76 if (TreatUnavailableAsInvalid && 77 isUnavailableAlignedAllocationFunction(*FD)) 78 return false; 79 } 80 81 // See if this function is unavailable. 82 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 83 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 84 return false; 85 86 return true; 87 } 88 89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 90 // Warn if this is used but marked unused. 91 if (const auto *A = D->getAttr<UnusedAttr>()) { 92 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 93 // should diagnose them. 94 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 95 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 96 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 97 if (DC && !DC->hasAttr<UnusedAttr>()) 98 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 99 } 100 } 101 } 102 103 /// Emit a note explaining that this function is deleted. 104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 105 assert(Decl && Decl->isDeleted()); 106 107 if (Decl->isDefaulted()) { 108 // If the method was explicitly defaulted, point at that declaration. 109 if (!Decl->isImplicit()) 110 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 111 112 // Try to diagnose why this special member function was implicitly 113 // deleted. This might fail, if that reason no longer applies. 114 DiagnoseDeletedDefaultedFunction(Decl); 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 253 // See if this is a deleted function. 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // [expr.prim.id]p4 267 // A program that refers explicitly or implicitly to a function with a 268 // trailing requires-clause whose constraint-expression is not satisfied, 269 // other than to declare it, is ill-formed. [...] 270 // 271 // See if this is a function with constraints that need to be satisfied. 272 // Check this before deducing the return type, as it might instantiate the 273 // definition. 274 if (FD->getTrailingRequiresClause()) { 275 ConstraintSatisfaction Satisfaction; 276 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 277 // A diagnostic will have already been generated (non-constant 278 // constraint expression, for example) 279 return true; 280 if (!Satisfaction.IsSatisfied) { 281 Diag(Loc, 282 diag::err_reference_to_function_with_unsatisfied_constraints) 283 << D; 284 DiagnoseUnsatisfiedConstraint(Satisfaction); 285 return true; 286 } 287 } 288 289 // If the function has a deduced return type, and we can't deduce it, 290 // then we can't use it either. 291 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 292 DeduceReturnType(FD, Loc)) 293 return true; 294 295 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 296 return true; 297 298 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 299 return true; 300 } 301 302 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 303 // Lambdas are only default-constructible or assignable in C++2a onwards. 304 if (MD->getParent()->isLambda() && 305 ((isa<CXXConstructorDecl>(MD) && 306 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 307 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 308 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 309 << !isa<CXXConstructorDecl>(MD); 310 } 311 } 312 313 auto getReferencedObjCProp = [](const NamedDecl *D) -> 314 const ObjCPropertyDecl * { 315 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 316 return MD->findPropertyDecl(); 317 return nullptr; 318 }; 319 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 320 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 321 return true; 322 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 323 return true; 324 } 325 326 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 327 // Only the variables omp_in and omp_out are allowed in the combiner. 328 // Only the variables omp_priv and omp_orig are allowed in the 329 // initializer-clause. 330 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 331 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 332 isa<VarDecl>(D)) { 333 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 334 << getCurFunction()->HasOMPDeclareReductionCombiner; 335 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 336 return true; 337 } 338 339 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 340 // List-items in map clauses on this construct may only refer to the declared 341 // variable var and entities that could be referenced by a procedure defined 342 // at the same location 343 if (LangOpts.OpenMP && isa<VarDecl>(D) && 344 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << getOpenMPDeclareMapperVarName(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 // CUDA/HIP: Diagnose invalid references of host global variables in device 359 // functions. Reference of device global variables in host functions is 360 // allowed through shadow variables therefore it is not diagnosed. 361 if (LangOpts.CUDAIsDevice) { 362 auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); 363 auto Target = IdentifyCUDATarget(FD); 364 if (FD && Target != CFT_Host) { 365 const auto *VD = dyn_cast<VarDecl>(D); 366 if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && 367 !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && 368 !VD->getType()->isCUDADeviceBuiltinSurfaceType() && 369 !VD->getType()->isCUDADeviceBuiltinTextureType() && 370 !VD->isConstexpr() && !VD->getType().isConstQualified()) 371 targetDiag(*Locs.begin(), diag::err_ref_bad_target) 372 << /*host*/ 2 << /*variable*/ 1 << VD << Target; 373 } 374 } 375 376 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 377 if (auto *VD = dyn_cast<ValueDecl>(D)) 378 checkDeviceDecl(VD, Loc); 379 380 if (!Context.getTargetInfo().isTLSSupported()) 381 if (const auto *VD = dyn_cast<VarDecl>(D)) 382 if (VD->getTLSKind() != VarDecl::TLS_None) 383 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 384 } 385 386 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 387 !isUnevaluatedContext()) { 388 // C++ [expr.prim.req.nested] p3 389 // A local parameter shall only appear as an unevaluated operand 390 // (Clause 8) within the constraint-expression. 391 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 392 << D; 393 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 394 return true; 395 } 396 397 return false; 398 } 399 400 /// DiagnoseSentinelCalls - This routine checks whether a call or 401 /// message-send is to a declaration with the sentinel attribute, and 402 /// if so, it checks that the requirements of the sentinel are 403 /// satisfied. 404 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 405 ArrayRef<Expr *> Args) { 406 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 407 if (!attr) 408 return; 409 410 // The number of formal parameters of the declaration. 411 unsigned numFormalParams; 412 413 // The kind of declaration. This is also an index into a %select in 414 // the diagnostic. 415 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 416 417 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 418 numFormalParams = MD->param_size(); 419 calleeType = CT_Method; 420 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 421 numFormalParams = FD->param_size(); 422 calleeType = CT_Function; 423 } else if (isa<VarDecl>(D)) { 424 QualType type = cast<ValueDecl>(D)->getType(); 425 const FunctionType *fn = nullptr; 426 if (const PointerType *ptr = type->getAs<PointerType>()) { 427 fn = ptr->getPointeeType()->getAs<FunctionType>(); 428 if (!fn) return; 429 calleeType = CT_Function; 430 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 431 fn = ptr->getPointeeType()->castAs<FunctionType>(); 432 calleeType = CT_Block; 433 } else { 434 return; 435 } 436 437 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 438 numFormalParams = proto->getNumParams(); 439 } else { 440 numFormalParams = 0; 441 } 442 } else { 443 return; 444 } 445 446 // "nullPos" is the number of formal parameters at the end which 447 // effectively count as part of the variadic arguments. This is 448 // useful if you would prefer to not have *any* formal parameters, 449 // but the language forces you to have at least one. 450 unsigned nullPos = attr->getNullPos(); 451 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 452 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 453 454 // The number of arguments which should follow the sentinel. 455 unsigned numArgsAfterSentinel = attr->getSentinel(); 456 457 // If there aren't enough arguments for all the formal parameters, 458 // the sentinel, and the args after the sentinel, complain. 459 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 460 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 461 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 462 return; 463 } 464 465 // Otherwise, find the sentinel expression. 466 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 467 if (!sentinelExpr) return; 468 if (sentinelExpr->isValueDependent()) return; 469 if (Context.isSentinelNullExpr(sentinelExpr)) return; 470 471 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 472 // or 'NULL' if those are actually defined in the context. Only use 473 // 'nil' for ObjC methods, where it's much more likely that the 474 // variadic arguments form a list of object pointers. 475 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 476 std::string NullValue; 477 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 478 NullValue = "nil"; 479 else if (getLangOpts().CPlusPlus11) 480 NullValue = "nullptr"; 481 else if (PP.isMacroDefined("NULL")) 482 NullValue = "NULL"; 483 else 484 NullValue = "(void*) 0"; 485 486 if (MissingNilLoc.isInvalid()) 487 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 488 else 489 Diag(MissingNilLoc, diag::warn_missing_sentinel) 490 << int(calleeType) 491 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 492 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 493 } 494 495 SourceRange Sema::getExprRange(Expr *E) const { 496 return E ? E->getSourceRange() : SourceRange(); 497 } 498 499 //===----------------------------------------------------------------------===// 500 // Standard Promotions and Conversions 501 //===----------------------------------------------------------------------===// 502 503 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 504 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 505 // Handle any placeholder expressions which made it here. 506 if (E->getType()->isPlaceholderType()) { 507 ExprResult result = CheckPlaceholderExpr(E); 508 if (result.isInvalid()) return ExprError(); 509 E = result.get(); 510 } 511 512 QualType Ty = E->getType(); 513 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 514 515 if (Ty->isFunctionType()) { 516 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 517 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 518 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 519 return ExprError(); 520 521 E = ImpCastExprToType(E, Context.getPointerType(Ty), 522 CK_FunctionToPointerDecay).get(); 523 } else if (Ty->isArrayType()) { 524 // In C90 mode, arrays only promote to pointers if the array expression is 525 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 526 // type 'array of type' is converted to an expression that has type 'pointer 527 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 528 // that has type 'array of type' ...". The relevant change is "an lvalue" 529 // (C90) to "an expression" (C99). 530 // 531 // C++ 4.2p1: 532 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 533 // T" can be converted to an rvalue of type "pointer to T". 534 // 535 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 536 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 537 CK_ArrayToPointerDecay).get(); 538 } 539 return E; 540 } 541 542 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 543 // Check to see if we are dereferencing a null pointer. If so, 544 // and if not volatile-qualified, this is undefined behavior that the 545 // optimizer will delete, so warn about it. People sometimes try to use this 546 // to get a deterministic trap and are surprised by clang's behavior. This 547 // only handles the pattern "*null", which is a very syntactic check. 548 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 549 if (UO && UO->getOpcode() == UO_Deref && 550 UO->getSubExpr()->getType()->isPointerType()) { 551 const LangAS AS = 552 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 553 if ((!isTargetAddressSpace(AS) || 554 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 555 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 556 S.Context, Expr::NPC_ValueDependentIsNotNull) && 557 !UO->getType().isVolatileQualified()) { 558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 559 S.PDiag(diag::warn_indirection_through_null) 560 << UO->getSubExpr()->getSourceRange()); 561 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 562 S.PDiag(diag::note_indirection_through_null)); 563 } 564 } 565 } 566 567 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 568 SourceLocation AssignLoc, 569 const Expr* RHS) { 570 const ObjCIvarDecl *IV = OIRE->getDecl(); 571 if (!IV) 572 return; 573 574 DeclarationName MemberName = IV->getDeclName(); 575 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 576 if (!Member || !Member->isStr("isa")) 577 return; 578 579 const Expr *Base = OIRE->getBase(); 580 QualType BaseType = Base->getType(); 581 if (OIRE->isArrow()) 582 BaseType = BaseType->getPointeeType(); 583 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 584 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 585 ObjCInterfaceDecl *ClassDeclared = nullptr; 586 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 587 if (!ClassDeclared->getSuperClass() 588 && (*ClassDeclared->ivar_begin()) == IV) { 589 if (RHS) { 590 NamedDecl *ObjectSetClass = 591 S.LookupSingleName(S.TUScope, 592 &S.Context.Idents.get("object_setClass"), 593 SourceLocation(), S.LookupOrdinaryName); 594 if (ObjectSetClass) { 595 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 596 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 597 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 598 "object_setClass(") 599 << FixItHint::CreateReplacement( 600 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 601 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 602 } 603 else 604 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 605 } else { 606 NamedDecl *ObjectGetClass = 607 S.LookupSingleName(S.TUScope, 608 &S.Context.Idents.get("object_getClass"), 609 SourceLocation(), S.LookupOrdinaryName); 610 if (ObjectGetClass) 611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 612 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 613 "object_getClass(") 614 << FixItHint::CreateReplacement( 615 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 616 else 617 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 618 } 619 S.Diag(IV->getLocation(), diag::note_ivar_decl); 620 } 621 } 622 } 623 624 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 625 // Handle any placeholder expressions which made it here. 626 if (E->getType()->isPlaceholderType()) { 627 ExprResult result = CheckPlaceholderExpr(E); 628 if (result.isInvalid()) return ExprError(); 629 E = result.get(); 630 } 631 632 // C++ [conv.lval]p1: 633 // A glvalue of a non-function, non-array type T can be 634 // converted to a prvalue. 635 if (!E->isGLValue()) return E; 636 637 QualType T = E->getType(); 638 assert(!T.isNull() && "r-value conversion on typeless expression?"); 639 640 // lvalue-to-rvalue conversion cannot be applied to function or array types. 641 if (T->isFunctionType() || T->isArrayType()) 642 return E; 643 644 // We don't want to throw lvalue-to-rvalue casts on top of 645 // expressions of certain types in C++. 646 if (getLangOpts().CPlusPlus && 647 (E->getType() == Context.OverloadTy || 648 T->isDependentType() || 649 T->isRecordType())) 650 return E; 651 652 // The C standard is actually really unclear on this point, and 653 // DR106 tells us what the result should be but not why. It's 654 // generally best to say that void types just doesn't undergo 655 // lvalue-to-rvalue at all. Note that expressions of unqualified 656 // 'void' type are never l-values, but qualified void can be. 657 if (T->isVoidType()) 658 return E; 659 660 // OpenCL usually rejects direct accesses to values of 'half' type. 661 if (getLangOpts().OpenCL && 662 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 663 T->isHalfType()) { 664 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 665 << 0 << T; 666 return ExprError(); 667 } 668 669 CheckForNullPointerDereference(*this, E); 670 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 671 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 672 &Context.Idents.get("object_getClass"), 673 SourceLocation(), LookupOrdinaryName); 674 if (ObjectGetClass) 675 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 676 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 677 << FixItHint::CreateReplacement( 678 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 679 else 680 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 681 } 682 else if (const ObjCIvarRefExpr *OIRE = 683 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 684 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 685 686 // C++ [conv.lval]p1: 687 // [...] If T is a non-class type, the type of the prvalue is the 688 // cv-unqualified version of T. Otherwise, the type of the 689 // rvalue is T. 690 // 691 // C99 6.3.2.1p2: 692 // If the lvalue has qualified type, the value has the unqualified 693 // version of the type of the lvalue; otherwise, the value has the 694 // type of the lvalue. 695 if (T.hasQualifiers()) 696 T = T.getUnqualifiedType(); 697 698 // Under the MS ABI, lock down the inheritance model now. 699 if (T->isMemberPointerType() && 700 Context.getTargetInfo().getCXXABI().isMicrosoft()) 701 (void)isCompleteType(E->getExprLoc(), T); 702 703 ExprResult Res = CheckLValueToRValueConversionOperand(E); 704 if (Res.isInvalid()) 705 return Res; 706 E = Res.get(); 707 708 // Loading a __weak object implicitly retains the value, so we need a cleanup to 709 // balance that. 710 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 711 Cleanup.setExprNeedsCleanups(true); 712 713 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 714 Cleanup.setExprNeedsCleanups(true); 715 716 // C++ [conv.lval]p3: 717 // If T is cv std::nullptr_t, the result is a null pointer constant. 718 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 719 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 720 CurFPFeatureOverrides()); 721 722 // C11 6.3.2.1p2: 723 // ... if the lvalue has atomic type, the value has the non-atomic version 724 // of the type of the lvalue ... 725 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 726 T = Atomic->getValueType().getUnqualifiedType(); 727 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 728 nullptr, VK_RValue, FPOptionsOverride()); 729 } 730 731 return Res; 732 } 733 734 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 735 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 736 if (Res.isInvalid()) 737 return ExprError(); 738 Res = DefaultLvalueConversion(Res.get()); 739 if (Res.isInvalid()) 740 return ExprError(); 741 return Res; 742 } 743 744 /// CallExprUnaryConversions - a special case of an unary conversion 745 /// performed on a function designator of a call expression. 746 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 747 QualType Ty = E->getType(); 748 ExprResult Res = E; 749 // Only do implicit cast for a function type, but not for a pointer 750 // to function type. 751 if (Ty->isFunctionType()) { 752 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 753 CK_FunctionToPointerDecay); 754 if (Res.isInvalid()) 755 return ExprError(); 756 } 757 Res = DefaultLvalueConversion(Res.get()); 758 if (Res.isInvalid()) 759 return ExprError(); 760 return Res.get(); 761 } 762 763 /// UsualUnaryConversions - Performs various conversions that are common to most 764 /// operators (C99 6.3). The conversions of array and function types are 765 /// sometimes suppressed. For example, the array->pointer conversion doesn't 766 /// apply if the array is an argument to the sizeof or address (&) operators. 767 /// In these instances, this routine should *not* be called. 768 ExprResult Sema::UsualUnaryConversions(Expr *E) { 769 // First, convert to an r-value. 770 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 771 if (Res.isInvalid()) 772 return ExprError(); 773 E = Res.get(); 774 775 QualType Ty = E->getType(); 776 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 777 778 // Half FP have to be promoted to float unless it is natively supported 779 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 780 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 781 782 // Try to perform integral promotions if the object has a theoretically 783 // promotable type. 784 if (Ty->isIntegralOrUnscopedEnumerationType()) { 785 // C99 6.3.1.1p2: 786 // 787 // The following may be used in an expression wherever an int or 788 // unsigned int may be used: 789 // - an object or expression with an integer type whose integer 790 // conversion rank is less than or equal to the rank of int 791 // and unsigned int. 792 // - A bit-field of type _Bool, int, signed int, or unsigned int. 793 // 794 // If an int can represent all values of the original type, the 795 // value is converted to an int; otherwise, it is converted to an 796 // unsigned int. These are called the integer promotions. All 797 // other types are unchanged by the integer promotions. 798 799 QualType PTy = Context.isPromotableBitField(E); 800 if (!PTy.isNull()) { 801 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 802 return E; 803 } 804 if (Ty->isPromotableIntegerType()) { 805 QualType PT = Context.getPromotedIntegerType(Ty); 806 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 807 return E; 808 } 809 } 810 return E; 811 } 812 813 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 814 /// do not have a prototype. Arguments that have type float or __fp16 815 /// are promoted to double. All other argument types are converted by 816 /// UsualUnaryConversions(). 817 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 818 QualType Ty = E->getType(); 819 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 820 821 ExprResult Res = UsualUnaryConversions(E); 822 if (Res.isInvalid()) 823 return ExprError(); 824 E = Res.get(); 825 826 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 827 // promote to double. 828 // Note that default argument promotion applies only to float (and 829 // half/fp16); it does not apply to _Float16. 830 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 831 if (BTy && (BTy->getKind() == BuiltinType::Half || 832 BTy->getKind() == BuiltinType::Float)) { 833 if (getLangOpts().OpenCL && 834 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 835 if (BTy->getKind() == BuiltinType::Half) { 836 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 837 } 838 } else { 839 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 840 } 841 } 842 843 // C++ performs lvalue-to-rvalue conversion as a default argument 844 // promotion, even on class types, but note: 845 // C++11 [conv.lval]p2: 846 // When an lvalue-to-rvalue conversion occurs in an unevaluated 847 // operand or a subexpression thereof the value contained in the 848 // referenced object is not accessed. Otherwise, if the glvalue 849 // has a class type, the conversion copy-initializes a temporary 850 // of type T from the glvalue and the result of the conversion 851 // is a prvalue for the temporary. 852 // FIXME: add some way to gate this entire thing for correctness in 853 // potentially potentially evaluated contexts. 854 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 855 ExprResult Temp = PerformCopyInitialization( 856 InitializedEntity::InitializeTemporary(E->getType()), 857 E->getExprLoc(), E); 858 if (Temp.isInvalid()) 859 return ExprError(); 860 E = Temp.get(); 861 } 862 863 return E; 864 } 865 866 /// Determine the degree of POD-ness for an expression. 867 /// Incomplete types are considered POD, since this check can be performed 868 /// when we're in an unevaluated context. 869 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 870 if (Ty->isIncompleteType()) { 871 // C++11 [expr.call]p7: 872 // After these conversions, if the argument does not have arithmetic, 873 // enumeration, pointer, pointer to member, or class type, the program 874 // is ill-formed. 875 // 876 // Since we've already performed array-to-pointer and function-to-pointer 877 // decay, the only such type in C++ is cv void. This also handles 878 // initializer lists as variadic arguments. 879 if (Ty->isVoidType()) 880 return VAK_Invalid; 881 882 if (Ty->isObjCObjectType()) 883 return VAK_Invalid; 884 return VAK_Valid; 885 } 886 887 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 888 return VAK_Invalid; 889 890 if (Ty.isCXX98PODType(Context)) 891 return VAK_Valid; 892 893 // C++11 [expr.call]p7: 894 // Passing a potentially-evaluated argument of class type (Clause 9) 895 // having a non-trivial copy constructor, a non-trivial move constructor, 896 // or a non-trivial destructor, with no corresponding parameter, 897 // is conditionally-supported with implementation-defined semantics. 898 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 899 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 900 if (!Record->hasNonTrivialCopyConstructor() && 901 !Record->hasNonTrivialMoveConstructor() && 902 !Record->hasNonTrivialDestructor()) 903 return VAK_ValidInCXX11; 904 905 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 906 return VAK_Valid; 907 908 if (Ty->isObjCObjectType()) 909 return VAK_Invalid; 910 911 if (getLangOpts().MSVCCompat) 912 return VAK_MSVCUndefined; 913 914 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 915 // permitted to reject them. We should consider doing so. 916 return VAK_Undefined; 917 } 918 919 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 920 // Don't allow one to pass an Objective-C interface to a vararg. 921 const QualType &Ty = E->getType(); 922 VarArgKind VAK = isValidVarArgType(Ty); 923 924 // Complain about passing non-POD types through varargs. 925 switch (VAK) { 926 case VAK_ValidInCXX11: 927 DiagRuntimeBehavior( 928 E->getBeginLoc(), nullptr, 929 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 930 LLVM_FALLTHROUGH; 931 case VAK_Valid: 932 if (Ty->isRecordType()) { 933 // This is unlikely to be what the user intended. If the class has a 934 // 'c_str' member function, the user probably meant to call that. 935 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 936 PDiag(diag::warn_pass_class_arg_to_vararg) 937 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 938 } 939 break; 940 941 case VAK_Undefined: 942 case VAK_MSVCUndefined: 943 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 944 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 945 << getLangOpts().CPlusPlus11 << Ty << CT); 946 break; 947 948 case VAK_Invalid: 949 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 950 Diag(E->getBeginLoc(), 951 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 952 << Ty << CT; 953 else if (Ty->isObjCObjectType()) 954 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 955 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 956 << Ty << CT); 957 else 958 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 959 << isa<InitListExpr>(E) << Ty << CT; 960 break; 961 } 962 } 963 964 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 965 /// will create a trap if the resulting type is not a POD type. 966 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 967 FunctionDecl *FDecl) { 968 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 969 // Strip the unbridged-cast placeholder expression off, if applicable. 970 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 971 (CT == VariadicMethod || 972 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 973 E = stripARCUnbridgedCast(E); 974 975 // Otherwise, do normal placeholder checking. 976 } else { 977 ExprResult ExprRes = CheckPlaceholderExpr(E); 978 if (ExprRes.isInvalid()) 979 return ExprError(); 980 E = ExprRes.get(); 981 } 982 } 983 984 ExprResult ExprRes = DefaultArgumentPromotion(E); 985 if (ExprRes.isInvalid()) 986 return ExprError(); 987 988 // Copy blocks to the heap. 989 if (ExprRes.get()->getType()->isBlockPointerType()) 990 maybeExtendBlockObject(ExprRes); 991 992 E = ExprRes.get(); 993 994 // Diagnostics regarding non-POD argument types are 995 // emitted along with format string checking in Sema::CheckFunctionCall(). 996 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 997 // Turn this into a trap. 998 CXXScopeSpec SS; 999 SourceLocation TemplateKWLoc; 1000 UnqualifiedId Name; 1001 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1002 E->getBeginLoc()); 1003 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1004 /*HasTrailingLParen=*/true, 1005 /*IsAddressOfOperand=*/false); 1006 if (TrapFn.isInvalid()) 1007 return ExprError(); 1008 1009 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1010 None, E->getEndLoc()); 1011 if (Call.isInvalid()) 1012 return ExprError(); 1013 1014 ExprResult Comma = 1015 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1016 if (Comma.isInvalid()) 1017 return ExprError(); 1018 return Comma.get(); 1019 } 1020 1021 if (!getLangOpts().CPlusPlus && 1022 RequireCompleteType(E->getExprLoc(), E->getType(), 1023 diag::err_call_incomplete_argument)) 1024 return ExprError(); 1025 1026 return E; 1027 } 1028 1029 /// Converts an integer to complex float type. Helper function of 1030 /// UsualArithmeticConversions() 1031 /// 1032 /// \return false if the integer expression is an integer type and is 1033 /// successfully converted to the complex type. 1034 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1035 ExprResult &ComplexExpr, 1036 QualType IntTy, 1037 QualType ComplexTy, 1038 bool SkipCast) { 1039 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1040 if (SkipCast) return false; 1041 if (IntTy->isIntegerType()) { 1042 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1043 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1044 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1045 CK_FloatingRealToComplex); 1046 } else { 1047 assert(IntTy->isComplexIntegerType()); 1048 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1049 CK_IntegralComplexToFloatingComplex); 1050 } 1051 return false; 1052 } 1053 1054 /// Handle arithmetic conversion with complex types. Helper function of 1055 /// UsualArithmeticConversions() 1056 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1057 ExprResult &RHS, QualType LHSType, 1058 QualType RHSType, 1059 bool IsCompAssign) { 1060 // if we have an integer operand, the result is the complex type. 1061 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1062 /*skipCast*/false)) 1063 return LHSType; 1064 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1065 /*skipCast*/IsCompAssign)) 1066 return RHSType; 1067 1068 // This handles complex/complex, complex/float, or float/complex. 1069 // When both operands are complex, the shorter operand is converted to the 1070 // type of the longer, and that is the type of the result. This corresponds 1071 // to what is done when combining two real floating-point operands. 1072 // The fun begins when size promotion occur across type domains. 1073 // From H&S 6.3.4: When one operand is complex and the other is a real 1074 // floating-point type, the less precise type is converted, within it's 1075 // real or complex domain, to the precision of the other type. For example, 1076 // when combining a "long double" with a "double _Complex", the 1077 // "double _Complex" is promoted to "long double _Complex". 1078 1079 // Compute the rank of the two types, regardless of whether they are complex. 1080 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1081 1082 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1083 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1084 QualType LHSElementType = 1085 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1086 QualType RHSElementType = 1087 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1088 1089 QualType ResultType = S.Context.getComplexType(LHSElementType); 1090 if (Order < 0) { 1091 // Promote the precision of the LHS if not an assignment. 1092 ResultType = S.Context.getComplexType(RHSElementType); 1093 if (!IsCompAssign) { 1094 if (LHSComplexType) 1095 LHS = 1096 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1097 else 1098 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1099 } 1100 } else if (Order > 0) { 1101 // Promote the precision of the RHS. 1102 if (RHSComplexType) 1103 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1104 else 1105 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1106 } 1107 return ResultType; 1108 } 1109 1110 /// Handle arithmetic conversion from integer to float. Helper function 1111 /// of UsualArithmeticConversions() 1112 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1113 ExprResult &IntExpr, 1114 QualType FloatTy, QualType IntTy, 1115 bool ConvertFloat, bool ConvertInt) { 1116 if (IntTy->isIntegerType()) { 1117 if (ConvertInt) 1118 // Convert intExpr to the lhs floating point type. 1119 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1120 CK_IntegralToFloating); 1121 return FloatTy; 1122 } 1123 1124 // Convert both sides to the appropriate complex float. 1125 assert(IntTy->isComplexIntegerType()); 1126 QualType result = S.Context.getComplexType(FloatTy); 1127 1128 // _Complex int -> _Complex float 1129 if (ConvertInt) 1130 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1131 CK_IntegralComplexToFloatingComplex); 1132 1133 // float -> _Complex float 1134 if (ConvertFloat) 1135 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1136 CK_FloatingRealToComplex); 1137 1138 return result; 1139 } 1140 1141 /// Handle arithmethic conversion with floating point types. Helper 1142 /// function of UsualArithmeticConversions() 1143 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1144 ExprResult &RHS, QualType LHSType, 1145 QualType RHSType, bool IsCompAssign) { 1146 bool LHSFloat = LHSType->isRealFloatingType(); 1147 bool RHSFloat = RHSType->isRealFloatingType(); 1148 1149 // N1169 4.1.4: If one of the operands has a floating type and the other 1150 // operand has a fixed-point type, the fixed-point operand 1151 // is converted to the floating type [...] 1152 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1153 if (LHSFloat) 1154 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1155 else if (!IsCompAssign) 1156 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1157 return LHSFloat ? LHSType : RHSType; 1158 } 1159 1160 // If we have two real floating types, convert the smaller operand 1161 // to the bigger result. 1162 if (LHSFloat && RHSFloat) { 1163 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1164 if (order > 0) { 1165 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1166 return LHSType; 1167 } 1168 1169 assert(order < 0 && "illegal float comparison"); 1170 if (!IsCompAssign) 1171 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1172 return RHSType; 1173 } 1174 1175 if (LHSFloat) { 1176 // Half FP has to be promoted to float unless it is natively supported 1177 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1178 LHSType = S.Context.FloatTy; 1179 1180 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1181 /*ConvertFloat=*/!IsCompAssign, 1182 /*ConvertInt=*/ true); 1183 } 1184 assert(RHSFloat); 1185 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1186 /*ConvertFloat=*/ true, 1187 /*ConvertInt=*/!IsCompAssign); 1188 } 1189 1190 /// Diagnose attempts to convert between __float128 and long double if 1191 /// there is no support for such conversion. Helper function of 1192 /// UsualArithmeticConversions(). 1193 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1194 QualType RHSType) { 1195 /* No issue converting if at least one of the types is not a floating point 1196 type or the two types have the same rank. 1197 */ 1198 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1199 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1200 return false; 1201 1202 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1203 "The remaining types must be floating point types."); 1204 1205 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1206 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1207 1208 QualType LHSElemType = LHSComplex ? 1209 LHSComplex->getElementType() : LHSType; 1210 QualType RHSElemType = RHSComplex ? 1211 RHSComplex->getElementType() : RHSType; 1212 1213 // No issue if the two types have the same representation 1214 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1215 &S.Context.getFloatTypeSemantics(RHSElemType)) 1216 return false; 1217 1218 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1219 RHSElemType == S.Context.LongDoubleTy); 1220 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1221 RHSElemType == S.Context.Float128Ty); 1222 1223 // We've handled the situation where __float128 and long double have the same 1224 // representation. We allow all conversions for all possible long double types 1225 // except PPC's double double. 1226 return Float128AndLongDouble && 1227 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1228 &llvm::APFloat::PPCDoubleDouble()); 1229 } 1230 1231 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1232 1233 namespace { 1234 /// These helper callbacks are placed in an anonymous namespace to 1235 /// permit their use as function template parameters. 1236 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1237 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1238 } 1239 1240 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1241 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1242 CK_IntegralComplexCast); 1243 } 1244 } 1245 1246 /// Handle integer arithmetic conversions. Helper function of 1247 /// UsualArithmeticConversions() 1248 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1249 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1250 ExprResult &RHS, QualType LHSType, 1251 QualType RHSType, bool IsCompAssign) { 1252 // The rules for this case are in C99 6.3.1.8 1253 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1254 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1255 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1256 if (LHSSigned == RHSSigned) { 1257 // Same signedness; use the higher-ranked type 1258 if (order >= 0) { 1259 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1260 return LHSType; 1261 } else if (!IsCompAssign) 1262 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1263 return RHSType; 1264 } else if (order != (LHSSigned ? 1 : -1)) { 1265 // The unsigned type has greater than or equal rank to the 1266 // signed type, so use the unsigned type 1267 if (RHSSigned) { 1268 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1269 return LHSType; 1270 } else if (!IsCompAssign) 1271 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1272 return RHSType; 1273 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1274 // The two types are different widths; if we are here, that 1275 // means the signed type is larger than the unsigned type, so 1276 // use the signed type. 1277 if (LHSSigned) { 1278 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1279 return LHSType; 1280 } else if (!IsCompAssign) 1281 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1282 return RHSType; 1283 } else { 1284 // The signed type is higher-ranked than the unsigned type, 1285 // but isn't actually any bigger (like unsigned int and long 1286 // on most 32-bit systems). Use the unsigned type corresponding 1287 // to the signed type. 1288 QualType result = 1289 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1290 RHS = (*doRHSCast)(S, RHS.get(), result); 1291 if (!IsCompAssign) 1292 LHS = (*doLHSCast)(S, LHS.get(), result); 1293 return result; 1294 } 1295 } 1296 1297 /// Handle conversions with GCC complex int extension. Helper function 1298 /// of UsualArithmeticConversions() 1299 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1300 ExprResult &RHS, QualType LHSType, 1301 QualType RHSType, 1302 bool IsCompAssign) { 1303 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1304 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1305 1306 if (LHSComplexInt && RHSComplexInt) { 1307 QualType LHSEltType = LHSComplexInt->getElementType(); 1308 QualType RHSEltType = RHSComplexInt->getElementType(); 1309 QualType ScalarType = 1310 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1311 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1312 1313 return S.Context.getComplexType(ScalarType); 1314 } 1315 1316 if (LHSComplexInt) { 1317 QualType LHSEltType = LHSComplexInt->getElementType(); 1318 QualType ScalarType = 1319 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1320 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1321 QualType ComplexType = S.Context.getComplexType(ScalarType); 1322 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1323 CK_IntegralRealToComplex); 1324 1325 return ComplexType; 1326 } 1327 1328 assert(RHSComplexInt); 1329 1330 QualType RHSEltType = RHSComplexInt->getElementType(); 1331 QualType ScalarType = 1332 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1333 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1334 QualType ComplexType = S.Context.getComplexType(ScalarType); 1335 1336 if (!IsCompAssign) 1337 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1338 CK_IntegralRealToComplex); 1339 return ComplexType; 1340 } 1341 1342 /// Return the rank of a given fixed point or integer type. The value itself 1343 /// doesn't matter, but the values must be increasing with proper increasing 1344 /// rank as described in N1169 4.1.1. 1345 static unsigned GetFixedPointRank(QualType Ty) { 1346 const auto *BTy = Ty->getAs<BuiltinType>(); 1347 assert(BTy && "Expected a builtin type."); 1348 1349 switch (BTy->getKind()) { 1350 case BuiltinType::ShortFract: 1351 case BuiltinType::UShortFract: 1352 case BuiltinType::SatShortFract: 1353 case BuiltinType::SatUShortFract: 1354 return 1; 1355 case BuiltinType::Fract: 1356 case BuiltinType::UFract: 1357 case BuiltinType::SatFract: 1358 case BuiltinType::SatUFract: 1359 return 2; 1360 case BuiltinType::LongFract: 1361 case BuiltinType::ULongFract: 1362 case BuiltinType::SatLongFract: 1363 case BuiltinType::SatULongFract: 1364 return 3; 1365 case BuiltinType::ShortAccum: 1366 case BuiltinType::UShortAccum: 1367 case BuiltinType::SatShortAccum: 1368 case BuiltinType::SatUShortAccum: 1369 return 4; 1370 case BuiltinType::Accum: 1371 case BuiltinType::UAccum: 1372 case BuiltinType::SatAccum: 1373 case BuiltinType::SatUAccum: 1374 return 5; 1375 case BuiltinType::LongAccum: 1376 case BuiltinType::ULongAccum: 1377 case BuiltinType::SatLongAccum: 1378 case BuiltinType::SatULongAccum: 1379 return 6; 1380 default: 1381 if (BTy->isInteger()) 1382 return 0; 1383 llvm_unreachable("Unexpected fixed point or integer type"); 1384 } 1385 } 1386 1387 /// handleFixedPointConversion - Fixed point operations between fixed 1388 /// point types and integers or other fixed point types do not fall under 1389 /// usual arithmetic conversion since these conversions could result in loss 1390 /// of precsision (N1169 4.1.4). These operations should be calculated with 1391 /// the full precision of their result type (N1169 4.1.6.2.1). 1392 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1393 QualType RHSTy) { 1394 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1395 "Expected at least one of the operands to be a fixed point type"); 1396 assert((LHSTy->isFixedPointOrIntegerType() || 1397 RHSTy->isFixedPointOrIntegerType()) && 1398 "Special fixed point arithmetic operation conversions are only " 1399 "applied to ints or other fixed point types"); 1400 1401 // If one operand has signed fixed-point type and the other operand has 1402 // unsigned fixed-point type, then the unsigned fixed-point operand is 1403 // converted to its corresponding signed fixed-point type and the resulting 1404 // type is the type of the converted operand. 1405 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1406 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1407 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1408 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1409 1410 // The result type is the type with the highest rank, whereby a fixed-point 1411 // conversion rank is always greater than an integer conversion rank; if the 1412 // type of either of the operands is a saturating fixedpoint type, the result 1413 // type shall be the saturating fixed-point type corresponding to the type 1414 // with the highest rank; the resulting value is converted (taking into 1415 // account rounding and overflow) to the precision of the resulting type. 1416 // Same ranks between signed and unsigned types are resolved earlier, so both 1417 // types are either signed or both unsigned at this point. 1418 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1419 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1420 1421 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1422 1423 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1424 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1425 1426 return ResultTy; 1427 } 1428 1429 /// Check that the usual arithmetic conversions can be performed on this pair of 1430 /// expressions that might be of enumeration type. 1431 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1432 SourceLocation Loc, 1433 Sema::ArithConvKind ACK) { 1434 // C++2a [expr.arith.conv]p1: 1435 // If one operand is of enumeration type and the other operand is of a 1436 // different enumeration type or a floating-point type, this behavior is 1437 // deprecated ([depr.arith.conv.enum]). 1438 // 1439 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1440 // Eventually we will presumably reject these cases (in C++23 onwards?). 1441 QualType L = LHS->getType(), R = RHS->getType(); 1442 bool LEnum = L->isUnscopedEnumerationType(), 1443 REnum = R->isUnscopedEnumerationType(); 1444 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1445 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1446 (REnum && L->isFloatingType())) { 1447 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1448 ? diag::warn_arith_conv_enum_float_cxx20 1449 : diag::warn_arith_conv_enum_float) 1450 << LHS->getSourceRange() << RHS->getSourceRange() 1451 << (int)ACK << LEnum << L << R; 1452 } else if (!IsCompAssign && LEnum && REnum && 1453 !S.Context.hasSameUnqualifiedType(L, R)) { 1454 unsigned DiagID; 1455 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1456 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1457 // If either enumeration type is unnamed, it's less likely that the 1458 // user cares about this, but this situation is still deprecated in 1459 // C++2a. Use a different warning group. 1460 DiagID = S.getLangOpts().CPlusPlus20 1461 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1462 : diag::warn_arith_conv_mixed_anon_enum_types; 1463 } else if (ACK == Sema::ACK_Conditional) { 1464 // Conditional expressions are separated out because they have 1465 // historically had a different warning flag. 1466 DiagID = S.getLangOpts().CPlusPlus20 1467 ? diag::warn_conditional_mixed_enum_types_cxx20 1468 : diag::warn_conditional_mixed_enum_types; 1469 } else if (ACK == Sema::ACK_Comparison) { 1470 // Comparison expressions are separated out because they have 1471 // historically had a different warning flag. 1472 DiagID = S.getLangOpts().CPlusPlus20 1473 ? diag::warn_comparison_mixed_enum_types_cxx20 1474 : diag::warn_comparison_mixed_enum_types; 1475 } else { 1476 DiagID = S.getLangOpts().CPlusPlus20 1477 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1478 : diag::warn_arith_conv_mixed_enum_types; 1479 } 1480 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1481 << (int)ACK << L << R; 1482 } 1483 } 1484 1485 /// UsualArithmeticConversions - Performs various conversions that are common to 1486 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1487 /// routine returns the first non-arithmetic type found. The client is 1488 /// responsible for emitting appropriate error diagnostics. 1489 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1490 SourceLocation Loc, 1491 ArithConvKind ACK) { 1492 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1493 1494 if (ACK != ACK_CompAssign) { 1495 LHS = UsualUnaryConversions(LHS.get()); 1496 if (LHS.isInvalid()) 1497 return QualType(); 1498 } 1499 1500 RHS = UsualUnaryConversions(RHS.get()); 1501 if (RHS.isInvalid()) 1502 return QualType(); 1503 1504 // For conversion purposes, we ignore any qualifiers. 1505 // For example, "const float" and "float" are equivalent. 1506 QualType LHSType = 1507 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1508 QualType RHSType = 1509 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1510 1511 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1512 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1513 LHSType = AtomicLHS->getValueType(); 1514 1515 // If both types are identical, no conversion is needed. 1516 if (LHSType == RHSType) 1517 return LHSType; 1518 1519 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1520 // The caller can deal with this (e.g. pointer + int). 1521 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1522 return QualType(); 1523 1524 // Apply unary and bitfield promotions to the LHS's type. 1525 QualType LHSUnpromotedType = LHSType; 1526 if (LHSType->isPromotableIntegerType()) 1527 LHSType = Context.getPromotedIntegerType(LHSType); 1528 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1529 if (!LHSBitfieldPromoteTy.isNull()) 1530 LHSType = LHSBitfieldPromoteTy; 1531 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1532 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1533 1534 // If both types are identical, no conversion is needed. 1535 if (LHSType == RHSType) 1536 return LHSType; 1537 1538 // ExtInt types aren't subject to conversions between them or normal integers, 1539 // so this fails. 1540 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1541 return QualType(); 1542 1543 // At this point, we have two different arithmetic types. 1544 1545 // Diagnose attempts to convert between __float128 and long double where 1546 // such conversions currently can't be handled. 1547 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1548 return QualType(); 1549 1550 // Handle complex types first (C99 6.3.1.8p1). 1551 if (LHSType->isComplexType() || RHSType->isComplexType()) 1552 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1553 ACK == ACK_CompAssign); 1554 1555 // Now handle "real" floating types (i.e. float, double, long double). 1556 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1557 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1558 ACK == ACK_CompAssign); 1559 1560 // Handle GCC complex int extension. 1561 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1562 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1563 ACK == ACK_CompAssign); 1564 1565 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1566 return handleFixedPointConversion(*this, LHSType, RHSType); 1567 1568 // Finally, we have two differing integer types. 1569 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1570 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1571 } 1572 1573 //===----------------------------------------------------------------------===// 1574 // Semantic Analysis for various Expression Types 1575 //===----------------------------------------------------------------------===// 1576 1577 1578 ExprResult 1579 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1580 SourceLocation DefaultLoc, 1581 SourceLocation RParenLoc, 1582 Expr *ControllingExpr, 1583 ArrayRef<ParsedType> ArgTypes, 1584 ArrayRef<Expr *> ArgExprs) { 1585 unsigned NumAssocs = ArgTypes.size(); 1586 assert(NumAssocs == ArgExprs.size()); 1587 1588 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1589 for (unsigned i = 0; i < NumAssocs; ++i) { 1590 if (ArgTypes[i]) 1591 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1592 else 1593 Types[i] = nullptr; 1594 } 1595 1596 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1597 ControllingExpr, 1598 llvm::makeArrayRef(Types, NumAssocs), 1599 ArgExprs); 1600 delete [] Types; 1601 return ER; 1602 } 1603 1604 ExprResult 1605 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1606 SourceLocation DefaultLoc, 1607 SourceLocation RParenLoc, 1608 Expr *ControllingExpr, 1609 ArrayRef<TypeSourceInfo *> Types, 1610 ArrayRef<Expr *> Exprs) { 1611 unsigned NumAssocs = Types.size(); 1612 assert(NumAssocs == Exprs.size()); 1613 1614 // Decay and strip qualifiers for the controlling expression type, and handle 1615 // placeholder type replacement. See committee discussion from WG14 DR423. 1616 { 1617 EnterExpressionEvaluationContext Unevaluated( 1618 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1619 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1620 if (R.isInvalid()) 1621 return ExprError(); 1622 ControllingExpr = R.get(); 1623 } 1624 1625 // The controlling expression is an unevaluated operand, so side effects are 1626 // likely unintended. 1627 if (!inTemplateInstantiation() && 1628 ControllingExpr->HasSideEffects(Context, false)) 1629 Diag(ControllingExpr->getExprLoc(), 1630 diag::warn_side_effects_unevaluated_context); 1631 1632 bool TypeErrorFound = false, 1633 IsResultDependent = ControllingExpr->isTypeDependent(), 1634 ContainsUnexpandedParameterPack 1635 = ControllingExpr->containsUnexpandedParameterPack(); 1636 1637 for (unsigned i = 0; i < NumAssocs; ++i) { 1638 if (Exprs[i]->containsUnexpandedParameterPack()) 1639 ContainsUnexpandedParameterPack = true; 1640 1641 if (Types[i]) { 1642 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1643 ContainsUnexpandedParameterPack = true; 1644 1645 if (Types[i]->getType()->isDependentType()) { 1646 IsResultDependent = true; 1647 } else { 1648 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1649 // complete object type other than a variably modified type." 1650 unsigned D = 0; 1651 if (Types[i]->getType()->isIncompleteType()) 1652 D = diag::err_assoc_type_incomplete; 1653 else if (!Types[i]->getType()->isObjectType()) 1654 D = diag::err_assoc_type_nonobject; 1655 else if (Types[i]->getType()->isVariablyModifiedType()) 1656 D = diag::err_assoc_type_variably_modified; 1657 1658 if (D != 0) { 1659 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1660 << Types[i]->getTypeLoc().getSourceRange() 1661 << Types[i]->getType(); 1662 TypeErrorFound = true; 1663 } 1664 1665 // C11 6.5.1.1p2 "No two generic associations in the same generic 1666 // selection shall specify compatible types." 1667 for (unsigned j = i+1; j < NumAssocs; ++j) 1668 if (Types[j] && !Types[j]->getType()->isDependentType() && 1669 Context.typesAreCompatible(Types[i]->getType(), 1670 Types[j]->getType())) { 1671 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1672 diag::err_assoc_compatible_types) 1673 << Types[j]->getTypeLoc().getSourceRange() 1674 << Types[j]->getType() 1675 << Types[i]->getType(); 1676 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1677 diag::note_compat_assoc) 1678 << Types[i]->getTypeLoc().getSourceRange() 1679 << Types[i]->getType(); 1680 TypeErrorFound = true; 1681 } 1682 } 1683 } 1684 } 1685 if (TypeErrorFound) 1686 return ExprError(); 1687 1688 // If we determined that the generic selection is result-dependent, don't 1689 // try to compute the result expression. 1690 if (IsResultDependent) 1691 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1692 Exprs, DefaultLoc, RParenLoc, 1693 ContainsUnexpandedParameterPack); 1694 1695 SmallVector<unsigned, 1> CompatIndices; 1696 unsigned DefaultIndex = -1U; 1697 for (unsigned i = 0; i < NumAssocs; ++i) { 1698 if (!Types[i]) 1699 DefaultIndex = i; 1700 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1701 Types[i]->getType())) 1702 CompatIndices.push_back(i); 1703 } 1704 1705 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1706 // type compatible with at most one of the types named in its generic 1707 // association list." 1708 if (CompatIndices.size() > 1) { 1709 // We strip parens here because the controlling expression is typically 1710 // parenthesized in macro definitions. 1711 ControllingExpr = ControllingExpr->IgnoreParens(); 1712 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1713 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1714 << (unsigned)CompatIndices.size(); 1715 for (unsigned I : CompatIndices) { 1716 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1717 diag::note_compat_assoc) 1718 << Types[I]->getTypeLoc().getSourceRange() 1719 << Types[I]->getType(); 1720 } 1721 return ExprError(); 1722 } 1723 1724 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1725 // its controlling expression shall have type compatible with exactly one of 1726 // the types named in its generic association list." 1727 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1728 // We strip parens here because the controlling expression is typically 1729 // parenthesized in macro definitions. 1730 ControllingExpr = ControllingExpr->IgnoreParens(); 1731 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1732 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1733 return ExprError(); 1734 } 1735 1736 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1737 // type name that is compatible with the type of the controlling expression, 1738 // then the result expression of the generic selection is the expression 1739 // in that generic association. Otherwise, the result expression of the 1740 // generic selection is the expression in the default generic association." 1741 unsigned ResultIndex = 1742 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1743 1744 return GenericSelectionExpr::Create( 1745 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1746 ContainsUnexpandedParameterPack, ResultIndex); 1747 } 1748 1749 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1750 /// location of the token and the offset of the ud-suffix within it. 1751 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1752 unsigned Offset) { 1753 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1754 S.getLangOpts()); 1755 } 1756 1757 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1758 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1759 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1760 IdentifierInfo *UDSuffix, 1761 SourceLocation UDSuffixLoc, 1762 ArrayRef<Expr*> Args, 1763 SourceLocation LitEndLoc) { 1764 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1765 1766 QualType ArgTy[2]; 1767 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1768 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1769 if (ArgTy[ArgIdx]->isArrayType()) 1770 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1771 } 1772 1773 DeclarationName OpName = 1774 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1775 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1776 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1777 1778 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1779 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1780 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1781 /*AllowStringTemplatePack*/ false, 1782 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1783 return ExprError(); 1784 1785 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1786 } 1787 1788 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1789 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1790 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1791 /// multiple tokens. However, the common case is that StringToks points to one 1792 /// string. 1793 /// 1794 ExprResult 1795 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1796 assert(!StringToks.empty() && "Must have at least one string!"); 1797 1798 StringLiteralParser Literal(StringToks, PP); 1799 if (Literal.hadError) 1800 return ExprError(); 1801 1802 SmallVector<SourceLocation, 4> StringTokLocs; 1803 for (const Token &Tok : StringToks) 1804 StringTokLocs.push_back(Tok.getLocation()); 1805 1806 QualType CharTy = Context.CharTy; 1807 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1808 if (Literal.isWide()) { 1809 CharTy = Context.getWideCharType(); 1810 Kind = StringLiteral::Wide; 1811 } else if (Literal.isUTF8()) { 1812 if (getLangOpts().Char8) 1813 CharTy = Context.Char8Ty; 1814 Kind = StringLiteral::UTF8; 1815 } else if (Literal.isUTF16()) { 1816 CharTy = Context.Char16Ty; 1817 Kind = StringLiteral::UTF16; 1818 } else if (Literal.isUTF32()) { 1819 CharTy = Context.Char32Ty; 1820 Kind = StringLiteral::UTF32; 1821 } else if (Literal.isPascal()) { 1822 CharTy = Context.UnsignedCharTy; 1823 } 1824 1825 // Warn on initializing an array of char from a u8 string literal; this 1826 // becomes ill-formed in C++2a. 1827 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1828 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1829 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1830 1831 // Create removals for all 'u8' prefixes in the string literal(s). This 1832 // ensures C++2a compatibility (but may change the program behavior when 1833 // built by non-Clang compilers for which the execution character set is 1834 // not always UTF-8). 1835 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1836 SourceLocation RemovalDiagLoc; 1837 for (const Token &Tok : StringToks) { 1838 if (Tok.getKind() == tok::utf8_string_literal) { 1839 if (RemovalDiagLoc.isInvalid()) 1840 RemovalDiagLoc = Tok.getLocation(); 1841 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1842 Tok.getLocation(), 1843 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1844 getSourceManager(), getLangOpts()))); 1845 } 1846 } 1847 Diag(RemovalDiagLoc, RemovalDiag); 1848 } 1849 1850 QualType StrTy = 1851 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1852 1853 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1854 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1855 Kind, Literal.Pascal, StrTy, 1856 &StringTokLocs[0], 1857 StringTokLocs.size()); 1858 if (Literal.getUDSuffix().empty()) 1859 return Lit; 1860 1861 // We're building a user-defined literal. 1862 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1863 SourceLocation UDSuffixLoc = 1864 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1865 Literal.getUDSuffixOffset()); 1866 1867 // Make sure we're allowed user-defined literals here. 1868 if (!UDLScope) 1869 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1870 1871 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1872 // operator "" X (str, len) 1873 QualType SizeType = Context.getSizeType(); 1874 1875 DeclarationName OpName = 1876 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1877 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1878 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1879 1880 QualType ArgTy[] = { 1881 Context.getArrayDecayedType(StrTy), SizeType 1882 }; 1883 1884 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1885 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1886 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1887 /*AllowStringTemplatePack*/ true, 1888 /*DiagnoseMissing*/ true, Lit)) { 1889 1890 case LOLR_Cooked: { 1891 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1892 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1893 StringTokLocs[0]); 1894 Expr *Args[] = { Lit, LenArg }; 1895 1896 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1897 } 1898 1899 case LOLR_Template: { 1900 TemplateArgumentListInfo ExplicitArgs; 1901 TemplateArgument Arg(Lit); 1902 TemplateArgumentLocInfo ArgInfo(Lit); 1903 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1904 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1905 &ExplicitArgs); 1906 } 1907 1908 case LOLR_StringTemplatePack: { 1909 TemplateArgumentListInfo ExplicitArgs; 1910 1911 unsigned CharBits = Context.getIntWidth(CharTy); 1912 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1913 llvm::APSInt Value(CharBits, CharIsUnsigned); 1914 1915 TemplateArgument TypeArg(CharTy); 1916 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1918 1919 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1920 Value = Lit->getCodeUnit(I); 1921 TemplateArgument Arg(Context, Value, CharTy); 1922 TemplateArgumentLocInfo ArgInfo; 1923 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1924 } 1925 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1926 &ExplicitArgs); 1927 } 1928 case LOLR_Raw: 1929 case LOLR_ErrorNoDiagnostic: 1930 llvm_unreachable("unexpected literal operator lookup result"); 1931 case LOLR_Error: 1932 return ExprError(); 1933 } 1934 llvm_unreachable("unexpected literal operator lookup result"); 1935 } 1936 1937 DeclRefExpr * 1938 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1939 SourceLocation Loc, 1940 const CXXScopeSpec *SS) { 1941 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1942 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1943 } 1944 1945 DeclRefExpr * 1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1947 const DeclarationNameInfo &NameInfo, 1948 const CXXScopeSpec *SS, NamedDecl *FoundD, 1949 SourceLocation TemplateKWLoc, 1950 const TemplateArgumentListInfo *TemplateArgs) { 1951 NestedNameSpecifierLoc NNS = 1952 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1953 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1954 TemplateArgs); 1955 } 1956 1957 // CUDA/HIP: Check whether a captured reference variable is referencing a 1958 // host variable in a device or host device lambda. 1959 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1960 VarDecl *VD) { 1961 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1962 return false; 1963 assert(VD->getType()->isReferenceType()); 1964 1965 // Check whether the reference variable is referencing a host variable. 1966 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1967 if (!DRE) 1968 return false; 1969 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1970 if (!Referee || !Referee->hasGlobalStorage() || 1971 Referee->hasAttr<CUDADeviceAttr>()) 1972 return false; 1973 1974 // Check whether the current function is a device or host device lambda. 1975 // Check whether the reference variable is a capture by getDeclContext() 1976 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1977 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1978 if (MD && MD->getParent()->isLambda() && 1979 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1980 VD->getDeclContext() != MD) 1981 return true; 1982 1983 return false; 1984 } 1985 1986 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1987 // A declaration named in an unevaluated operand never constitutes an odr-use. 1988 if (isUnevaluatedContext()) 1989 return NOUR_Unevaluated; 1990 1991 // C++2a [basic.def.odr]p4: 1992 // A variable x whose name appears as a potentially-evaluated expression e 1993 // is odr-used by e unless [...] x is a reference that is usable in 1994 // constant expressions. 1995 // CUDA/HIP: 1996 // If a reference variable referencing a host variable is captured in a 1997 // device or host device lambda, the value of the referee must be copied 1998 // to the capture and the reference variable must be treated as odr-use 1999 // since the value of the referee is not known at compile time and must 2000 // be loaded from the captured. 2001 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2002 if (VD->getType()->isReferenceType() && 2003 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2004 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2005 VD->isUsableInConstantExpressions(Context)) 2006 return NOUR_Constant; 2007 } 2008 2009 // All remaining non-variable cases constitute an odr-use. For variables, we 2010 // need to wait and see how the expression is used. 2011 return NOUR_None; 2012 } 2013 2014 /// BuildDeclRefExpr - Build an expression that references a 2015 /// declaration that does not require a closure capture. 2016 DeclRefExpr * 2017 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2018 const DeclarationNameInfo &NameInfo, 2019 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2020 SourceLocation TemplateKWLoc, 2021 const TemplateArgumentListInfo *TemplateArgs) { 2022 bool RefersToCapturedVariable = 2023 isa<VarDecl>(D) && 2024 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2025 2026 DeclRefExpr *E = DeclRefExpr::Create( 2027 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2028 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2029 MarkDeclRefReferenced(E); 2030 2031 // C++ [except.spec]p17: 2032 // An exception-specification is considered to be needed when: 2033 // - in an expression, the function is the unique lookup result or 2034 // the selected member of a set of overloaded functions. 2035 // 2036 // We delay doing this until after we've built the function reference and 2037 // marked it as used so that: 2038 // a) if the function is defaulted, we get errors from defining it before / 2039 // instead of errors from computing its exception specification, and 2040 // b) if the function is a defaulted comparison, we can use the body we 2041 // build when defining it as input to the exception specification 2042 // computation rather than computing a new body. 2043 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2044 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2045 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2046 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2047 } 2048 } 2049 2050 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2051 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2052 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2053 getCurFunction()->recordUseOfWeak(E); 2054 2055 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2056 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2057 FD = IFD->getAnonField(); 2058 if (FD) { 2059 UnusedPrivateFields.remove(FD); 2060 // Just in case we're building an illegal pointer-to-member. 2061 if (FD->isBitField()) 2062 E->setObjectKind(OK_BitField); 2063 } 2064 2065 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2066 // designates a bit-field. 2067 if (auto *BD = dyn_cast<BindingDecl>(D)) 2068 if (auto *BE = BD->getBinding()) 2069 E->setObjectKind(BE->getObjectKind()); 2070 2071 return E; 2072 } 2073 2074 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2075 /// possibly a list of template arguments. 2076 /// 2077 /// If this produces template arguments, it is permitted to call 2078 /// DecomposeTemplateName. 2079 /// 2080 /// This actually loses a lot of source location information for 2081 /// non-standard name kinds; we should consider preserving that in 2082 /// some way. 2083 void 2084 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2085 TemplateArgumentListInfo &Buffer, 2086 DeclarationNameInfo &NameInfo, 2087 const TemplateArgumentListInfo *&TemplateArgs) { 2088 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2089 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2090 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2091 2092 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2093 Id.TemplateId->NumArgs); 2094 translateTemplateArguments(TemplateArgsPtr, Buffer); 2095 2096 TemplateName TName = Id.TemplateId->Template.get(); 2097 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2098 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2099 TemplateArgs = &Buffer; 2100 } else { 2101 NameInfo = GetNameFromUnqualifiedId(Id); 2102 TemplateArgs = nullptr; 2103 } 2104 } 2105 2106 static void emitEmptyLookupTypoDiagnostic( 2107 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2108 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2109 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2110 DeclContext *Ctx = 2111 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2112 if (!TC) { 2113 // Emit a special diagnostic for failed member lookups. 2114 // FIXME: computing the declaration context might fail here (?) 2115 if (Ctx) 2116 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2117 << SS.getRange(); 2118 else 2119 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2120 return; 2121 } 2122 2123 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2124 bool DroppedSpecifier = 2125 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2126 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2127 ? diag::note_implicit_param_decl 2128 : diag::note_previous_decl; 2129 if (!Ctx) 2130 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2131 SemaRef.PDiag(NoteID)); 2132 else 2133 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2134 << Typo << Ctx << DroppedSpecifier 2135 << SS.getRange(), 2136 SemaRef.PDiag(NoteID)); 2137 } 2138 2139 /// Diagnose a lookup that found results in an enclosing class during error 2140 /// recovery. This usually indicates that the results were found in a dependent 2141 /// base class that could not be searched as part of a template definition. 2142 /// Always issues a diagnostic (though this may be only a warning in MS 2143 /// compatibility mode). 2144 /// 2145 /// Return \c true if the error is unrecoverable, or \c false if the caller 2146 /// should attempt to recover using these lookup results. 2147 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2148 // During a default argument instantiation the CurContext points 2149 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2150 // function parameter list, hence add an explicit check. 2151 bool isDefaultArgument = 2152 !CodeSynthesisContexts.empty() && 2153 CodeSynthesisContexts.back().Kind == 2154 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2155 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2156 bool isInstance = CurMethod && CurMethod->isInstance() && 2157 R.getNamingClass() == CurMethod->getParent() && 2158 !isDefaultArgument; 2159 2160 // There are two ways we can find a class-scope declaration during template 2161 // instantiation that we did not find in the template definition: if it is a 2162 // member of a dependent base class, or if it is declared after the point of 2163 // use in the same class. Distinguish these by comparing the class in which 2164 // the member was found to the naming class of the lookup. 2165 unsigned DiagID = diag::err_found_in_dependent_base; 2166 unsigned NoteID = diag::note_member_declared_at; 2167 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2168 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2169 : diag::err_found_later_in_class; 2170 } else if (getLangOpts().MSVCCompat) { 2171 DiagID = diag::ext_found_in_dependent_base; 2172 NoteID = diag::note_dependent_member_use; 2173 } 2174 2175 if (isInstance) { 2176 // Give a code modification hint to insert 'this->'. 2177 Diag(R.getNameLoc(), DiagID) 2178 << R.getLookupName() 2179 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2180 CheckCXXThisCapture(R.getNameLoc()); 2181 } else { 2182 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2183 // they're not shadowed). 2184 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2185 } 2186 2187 for (NamedDecl *D : R) 2188 Diag(D->getLocation(), NoteID); 2189 2190 // Return true if we are inside a default argument instantiation 2191 // and the found name refers to an instance member function, otherwise 2192 // the caller will try to create an implicit member call and this is wrong 2193 // for default arguments. 2194 // 2195 // FIXME: Is this special case necessary? We could allow the caller to 2196 // diagnose this. 2197 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2198 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2199 return true; 2200 } 2201 2202 // Tell the callee to try to recover. 2203 return false; 2204 } 2205 2206 /// Diagnose an empty lookup. 2207 /// 2208 /// \return false if new lookup candidates were found 2209 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2210 CorrectionCandidateCallback &CCC, 2211 TemplateArgumentListInfo *ExplicitTemplateArgs, 2212 ArrayRef<Expr *> Args, TypoExpr **Out) { 2213 DeclarationName Name = R.getLookupName(); 2214 2215 unsigned diagnostic = diag::err_undeclared_var_use; 2216 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2217 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2218 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2219 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2220 diagnostic = diag::err_undeclared_use; 2221 diagnostic_suggest = diag::err_undeclared_use_suggest; 2222 } 2223 2224 // If the original lookup was an unqualified lookup, fake an 2225 // unqualified lookup. This is useful when (for example) the 2226 // original lookup would not have found something because it was a 2227 // dependent name. 2228 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2229 while (DC) { 2230 if (isa<CXXRecordDecl>(DC)) { 2231 LookupQualifiedName(R, DC); 2232 2233 if (!R.empty()) { 2234 // Don't give errors about ambiguities in this lookup. 2235 R.suppressDiagnostics(); 2236 2237 // If there's a best viable function among the results, only mention 2238 // that one in the notes. 2239 OverloadCandidateSet Candidates(R.getNameLoc(), 2240 OverloadCandidateSet::CSK_Normal); 2241 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2242 OverloadCandidateSet::iterator Best; 2243 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2244 OR_Success) { 2245 R.clear(); 2246 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2247 R.resolveKind(); 2248 } 2249 2250 return DiagnoseDependentMemberLookup(R); 2251 } 2252 2253 R.clear(); 2254 } 2255 2256 DC = DC->getLookupParent(); 2257 } 2258 2259 // We didn't find anything, so try to correct for a typo. 2260 TypoCorrection Corrected; 2261 if (S && Out) { 2262 SourceLocation TypoLoc = R.getNameLoc(); 2263 assert(!ExplicitTemplateArgs && 2264 "Diagnosing an empty lookup with explicit template args!"); 2265 *Out = CorrectTypoDelayed( 2266 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2267 [=](const TypoCorrection &TC) { 2268 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2269 diagnostic, diagnostic_suggest); 2270 }, 2271 nullptr, CTK_ErrorRecovery); 2272 if (*Out) 2273 return true; 2274 } else if (S && 2275 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2276 S, &SS, CCC, CTK_ErrorRecovery))) { 2277 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2278 bool DroppedSpecifier = 2279 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2280 R.setLookupName(Corrected.getCorrection()); 2281 2282 bool AcceptableWithRecovery = false; 2283 bool AcceptableWithoutRecovery = false; 2284 NamedDecl *ND = Corrected.getFoundDecl(); 2285 if (ND) { 2286 if (Corrected.isOverloaded()) { 2287 OverloadCandidateSet OCS(R.getNameLoc(), 2288 OverloadCandidateSet::CSK_Normal); 2289 OverloadCandidateSet::iterator Best; 2290 for (NamedDecl *CD : Corrected) { 2291 if (FunctionTemplateDecl *FTD = 2292 dyn_cast<FunctionTemplateDecl>(CD)) 2293 AddTemplateOverloadCandidate( 2294 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2295 Args, OCS); 2296 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2297 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2298 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2299 Args, OCS); 2300 } 2301 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2302 case OR_Success: 2303 ND = Best->FoundDecl; 2304 Corrected.setCorrectionDecl(ND); 2305 break; 2306 default: 2307 // FIXME: Arbitrarily pick the first declaration for the note. 2308 Corrected.setCorrectionDecl(ND); 2309 break; 2310 } 2311 } 2312 R.addDecl(ND); 2313 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2314 CXXRecordDecl *Record = nullptr; 2315 if (Corrected.getCorrectionSpecifier()) { 2316 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2317 Record = Ty->getAsCXXRecordDecl(); 2318 } 2319 if (!Record) 2320 Record = cast<CXXRecordDecl>( 2321 ND->getDeclContext()->getRedeclContext()); 2322 R.setNamingClass(Record); 2323 } 2324 2325 auto *UnderlyingND = ND->getUnderlyingDecl(); 2326 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2327 isa<FunctionTemplateDecl>(UnderlyingND); 2328 // FIXME: If we ended up with a typo for a type name or 2329 // Objective-C class name, we're in trouble because the parser 2330 // is in the wrong place to recover. Suggest the typo 2331 // correction, but don't make it a fix-it since we're not going 2332 // to recover well anyway. 2333 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2334 getAsTypeTemplateDecl(UnderlyingND) || 2335 isa<ObjCInterfaceDecl>(UnderlyingND); 2336 } else { 2337 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2338 // because we aren't able to recover. 2339 AcceptableWithoutRecovery = true; 2340 } 2341 2342 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2343 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2344 ? diag::note_implicit_param_decl 2345 : diag::note_previous_decl; 2346 if (SS.isEmpty()) 2347 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2348 PDiag(NoteID), AcceptableWithRecovery); 2349 else 2350 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2351 << Name << computeDeclContext(SS, false) 2352 << DroppedSpecifier << SS.getRange(), 2353 PDiag(NoteID), AcceptableWithRecovery); 2354 2355 // Tell the callee whether to try to recover. 2356 return !AcceptableWithRecovery; 2357 } 2358 } 2359 R.clear(); 2360 2361 // Emit a special diagnostic for failed member lookups. 2362 // FIXME: computing the declaration context might fail here (?) 2363 if (!SS.isEmpty()) { 2364 Diag(R.getNameLoc(), diag::err_no_member) 2365 << Name << computeDeclContext(SS, false) 2366 << SS.getRange(); 2367 return true; 2368 } 2369 2370 // Give up, we can't recover. 2371 Diag(R.getNameLoc(), diagnostic) << Name; 2372 return true; 2373 } 2374 2375 /// In Microsoft mode, if we are inside a template class whose parent class has 2376 /// dependent base classes, and we can't resolve an unqualified identifier, then 2377 /// assume the identifier is a member of a dependent base class. We can only 2378 /// recover successfully in static methods, instance methods, and other contexts 2379 /// where 'this' is available. This doesn't precisely match MSVC's 2380 /// instantiation model, but it's close enough. 2381 static Expr * 2382 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2383 DeclarationNameInfo &NameInfo, 2384 SourceLocation TemplateKWLoc, 2385 const TemplateArgumentListInfo *TemplateArgs) { 2386 // Only try to recover from lookup into dependent bases in static methods or 2387 // contexts where 'this' is available. 2388 QualType ThisType = S.getCurrentThisType(); 2389 const CXXRecordDecl *RD = nullptr; 2390 if (!ThisType.isNull()) 2391 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2392 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2393 RD = MD->getParent(); 2394 if (!RD || !RD->hasAnyDependentBases()) 2395 return nullptr; 2396 2397 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2398 // is available, suggest inserting 'this->' as a fixit. 2399 SourceLocation Loc = NameInfo.getLoc(); 2400 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2401 DB << NameInfo.getName() << RD; 2402 2403 if (!ThisType.isNull()) { 2404 DB << FixItHint::CreateInsertion(Loc, "this->"); 2405 return CXXDependentScopeMemberExpr::Create( 2406 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2407 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2408 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2409 } 2410 2411 // Synthesize a fake NNS that points to the derived class. This will 2412 // perform name lookup during template instantiation. 2413 CXXScopeSpec SS; 2414 auto *NNS = 2415 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2416 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2417 return DependentScopeDeclRefExpr::Create( 2418 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2419 TemplateArgs); 2420 } 2421 2422 ExprResult 2423 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2424 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2425 bool HasTrailingLParen, bool IsAddressOfOperand, 2426 CorrectionCandidateCallback *CCC, 2427 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2428 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2429 "cannot be direct & operand and have a trailing lparen"); 2430 if (SS.isInvalid()) 2431 return ExprError(); 2432 2433 TemplateArgumentListInfo TemplateArgsBuffer; 2434 2435 // Decompose the UnqualifiedId into the following data. 2436 DeclarationNameInfo NameInfo; 2437 const TemplateArgumentListInfo *TemplateArgs; 2438 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2439 2440 DeclarationName Name = NameInfo.getName(); 2441 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2442 SourceLocation NameLoc = NameInfo.getLoc(); 2443 2444 if (II && II->isEditorPlaceholder()) { 2445 // FIXME: When typed placeholders are supported we can create a typed 2446 // placeholder expression node. 2447 return ExprError(); 2448 } 2449 2450 // C++ [temp.dep.expr]p3: 2451 // An id-expression is type-dependent if it contains: 2452 // -- an identifier that was declared with a dependent type, 2453 // (note: handled after lookup) 2454 // -- a template-id that is dependent, 2455 // (note: handled in BuildTemplateIdExpr) 2456 // -- a conversion-function-id that specifies a dependent type, 2457 // -- a nested-name-specifier that contains a class-name that 2458 // names a dependent type. 2459 // Determine whether this is a member of an unknown specialization; 2460 // we need to handle these differently. 2461 bool DependentID = false; 2462 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2463 Name.getCXXNameType()->isDependentType()) { 2464 DependentID = true; 2465 } else if (SS.isSet()) { 2466 if (DeclContext *DC = computeDeclContext(SS, false)) { 2467 if (RequireCompleteDeclContext(SS, DC)) 2468 return ExprError(); 2469 } else { 2470 DependentID = true; 2471 } 2472 } 2473 2474 if (DependentID) 2475 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2476 IsAddressOfOperand, TemplateArgs); 2477 2478 // Perform the required lookup. 2479 LookupResult R(*this, NameInfo, 2480 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2481 ? LookupObjCImplicitSelfParam 2482 : LookupOrdinaryName); 2483 if (TemplateKWLoc.isValid() || TemplateArgs) { 2484 // Lookup the template name again to correctly establish the context in 2485 // which it was found. This is really unfortunate as we already did the 2486 // lookup to determine that it was a template name in the first place. If 2487 // this becomes a performance hit, we can work harder to preserve those 2488 // results until we get here but it's likely not worth it. 2489 bool MemberOfUnknownSpecialization; 2490 AssumedTemplateKind AssumedTemplate; 2491 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2492 MemberOfUnknownSpecialization, TemplateKWLoc, 2493 &AssumedTemplate)) 2494 return ExprError(); 2495 2496 if (MemberOfUnknownSpecialization || 2497 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2498 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2499 IsAddressOfOperand, TemplateArgs); 2500 } else { 2501 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2502 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2503 2504 // If the result might be in a dependent base class, this is a dependent 2505 // id-expression. 2506 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2507 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2508 IsAddressOfOperand, TemplateArgs); 2509 2510 // If this reference is in an Objective-C method, then we need to do 2511 // some special Objective-C lookup, too. 2512 if (IvarLookupFollowUp) { 2513 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2514 if (E.isInvalid()) 2515 return ExprError(); 2516 2517 if (Expr *Ex = E.getAs<Expr>()) 2518 return Ex; 2519 } 2520 } 2521 2522 if (R.isAmbiguous()) 2523 return ExprError(); 2524 2525 // This could be an implicitly declared function reference (legal in C90, 2526 // extension in C99, forbidden in C++). 2527 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2528 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2529 if (D) R.addDecl(D); 2530 } 2531 2532 // Determine whether this name might be a candidate for 2533 // argument-dependent lookup. 2534 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2535 2536 if (R.empty() && !ADL) { 2537 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2538 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2539 TemplateKWLoc, TemplateArgs)) 2540 return E; 2541 } 2542 2543 // Don't diagnose an empty lookup for inline assembly. 2544 if (IsInlineAsmIdentifier) 2545 return ExprError(); 2546 2547 // If this name wasn't predeclared and if this is not a function 2548 // call, diagnose the problem. 2549 TypoExpr *TE = nullptr; 2550 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2551 : nullptr); 2552 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2553 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2554 "Typo correction callback misconfigured"); 2555 if (CCC) { 2556 // Make sure the callback knows what the typo being diagnosed is. 2557 CCC->setTypoName(II); 2558 if (SS.isValid()) 2559 CCC->setTypoNNS(SS.getScopeRep()); 2560 } 2561 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2562 // a template name, but we happen to have always already looked up the name 2563 // before we get here if it must be a template name. 2564 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2565 None, &TE)) { 2566 if (TE && KeywordReplacement) { 2567 auto &State = getTypoExprState(TE); 2568 auto BestTC = State.Consumer->getNextCorrection(); 2569 if (BestTC.isKeyword()) { 2570 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2571 if (State.DiagHandler) 2572 State.DiagHandler(BestTC); 2573 KeywordReplacement->startToken(); 2574 KeywordReplacement->setKind(II->getTokenID()); 2575 KeywordReplacement->setIdentifierInfo(II); 2576 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2577 // Clean up the state associated with the TypoExpr, since it has 2578 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2579 clearDelayedTypo(TE); 2580 // Signal that a correction to a keyword was performed by returning a 2581 // valid-but-null ExprResult. 2582 return (Expr*)nullptr; 2583 } 2584 State.Consumer->resetCorrectionStream(); 2585 } 2586 return TE ? TE : ExprError(); 2587 } 2588 2589 assert(!R.empty() && 2590 "DiagnoseEmptyLookup returned false but added no results"); 2591 2592 // If we found an Objective-C instance variable, let 2593 // LookupInObjCMethod build the appropriate expression to 2594 // reference the ivar. 2595 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2596 R.clear(); 2597 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2598 // In a hopelessly buggy code, Objective-C instance variable 2599 // lookup fails and no expression will be built to reference it. 2600 if (!E.isInvalid() && !E.get()) 2601 return ExprError(); 2602 return E; 2603 } 2604 } 2605 2606 // This is guaranteed from this point on. 2607 assert(!R.empty() || ADL); 2608 2609 // Check whether this might be a C++ implicit instance member access. 2610 // C++ [class.mfct.non-static]p3: 2611 // When an id-expression that is not part of a class member access 2612 // syntax and not used to form a pointer to member is used in the 2613 // body of a non-static member function of class X, if name lookup 2614 // resolves the name in the id-expression to a non-static non-type 2615 // member of some class C, the id-expression is transformed into a 2616 // class member access expression using (*this) as the 2617 // postfix-expression to the left of the . operator. 2618 // 2619 // But we don't actually need to do this for '&' operands if R 2620 // resolved to a function or overloaded function set, because the 2621 // expression is ill-formed if it actually works out to be a 2622 // non-static member function: 2623 // 2624 // C++ [expr.ref]p4: 2625 // Otherwise, if E1.E2 refers to a non-static member function. . . 2626 // [t]he expression can be used only as the left-hand operand of a 2627 // member function call. 2628 // 2629 // There are other safeguards against such uses, but it's important 2630 // to get this right here so that we don't end up making a 2631 // spuriously dependent expression if we're inside a dependent 2632 // instance method. 2633 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2634 bool MightBeImplicitMember; 2635 if (!IsAddressOfOperand) 2636 MightBeImplicitMember = true; 2637 else if (!SS.isEmpty()) 2638 MightBeImplicitMember = false; 2639 else if (R.isOverloadedResult()) 2640 MightBeImplicitMember = false; 2641 else if (R.isUnresolvableResult()) 2642 MightBeImplicitMember = true; 2643 else 2644 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2645 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2646 isa<MSPropertyDecl>(R.getFoundDecl()); 2647 2648 if (MightBeImplicitMember) 2649 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2650 R, TemplateArgs, S); 2651 } 2652 2653 if (TemplateArgs || TemplateKWLoc.isValid()) { 2654 2655 // In C++1y, if this is a variable template id, then check it 2656 // in BuildTemplateIdExpr(). 2657 // The single lookup result must be a variable template declaration. 2658 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2659 Id.TemplateId->Kind == TNK_Var_template) { 2660 assert(R.getAsSingle<VarTemplateDecl>() && 2661 "There should only be one declaration found."); 2662 } 2663 2664 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2665 } 2666 2667 return BuildDeclarationNameExpr(SS, R, ADL); 2668 } 2669 2670 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2671 /// declaration name, generally during template instantiation. 2672 /// There's a large number of things which don't need to be done along 2673 /// this path. 2674 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2675 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2676 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2677 DeclContext *DC = computeDeclContext(SS, false); 2678 if (!DC) 2679 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2680 NameInfo, /*TemplateArgs=*/nullptr); 2681 2682 if (RequireCompleteDeclContext(SS, DC)) 2683 return ExprError(); 2684 2685 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2686 LookupQualifiedName(R, DC); 2687 2688 if (R.isAmbiguous()) 2689 return ExprError(); 2690 2691 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2692 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2693 NameInfo, /*TemplateArgs=*/nullptr); 2694 2695 if (R.empty()) { 2696 // Don't diagnose problems with invalid record decl, the secondary no_member 2697 // diagnostic during template instantiation is likely bogus, e.g. if a class 2698 // is invalid because it's derived from an invalid base class, then missing 2699 // members were likely supposed to be inherited. 2700 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2701 if (CD->isInvalidDecl()) 2702 return ExprError(); 2703 Diag(NameInfo.getLoc(), diag::err_no_member) 2704 << NameInfo.getName() << DC << SS.getRange(); 2705 return ExprError(); 2706 } 2707 2708 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2709 // Diagnose a missing typename if this resolved unambiguously to a type in 2710 // a dependent context. If we can recover with a type, downgrade this to 2711 // a warning in Microsoft compatibility mode. 2712 unsigned DiagID = diag::err_typename_missing; 2713 if (RecoveryTSI && getLangOpts().MSVCCompat) 2714 DiagID = diag::ext_typename_missing; 2715 SourceLocation Loc = SS.getBeginLoc(); 2716 auto D = Diag(Loc, DiagID); 2717 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2718 << SourceRange(Loc, NameInfo.getEndLoc()); 2719 2720 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2721 // context. 2722 if (!RecoveryTSI) 2723 return ExprError(); 2724 2725 // Only issue the fixit if we're prepared to recover. 2726 D << FixItHint::CreateInsertion(Loc, "typename "); 2727 2728 // Recover by pretending this was an elaborated type. 2729 QualType Ty = Context.getTypeDeclType(TD); 2730 TypeLocBuilder TLB; 2731 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2732 2733 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2734 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2735 QTL.setElaboratedKeywordLoc(SourceLocation()); 2736 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2737 2738 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2739 2740 return ExprEmpty(); 2741 } 2742 2743 // Defend against this resolving to an implicit member access. We usually 2744 // won't get here if this might be a legitimate a class member (we end up in 2745 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2746 // a pointer-to-member or in an unevaluated context in C++11. 2747 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2748 return BuildPossibleImplicitMemberExpr(SS, 2749 /*TemplateKWLoc=*/SourceLocation(), 2750 R, /*TemplateArgs=*/nullptr, S); 2751 2752 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2753 } 2754 2755 /// The parser has read a name in, and Sema has detected that we're currently 2756 /// inside an ObjC method. Perform some additional checks and determine if we 2757 /// should form a reference to an ivar. 2758 /// 2759 /// Ideally, most of this would be done by lookup, but there's 2760 /// actually quite a lot of extra work involved. 2761 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2762 IdentifierInfo *II) { 2763 SourceLocation Loc = Lookup.getNameLoc(); 2764 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2765 2766 // Check for error condition which is already reported. 2767 if (!CurMethod) 2768 return DeclResult(true); 2769 2770 // There are two cases to handle here. 1) scoped lookup could have failed, 2771 // in which case we should look for an ivar. 2) scoped lookup could have 2772 // found a decl, but that decl is outside the current instance method (i.e. 2773 // a global variable). In these two cases, we do a lookup for an ivar with 2774 // this name, if the lookup sucedes, we replace it our current decl. 2775 2776 // If we're in a class method, we don't normally want to look for 2777 // ivars. But if we don't find anything else, and there's an 2778 // ivar, that's an error. 2779 bool IsClassMethod = CurMethod->isClassMethod(); 2780 2781 bool LookForIvars; 2782 if (Lookup.empty()) 2783 LookForIvars = true; 2784 else if (IsClassMethod) 2785 LookForIvars = false; 2786 else 2787 LookForIvars = (Lookup.isSingleResult() && 2788 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2789 ObjCInterfaceDecl *IFace = nullptr; 2790 if (LookForIvars) { 2791 IFace = CurMethod->getClassInterface(); 2792 ObjCInterfaceDecl *ClassDeclared; 2793 ObjCIvarDecl *IV = nullptr; 2794 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2795 // Diagnose using an ivar in a class method. 2796 if (IsClassMethod) { 2797 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2798 return DeclResult(true); 2799 } 2800 2801 // Diagnose the use of an ivar outside of the declaring class. 2802 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2803 !declaresSameEntity(ClassDeclared, IFace) && 2804 !getLangOpts().DebuggerSupport) 2805 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2806 2807 // Success. 2808 return IV; 2809 } 2810 } else if (CurMethod->isInstanceMethod()) { 2811 // We should warn if a local variable hides an ivar. 2812 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2813 ObjCInterfaceDecl *ClassDeclared; 2814 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2815 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2816 declaresSameEntity(IFace, ClassDeclared)) 2817 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2818 } 2819 } 2820 } else if (Lookup.isSingleResult() && 2821 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2822 // If accessing a stand-alone ivar in a class method, this is an error. 2823 if (const ObjCIvarDecl *IV = 2824 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2825 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2826 return DeclResult(true); 2827 } 2828 } 2829 2830 // Didn't encounter an error, didn't find an ivar. 2831 return DeclResult(false); 2832 } 2833 2834 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2835 ObjCIvarDecl *IV) { 2836 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2837 assert(CurMethod && CurMethod->isInstanceMethod() && 2838 "should not reference ivar from this context"); 2839 2840 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2841 assert(IFace && "should not reference ivar from this context"); 2842 2843 // If we're referencing an invalid decl, just return this as a silent 2844 // error node. The error diagnostic was already emitted on the decl. 2845 if (IV->isInvalidDecl()) 2846 return ExprError(); 2847 2848 // Check if referencing a field with __attribute__((deprecated)). 2849 if (DiagnoseUseOfDecl(IV, Loc)) 2850 return ExprError(); 2851 2852 // FIXME: This should use a new expr for a direct reference, don't 2853 // turn this into Self->ivar, just return a BareIVarExpr or something. 2854 IdentifierInfo &II = Context.Idents.get("self"); 2855 UnqualifiedId SelfName; 2856 SelfName.setImplicitSelfParam(&II); 2857 CXXScopeSpec SelfScopeSpec; 2858 SourceLocation TemplateKWLoc; 2859 ExprResult SelfExpr = 2860 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2861 /*HasTrailingLParen=*/false, 2862 /*IsAddressOfOperand=*/false); 2863 if (SelfExpr.isInvalid()) 2864 return ExprError(); 2865 2866 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2867 if (SelfExpr.isInvalid()) 2868 return ExprError(); 2869 2870 MarkAnyDeclReferenced(Loc, IV, true); 2871 2872 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2873 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2874 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2875 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2876 2877 ObjCIvarRefExpr *Result = new (Context) 2878 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2879 IV->getLocation(), SelfExpr.get(), true, true); 2880 2881 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2882 if (!isUnevaluatedContext() && 2883 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2884 getCurFunction()->recordUseOfWeak(Result); 2885 } 2886 if (getLangOpts().ObjCAutoRefCount) 2887 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2888 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2889 2890 return Result; 2891 } 2892 2893 /// The parser has read a name in, and Sema has detected that we're currently 2894 /// inside an ObjC method. Perform some additional checks and determine if we 2895 /// should form a reference to an ivar. If so, build an expression referencing 2896 /// that ivar. 2897 ExprResult 2898 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2899 IdentifierInfo *II, bool AllowBuiltinCreation) { 2900 // FIXME: Integrate this lookup step into LookupParsedName. 2901 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2902 if (Ivar.isInvalid()) 2903 return ExprError(); 2904 if (Ivar.isUsable()) 2905 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2906 cast<ObjCIvarDecl>(Ivar.get())); 2907 2908 if (Lookup.empty() && II && AllowBuiltinCreation) 2909 LookupBuiltin(Lookup); 2910 2911 // Sentinel value saying that we didn't do anything special. 2912 return ExprResult(false); 2913 } 2914 2915 /// Cast a base object to a member's actual type. 2916 /// 2917 /// There are two relevant checks: 2918 /// 2919 /// C++ [class.access.base]p7: 2920 /// 2921 /// If a class member access operator [...] is used to access a non-static 2922 /// data member or non-static member function, the reference is ill-formed if 2923 /// the left operand [...] cannot be implicitly converted to a pointer to the 2924 /// naming class of the right operand. 2925 /// 2926 /// C++ [expr.ref]p7: 2927 /// 2928 /// If E2 is a non-static data member or a non-static member function, the 2929 /// program is ill-formed if the class of which E2 is directly a member is an 2930 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2931 /// 2932 /// Note that the latter check does not consider access; the access of the 2933 /// "real" base class is checked as appropriate when checking the access of the 2934 /// member name. 2935 ExprResult 2936 Sema::PerformObjectMemberConversion(Expr *From, 2937 NestedNameSpecifier *Qualifier, 2938 NamedDecl *FoundDecl, 2939 NamedDecl *Member) { 2940 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2941 if (!RD) 2942 return From; 2943 2944 QualType DestRecordType; 2945 QualType DestType; 2946 QualType FromRecordType; 2947 QualType FromType = From->getType(); 2948 bool PointerConversions = false; 2949 if (isa<FieldDecl>(Member)) { 2950 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2951 auto FromPtrType = FromType->getAs<PointerType>(); 2952 DestRecordType = Context.getAddrSpaceQualType( 2953 DestRecordType, FromPtrType 2954 ? FromType->getPointeeType().getAddressSpace() 2955 : FromType.getAddressSpace()); 2956 2957 if (FromPtrType) { 2958 DestType = Context.getPointerType(DestRecordType); 2959 FromRecordType = FromPtrType->getPointeeType(); 2960 PointerConversions = true; 2961 } else { 2962 DestType = DestRecordType; 2963 FromRecordType = FromType; 2964 } 2965 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2966 if (Method->isStatic()) 2967 return From; 2968 2969 DestType = Method->getThisType(); 2970 DestRecordType = DestType->getPointeeType(); 2971 2972 if (FromType->getAs<PointerType>()) { 2973 FromRecordType = FromType->getPointeeType(); 2974 PointerConversions = true; 2975 } else { 2976 FromRecordType = FromType; 2977 DestType = DestRecordType; 2978 } 2979 2980 LangAS FromAS = FromRecordType.getAddressSpace(); 2981 LangAS DestAS = DestRecordType.getAddressSpace(); 2982 if (FromAS != DestAS) { 2983 QualType FromRecordTypeWithoutAS = 2984 Context.removeAddrSpaceQualType(FromRecordType); 2985 QualType FromTypeWithDestAS = 2986 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2987 if (PointerConversions) 2988 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2989 From = ImpCastExprToType(From, FromTypeWithDestAS, 2990 CK_AddressSpaceConversion, From->getValueKind()) 2991 .get(); 2992 } 2993 } else { 2994 // No conversion necessary. 2995 return From; 2996 } 2997 2998 if (DestType->isDependentType() || FromType->isDependentType()) 2999 return From; 3000 3001 // If the unqualified types are the same, no conversion is necessary. 3002 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3003 return From; 3004 3005 SourceRange FromRange = From->getSourceRange(); 3006 SourceLocation FromLoc = FromRange.getBegin(); 3007 3008 ExprValueKind VK = From->getValueKind(); 3009 3010 // C++ [class.member.lookup]p8: 3011 // [...] Ambiguities can often be resolved by qualifying a name with its 3012 // class name. 3013 // 3014 // If the member was a qualified name and the qualified referred to a 3015 // specific base subobject type, we'll cast to that intermediate type 3016 // first and then to the object in which the member is declared. That allows 3017 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3018 // 3019 // class Base { public: int x; }; 3020 // class Derived1 : public Base { }; 3021 // class Derived2 : public Base { }; 3022 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3023 // 3024 // void VeryDerived::f() { 3025 // x = 17; // error: ambiguous base subobjects 3026 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3027 // } 3028 if (Qualifier && Qualifier->getAsType()) { 3029 QualType QType = QualType(Qualifier->getAsType(), 0); 3030 assert(QType->isRecordType() && "lookup done with non-record type"); 3031 3032 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3033 3034 // In C++98, the qualifier type doesn't actually have to be a base 3035 // type of the object type, in which case we just ignore it. 3036 // Otherwise build the appropriate casts. 3037 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3038 CXXCastPath BasePath; 3039 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3040 FromLoc, FromRange, &BasePath)) 3041 return ExprError(); 3042 3043 if (PointerConversions) 3044 QType = Context.getPointerType(QType); 3045 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3046 VK, &BasePath).get(); 3047 3048 FromType = QType; 3049 FromRecordType = QRecordType; 3050 3051 // If the qualifier type was the same as the destination type, 3052 // we're done. 3053 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3054 return From; 3055 } 3056 } 3057 3058 CXXCastPath BasePath; 3059 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3060 FromLoc, FromRange, &BasePath, 3061 /*IgnoreAccess=*/true)) 3062 return ExprError(); 3063 3064 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3065 VK, &BasePath); 3066 } 3067 3068 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3069 const LookupResult &R, 3070 bool HasTrailingLParen) { 3071 // Only when used directly as the postfix-expression of a call. 3072 if (!HasTrailingLParen) 3073 return false; 3074 3075 // Never if a scope specifier was provided. 3076 if (SS.isSet()) 3077 return false; 3078 3079 // Only in C++ or ObjC++. 3080 if (!getLangOpts().CPlusPlus) 3081 return false; 3082 3083 // Turn off ADL when we find certain kinds of declarations during 3084 // normal lookup: 3085 for (NamedDecl *D : R) { 3086 // C++0x [basic.lookup.argdep]p3: 3087 // -- a declaration of a class member 3088 // Since using decls preserve this property, we check this on the 3089 // original decl. 3090 if (D->isCXXClassMember()) 3091 return false; 3092 3093 // C++0x [basic.lookup.argdep]p3: 3094 // -- a block-scope function declaration that is not a 3095 // using-declaration 3096 // NOTE: we also trigger this for function templates (in fact, we 3097 // don't check the decl type at all, since all other decl types 3098 // turn off ADL anyway). 3099 if (isa<UsingShadowDecl>(D)) 3100 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3101 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3102 return false; 3103 3104 // C++0x [basic.lookup.argdep]p3: 3105 // -- a declaration that is neither a function or a function 3106 // template 3107 // And also for builtin functions. 3108 if (isa<FunctionDecl>(D)) { 3109 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3110 3111 // But also builtin functions. 3112 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3113 return false; 3114 } else if (!isa<FunctionTemplateDecl>(D)) 3115 return false; 3116 } 3117 3118 return true; 3119 } 3120 3121 3122 /// Diagnoses obvious problems with the use of the given declaration 3123 /// as an expression. This is only actually called for lookups that 3124 /// were not overloaded, and it doesn't promise that the declaration 3125 /// will in fact be used. 3126 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3127 if (D->isInvalidDecl()) 3128 return true; 3129 3130 if (isa<TypedefNameDecl>(D)) { 3131 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3132 return true; 3133 } 3134 3135 if (isa<ObjCInterfaceDecl>(D)) { 3136 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3137 return true; 3138 } 3139 3140 if (isa<NamespaceDecl>(D)) { 3141 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3142 return true; 3143 } 3144 3145 return false; 3146 } 3147 3148 // Certain multiversion types should be treated as overloaded even when there is 3149 // only one result. 3150 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3151 assert(R.isSingleResult() && "Expected only a single result"); 3152 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3153 return FD && 3154 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3155 } 3156 3157 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3158 LookupResult &R, bool NeedsADL, 3159 bool AcceptInvalidDecl) { 3160 // If this is a single, fully-resolved result and we don't need ADL, 3161 // just build an ordinary singleton decl ref. 3162 if (!NeedsADL && R.isSingleResult() && 3163 !R.getAsSingle<FunctionTemplateDecl>() && 3164 !ShouldLookupResultBeMultiVersionOverload(R)) 3165 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3166 R.getRepresentativeDecl(), nullptr, 3167 AcceptInvalidDecl); 3168 3169 // We only need to check the declaration if there's exactly one 3170 // result, because in the overloaded case the results can only be 3171 // functions and function templates. 3172 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3173 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3174 return ExprError(); 3175 3176 // Otherwise, just build an unresolved lookup expression. Suppress 3177 // any lookup-related diagnostics; we'll hash these out later, when 3178 // we've picked a target. 3179 R.suppressDiagnostics(); 3180 3181 UnresolvedLookupExpr *ULE 3182 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3183 SS.getWithLocInContext(Context), 3184 R.getLookupNameInfo(), 3185 NeedsADL, R.isOverloadedResult(), 3186 R.begin(), R.end()); 3187 3188 return ULE; 3189 } 3190 3191 static void 3192 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3193 ValueDecl *var, DeclContext *DC); 3194 3195 /// Complete semantic analysis for a reference to the given declaration. 3196 ExprResult Sema::BuildDeclarationNameExpr( 3197 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3198 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3199 bool AcceptInvalidDecl) { 3200 assert(D && "Cannot refer to a NULL declaration"); 3201 assert(!isa<FunctionTemplateDecl>(D) && 3202 "Cannot refer unambiguously to a function template"); 3203 3204 SourceLocation Loc = NameInfo.getLoc(); 3205 if (CheckDeclInExpr(*this, Loc, D)) 3206 return ExprError(); 3207 3208 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3209 // Specifically diagnose references to class templates that are missing 3210 // a template argument list. 3211 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3212 return ExprError(); 3213 } 3214 3215 // Make sure that we're referring to a value. 3216 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3217 if (!VD) { 3218 Diag(Loc, diag::err_ref_non_value) 3219 << D << SS.getRange(); 3220 Diag(D->getLocation(), diag::note_declared_at); 3221 return ExprError(); 3222 } 3223 3224 // Check whether this declaration can be used. Note that we suppress 3225 // this check when we're going to perform argument-dependent lookup 3226 // on this function name, because this might not be the function 3227 // that overload resolution actually selects. 3228 if (DiagnoseUseOfDecl(VD, Loc)) 3229 return ExprError(); 3230 3231 // Only create DeclRefExpr's for valid Decl's. 3232 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3233 return ExprError(); 3234 3235 // Handle members of anonymous structs and unions. If we got here, 3236 // and the reference is to a class member indirect field, then this 3237 // must be the subject of a pointer-to-member expression. 3238 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3239 if (!indirectField->isCXXClassMember()) 3240 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3241 indirectField); 3242 3243 { 3244 QualType type = VD->getType(); 3245 if (type.isNull()) 3246 return ExprError(); 3247 ExprValueKind valueKind = VK_RValue; 3248 3249 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3250 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3251 // is expanded by some outer '...' in the context of the use. 3252 type = type.getNonPackExpansionType(); 3253 3254 switch (D->getKind()) { 3255 // Ignore all the non-ValueDecl kinds. 3256 #define ABSTRACT_DECL(kind) 3257 #define VALUE(type, base) 3258 #define DECL(type, base) \ 3259 case Decl::type: 3260 #include "clang/AST/DeclNodes.inc" 3261 llvm_unreachable("invalid value decl kind"); 3262 3263 // These shouldn't make it here. 3264 case Decl::ObjCAtDefsField: 3265 llvm_unreachable("forming non-member reference to ivar?"); 3266 3267 // Enum constants are always r-values and never references. 3268 // Unresolved using declarations are dependent. 3269 case Decl::EnumConstant: 3270 case Decl::UnresolvedUsingValue: 3271 case Decl::OMPDeclareReduction: 3272 case Decl::OMPDeclareMapper: 3273 valueKind = VK_RValue; 3274 break; 3275 3276 // Fields and indirect fields that got here must be for 3277 // pointer-to-member expressions; we just call them l-values for 3278 // internal consistency, because this subexpression doesn't really 3279 // exist in the high-level semantics. 3280 case Decl::Field: 3281 case Decl::IndirectField: 3282 case Decl::ObjCIvar: 3283 assert(getLangOpts().CPlusPlus && 3284 "building reference to field in C?"); 3285 3286 // These can't have reference type in well-formed programs, but 3287 // for internal consistency we do this anyway. 3288 type = type.getNonReferenceType(); 3289 valueKind = VK_LValue; 3290 break; 3291 3292 // Non-type template parameters are either l-values or r-values 3293 // depending on the type. 3294 case Decl::NonTypeTemplateParm: { 3295 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3296 type = reftype->getPointeeType(); 3297 valueKind = VK_LValue; // even if the parameter is an r-value reference 3298 break; 3299 } 3300 3301 // [expr.prim.id.unqual]p2: 3302 // If the entity is a template parameter object for a template 3303 // parameter of type T, the type of the expression is const T. 3304 // [...] The expression is an lvalue if the entity is a [...] template 3305 // parameter object. 3306 if (type->isRecordType()) { 3307 type = type.getUnqualifiedType().withConst(); 3308 valueKind = VK_LValue; 3309 break; 3310 } 3311 3312 // For non-references, we need to strip qualifiers just in case 3313 // the template parameter was declared as 'const int' or whatever. 3314 valueKind = VK_RValue; 3315 type = type.getUnqualifiedType(); 3316 break; 3317 } 3318 3319 case Decl::Var: 3320 case Decl::VarTemplateSpecialization: 3321 case Decl::VarTemplatePartialSpecialization: 3322 case Decl::Decomposition: 3323 case Decl::OMPCapturedExpr: 3324 // In C, "extern void blah;" is valid and is an r-value. 3325 if (!getLangOpts().CPlusPlus && 3326 !type.hasQualifiers() && 3327 type->isVoidType()) { 3328 valueKind = VK_RValue; 3329 break; 3330 } 3331 LLVM_FALLTHROUGH; 3332 3333 case Decl::ImplicitParam: 3334 case Decl::ParmVar: { 3335 // These are always l-values. 3336 valueKind = VK_LValue; 3337 type = type.getNonReferenceType(); 3338 3339 // FIXME: Does the addition of const really only apply in 3340 // potentially-evaluated contexts? Since the variable isn't actually 3341 // captured in an unevaluated context, it seems that the answer is no. 3342 if (!isUnevaluatedContext()) { 3343 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3344 if (!CapturedType.isNull()) 3345 type = CapturedType; 3346 } 3347 3348 break; 3349 } 3350 3351 case Decl::Binding: { 3352 // These are always lvalues. 3353 valueKind = VK_LValue; 3354 type = type.getNonReferenceType(); 3355 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3356 // decides how that's supposed to work. 3357 auto *BD = cast<BindingDecl>(VD); 3358 if (BD->getDeclContext() != CurContext) { 3359 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3360 if (DD && DD->hasLocalStorage()) 3361 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3362 } 3363 break; 3364 } 3365 3366 case Decl::Function: { 3367 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3368 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3369 type = Context.BuiltinFnTy; 3370 valueKind = VK_RValue; 3371 break; 3372 } 3373 } 3374 3375 const FunctionType *fty = type->castAs<FunctionType>(); 3376 3377 // If we're referring to a function with an __unknown_anytype 3378 // result type, make the entire expression __unknown_anytype. 3379 if (fty->getReturnType() == Context.UnknownAnyTy) { 3380 type = Context.UnknownAnyTy; 3381 valueKind = VK_RValue; 3382 break; 3383 } 3384 3385 // Functions are l-values in C++. 3386 if (getLangOpts().CPlusPlus) { 3387 valueKind = VK_LValue; 3388 break; 3389 } 3390 3391 // C99 DR 316 says that, if a function type comes from a 3392 // function definition (without a prototype), that type is only 3393 // used for checking compatibility. Therefore, when referencing 3394 // the function, we pretend that we don't have the full function 3395 // type. 3396 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3397 isa<FunctionProtoType>(fty)) 3398 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3399 fty->getExtInfo()); 3400 3401 // Functions are r-values in C. 3402 valueKind = VK_RValue; 3403 break; 3404 } 3405 3406 case Decl::CXXDeductionGuide: 3407 llvm_unreachable("building reference to deduction guide"); 3408 3409 case Decl::MSProperty: 3410 case Decl::MSGuid: 3411 case Decl::TemplateParamObject: 3412 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3413 // capture in OpenMP, or duplicated between host and device? 3414 valueKind = VK_LValue; 3415 break; 3416 3417 case Decl::CXXMethod: 3418 // If we're referring to a method with an __unknown_anytype 3419 // result type, make the entire expression __unknown_anytype. 3420 // This should only be possible with a type written directly. 3421 if (const FunctionProtoType *proto 3422 = dyn_cast<FunctionProtoType>(VD->getType())) 3423 if (proto->getReturnType() == Context.UnknownAnyTy) { 3424 type = Context.UnknownAnyTy; 3425 valueKind = VK_RValue; 3426 break; 3427 } 3428 3429 // C++ methods are l-values if static, r-values if non-static. 3430 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3431 valueKind = VK_LValue; 3432 break; 3433 } 3434 LLVM_FALLTHROUGH; 3435 3436 case Decl::CXXConversion: 3437 case Decl::CXXDestructor: 3438 case Decl::CXXConstructor: 3439 valueKind = VK_RValue; 3440 break; 3441 } 3442 3443 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3444 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3445 TemplateArgs); 3446 } 3447 } 3448 3449 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3450 SmallString<32> &Target) { 3451 Target.resize(CharByteWidth * (Source.size() + 1)); 3452 char *ResultPtr = &Target[0]; 3453 const llvm::UTF8 *ErrorPtr; 3454 bool success = 3455 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3456 (void)success; 3457 assert(success); 3458 Target.resize(ResultPtr - &Target[0]); 3459 } 3460 3461 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3462 PredefinedExpr::IdentKind IK) { 3463 // Pick the current block, lambda, captured statement or function. 3464 Decl *currentDecl = nullptr; 3465 if (const BlockScopeInfo *BSI = getCurBlock()) 3466 currentDecl = BSI->TheDecl; 3467 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3468 currentDecl = LSI->CallOperator; 3469 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3470 currentDecl = CSI->TheCapturedDecl; 3471 else 3472 currentDecl = getCurFunctionOrMethodDecl(); 3473 3474 if (!currentDecl) { 3475 Diag(Loc, diag::ext_predef_outside_function); 3476 currentDecl = Context.getTranslationUnitDecl(); 3477 } 3478 3479 QualType ResTy; 3480 StringLiteral *SL = nullptr; 3481 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3482 ResTy = Context.DependentTy; 3483 else { 3484 // Pre-defined identifiers are of type char[x], where x is the length of 3485 // the string. 3486 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3487 unsigned Length = Str.length(); 3488 3489 llvm::APInt LengthI(32, Length + 1); 3490 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3491 ResTy = 3492 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3493 SmallString<32> RawChars; 3494 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3495 Str, RawChars); 3496 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3497 ArrayType::Normal, 3498 /*IndexTypeQuals*/ 0); 3499 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3500 /*Pascal*/ false, ResTy, Loc); 3501 } else { 3502 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3503 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3504 ArrayType::Normal, 3505 /*IndexTypeQuals*/ 0); 3506 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3507 /*Pascal*/ false, ResTy, Loc); 3508 } 3509 } 3510 3511 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3512 } 3513 3514 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3515 PredefinedExpr::IdentKind IK; 3516 3517 switch (Kind) { 3518 default: llvm_unreachable("Unknown simple primary expr!"); 3519 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3520 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3521 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3522 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3523 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3524 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3525 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3526 } 3527 3528 return BuildPredefinedExpr(Loc, IK); 3529 } 3530 3531 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3532 SmallString<16> CharBuffer; 3533 bool Invalid = false; 3534 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3535 if (Invalid) 3536 return ExprError(); 3537 3538 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3539 PP, Tok.getKind()); 3540 if (Literal.hadError()) 3541 return ExprError(); 3542 3543 QualType Ty; 3544 if (Literal.isWide()) 3545 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3546 else if (Literal.isUTF8() && getLangOpts().Char8) 3547 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3548 else if (Literal.isUTF16()) 3549 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3550 else if (Literal.isUTF32()) 3551 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3552 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3553 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3554 else 3555 Ty = Context.CharTy; // 'x' -> char in C++ 3556 3557 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3558 if (Literal.isWide()) 3559 Kind = CharacterLiteral::Wide; 3560 else if (Literal.isUTF16()) 3561 Kind = CharacterLiteral::UTF16; 3562 else if (Literal.isUTF32()) 3563 Kind = CharacterLiteral::UTF32; 3564 else if (Literal.isUTF8()) 3565 Kind = CharacterLiteral::UTF8; 3566 3567 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3568 Tok.getLocation()); 3569 3570 if (Literal.getUDSuffix().empty()) 3571 return Lit; 3572 3573 // We're building a user-defined literal. 3574 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3575 SourceLocation UDSuffixLoc = 3576 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3577 3578 // Make sure we're allowed user-defined literals here. 3579 if (!UDLScope) 3580 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3581 3582 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3583 // operator "" X (ch) 3584 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3585 Lit, Tok.getLocation()); 3586 } 3587 3588 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3589 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3590 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3591 Context.IntTy, Loc); 3592 } 3593 3594 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3595 QualType Ty, SourceLocation Loc) { 3596 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3597 3598 using llvm::APFloat; 3599 APFloat Val(Format); 3600 3601 APFloat::opStatus result = Literal.GetFloatValue(Val); 3602 3603 // Overflow is always an error, but underflow is only an error if 3604 // we underflowed to zero (APFloat reports denormals as underflow). 3605 if ((result & APFloat::opOverflow) || 3606 ((result & APFloat::opUnderflow) && Val.isZero())) { 3607 unsigned diagnostic; 3608 SmallString<20> buffer; 3609 if (result & APFloat::opOverflow) { 3610 diagnostic = diag::warn_float_overflow; 3611 APFloat::getLargest(Format).toString(buffer); 3612 } else { 3613 diagnostic = diag::warn_float_underflow; 3614 APFloat::getSmallest(Format).toString(buffer); 3615 } 3616 3617 S.Diag(Loc, diagnostic) 3618 << Ty 3619 << StringRef(buffer.data(), buffer.size()); 3620 } 3621 3622 bool isExact = (result == APFloat::opOK); 3623 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3624 } 3625 3626 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3627 assert(E && "Invalid expression"); 3628 3629 if (E->isValueDependent()) 3630 return false; 3631 3632 QualType QT = E->getType(); 3633 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3634 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3635 return true; 3636 } 3637 3638 llvm::APSInt ValueAPS; 3639 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3640 3641 if (R.isInvalid()) 3642 return true; 3643 3644 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3645 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3646 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3647 << ValueAPS.toString(10) << ValueIsPositive; 3648 return true; 3649 } 3650 3651 return false; 3652 } 3653 3654 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3655 // Fast path for a single digit (which is quite common). A single digit 3656 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3657 if (Tok.getLength() == 1) { 3658 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3659 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3660 } 3661 3662 SmallString<128> SpellingBuffer; 3663 // NumericLiteralParser wants to overread by one character. Add padding to 3664 // the buffer in case the token is copied to the buffer. If getSpelling() 3665 // returns a StringRef to the memory buffer, it should have a null char at 3666 // the EOF, so it is also safe. 3667 SpellingBuffer.resize(Tok.getLength() + 1); 3668 3669 // Get the spelling of the token, which eliminates trigraphs, etc. 3670 bool Invalid = false; 3671 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3672 if (Invalid) 3673 return ExprError(); 3674 3675 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3676 PP.getSourceManager(), PP.getLangOpts(), 3677 PP.getTargetInfo(), PP.getDiagnostics()); 3678 if (Literal.hadError) 3679 return ExprError(); 3680 3681 if (Literal.hasUDSuffix()) { 3682 // We're building a user-defined literal. 3683 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3684 SourceLocation UDSuffixLoc = 3685 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3686 3687 // Make sure we're allowed user-defined literals here. 3688 if (!UDLScope) 3689 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3690 3691 QualType CookedTy; 3692 if (Literal.isFloatingLiteral()) { 3693 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3694 // long double, the literal is treated as a call of the form 3695 // operator "" X (f L) 3696 CookedTy = Context.LongDoubleTy; 3697 } else { 3698 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3699 // unsigned long long, the literal is treated as a call of the form 3700 // operator "" X (n ULL) 3701 CookedTy = Context.UnsignedLongLongTy; 3702 } 3703 3704 DeclarationName OpName = 3705 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3706 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3707 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3708 3709 SourceLocation TokLoc = Tok.getLocation(); 3710 3711 // Perform literal operator lookup to determine if we're building a raw 3712 // literal or a cooked one. 3713 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3714 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3715 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3716 /*AllowStringTemplatePack*/ false, 3717 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3718 case LOLR_ErrorNoDiagnostic: 3719 // Lookup failure for imaginary constants isn't fatal, there's still the 3720 // GNU extension producing _Complex types. 3721 break; 3722 case LOLR_Error: 3723 return ExprError(); 3724 case LOLR_Cooked: { 3725 Expr *Lit; 3726 if (Literal.isFloatingLiteral()) { 3727 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3728 } else { 3729 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3730 if (Literal.GetIntegerValue(ResultVal)) 3731 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3732 << /* Unsigned */ 1; 3733 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3734 Tok.getLocation()); 3735 } 3736 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3737 } 3738 3739 case LOLR_Raw: { 3740 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3741 // literal is treated as a call of the form 3742 // operator "" X ("n") 3743 unsigned Length = Literal.getUDSuffixOffset(); 3744 QualType StrTy = Context.getConstantArrayType( 3745 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3746 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3747 Expr *Lit = StringLiteral::Create( 3748 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3749 /*Pascal*/false, StrTy, &TokLoc, 1); 3750 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3751 } 3752 3753 case LOLR_Template: { 3754 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3755 // template), L is treated as a call fo the form 3756 // operator "" X <'c1', 'c2', ... 'ck'>() 3757 // where n is the source character sequence c1 c2 ... ck. 3758 TemplateArgumentListInfo ExplicitArgs; 3759 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3760 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3761 llvm::APSInt Value(CharBits, CharIsUnsigned); 3762 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3763 Value = TokSpelling[I]; 3764 TemplateArgument Arg(Context, Value, Context.CharTy); 3765 TemplateArgumentLocInfo ArgInfo; 3766 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3767 } 3768 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3769 &ExplicitArgs); 3770 } 3771 case LOLR_StringTemplatePack: 3772 llvm_unreachable("unexpected literal operator lookup result"); 3773 } 3774 } 3775 3776 Expr *Res; 3777 3778 if (Literal.isFixedPointLiteral()) { 3779 QualType Ty; 3780 3781 if (Literal.isAccum) { 3782 if (Literal.isHalf) { 3783 Ty = Context.ShortAccumTy; 3784 } else if (Literal.isLong) { 3785 Ty = Context.LongAccumTy; 3786 } else { 3787 Ty = Context.AccumTy; 3788 } 3789 } else if (Literal.isFract) { 3790 if (Literal.isHalf) { 3791 Ty = Context.ShortFractTy; 3792 } else if (Literal.isLong) { 3793 Ty = Context.LongFractTy; 3794 } else { 3795 Ty = Context.FractTy; 3796 } 3797 } 3798 3799 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3800 3801 bool isSigned = !Literal.isUnsigned; 3802 unsigned scale = Context.getFixedPointScale(Ty); 3803 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3804 3805 llvm::APInt Val(bit_width, 0, isSigned); 3806 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3807 bool ValIsZero = Val.isNullValue() && !Overflowed; 3808 3809 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3810 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3811 // Clause 6.4.4 - The value of a constant shall be in the range of 3812 // representable values for its type, with exception for constants of a 3813 // fract type with a value of exactly 1; such a constant shall denote 3814 // the maximal value for the type. 3815 --Val; 3816 else if (Val.ugt(MaxVal) || Overflowed) 3817 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3818 3819 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3820 Tok.getLocation(), scale); 3821 } else if (Literal.isFloatingLiteral()) { 3822 QualType Ty; 3823 if (Literal.isHalf){ 3824 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3825 Ty = Context.HalfTy; 3826 else { 3827 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3828 return ExprError(); 3829 } 3830 } else if (Literal.isFloat) 3831 Ty = Context.FloatTy; 3832 else if (Literal.isLong) 3833 Ty = Context.LongDoubleTy; 3834 else if (Literal.isFloat16) 3835 Ty = Context.Float16Ty; 3836 else if (Literal.isFloat128) 3837 Ty = Context.Float128Ty; 3838 else 3839 Ty = Context.DoubleTy; 3840 3841 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3842 3843 if (Ty == Context.DoubleTy) { 3844 if (getLangOpts().SinglePrecisionConstants) { 3845 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3846 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3847 } 3848 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3849 "cl_khr_fp64", getLangOpts())) { 3850 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3851 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3852 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3853 } 3854 } 3855 } else if (!Literal.isIntegerLiteral()) { 3856 return ExprError(); 3857 } else { 3858 QualType Ty; 3859 3860 // 'long long' is a C99 or C++11 feature. 3861 if (!getLangOpts().C99 && Literal.isLongLong) { 3862 if (getLangOpts().CPlusPlus) 3863 Diag(Tok.getLocation(), 3864 getLangOpts().CPlusPlus11 ? 3865 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3866 else 3867 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3868 } 3869 3870 // Get the value in the widest-possible width. 3871 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3872 llvm::APInt ResultVal(MaxWidth, 0); 3873 3874 if (Literal.GetIntegerValue(ResultVal)) { 3875 // If this value didn't fit into uintmax_t, error and force to ull. 3876 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3877 << /* Unsigned */ 1; 3878 Ty = Context.UnsignedLongLongTy; 3879 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3880 "long long is not intmax_t?"); 3881 } else { 3882 // If this value fits into a ULL, try to figure out what else it fits into 3883 // according to the rules of C99 6.4.4.1p5. 3884 3885 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3886 // be an unsigned int. 3887 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3888 3889 // Check from smallest to largest, picking the smallest type we can. 3890 unsigned Width = 0; 3891 3892 // Microsoft specific integer suffixes are explicitly sized. 3893 if (Literal.MicrosoftInteger) { 3894 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3895 Width = 8; 3896 Ty = Context.CharTy; 3897 } else { 3898 Width = Literal.MicrosoftInteger; 3899 Ty = Context.getIntTypeForBitwidth(Width, 3900 /*Signed=*/!Literal.isUnsigned); 3901 } 3902 } 3903 3904 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3905 // Are int/unsigned possibilities? 3906 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3907 3908 // Does it fit in a unsigned int? 3909 if (ResultVal.isIntN(IntSize)) { 3910 // Does it fit in a signed int? 3911 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3912 Ty = Context.IntTy; 3913 else if (AllowUnsigned) 3914 Ty = Context.UnsignedIntTy; 3915 Width = IntSize; 3916 } 3917 } 3918 3919 // Are long/unsigned long possibilities? 3920 if (Ty.isNull() && !Literal.isLongLong) { 3921 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3922 3923 // Does it fit in a unsigned long? 3924 if (ResultVal.isIntN(LongSize)) { 3925 // Does it fit in a signed long? 3926 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3927 Ty = Context.LongTy; 3928 else if (AllowUnsigned) 3929 Ty = Context.UnsignedLongTy; 3930 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3931 // is compatible. 3932 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3933 const unsigned LongLongSize = 3934 Context.getTargetInfo().getLongLongWidth(); 3935 Diag(Tok.getLocation(), 3936 getLangOpts().CPlusPlus 3937 ? Literal.isLong 3938 ? diag::warn_old_implicitly_unsigned_long_cxx 3939 : /*C++98 UB*/ diag:: 3940 ext_old_implicitly_unsigned_long_cxx 3941 : diag::warn_old_implicitly_unsigned_long) 3942 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3943 : /*will be ill-formed*/ 1); 3944 Ty = Context.UnsignedLongTy; 3945 } 3946 Width = LongSize; 3947 } 3948 } 3949 3950 // Check long long if needed. 3951 if (Ty.isNull()) { 3952 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3953 3954 // Does it fit in a unsigned long long? 3955 if (ResultVal.isIntN(LongLongSize)) { 3956 // Does it fit in a signed long long? 3957 // To be compatible with MSVC, hex integer literals ending with the 3958 // LL or i64 suffix are always signed in Microsoft mode. 3959 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3960 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3961 Ty = Context.LongLongTy; 3962 else if (AllowUnsigned) 3963 Ty = Context.UnsignedLongLongTy; 3964 Width = LongLongSize; 3965 } 3966 } 3967 3968 // If we still couldn't decide a type, we probably have something that 3969 // does not fit in a signed long long, but has no U suffix. 3970 if (Ty.isNull()) { 3971 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3972 Ty = Context.UnsignedLongLongTy; 3973 Width = Context.getTargetInfo().getLongLongWidth(); 3974 } 3975 3976 if (ResultVal.getBitWidth() != Width) 3977 ResultVal = ResultVal.trunc(Width); 3978 } 3979 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3980 } 3981 3982 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3983 if (Literal.isImaginary) { 3984 Res = new (Context) ImaginaryLiteral(Res, 3985 Context.getComplexType(Res->getType())); 3986 3987 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3988 } 3989 return Res; 3990 } 3991 3992 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3993 assert(E && "ActOnParenExpr() missing expr"); 3994 return new (Context) ParenExpr(L, R, E); 3995 } 3996 3997 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3998 SourceLocation Loc, 3999 SourceRange ArgRange) { 4000 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4001 // scalar or vector data type argument..." 4002 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4003 // type (C99 6.2.5p18) or void. 4004 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4005 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4006 << T << ArgRange; 4007 return true; 4008 } 4009 4010 assert((T->isVoidType() || !T->isIncompleteType()) && 4011 "Scalar types should always be complete"); 4012 return false; 4013 } 4014 4015 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4016 SourceLocation Loc, 4017 SourceRange ArgRange, 4018 UnaryExprOrTypeTrait TraitKind) { 4019 // Invalid types must be hard errors for SFINAE in C++. 4020 if (S.LangOpts.CPlusPlus) 4021 return true; 4022 4023 // C99 6.5.3.4p1: 4024 if (T->isFunctionType() && 4025 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4026 TraitKind == UETT_PreferredAlignOf)) { 4027 // sizeof(function)/alignof(function) is allowed as an extension. 4028 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4029 << getTraitSpelling(TraitKind) << ArgRange; 4030 return false; 4031 } 4032 4033 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4034 // this is an error (OpenCL v1.1 s6.3.k) 4035 if (T->isVoidType()) { 4036 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4037 : diag::ext_sizeof_alignof_void_type; 4038 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4039 return false; 4040 } 4041 4042 return true; 4043 } 4044 4045 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4046 SourceLocation Loc, 4047 SourceRange ArgRange, 4048 UnaryExprOrTypeTrait TraitKind) { 4049 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4050 // runtime doesn't allow it. 4051 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4052 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4053 << T << (TraitKind == UETT_SizeOf) 4054 << ArgRange; 4055 return true; 4056 } 4057 4058 return false; 4059 } 4060 4061 /// Check whether E is a pointer from a decayed array type (the decayed 4062 /// pointer type is equal to T) and emit a warning if it is. 4063 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4064 Expr *E) { 4065 // Don't warn if the operation changed the type. 4066 if (T != E->getType()) 4067 return; 4068 4069 // Now look for array decays. 4070 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4071 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4072 return; 4073 4074 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4075 << ICE->getType() 4076 << ICE->getSubExpr()->getType(); 4077 } 4078 4079 /// Check the constraints on expression operands to unary type expression 4080 /// and type traits. 4081 /// 4082 /// Completes any types necessary and validates the constraints on the operand 4083 /// expression. The logic mostly mirrors the type-based overload, but may modify 4084 /// the expression as it completes the type for that expression through template 4085 /// instantiation, etc. 4086 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4087 UnaryExprOrTypeTrait ExprKind) { 4088 QualType ExprTy = E->getType(); 4089 assert(!ExprTy->isReferenceType()); 4090 4091 bool IsUnevaluatedOperand = 4092 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4093 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4094 if (IsUnevaluatedOperand) { 4095 ExprResult Result = CheckUnevaluatedOperand(E); 4096 if (Result.isInvalid()) 4097 return true; 4098 E = Result.get(); 4099 } 4100 4101 // The operand for sizeof and alignof is in an unevaluated expression context, 4102 // so side effects could result in unintended consequences. 4103 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4104 // used to build SFINAE gadgets. 4105 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4106 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4107 !E->isInstantiationDependent() && 4108 E->HasSideEffects(Context, false)) 4109 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4110 4111 if (ExprKind == UETT_VecStep) 4112 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4113 E->getSourceRange()); 4114 4115 // Explicitly list some types as extensions. 4116 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4117 E->getSourceRange(), ExprKind)) 4118 return false; 4119 4120 // 'alignof' applied to an expression only requires the base element type of 4121 // the expression to be complete. 'sizeof' requires the expression's type to 4122 // be complete (and will attempt to complete it if it's an array of unknown 4123 // bound). 4124 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4125 if (RequireCompleteSizedType( 4126 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4127 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4128 getTraitSpelling(ExprKind), E->getSourceRange())) 4129 return true; 4130 } else { 4131 if (RequireCompleteSizedExprType( 4132 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4133 getTraitSpelling(ExprKind), E->getSourceRange())) 4134 return true; 4135 } 4136 4137 // Completing the expression's type may have changed it. 4138 ExprTy = E->getType(); 4139 assert(!ExprTy->isReferenceType()); 4140 4141 if (ExprTy->isFunctionType()) { 4142 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4143 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4144 return true; 4145 } 4146 4147 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4148 E->getSourceRange(), ExprKind)) 4149 return true; 4150 4151 if (ExprKind == UETT_SizeOf) { 4152 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4153 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4154 QualType OType = PVD->getOriginalType(); 4155 QualType Type = PVD->getType(); 4156 if (Type->isPointerType() && OType->isArrayType()) { 4157 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4158 << Type << OType; 4159 Diag(PVD->getLocation(), diag::note_declared_at); 4160 } 4161 } 4162 } 4163 4164 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4165 // decays into a pointer and returns an unintended result. This is most 4166 // likely a typo for "sizeof(array) op x". 4167 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4168 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4169 BO->getLHS()); 4170 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4171 BO->getRHS()); 4172 } 4173 } 4174 4175 return false; 4176 } 4177 4178 /// Check the constraints on operands to unary expression and type 4179 /// traits. 4180 /// 4181 /// This will complete any types necessary, and validate the various constraints 4182 /// on those operands. 4183 /// 4184 /// The UsualUnaryConversions() function is *not* called by this routine. 4185 /// C99 6.3.2.1p[2-4] all state: 4186 /// Except when it is the operand of the sizeof operator ... 4187 /// 4188 /// C++ [expr.sizeof]p4 4189 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4190 /// standard conversions are not applied to the operand of sizeof. 4191 /// 4192 /// This policy is followed for all of the unary trait expressions. 4193 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4194 SourceLocation OpLoc, 4195 SourceRange ExprRange, 4196 UnaryExprOrTypeTrait ExprKind) { 4197 if (ExprType->isDependentType()) 4198 return false; 4199 4200 // C++ [expr.sizeof]p2: 4201 // When applied to a reference or a reference type, the result 4202 // is the size of the referenced type. 4203 // C++11 [expr.alignof]p3: 4204 // When alignof is applied to a reference type, the result 4205 // shall be the alignment of the referenced type. 4206 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4207 ExprType = Ref->getPointeeType(); 4208 4209 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4210 // When alignof or _Alignof is applied to an array type, the result 4211 // is the alignment of the element type. 4212 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4213 ExprKind == UETT_OpenMPRequiredSimdAlign) 4214 ExprType = Context.getBaseElementType(ExprType); 4215 4216 if (ExprKind == UETT_VecStep) 4217 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4218 4219 // Explicitly list some types as extensions. 4220 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4221 ExprKind)) 4222 return false; 4223 4224 if (RequireCompleteSizedType( 4225 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4226 getTraitSpelling(ExprKind), ExprRange)) 4227 return true; 4228 4229 if (ExprType->isFunctionType()) { 4230 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4231 << getTraitSpelling(ExprKind) << ExprRange; 4232 return true; 4233 } 4234 4235 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4236 ExprKind)) 4237 return true; 4238 4239 return false; 4240 } 4241 4242 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4243 // Cannot know anything else if the expression is dependent. 4244 if (E->isTypeDependent()) 4245 return false; 4246 4247 if (E->getObjectKind() == OK_BitField) { 4248 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4249 << 1 << E->getSourceRange(); 4250 return true; 4251 } 4252 4253 ValueDecl *D = nullptr; 4254 Expr *Inner = E->IgnoreParens(); 4255 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4256 D = DRE->getDecl(); 4257 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4258 D = ME->getMemberDecl(); 4259 } 4260 4261 // If it's a field, require the containing struct to have a 4262 // complete definition so that we can compute the layout. 4263 // 4264 // This can happen in C++11 onwards, either by naming the member 4265 // in a way that is not transformed into a member access expression 4266 // (in an unevaluated operand, for instance), or by naming the member 4267 // in a trailing-return-type. 4268 // 4269 // For the record, since __alignof__ on expressions is a GCC 4270 // extension, GCC seems to permit this but always gives the 4271 // nonsensical answer 0. 4272 // 4273 // We don't really need the layout here --- we could instead just 4274 // directly check for all the appropriate alignment-lowing 4275 // attributes --- but that would require duplicating a lot of 4276 // logic that just isn't worth duplicating for such a marginal 4277 // use-case. 4278 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4279 // Fast path this check, since we at least know the record has a 4280 // definition if we can find a member of it. 4281 if (!FD->getParent()->isCompleteDefinition()) { 4282 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4283 << E->getSourceRange(); 4284 return true; 4285 } 4286 4287 // Otherwise, if it's a field, and the field doesn't have 4288 // reference type, then it must have a complete type (or be a 4289 // flexible array member, which we explicitly want to 4290 // white-list anyway), which makes the following checks trivial. 4291 if (!FD->getType()->isReferenceType()) 4292 return false; 4293 } 4294 4295 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4296 } 4297 4298 bool Sema::CheckVecStepExpr(Expr *E) { 4299 E = E->IgnoreParens(); 4300 4301 // Cannot know anything else if the expression is dependent. 4302 if (E->isTypeDependent()) 4303 return false; 4304 4305 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4306 } 4307 4308 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4309 CapturingScopeInfo *CSI) { 4310 assert(T->isVariablyModifiedType()); 4311 assert(CSI != nullptr); 4312 4313 // We're going to walk down into the type and look for VLA expressions. 4314 do { 4315 const Type *Ty = T.getTypePtr(); 4316 switch (Ty->getTypeClass()) { 4317 #define TYPE(Class, Base) 4318 #define ABSTRACT_TYPE(Class, Base) 4319 #define NON_CANONICAL_TYPE(Class, Base) 4320 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4321 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4322 #include "clang/AST/TypeNodes.inc" 4323 T = QualType(); 4324 break; 4325 // These types are never variably-modified. 4326 case Type::Builtin: 4327 case Type::Complex: 4328 case Type::Vector: 4329 case Type::ExtVector: 4330 case Type::ConstantMatrix: 4331 case Type::Record: 4332 case Type::Enum: 4333 case Type::Elaborated: 4334 case Type::TemplateSpecialization: 4335 case Type::ObjCObject: 4336 case Type::ObjCInterface: 4337 case Type::ObjCObjectPointer: 4338 case Type::ObjCTypeParam: 4339 case Type::Pipe: 4340 case Type::ExtInt: 4341 llvm_unreachable("type class is never variably-modified!"); 4342 case Type::Adjusted: 4343 T = cast<AdjustedType>(Ty)->getOriginalType(); 4344 break; 4345 case Type::Decayed: 4346 T = cast<DecayedType>(Ty)->getPointeeType(); 4347 break; 4348 case Type::Pointer: 4349 T = cast<PointerType>(Ty)->getPointeeType(); 4350 break; 4351 case Type::BlockPointer: 4352 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4353 break; 4354 case Type::LValueReference: 4355 case Type::RValueReference: 4356 T = cast<ReferenceType>(Ty)->getPointeeType(); 4357 break; 4358 case Type::MemberPointer: 4359 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4360 break; 4361 case Type::ConstantArray: 4362 case Type::IncompleteArray: 4363 // Losing element qualification here is fine. 4364 T = cast<ArrayType>(Ty)->getElementType(); 4365 break; 4366 case Type::VariableArray: { 4367 // Losing element qualification here is fine. 4368 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4369 4370 // Unknown size indication requires no size computation. 4371 // Otherwise, evaluate and record it. 4372 auto Size = VAT->getSizeExpr(); 4373 if (Size && !CSI->isVLATypeCaptured(VAT) && 4374 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4375 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4376 4377 T = VAT->getElementType(); 4378 break; 4379 } 4380 case Type::FunctionProto: 4381 case Type::FunctionNoProto: 4382 T = cast<FunctionType>(Ty)->getReturnType(); 4383 break; 4384 case Type::Paren: 4385 case Type::TypeOf: 4386 case Type::UnaryTransform: 4387 case Type::Attributed: 4388 case Type::SubstTemplateTypeParm: 4389 case Type::MacroQualified: 4390 // Keep walking after single level desugaring. 4391 T = T.getSingleStepDesugaredType(Context); 4392 break; 4393 case Type::Typedef: 4394 T = cast<TypedefType>(Ty)->desugar(); 4395 break; 4396 case Type::Decltype: 4397 T = cast<DecltypeType>(Ty)->desugar(); 4398 break; 4399 case Type::Auto: 4400 case Type::DeducedTemplateSpecialization: 4401 T = cast<DeducedType>(Ty)->getDeducedType(); 4402 break; 4403 case Type::TypeOfExpr: 4404 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4405 break; 4406 case Type::Atomic: 4407 T = cast<AtomicType>(Ty)->getValueType(); 4408 break; 4409 } 4410 } while (!T.isNull() && T->isVariablyModifiedType()); 4411 } 4412 4413 /// Build a sizeof or alignof expression given a type operand. 4414 ExprResult 4415 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4416 SourceLocation OpLoc, 4417 UnaryExprOrTypeTrait ExprKind, 4418 SourceRange R) { 4419 if (!TInfo) 4420 return ExprError(); 4421 4422 QualType T = TInfo->getType(); 4423 4424 if (!T->isDependentType() && 4425 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4426 return ExprError(); 4427 4428 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4429 if (auto *TT = T->getAs<TypedefType>()) { 4430 for (auto I = FunctionScopes.rbegin(), 4431 E = std::prev(FunctionScopes.rend()); 4432 I != E; ++I) { 4433 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4434 if (CSI == nullptr) 4435 break; 4436 DeclContext *DC = nullptr; 4437 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4438 DC = LSI->CallOperator; 4439 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4440 DC = CRSI->TheCapturedDecl; 4441 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4442 DC = BSI->TheDecl; 4443 if (DC) { 4444 if (DC->containsDecl(TT->getDecl())) 4445 break; 4446 captureVariablyModifiedType(Context, T, CSI); 4447 } 4448 } 4449 } 4450 } 4451 4452 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4453 return new (Context) UnaryExprOrTypeTraitExpr( 4454 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4455 } 4456 4457 /// Build a sizeof or alignof expression given an expression 4458 /// operand. 4459 ExprResult 4460 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4461 UnaryExprOrTypeTrait ExprKind) { 4462 ExprResult PE = CheckPlaceholderExpr(E); 4463 if (PE.isInvalid()) 4464 return ExprError(); 4465 4466 E = PE.get(); 4467 4468 // Verify that the operand is valid. 4469 bool isInvalid = false; 4470 if (E->isTypeDependent()) { 4471 // Delay type-checking for type-dependent expressions. 4472 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4473 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4474 } else if (ExprKind == UETT_VecStep) { 4475 isInvalid = CheckVecStepExpr(E); 4476 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4477 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4478 isInvalid = true; 4479 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4480 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4481 isInvalid = true; 4482 } else { 4483 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4484 } 4485 4486 if (isInvalid) 4487 return ExprError(); 4488 4489 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4490 PE = TransformToPotentiallyEvaluated(E); 4491 if (PE.isInvalid()) return ExprError(); 4492 E = PE.get(); 4493 } 4494 4495 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4496 return new (Context) UnaryExprOrTypeTraitExpr( 4497 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4498 } 4499 4500 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4501 /// expr and the same for @c alignof and @c __alignof 4502 /// Note that the ArgRange is invalid if isType is false. 4503 ExprResult 4504 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4505 UnaryExprOrTypeTrait ExprKind, bool IsType, 4506 void *TyOrEx, SourceRange ArgRange) { 4507 // If error parsing type, ignore. 4508 if (!TyOrEx) return ExprError(); 4509 4510 if (IsType) { 4511 TypeSourceInfo *TInfo; 4512 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4513 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4514 } 4515 4516 Expr *ArgEx = (Expr *)TyOrEx; 4517 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4518 return Result; 4519 } 4520 4521 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4522 bool IsReal) { 4523 if (V.get()->isTypeDependent()) 4524 return S.Context.DependentTy; 4525 4526 // _Real and _Imag are only l-values for normal l-values. 4527 if (V.get()->getObjectKind() != OK_Ordinary) { 4528 V = S.DefaultLvalueConversion(V.get()); 4529 if (V.isInvalid()) 4530 return QualType(); 4531 } 4532 4533 // These operators return the element type of a complex type. 4534 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4535 return CT->getElementType(); 4536 4537 // Otherwise they pass through real integer and floating point types here. 4538 if (V.get()->getType()->isArithmeticType()) 4539 return V.get()->getType(); 4540 4541 // Test for placeholders. 4542 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4543 if (PR.isInvalid()) return QualType(); 4544 if (PR.get() != V.get()) { 4545 V = PR; 4546 return CheckRealImagOperand(S, V, Loc, IsReal); 4547 } 4548 4549 // Reject anything else. 4550 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4551 << (IsReal ? "__real" : "__imag"); 4552 return QualType(); 4553 } 4554 4555 4556 4557 ExprResult 4558 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4559 tok::TokenKind Kind, Expr *Input) { 4560 UnaryOperatorKind Opc; 4561 switch (Kind) { 4562 default: llvm_unreachable("Unknown unary op!"); 4563 case tok::plusplus: Opc = UO_PostInc; break; 4564 case tok::minusminus: Opc = UO_PostDec; break; 4565 } 4566 4567 // Since this might is a postfix expression, get rid of ParenListExprs. 4568 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4569 if (Result.isInvalid()) return ExprError(); 4570 Input = Result.get(); 4571 4572 return BuildUnaryOp(S, OpLoc, Opc, Input); 4573 } 4574 4575 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4576 /// 4577 /// \return true on error 4578 static bool checkArithmeticOnObjCPointer(Sema &S, 4579 SourceLocation opLoc, 4580 Expr *op) { 4581 assert(op->getType()->isObjCObjectPointerType()); 4582 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4583 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4584 return false; 4585 4586 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4587 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4588 << op->getSourceRange(); 4589 return true; 4590 } 4591 4592 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4593 auto *BaseNoParens = Base->IgnoreParens(); 4594 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4595 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4596 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4597 } 4598 4599 ExprResult 4600 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4601 Expr *idx, SourceLocation rbLoc) { 4602 if (base && !base->getType().isNull() && 4603 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4604 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4605 SourceLocation(), /*Length*/ nullptr, 4606 /*Stride=*/nullptr, rbLoc); 4607 4608 // Since this might be a postfix expression, get rid of ParenListExprs. 4609 if (isa<ParenListExpr>(base)) { 4610 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4611 if (result.isInvalid()) return ExprError(); 4612 base = result.get(); 4613 } 4614 4615 // Check if base and idx form a MatrixSubscriptExpr. 4616 // 4617 // Helper to check for comma expressions, which are not allowed as indices for 4618 // matrix subscript expressions. 4619 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4620 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4621 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4622 << SourceRange(base->getBeginLoc(), rbLoc); 4623 return true; 4624 } 4625 return false; 4626 }; 4627 // The matrix subscript operator ([][])is considered a single operator. 4628 // Separating the index expressions by parenthesis is not allowed. 4629 if (base->getType()->isSpecificPlaceholderType( 4630 BuiltinType::IncompleteMatrixIdx) && 4631 !isa<MatrixSubscriptExpr>(base)) { 4632 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4633 << SourceRange(base->getBeginLoc(), rbLoc); 4634 return ExprError(); 4635 } 4636 // If the base is a MatrixSubscriptExpr, try to create a new 4637 // MatrixSubscriptExpr. 4638 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4639 if (matSubscriptE) { 4640 if (CheckAndReportCommaError(idx)) 4641 return ExprError(); 4642 4643 assert(matSubscriptE->isIncomplete() && 4644 "base has to be an incomplete matrix subscript"); 4645 return CreateBuiltinMatrixSubscriptExpr( 4646 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4647 } 4648 4649 // Handle any non-overload placeholder types in the base and index 4650 // expressions. We can't handle overloads here because the other 4651 // operand might be an overloadable type, in which case the overload 4652 // resolution for the operator overload should get the first crack 4653 // at the overload. 4654 bool IsMSPropertySubscript = false; 4655 if (base->getType()->isNonOverloadPlaceholderType()) { 4656 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4657 if (!IsMSPropertySubscript) { 4658 ExprResult result = CheckPlaceholderExpr(base); 4659 if (result.isInvalid()) 4660 return ExprError(); 4661 base = result.get(); 4662 } 4663 } 4664 4665 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4666 if (base->getType()->isMatrixType()) { 4667 if (CheckAndReportCommaError(idx)) 4668 return ExprError(); 4669 4670 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4671 } 4672 4673 // A comma-expression as the index is deprecated in C++2a onwards. 4674 if (getLangOpts().CPlusPlus20 && 4675 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4676 (isa<CXXOperatorCallExpr>(idx) && 4677 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4678 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4679 << SourceRange(base->getBeginLoc(), rbLoc); 4680 } 4681 4682 if (idx->getType()->isNonOverloadPlaceholderType()) { 4683 ExprResult result = CheckPlaceholderExpr(idx); 4684 if (result.isInvalid()) return ExprError(); 4685 idx = result.get(); 4686 } 4687 4688 // Build an unanalyzed expression if either operand is type-dependent. 4689 if (getLangOpts().CPlusPlus && 4690 (base->isTypeDependent() || idx->isTypeDependent())) { 4691 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4692 VK_LValue, OK_Ordinary, rbLoc); 4693 } 4694 4695 // MSDN, property (C++) 4696 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4697 // This attribute can also be used in the declaration of an empty array in a 4698 // class or structure definition. For example: 4699 // __declspec(property(get=GetX, put=PutX)) int x[]; 4700 // The above statement indicates that x[] can be used with one or more array 4701 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4702 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4703 if (IsMSPropertySubscript) { 4704 // Build MS property subscript expression if base is MS property reference 4705 // or MS property subscript. 4706 return new (Context) MSPropertySubscriptExpr( 4707 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4708 } 4709 4710 // Use C++ overloaded-operator rules if either operand has record 4711 // type. The spec says to do this if either type is *overloadable*, 4712 // but enum types can't declare subscript operators or conversion 4713 // operators, so there's nothing interesting for overload resolution 4714 // to do if there aren't any record types involved. 4715 // 4716 // ObjC pointers have their own subscripting logic that is not tied 4717 // to overload resolution and so should not take this path. 4718 if (getLangOpts().CPlusPlus && 4719 (base->getType()->isRecordType() || 4720 (!base->getType()->isObjCObjectPointerType() && 4721 idx->getType()->isRecordType()))) { 4722 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4723 } 4724 4725 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4726 4727 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4728 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4729 4730 return Res; 4731 } 4732 4733 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4734 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4735 InitializationKind Kind = 4736 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4737 InitializationSequence InitSeq(*this, Entity, Kind, E); 4738 return InitSeq.Perform(*this, Entity, Kind, E); 4739 } 4740 4741 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4742 Expr *ColumnIdx, 4743 SourceLocation RBLoc) { 4744 ExprResult BaseR = CheckPlaceholderExpr(Base); 4745 if (BaseR.isInvalid()) 4746 return BaseR; 4747 Base = BaseR.get(); 4748 4749 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4750 if (RowR.isInvalid()) 4751 return RowR; 4752 RowIdx = RowR.get(); 4753 4754 if (!ColumnIdx) 4755 return new (Context) MatrixSubscriptExpr( 4756 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4757 4758 // Build an unanalyzed expression if any of the operands is type-dependent. 4759 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4760 ColumnIdx->isTypeDependent()) 4761 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4762 Context.DependentTy, RBLoc); 4763 4764 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4765 if (ColumnR.isInvalid()) 4766 return ColumnR; 4767 ColumnIdx = ColumnR.get(); 4768 4769 // Check that IndexExpr is an integer expression. If it is a constant 4770 // expression, check that it is less than Dim (= the number of elements in the 4771 // corresponding dimension). 4772 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4773 bool IsColumnIdx) -> Expr * { 4774 if (!IndexExpr->getType()->isIntegerType() && 4775 !IndexExpr->isTypeDependent()) { 4776 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4777 << IsColumnIdx; 4778 return nullptr; 4779 } 4780 4781 if (Optional<llvm::APSInt> Idx = 4782 IndexExpr->getIntegerConstantExpr(Context)) { 4783 if ((*Idx < 0 || *Idx >= Dim)) { 4784 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4785 << IsColumnIdx << Dim; 4786 return nullptr; 4787 } 4788 } 4789 4790 ExprResult ConvExpr = 4791 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4792 assert(!ConvExpr.isInvalid() && 4793 "should be able to convert any integer type to size type"); 4794 return ConvExpr.get(); 4795 }; 4796 4797 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4798 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4799 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4800 if (!RowIdx || !ColumnIdx) 4801 return ExprError(); 4802 4803 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4804 MTy->getElementType(), RBLoc); 4805 } 4806 4807 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4808 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4809 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4810 4811 // For expressions like `&(*s).b`, the base is recorded and what should be 4812 // checked. 4813 const MemberExpr *Member = nullptr; 4814 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4815 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4816 4817 LastRecord.PossibleDerefs.erase(StrippedExpr); 4818 } 4819 4820 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4821 if (isUnevaluatedContext()) 4822 return; 4823 4824 QualType ResultTy = E->getType(); 4825 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4826 4827 // Bail if the element is an array since it is not memory access. 4828 if (isa<ArrayType>(ResultTy)) 4829 return; 4830 4831 if (ResultTy->hasAttr(attr::NoDeref)) { 4832 LastRecord.PossibleDerefs.insert(E); 4833 return; 4834 } 4835 4836 // Check if the base type is a pointer to a member access of a struct 4837 // marked with noderef. 4838 const Expr *Base = E->getBase(); 4839 QualType BaseTy = Base->getType(); 4840 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4841 // Not a pointer access 4842 return; 4843 4844 const MemberExpr *Member = nullptr; 4845 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4846 Member->isArrow()) 4847 Base = Member->getBase(); 4848 4849 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4850 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4851 LastRecord.PossibleDerefs.insert(E); 4852 } 4853 } 4854 4855 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4856 Expr *LowerBound, 4857 SourceLocation ColonLocFirst, 4858 SourceLocation ColonLocSecond, 4859 Expr *Length, Expr *Stride, 4860 SourceLocation RBLoc) { 4861 if (Base->getType()->isPlaceholderType() && 4862 !Base->getType()->isSpecificPlaceholderType( 4863 BuiltinType::OMPArraySection)) { 4864 ExprResult Result = CheckPlaceholderExpr(Base); 4865 if (Result.isInvalid()) 4866 return ExprError(); 4867 Base = Result.get(); 4868 } 4869 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4870 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4871 if (Result.isInvalid()) 4872 return ExprError(); 4873 Result = DefaultLvalueConversion(Result.get()); 4874 if (Result.isInvalid()) 4875 return ExprError(); 4876 LowerBound = Result.get(); 4877 } 4878 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4879 ExprResult Result = CheckPlaceholderExpr(Length); 4880 if (Result.isInvalid()) 4881 return ExprError(); 4882 Result = DefaultLvalueConversion(Result.get()); 4883 if (Result.isInvalid()) 4884 return ExprError(); 4885 Length = Result.get(); 4886 } 4887 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4888 ExprResult Result = CheckPlaceholderExpr(Stride); 4889 if (Result.isInvalid()) 4890 return ExprError(); 4891 Result = DefaultLvalueConversion(Result.get()); 4892 if (Result.isInvalid()) 4893 return ExprError(); 4894 Stride = Result.get(); 4895 } 4896 4897 // Build an unanalyzed expression if either operand is type-dependent. 4898 if (Base->isTypeDependent() || 4899 (LowerBound && 4900 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4901 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4902 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4903 return new (Context) OMPArraySectionExpr( 4904 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4905 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4906 } 4907 4908 // Perform default conversions. 4909 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4910 QualType ResultTy; 4911 if (OriginalTy->isAnyPointerType()) { 4912 ResultTy = OriginalTy->getPointeeType(); 4913 } else if (OriginalTy->isArrayType()) { 4914 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4915 } else { 4916 return ExprError( 4917 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4918 << Base->getSourceRange()); 4919 } 4920 // C99 6.5.2.1p1 4921 if (LowerBound) { 4922 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4923 LowerBound); 4924 if (Res.isInvalid()) 4925 return ExprError(Diag(LowerBound->getExprLoc(), 4926 diag::err_omp_typecheck_section_not_integer) 4927 << 0 << LowerBound->getSourceRange()); 4928 LowerBound = Res.get(); 4929 4930 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4931 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4932 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4933 << 0 << LowerBound->getSourceRange(); 4934 } 4935 if (Length) { 4936 auto Res = 4937 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4938 if (Res.isInvalid()) 4939 return ExprError(Diag(Length->getExprLoc(), 4940 diag::err_omp_typecheck_section_not_integer) 4941 << 1 << Length->getSourceRange()); 4942 Length = Res.get(); 4943 4944 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4945 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4946 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4947 << 1 << Length->getSourceRange(); 4948 } 4949 if (Stride) { 4950 ExprResult Res = 4951 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4952 if (Res.isInvalid()) 4953 return ExprError(Diag(Stride->getExprLoc(), 4954 diag::err_omp_typecheck_section_not_integer) 4955 << 1 << Stride->getSourceRange()); 4956 Stride = Res.get(); 4957 4958 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4959 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4960 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4961 << 1 << Stride->getSourceRange(); 4962 } 4963 4964 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4965 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4966 // type. Note that functions are not objects, and that (in C99 parlance) 4967 // incomplete types are not object types. 4968 if (ResultTy->isFunctionType()) { 4969 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4970 << ResultTy << Base->getSourceRange(); 4971 return ExprError(); 4972 } 4973 4974 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4975 diag::err_omp_section_incomplete_type, Base)) 4976 return ExprError(); 4977 4978 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4979 Expr::EvalResult Result; 4980 if (LowerBound->EvaluateAsInt(Result, Context)) { 4981 // OpenMP 5.0, [2.1.5 Array Sections] 4982 // The array section must be a subset of the original array. 4983 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4984 if (LowerBoundValue.isNegative()) { 4985 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4986 << LowerBound->getSourceRange(); 4987 return ExprError(); 4988 } 4989 } 4990 } 4991 4992 if (Length) { 4993 Expr::EvalResult Result; 4994 if (Length->EvaluateAsInt(Result, Context)) { 4995 // OpenMP 5.0, [2.1.5 Array Sections] 4996 // The length must evaluate to non-negative integers. 4997 llvm::APSInt LengthValue = Result.Val.getInt(); 4998 if (LengthValue.isNegative()) { 4999 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5000 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 5001 << Length->getSourceRange(); 5002 return ExprError(); 5003 } 5004 } 5005 } else if (ColonLocFirst.isValid() && 5006 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5007 !OriginalTy->isVariableArrayType()))) { 5008 // OpenMP 5.0, [2.1.5 Array Sections] 5009 // When the size of the array dimension is not known, the length must be 5010 // specified explicitly. 5011 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5012 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5013 return ExprError(); 5014 } 5015 5016 if (Stride) { 5017 Expr::EvalResult Result; 5018 if (Stride->EvaluateAsInt(Result, Context)) { 5019 // OpenMP 5.0, [2.1.5 Array Sections] 5020 // The stride must evaluate to a positive integer. 5021 llvm::APSInt StrideValue = Result.Val.getInt(); 5022 if (!StrideValue.isStrictlyPositive()) { 5023 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5024 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5025 << Stride->getSourceRange(); 5026 return ExprError(); 5027 } 5028 } 5029 } 5030 5031 if (!Base->getType()->isSpecificPlaceholderType( 5032 BuiltinType::OMPArraySection)) { 5033 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5034 if (Result.isInvalid()) 5035 return ExprError(); 5036 Base = Result.get(); 5037 } 5038 return new (Context) OMPArraySectionExpr( 5039 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5040 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5041 } 5042 5043 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5044 SourceLocation RParenLoc, 5045 ArrayRef<Expr *> Dims, 5046 ArrayRef<SourceRange> Brackets) { 5047 if (Base->getType()->isPlaceholderType()) { 5048 ExprResult Result = CheckPlaceholderExpr(Base); 5049 if (Result.isInvalid()) 5050 return ExprError(); 5051 Result = DefaultLvalueConversion(Result.get()); 5052 if (Result.isInvalid()) 5053 return ExprError(); 5054 Base = Result.get(); 5055 } 5056 QualType BaseTy = Base->getType(); 5057 // Delay analysis of the types/expressions if instantiation/specialization is 5058 // required. 5059 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5060 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5061 LParenLoc, RParenLoc, Dims, Brackets); 5062 if (!BaseTy->isPointerType() || 5063 (!Base->isTypeDependent() && 5064 BaseTy->getPointeeType()->isIncompleteType())) 5065 return ExprError(Diag(Base->getExprLoc(), 5066 diag::err_omp_non_pointer_type_array_shaping_base) 5067 << Base->getSourceRange()); 5068 5069 SmallVector<Expr *, 4> NewDims; 5070 bool ErrorFound = false; 5071 for (Expr *Dim : Dims) { 5072 if (Dim->getType()->isPlaceholderType()) { 5073 ExprResult Result = CheckPlaceholderExpr(Dim); 5074 if (Result.isInvalid()) { 5075 ErrorFound = true; 5076 continue; 5077 } 5078 Result = DefaultLvalueConversion(Result.get()); 5079 if (Result.isInvalid()) { 5080 ErrorFound = true; 5081 continue; 5082 } 5083 Dim = Result.get(); 5084 } 5085 if (!Dim->isTypeDependent()) { 5086 ExprResult Result = 5087 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5088 if (Result.isInvalid()) { 5089 ErrorFound = true; 5090 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5091 << Dim->getSourceRange(); 5092 continue; 5093 } 5094 Dim = Result.get(); 5095 Expr::EvalResult EvResult; 5096 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5097 // OpenMP 5.0, [2.1.4 Array Shaping] 5098 // Each si is an integral type expression that must evaluate to a 5099 // positive integer. 5100 llvm::APSInt Value = EvResult.Val.getInt(); 5101 if (!Value.isStrictlyPositive()) { 5102 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5103 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5104 << Dim->getSourceRange(); 5105 ErrorFound = true; 5106 continue; 5107 } 5108 } 5109 } 5110 NewDims.push_back(Dim); 5111 } 5112 if (ErrorFound) 5113 return ExprError(); 5114 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5115 LParenLoc, RParenLoc, NewDims, Brackets); 5116 } 5117 5118 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5119 SourceLocation LLoc, SourceLocation RLoc, 5120 ArrayRef<OMPIteratorData> Data) { 5121 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5122 bool IsCorrect = true; 5123 for (const OMPIteratorData &D : Data) { 5124 TypeSourceInfo *TInfo = nullptr; 5125 SourceLocation StartLoc; 5126 QualType DeclTy; 5127 if (!D.Type.getAsOpaquePtr()) { 5128 // OpenMP 5.0, 2.1.6 Iterators 5129 // In an iterator-specifier, if the iterator-type is not specified then 5130 // the type of that iterator is of int type. 5131 DeclTy = Context.IntTy; 5132 StartLoc = D.DeclIdentLoc; 5133 } else { 5134 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5135 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5136 } 5137 5138 bool IsDeclTyDependent = DeclTy->isDependentType() || 5139 DeclTy->containsUnexpandedParameterPack() || 5140 DeclTy->isInstantiationDependentType(); 5141 if (!IsDeclTyDependent) { 5142 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5143 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5144 // The iterator-type must be an integral or pointer type. 5145 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5146 << DeclTy; 5147 IsCorrect = false; 5148 continue; 5149 } 5150 if (DeclTy.isConstant(Context)) { 5151 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5152 // The iterator-type must not be const qualified. 5153 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5154 << DeclTy; 5155 IsCorrect = false; 5156 continue; 5157 } 5158 } 5159 5160 // Iterator declaration. 5161 assert(D.DeclIdent && "Identifier expected."); 5162 // Always try to create iterator declarator to avoid extra error messages 5163 // about unknown declarations use. 5164 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5165 D.DeclIdent, DeclTy, TInfo, SC_None); 5166 VD->setImplicit(); 5167 if (S) { 5168 // Check for conflicting previous declaration. 5169 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5170 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5171 ForVisibleRedeclaration); 5172 Previous.suppressDiagnostics(); 5173 LookupName(Previous, S); 5174 5175 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5176 /*AllowInlineNamespace=*/false); 5177 if (!Previous.empty()) { 5178 NamedDecl *Old = Previous.getRepresentativeDecl(); 5179 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5180 Diag(Old->getLocation(), diag::note_previous_definition); 5181 } else { 5182 PushOnScopeChains(VD, S); 5183 } 5184 } else { 5185 CurContext->addDecl(VD); 5186 } 5187 Expr *Begin = D.Range.Begin; 5188 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5189 ExprResult BeginRes = 5190 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5191 Begin = BeginRes.get(); 5192 } 5193 Expr *End = D.Range.End; 5194 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5195 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5196 End = EndRes.get(); 5197 } 5198 Expr *Step = D.Range.Step; 5199 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5200 if (!Step->getType()->isIntegralType(Context)) { 5201 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5202 << Step << Step->getSourceRange(); 5203 IsCorrect = false; 5204 continue; 5205 } 5206 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5207 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5208 // If the step expression of a range-specification equals zero, the 5209 // behavior is unspecified. 5210 if (Result && Result->isNullValue()) { 5211 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5212 << Step << Step->getSourceRange(); 5213 IsCorrect = false; 5214 continue; 5215 } 5216 } 5217 if (!Begin || !End || !IsCorrect) { 5218 IsCorrect = false; 5219 continue; 5220 } 5221 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5222 IDElem.IteratorDecl = VD; 5223 IDElem.AssignmentLoc = D.AssignLoc; 5224 IDElem.Range.Begin = Begin; 5225 IDElem.Range.End = End; 5226 IDElem.Range.Step = Step; 5227 IDElem.ColonLoc = D.ColonLoc; 5228 IDElem.SecondColonLoc = D.SecColonLoc; 5229 } 5230 if (!IsCorrect) { 5231 // Invalidate all created iterator declarations if error is found. 5232 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5233 if (Decl *ID = D.IteratorDecl) 5234 ID->setInvalidDecl(); 5235 } 5236 return ExprError(); 5237 } 5238 SmallVector<OMPIteratorHelperData, 4> Helpers; 5239 if (!CurContext->isDependentContext()) { 5240 // Build number of ityeration for each iteration range. 5241 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5242 // ((Begini-Stepi-1-Endi) / -Stepi); 5243 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5244 // (Endi - Begini) 5245 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5246 D.Range.Begin); 5247 if(!Res.isUsable()) { 5248 IsCorrect = false; 5249 continue; 5250 } 5251 ExprResult St, St1; 5252 if (D.Range.Step) { 5253 St = D.Range.Step; 5254 // (Endi - Begini) + Stepi 5255 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5256 if (!Res.isUsable()) { 5257 IsCorrect = false; 5258 continue; 5259 } 5260 // (Endi - Begini) + Stepi - 1 5261 Res = 5262 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5263 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5264 if (!Res.isUsable()) { 5265 IsCorrect = false; 5266 continue; 5267 } 5268 // ((Endi - Begini) + Stepi - 1) / Stepi 5269 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5270 if (!Res.isUsable()) { 5271 IsCorrect = false; 5272 continue; 5273 } 5274 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5275 // (Begini - Endi) 5276 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5277 D.Range.Begin, D.Range.End); 5278 if (!Res1.isUsable()) { 5279 IsCorrect = false; 5280 continue; 5281 } 5282 // (Begini - Endi) - Stepi 5283 Res1 = 5284 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5285 if (!Res1.isUsable()) { 5286 IsCorrect = false; 5287 continue; 5288 } 5289 // (Begini - Endi) - Stepi - 1 5290 Res1 = 5291 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5292 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5293 if (!Res1.isUsable()) { 5294 IsCorrect = false; 5295 continue; 5296 } 5297 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5298 Res1 = 5299 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5300 if (!Res1.isUsable()) { 5301 IsCorrect = false; 5302 continue; 5303 } 5304 // Stepi > 0. 5305 ExprResult CmpRes = 5306 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5307 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5308 if (!CmpRes.isUsable()) { 5309 IsCorrect = false; 5310 continue; 5311 } 5312 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5313 Res.get(), Res1.get()); 5314 if (!Res.isUsable()) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 } 5319 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5320 if (!Res.isUsable()) { 5321 IsCorrect = false; 5322 continue; 5323 } 5324 5325 // Build counter update. 5326 // Build counter. 5327 auto *CounterVD = 5328 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5329 D.IteratorDecl->getBeginLoc(), nullptr, 5330 Res.get()->getType(), nullptr, SC_None); 5331 CounterVD->setImplicit(); 5332 ExprResult RefRes = 5333 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5334 D.IteratorDecl->getBeginLoc()); 5335 // Build counter update. 5336 // I = Begini + counter * Stepi; 5337 ExprResult UpdateRes; 5338 if (D.Range.Step) { 5339 UpdateRes = CreateBuiltinBinOp( 5340 D.AssignmentLoc, BO_Mul, 5341 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5342 } else { 5343 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5344 } 5345 if (!UpdateRes.isUsable()) { 5346 IsCorrect = false; 5347 continue; 5348 } 5349 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5350 UpdateRes.get()); 5351 if (!UpdateRes.isUsable()) { 5352 IsCorrect = false; 5353 continue; 5354 } 5355 ExprResult VDRes = 5356 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5357 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5358 D.IteratorDecl->getBeginLoc()); 5359 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5360 UpdateRes.get()); 5361 if (!UpdateRes.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 UpdateRes = 5366 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5367 if (!UpdateRes.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 ExprResult CounterUpdateRes = 5372 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5373 if (!CounterUpdateRes.isUsable()) { 5374 IsCorrect = false; 5375 continue; 5376 } 5377 CounterUpdateRes = 5378 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5379 if (!CounterUpdateRes.isUsable()) { 5380 IsCorrect = false; 5381 continue; 5382 } 5383 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5384 HD.CounterVD = CounterVD; 5385 HD.Upper = Res.get(); 5386 HD.Update = UpdateRes.get(); 5387 HD.CounterUpdate = CounterUpdateRes.get(); 5388 } 5389 } else { 5390 Helpers.assign(ID.size(), {}); 5391 } 5392 if (!IsCorrect) { 5393 // Invalidate all created iterator declarations if error is found. 5394 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5395 if (Decl *ID = D.IteratorDecl) 5396 ID->setInvalidDecl(); 5397 } 5398 return ExprError(); 5399 } 5400 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5401 LLoc, RLoc, ID, Helpers); 5402 } 5403 5404 ExprResult 5405 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5406 Expr *Idx, SourceLocation RLoc) { 5407 Expr *LHSExp = Base; 5408 Expr *RHSExp = Idx; 5409 5410 ExprValueKind VK = VK_LValue; 5411 ExprObjectKind OK = OK_Ordinary; 5412 5413 // Per C++ core issue 1213, the result is an xvalue if either operand is 5414 // a non-lvalue array, and an lvalue otherwise. 5415 if (getLangOpts().CPlusPlus11) { 5416 for (auto *Op : {LHSExp, RHSExp}) { 5417 Op = Op->IgnoreImplicit(); 5418 if (Op->getType()->isArrayType() && !Op->isLValue()) 5419 VK = VK_XValue; 5420 } 5421 } 5422 5423 // Perform default conversions. 5424 if (!LHSExp->getType()->getAs<VectorType>()) { 5425 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5426 if (Result.isInvalid()) 5427 return ExprError(); 5428 LHSExp = Result.get(); 5429 } 5430 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5431 if (Result.isInvalid()) 5432 return ExprError(); 5433 RHSExp = Result.get(); 5434 5435 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5436 5437 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5438 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5439 // in the subscript position. As a result, we need to derive the array base 5440 // and index from the expression types. 5441 Expr *BaseExpr, *IndexExpr; 5442 QualType ResultType; 5443 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5444 BaseExpr = LHSExp; 5445 IndexExpr = RHSExp; 5446 ResultType = Context.DependentTy; 5447 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5448 BaseExpr = LHSExp; 5449 IndexExpr = RHSExp; 5450 ResultType = PTy->getPointeeType(); 5451 } else if (const ObjCObjectPointerType *PTy = 5452 LHSTy->getAs<ObjCObjectPointerType>()) { 5453 BaseExpr = LHSExp; 5454 IndexExpr = RHSExp; 5455 5456 // Use custom logic if this should be the pseudo-object subscript 5457 // expression. 5458 if (!LangOpts.isSubscriptPointerArithmetic()) 5459 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5460 nullptr); 5461 5462 ResultType = PTy->getPointeeType(); 5463 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5464 // Handle the uncommon case of "123[Ptr]". 5465 BaseExpr = RHSExp; 5466 IndexExpr = LHSExp; 5467 ResultType = PTy->getPointeeType(); 5468 } else if (const ObjCObjectPointerType *PTy = 5469 RHSTy->getAs<ObjCObjectPointerType>()) { 5470 // Handle the uncommon case of "123[Ptr]". 5471 BaseExpr = RHSExp; 5472 IndexExpr = LHSExp; 5473 ResultType = PTy->getPointeeType(); 5474 if (!LangOpts.isSubscriptPointerArithmetic()) { 5475 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5476 << ResultType << BaseExpr->getSourceRange(); 5477 return ExprError(); 5478 } 5479 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5480 BaseExpr = LHSExp; // vectors: V[123] 5481 IndexExpr = RHSExp; 5482 // We apply C++ DR1213 to vector subscripting too. 5483 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5484 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5485 if (Materialized.isInvalid()) 5486 return ExprError(); 5487 LHSExp = Materialized.get(); 5488 } 5489 VK = LHSExp->getValueKind(); 5490 if (VK != VK_RValue) 5491 OK = OK_VectorComponent; 5492 5493 ResultType = VTy->getElementType(); 5494 QualType BaseType = BaseExpr->getType(); 5495 Qualifiers BaseQuals = BaseType.getQualifiers(); 5496 Qualifiers MemberQuals = ResultType.getQualifiers(); 5497 Qualifiers Combined = BaseQuals + MemberQuals; 5498 if (Combined != MemberQuals) 5499 ResultType = Context.getQualifiedType(ResultType, Combined); 5500 } else if (LHSTy->isArrayType()) { 5501 // If we see an array that wasn't promoted by 5502 // DefaultFunctionArrayLvalueConversion, it must be an array that 5503 // wasn't promoted because of the C90 rule that doesn't 5504 // allow promoting non-lvalue arrays. Warn, then 5505 // force the promotion here. 5506 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5507 << LHSExp->getSourceRange(); 5508 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5509 CK_ArrayToPointerDecay).get(); 5510 LHSTy = LHSExp->getType(); 5511 5512 BaseExpr = LHSExp; 5513 IndexExpr = RHSExp; 5514 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5515 } else if (RHSTy->isArrayType()) { 5516 // Same as previous, except for 123[f().a] case 5517 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5518 << RHSExp->getSourceRange(); 5519 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5520 CK_ArrayToPointerDecay).get(); 5521 RHSTy = RHSExp->getType(); 5522 5523 BaseExpr = RHSExp; 5524 IndexExpr = LHSExp; 5525 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5526 } else { 5527 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5528 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5529 } 5530 // C99 6.5.2.1p1 5531 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5532 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5533 << IndexExpr->getSourceRange()); 5534 5535 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5536 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5537 && !IndexExpr->isTypeDependent()) 5538 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5539 5540 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5541 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5542 // type. Note that Functions are not objects, and that (in C99 parlance) 5543 // incomplete types are not object types. 5544 if (ResultType->isFunctionType()) { 5545 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5546 << ResultType << BaseExpr->getSourceRange(); 5547 return ExprError(); 5548 } 5549 5550 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5551 // GNU extension: subscripting on pointer to void 5552 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5553 << BaseExpr->getSourceRange(); 5554 5555 // C forbids expressions of unqualified void type from being l-values. 5556 // See IsCForbiddenLValueType. 5557 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5558 } else if (!ResultType->isDependentType() && 5559 RequireCompleteSizedType( 5560 LLoc, ResultType, 5561 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5562 return ExprError(); 5563 5564 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5565 !ResultType.isCForbiddenLValueType()); 5566 5567 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5568 FunctionScopes.size() > 1) { 5569 if (auto *TT = 5570 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5571 for (auto I = FunctionScopes.rbegin(), 5572 E = std::prev(FunctionScopes.rend()); 5573 I != E; ++I) { 5574 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5575 if (CSI == nullptr) 5576 break; 5577 DeclContext *DC = nullptr; 5578 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5579 DC = LSI->CallOperator; 5580 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5581 DC = CRSI->TheCapturedDecl; 5582 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5583 DC = BSI->TheDecl; 5584 if (DC) { 5585 if (DC->containsDecl(TT->getDecl())) 5586 break; 5587 captureVariablyModifiedType( 5588 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5589 } 5590 } 5591 } 5592 } 5593 5594 return new (Context) 5595 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5596 } 5597 5598 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5599 ParmVarDecl *Param) { 5600 if (Param->hasUnparsedDefaultArg()) { 5601 // If we've already cleared out the location for the default argument, 5602 // that means we're parsing it right now. 5603 if (!UnparsedDefaultArgLocs.count(Param)) { 5604 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5605 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5606 Param->setInvalidDecl(); 5607 return true; 5608 } 5609 5610 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5611 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5612 Diag(UnparsedDefaultArgLocs[Param], 5613 diag::note_default_argument_declared_here); 5614 return true; 5615 } 5616 5617 if (Param->hasUninstantiatedDefaultArg() && 5618 InstantiateDefaultArgument(CallLoc, FD, Param)) 5619 return true; 5620 5621 assert(Param->hasInit() && "default argument but no initializer?"); 5622 5623 // If the default expression creates temporaries, we need to 5624 // push them to the current stack of expression temporaries so they'll 5625 // be properly destroyed. 5626 // FIXME: We should really be rebuilding the default argument with new 5627 // bound temporaries; see the comment in PR5810. 5628 // We don't need to do that with block decls, though, because 5629 // blocks in default argument expression can never capture anything. 5630 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5631 // Set the "needs cleanups" bit regardless of whether there are 5632 // any explicit objects. 5633 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5634 5635 // Append all the objects to the cleanup list. Right now, this 5636 // should always be a no-op, because blocks in default argument 5637 // expressions should never be able to capture anything. 5638 assert(!Init->getNumObjects() && 5639 "default argument expression has capturing blocks?"); 5640 } 5641 5642 // We already type-checked the argument, so we know it works. 5643 // Just mark all of the declarations in this potentially-evaluated expression 5644 // as being "referenced". 5645 EnterExpressionEvaluationContext EvalContext( 5646 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5647 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5648 /*SkipLocalVariables=*/true); 5649 return false; 5650 } 5651 5652 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5653 FunctionDecl *FD, ParmVarDecl *Param) { 5654 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5655 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5656 return ExprError(); 5657 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5658 } 5659 5660 Sema::VariadicCallType 5661 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5662 Expr *Fn) { 5663 if (Proto && Proto->isVariadic()) { 5664 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5665 return VariadicConstructor; 5666 else if (Fn && Fn->getType()->isBlockPointerType()) 5667 return VariadicBlock; 5668 else if (FDecl) { 5669 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5670 if (Method->isInstance()) 5671 return VariadicMethod; 5672 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5673 return VariadicMethod; 5674 return VariadicFunction; 5675 } 5676 return VariadicDoesNotApply; 5677 } 5678 5679 namespace { 5680 class FunctionCallCCC final : public FunctionCallFilterCCC { 5681 public: 5682 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5683 unsigned NumArgs, MemberExpr *ME) 5684 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5685 FunctionName(FuncName) {} 5686 5687 bool ValidateCandidate(const TypoCorrection &candidate) override { 5688 if (!candidate.getCorrectionSpecifier() || 5689 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5690 return false; 5691 } 5692 5693 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5694 } 5695 5696 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5697 return std::make_unique<FunctionCallCCC>(*this); 5698 } 5699 5700 private: 5701 const IdentifierInfo *const FunctionName; 5702 }; 5703 } 5704 5705 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5706 FunctionDecl *FDecl, 5707 ArrayRef<Expr *> Args) { 5708 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5709 DeclarationName FuncName = FDecl->getDeclName(); 5710 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5711 5712 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5713 if (TypoCorrection Corrected = S.CorrectTypo( 5714 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5715 S.getScopeForContext(S.CurContext), nullptr, CCC, 5716 Sema::CTK_ErrorRecovery)) { 5717 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5718 if (Corrected.isOverloaded()) { 5719 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5720 OverloadCandidateSet::iterator Best; 5721 for (NamedDecl *CD : Corrected) { 5722 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5723 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5724 OCS); 5725 } 5726 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5727 case OR_Success: 5728 ND = Best->FoundDecl; 5729 Corrected.setCorrectionDecl(ND); 5730 break; 5731 default: 5732 break; 5733 } 5734 } 5735 ND = ND->getUnderlyingDecl(); 5736 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5737 return Corrected; 5738 } 5739 } 5740 return TypoCorrection(); 5741 } 5742 5743 /// ConvertArgumentsForCall - Converts the arguments specified in 5744 /// Args/NumArgs to the parameter types of the function FDecl with 5745 /// function prototype Proto. Call is the call expression itself, and 5746 /// Fn is the function expression. For a C++ member function, this 5747 /// routine does not attempt to convert the object argument. Returns 5748 /// true if the call is ill-formed. 5749 bool 5750 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5751 FunctionDecl *FDecl, 5752 const FunctionProtoType *Proto, 5753 ArrayRef<Expr *> Args, 5754 SourceLocation RParenLoc, 5755 bool IsExecConfig) { 5756 // Bail out early if calling a builtin with custom typechecking. 5757 if (FDecl) 5758 if (unsigned ID = FDecl->getBuiltinID()) 5759 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5760 return false; 5761 5762 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5763 // assignment, to the types of the corresponding parameter, ... 5764 unsigned NumParams = Proto->getNumParams(); 5765 bool Invalid = false; 5766 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5767 unsigned FnKind = Fn->getType()->isBlockPointerType() 5768 ? 1 /* block */ 5769 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5770 : 0 /* function */); 5771 5772 // If too few arguments are available (and we don't have default 5773 // arguments for the remaining parameters), don't make the call. 5774 if (Args.size() < NumParams) { 5775 if (Args.size() < MinArgs) { 5776 TypoCorrection TC; 5777 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5778 unsigned diag_id = 5779 MinArgs == NumParams && !Proto->isVariadic() 5780 ? diag::err_typecheck_call_too_few_args_suggest 5781 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5782 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5783 << static_cast<unsigned>(Args.size()) 5784 << TC.getCorrectionRange()); 5785 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5786 Diag(RParenLoc, 5787 MinArgs == NumParams && !Proto->isVariadic() 5788 ? diag::err_typecheck_call_too_few_args_one 5789 : diag::err_typecheck_call_too_few_args_at_least_one) 5790 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5791 else 5792 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5793 ? diag::err_typecheck_call_too_few_args 5794 : diag::err_typecheck_call_too_few_args_at_least) 5795 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5796 << Fn->getSourceRange(); 5797 5798 // Emit the location of the prototype. 5799 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5800 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5801 5802 return true; 5803 } 5804 // We reserve space for the default arguments when we create 5805 // the call expression, before calling ConvertArgumentsForCall. 5806 assert((Call->getNumArgs() == NumParams) && 5807 "We should have reserved space for the default arguments before!"); 5808 } 5809 5810 // If too many are passed and not variadic, error on the extras and drop 5811 // them. 5812 if (Args.size() > NumParams) { 5813 if (!Proto->isVariadic()) { 5814 TypoCorrection TC; 5815 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5816 unsigned diag_id = 5817 MinArgs == NumParams && !Proto->isVariadic() 5818 ? diag::err_typecheck_call_too_many_args_suggest 5819 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5820 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5821 << static_cast<unsigned>(Args.size()) 5822 << TC.getCorrectionRange()); 5823 } else if (NumParams == 1 && FDecl && 5824 FDecl->getParamDecl(0)->getDeclName()) 5825 Diag(Args[NumParams]->getBeginLoc(), 5826 MinArgs == NumParams 5827 ? diag::err_typecheck_call_too_many_args_one 5828 : diag::err_typecheck_call_too_many_args_at_most_one) 5829 << FnKind << FDecl->getParamDecl(0) 5830 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5831 << SourceRange(Args[NumParams]->getBeginLoc(), 5832 Args.back()->getEndLoc()); 5833 else 5834 Diag(Args[NumParams]->getBeginLoc(), 5835 MinArgs == NumParams 5836 ? diag::err_typecheck_call_too_many_args 5837 : diag::err_typecheck_call_too_many_args_at_most) 5838 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5839 << Fn->getSourceRange() 5840 << SourceRange(Args[NumParams]->getBeginLoc(), 5841 Args.back()->getEndLoc()); 5842 5843 // Emit the location of the prototype. 5844 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5845 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5846 5847 // This deletes the extra arguments. 5848 Call->shrinkNumArgs(NumParams); 5849 return true; 5850 } 5851 } 5852 SmallVector<Expr *, 8> AllArgs; 5853 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5854 5855 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5856 AllArgs, CallType); 5857 if (Invalid) 5858 return true; 5859 unsigned TotalNumArgs = AllArgs.size(); 5860 for (unsigned i = 0; i < TotalNumArgs; ++i) 5861 Call->setArg(i, AllArgs[i]); 5862 5863 return false; 5864 } 5865 5866 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5867 const FunctionProtoType *Proto, 5868 unsigned FirstParam, ArrayRef<Expr *> Args, 5869 SmallVectorImpl<Expr *> &AllArgs, 5870 VariadicCallType CallType, bool AllowExplicit, 5871 bool IsListInitialization) { 5872 unsigned NumParams = Proto->getNumParams(); 5873 bool Invalid = false; 5874 size_t ArgIx = 0; 5875 // Continue to check argument types (even if we have too few/many args). 5876 for (unsigned i = FirstParam; i < NumParams; i++) { 5877 QualType ProtoArgType = Proto->getParamType(i); 5878 5879 Expr *Arg; 5880 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5881 if (ArgIx < Args.size()) { 5882 Arg = Args[ArgIx++]; 5883 5884 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5885 diag::err_call_incomplete_argument, Arg)) 5886 return true; 5887 5888 // Strip the unbridged-cast placeholder expression off, if applicable. 5889 bool CFAudited = false; 5890 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5891 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5892 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5893 Arg = stripARCUnbridgedCast(Arg); 5894 else if (getLangOpts().ObjCAutoRefCount && 5895 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5896 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5897 CFAudited = true; 5898 5899 if (Proto->getExtParameterInfo(i).isNoEscape()) 5900 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5901 BE->getBlockDecl()->setDoesNotEscape(); 5902 5903 InitializedEntity Entity = 5904 Param ? InitializedEntity::InitializeParameter(Context, Param, 5905 ProtoArgType) 5906 : InitializedEntity::InitializeParameter( 5907 Context, ProtoArgType, Proto->isParamConsumed(i)); 5908 5909 // Remember that parameter belongs to a CF audited API. 5910 if (CFAudited) 5911 Entity.setParameterCFAudited(); 5912 5913 ExprResult ArgE = PerformCopyInitialization( 5914 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5915 if (ArgE.isInvalid()) 5916 return true; 5917 5918 Arg = ArgE.getAs<Expr>(); 5919 } else { 5920 assert(Param && "can't use default arguments without a known callee"); 5921 5922 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5923 if (ArgExpr.isInvalid()) 5924 return true; 5925 5926 Arg = ArgExpr.getAs<Expr>(); 5927 } 5928 5929 // Check for array bounds violations for each argument to the call. This 5930 // check only triggers warnings when the argument isn't a more complex Expr 5931 // with its own checking, such as a BinaryOperator. 5932 CheckArrayAccess(Arg); 5933 5934 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5935 CheckStaticArrayArgument(CallLoc, Param, Arg); 5936 5937 AllArgs.push_back(Arg); 5938 } 5939 5940 // If this is a variadic call, handle args passed through "...". 5941 if (CallType != VariadicDoesNotApply) { 5942 // Assume that extern "C" functions with variadic arguments that 5943 // return __unknown_anytype aren't *really* variadic. 5944 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5945 FDecl->isExternC()) { 5946 for (Expr *A : Args.slice(ArgIx)) { 5947 QualType paramType; // ignored 5948 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5949 Invalid |= arg.isInvalid(); 5950 AllArgs.push_back(arg.get()); 5951 } 5952 5953 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5954 } else { 5955 for (Expr *A : Args.slice(ArgIx)) { 5956 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5957 Invalid |= Arg.isInvalid(); 5958 AllArgs.push_back(Arg.get()); 5959 } 5960 } 5961 5962 // Check for array bounds violations. 5963 for (Expr *A : Args.slice(ArgIx)) 5964 CheckArrayAccess(A); 5965 } 5966 return Invalid; 5967 } 5968 5969 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5970 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5971 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5972 TL = DTL.getOriginalLoc(); 5973 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5974 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5975 << ATL.getLocalSourceRange(); 5976 } 5977 5978 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5979 /// array parameter, check that it is non-null, and that if it is formed by 5980 /// array-to-pointer decay, the underlying array is sufficiently large. 5981 /// 5982 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5983 /// array type derivation, then for each call to the function, the value of the 5984 /// corresponding actual argument shall provide access to the first element of 5985 /// an array with at least as many elements as specified by the size expression. 5986 void 5987 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5988 ParmVarDecl *Param, 5989 const Expr *ArgExpr) { 5990 // Static array parameters are not supported in C++. 5991 if (!Param || getLangOpts().CPlusPlus) 5992 return; 5993 5994 QualType OrigTy = Param->getOriginalType(); 5995 5996 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5997 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5998 return; 5999 6000 if (ArgExpr->isNullPointerConstant(Context, 6001 Expr::NPC_NeverValueDependent)) { 6002 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6003 DiagnoseCalleeStaticArrayParam(*this, Param); 6004 return; 6005 } 6006 6007 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6008 if (!CAT) 6009 return; 6010 6011 const ConstantArrayType *ArgCAT = 6012 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6013 if (!ArgCAT) 6014 return; 6015 6016 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6017 ArgCAT->getElementType())) { 6018 if (ArgCAT->getSize().ult(CAT->getSize())) { 6019 Diag(CallLoc, diag::warn_static_array_too_small) 6020 << ArgExpr->getSourceRange() 6021 << (unsigned)ArgCAT->getSize().getZExtValue() 6022 << (unsigned)CAT->getSize().getZExtValue() << 0; 6023 DiagnoseCalleeStaticArrayParam(*this, Param); 6024 } 6025 return; 6026 } 6027 6028 Optional<CharUnits> ArgSize = 6029 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6030 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6031 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6032 Diag(CallLoc, diag::warn_static_array_too_small) 6033 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6034 << (unsigned)ParmSize->getQuantity() << 1; 6035 DiagnoseCalleeStaticArrayParam(*this, Param); 6036 } 6037 } 6038 6039 /// Given a function expression of unknown-any type, try to rebuild it 6040 /// to have a function type. 6041 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6042 6043 /// Is the given type a placeholder that we need to lower out 6044 /// immediately during argument processing? 6045 static bool isPlaceholderToRemoveAsArg(QualType type) { 6046 // Placeholders are never sugared. 6047 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6048 if (!placeholder) return false; 6049 6050 switch (placeholder->getKind()) { 6051 // Ignore all the non-placeholder types. 6052 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6053 case BuiltinType::Id: 6054 #include "clang/Basic/OpenCLImageTypes.def" 6055 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6056 case BuiltinType::Id: 6057 #include "clang/Basic/OpenCLExtensionTypes.def" 6058 // In practice we'll never use this, since all SVE types are sugared 6059 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6060 #define SVE_TYPE(Name, Id, SingletonId) \ 6061 case BuiltinType::Id: 6062 #include "clang/Basic/AArch64SVEACLETypes.def" 6063 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6064 case BuiltinType::Id: 6065 #include "clang/Basic/PPCTypes.def" 6066 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6067 #include "clang/Basic/RISCVVTypes.def" 6068 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6069 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6070 #include "clang/AST/BuiltinTypes.def" 6071 return false; 6072 6073 // We cannot lower out overload sets; they might validly be resolved 6074 // by the call machinery. 6075 case BuiltinType::Overload: 6076 return false; 6077 6078 // Unbridged casts in ARC can be handled in some call positions and 6079 // should be left in place. 6080 case BuiltinType::ARCUnbridgedCast: 6081 return false; 6082 6083 // Pseudo-objects should be converted as soon as possible. 6084 case BuiltinType::PseudoObject: 6085 return true; 6086 6087 // The debugger mode could theoretically but currently does not try 6088 // to resolve unknown-typed arguments based on known parameter types. 6089 case BuiltinType::UnknownAny: 6090 return true; 6091 6092 // These are always invalid as call arguments and should be reported. 6093 case BuiltinType::BoundMember: 6094 case BuiltinType::BuiltinFn: 6095 case BuiltinType::IncompleteMatrixIdx: 6096 case BuiltinType::OMPArraySection: 6097 case BuiltinType::OMPArrayShaping: 6098 case BuiltinType::OMPIterator: 6099 return true; 6100 6101 } 6102 llvm_unreachable("bad builtin type kind"); 6103 } 6104 6105 /// Check an argument list for placeholders that we won't try to 6106 /// handle later. 6107 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6108 // Apply this processing to all the arguments at once instead of 6109 // dying at the first failure. 6110 bool hasInvalid = false; 6111 for (size_t i = 0, e = args.size(); i != e; i++) { 6112 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6113 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6114 if (result.isInvalid()) hasInvalid = true; 6115 else args[i] = result.get(); 6116 } 6117 } 6118 return hasInvalid; 6119 } 6120 6121 /// If a builtin function has a pointer argument with no explicit address 6122 /// space, then it should be able to accept a pointer to any address 6123 /// space as input. In order to do this, we need to replace the 6124 /// standard builtin declaration with one that uses the same address space 6125 /// as the call. 6126 /// 6127 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6128 /// it does not contain any pointer arguments without 6129 /// an address space qualifer. Otherwise the rewritten 6130 /// FunctionDecl is returned. 6131 /// TODO: Handle pointer return types. 6132 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6133 FunctionDecl *FDecl, 6134 MultiExprArg ArgExprs) { 6135 6136 QualType DeclType = FDecl->getType(); 6137 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6138 6139 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6140 ArgExprs.size() < FT->getNumParams()) 6141 return nullptr; 6142 6143 bool NeedsNewDecl = false; 6144 unsigned i = 0; 6145 SmallVector<QualType, 8> OverloadParams; 6146 6147 for (QualType ParamType : FT->param_types()) { 6148 6149 // Convert array arguments to pointer to simplify type lookup. 6150 ExprResult ArgRes = 6151 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6152 if (ArgRes.isInvalid()) 6153 return nullptr; 6154 Expr *Arg = ArgRes.get(); 6155 QualType ArgType = Arg->getType(); 6156 if (!ParamType->isPointerType() || 6157 ParamType.hasAddressSpace() || 6158 !ArgType->isPointerType() || 6159 !ArgType->getPointeeType().hasAddressSpace()) { 6160 OverloadParams.push_back(ParamType); 6161 continue; 6162 } 6163 6164 QualType PointeeType = ParamType->getPointeeType(); 6165 if (PointeeType.hasAddressSpace()) 6166 continue; 6167 6168 NeedsNewDecl = true; 6169 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6170 6171 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6172 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6173 } 6174 6175 if (!NeedsNewDecl) 6176 return nullptr; 6177 6178 FunctionProtoType::ExtProtoInfo EPI; 6179 EPI.Variadic = FT->isVariadic(); 6180 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6181 OverloadParams, EPI); 6182 DeclContext *Parent = FDecl->getParent(); 6183 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6184 FDecl->getLocation(), 6185 FDecl->getLocation(), 6186 FDecl->getIdentifier(), 6187 OverloadTy, 6188 /*TInfo=*/nullptr, 6189 SC_Extern, false, 6190 /*hasPrototype=*/true); 6191 SmallVector<ParmVarDecl*, 16> Params; 6192 FT = cast<FunctionProtoType>(OverloadTy); 6193 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6194 QualType ParamType = FT->getParamType(i); 6195 ParmVarDecl *Parm = 6196 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6197 SourceLocation(), nullptr, ParamType, 6198 /*TInfo=*/nullptr, SC_None, nullptr); 6199 Parm->setScopeInfo(0, i); 6200 Params.push_back(Parm); 6201 } 6202 OverloadDecl->setParams(Params); 6203 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6204 return OverloadDecl; 6205 } 6206 6207 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6208 FunctionDecl *Callee, 6209 MultiExprArg ArgExprs) { 6210 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6211 // similar attributes) really don't like it when functions are called with an 6212 // invalid number of args. 6213 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6214 /*PartialOverloading=*/false) && 6215 !Callee->isVariadic()) 6216 return; 6217 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6218 return; 6219 6220 if (const EnableIfAttr *Attr = 6221 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6222 S.Diag(Fn->getBeginLoc(), 6223 isa<CXXMethodDecl>(Callee) 6224 ? diag::err_ovl_no_viable_member_function_in_call 6225 : diag::err_ovl_no_viable_function_in_call) 6226 << Callee << Callee->getSourceRange(); 6227 S.Diag(Callee->getLocation(), 6228 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6229 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6230 return; 6231 } 6232 } 6233 6234 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6235 const UnresolvedMemberExpr *const UME, Sema &S) { 6236 6237 const auto GetFunctionLevelDCIfCXXClass = 6238 [](Sema &S) -> const CXXRecordDecl * { 6239 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6240 if (!DC || !DC->getParent()) 6241 return nullptr; 6242 6243 // If the call to some member function was made from within a member 6244 // function body 'M' return return 'M's parent. 6245 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6246 return MD->getParent()->getCanonicalDecl(); 6247 // else the call was made from within a default member initializer of a 6248 // class, so return the class. 6249 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6250 return RD->getCanonicalDecl(); 6251 return nullptr; 6252 }; 6253 // If our DeclContext is neither a member function nor a class (in the 6254 // case of a lambda in a default member initializer), we can't have an 6255 // enclosing 'this'. 6256 6257 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6258 if (!CurParentClass) 6259 return false; 6260 6261 // The naming class for implicit member functions call is the class in which 6262 // name lookup starts. 6263 const CXXRecordDecl *const NamingClass = 6264 UME->getNamingClass()->getCanonicalDecl(); 6265 assert(NamingClass && "Must have naming class even for implicit access"); 6266 6267 // If the unresolved member functions were found in a 'naming class' that is 6268 // related (either the same or derived from) to the class that contains the 6269 // member function that itself contained the implicit member access. 6270 6271 return CurParentClass == NamingClass || 6272 CurParentClass->isDerivedFrom(NamingClass); 6273 } 6274 6275 static void 6276 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6277 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6278 6279 if (!UME) 6280 return; 6281 6282 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6283 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6284 // already been captured, or if this is an implicit member function call (if 6285 // it isn't, an attempt to capture 'this' should already have been made). 6286 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6287 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6288 return; 6289 6290 // Check if the naming class in which the unresolved members were found is 6291 // related (same as or is a base of) to the enclosing class. 6292 6293 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6294 return; 6295 6296 6297 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6298 // If the enclosing function is not dependent, then this lambda is 6299 // capture ready, so if we can capture this, do so. 6300 if (!EnclosingFunctionCtx->isDependentContext()) { 6301 // If the current lambda and all enclosing lambdas can capture 'this' - 6302 // then go ahead and capture 'this' (since our unresolved overload set 6303 // contains at least one non-static member function). 6304 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6305 S.CheckCXXThisCapture(CallLoc); 6306 } else if (S.CurContext->isDependentContext()) { 6307 // ... since this is an implicit member reference, that might potentially 6308 // involve a 'this' capture, mark 'this' for potential capture in 6309 // enclosing lambdas. 6310 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6311 CurLSI->addPotentialThisCapture(CallLoc); 6312 } 6313 } 6314 6315 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6316 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6317 Expr *ExecConfig) { 6318 ExprResult Call = 6319 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6320 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6321 if (Call.isInvalid()) 6322 return Call; 6323 6324 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6325 // language modes. 6326 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6327 if (ULE->hasExplicitTemplateArgs() && 6328 ULE->decls_begin() == ULE->decls_end()) { 6329 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6330 ? diag::warn_cxx17_compat_adl_only_template_id 6331 : diag::ext_adl_only_template_id) 6332 << ULE->getName(); 6333 } 6334 } 6335 6336 if (LangOpts.OpenMP) 6337 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6338 ExecConfig); 6339 6340 return Call; 6341 } 6342 6343 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6344 /// This provides the location of the left/right parens and a list of comma 6345 /// locations. 6346 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6347 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6348 Expr *ExecConfig, bool IsExecConfig, 6349 bool AllowRecovery) { 6350 // Since this might be a postfix expression, get rid of ParenListExprs. 6351 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6352 if (Result.isInvalid()) return ExprError(); 6353 Fn = Result.get(); 6354 6355 if (checkArgsForPlaceholders(*this, ArgExprs)) 6356 return ExprError(); 6357 6358 if (getLangOpts().CPlusPlus) { 6359 // If this is a pseudo-destructor expression, build the call immediately. 6360 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6361 if (!ArgExprs.empty()) { 6362 // Pseudo-destructor calls should not have any arguments. 6363 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6364 << FixItHint::CreateRemoval( 6365 SourceRange(ArgExprs.front()->getBeginLoc(), 6366 ArgExprs.back()->getEndLoc())); 6367 } 6368 6369 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6370 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6371 } 6372 if (Fn->getType() == Context.PseudoObjectTy) { 6373 ExprResult result = CheckPlaceholderExpr(Fn); 6374 if (result.isInvalid()) return ExprError(); 6375 Fn = result.get(); 6376 } 6377 6378 // Determine whether this is a dependent call inside a C++ template, 6379 // in which case we won't do any semantic analysis now. 6380 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6381 if (ExecConfig) { 6382 return CUDAKernelCallExpr::Create( 6383 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6384 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6385 } else { 6386 6387 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6388 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6389 Fn->getBeginLoc()); 6390 6391 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6392 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6393 } 6394 } 6395 6396 // Determine whether this is a call to an object (C++ [over.call.object]). 6397 if (Fn->getType()->isRecordType()) 6398 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6399 RParenLoc); 6400 6401 if (Fn->getType() == Context.UnknownAnyTy) { 6402 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6403 if (result.isInvalid()) return ExprError(); 6404 Fn = result.get(); 6405 } 6406 6407 if (Fn->getType() == Context.BoundMemberTy) { 6408 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6409 RParenLoc, AllowRecovery); 6410 } 6411 } 6412 6413 // Check for overloaded calls. This can happen even in C due to extensions. 6414 if (Fn->getType() == Context.OverloadTy) { 6415 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6416 6417 // We aren't supposed to apply this logic if there's an '&' involved. 6418 if (!find.HasFormOfMemberPointer) { 6419 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6420 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6421 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6422 OverloadExpr *ovl = find.Expression; 6423 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6424 return BuildOverloadedCallExpr( 6425 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6426 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6427 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6428 RParenLoc, AllowRecovery); 6429 } 6430 } 6431 6432 // If we're directly calling a function, get the appropriate declaration. 6433 if (Fn->getType() == Context.UnknownAnyTy) { 6434 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6435 if (result.isInvalid()) return ExprError(); 6436 Fn = result.get(); 6437 } 6438 6439 Expr *NakedFn = Fn->IgnoreParens(); 6440 6441 bool CallingNDeclIndirectly = false; 6442 NamedDecl *NDecl = nullptr; 6443 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6444 if (UnOp->getOpcode() == UO_AddrOf) { 6445 CallingNDeclIndirectly = true; 6446 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6447 } 6448 } 6449 6450 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6451 NDecl = DRE->getDecl(); 6452 6453 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6454 if (FDecl && FDecl->getBuiltinID()) { 6455 // Rewrite the function decl for this builtin by replacing parameters 6456 // with no explicit address space with the address space of the arguments 6457 // in ArgExprs. 6458 if ((FDecl = 6459 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6460 NDecl = FDecl; 6461 Fn = DeclRefExpr::Create( 6462 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6463 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6464 nullptr, DRE->isNonOdrUse()); 6465 } 6466 } 6467 } else if (isa<MemberExpr>(NakedFn)) 6468 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6469 6470 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6471 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6472 FD, /*Complain=*/true, Fn->getBeginLoc())) 6473 return ExprError(); 6474 6475 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6476 return ExprError(); 6477 6478 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6479 } 6480 6481 if (Context.isDependenceAllowed() && 6482 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6483 assert(!getLangOpts().CPlusPlus); 6484 assert((Fn->containsErrors() || 6485 llvm::any_of(ArgExprs, 6486 [](clang::Expr *E) { return E->containsErrors(); })) && 6487 "should only occur in error-recovery path."); 6488 QualType ReturnType = 6489 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6490 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6491 : Context.DependentTy; 6492 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6493 Expr::getValueKindForType(ReturnType), RParenLoc, 6494 CurFPFeatureOverrides()); 6495 } 6496 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6497 ExecConfig, IsExecConfig); 6498 } 6499 6500 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6501 /// 6502 /// __builtin_astype( value, dst type ) 6503 /// 6504 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6505 SourceLocation BuiltinLoc, 6506 SourceLocation RParenLoc) { 6507 ExprValueKind VK = VK_RValue; 6508 ExprObjectKind OK = OK_Ordinary; 6509 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6510 QualType SrcTy = E->getType(); 6511 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6512 return ExprError(Diag(BuiltinLoc, 6513 diag::err_invalid_astype_of_different_size) 6514 << DstTy 6515 << SrcTy 6516 << E->getSourceRange()); 6517 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6518 } 6519 6520 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6521 /// provided arguments. 6522 /// 6523 /// __builtin_convertvector( value, dst type ) 6524 /// 6525 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6526 SourceLocation BuiltinLoc, 6527 SourceLocation RParenLoc) { 6528 TypeSourceInfo *TInfo; 6529 GetTypeFromParser(ParsedDestTy, &TInfo); 6530 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6531 } 6532 6533 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6534 /// i.e. an expression not of \p OverloadTy. The expression should 6535 /// unary-convert to an expression of function-pointer or 6536 /// block-pointer type. 6537 /// 6538 /// \param NDecl the declaration being called, if available 6539 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6540 SourceLocation LParenLoc, 6541 ArrayRef<Expr *> Args, 6542 SourceLocation RParenLoc, Expr *Config, 6543 bool IsExecConfig, ADLCallKind UsesADL) { 6544 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6545 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6546 6547 // Functions with 'interrupt' attribute cannot be called directly. 6548 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6549 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6550 return ExprError(); 6551 } 6552 6553 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6554 // so there's some risk when calling out to non-interrupt handler functions 6555 // that the callee might not preserve them. This is easy to diagnose here, 6556 // but can be very challenging to debug. 6557 // Likewise, X86 interrupt handlers may only call routines with attribute 6558 // no_caller_saved_registers since there is no efficient way to 6559 // save and restore the non-GPR state. 6560 if (auto *Caller = getCurFunctionDecl()) { 6561 if (Caller->hasAttr<ARMInterruptAttr>()) { 6562 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6563 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6564 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6565 if (FDecl) 6566 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6567 } 6568 } 6569 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6570 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6571 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_regsave); 6572 if (FDecl) 6573 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6574 } 6575 } 6576 6577 // Promote the function operand. 6578 // We special-case function promotion here because we only allow promoting 6579 // builtin functions to function pointers in the callee of a call. 6580 ExprResult Result; 6581 QualType ResultTy; 6582 if (BuiltinID && 6583 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6584 // Extract the return type from the (builtin) function pointer type. 6585 // FIXME Several builtins still have setType in 6586 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6587 // Builtins.def to ensure they are correct before removing setType calls. 6588 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6589 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6590 ResultTy = FDecl->getCallResultType(); 6591 } else { 6592 Result = CallExprUnaryConversions(Fn); 6593 ResultTy = Context.BoolTy; 6594 } 6595 if (Result.isInvalid()) 6596 return ExprError(); 6597 Fn = Result.get(); 6598 6599 // Check for a valid function type, but only if it is not a builtin which 6600 // requires custom type checking. These will be handled by 6601 // CheckBuiltinFunctionCall below just after creation of the call expression. 6602 const FunctionType *FuncT = nullptr; 6603 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6604 retry: 6605 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6606 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6607 // have type pointer to function". 6608 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6609 if (!FuncT) 6610 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6611 << Fn->getType() << Fn->getSourceRange()); 6612 } else if (const BlockPointerType *BPT = 6613 Fn->getType()->getAs<BlockPointerType>()) { 6614 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6615 } else { 6616 // Handle calls to expressions of unknown-any type. 6617 if (Fn->getType() == Context.UnknownAnyTy) { 6618 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6619 if (rewrite.isInvalid()) 6620 return ExprError(); 6621 Fn = rewrite.get(); 6622 goto retry; 6623 } 6624 6625 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6626 << Fn->getType() << Fn->getSourceRange()); 6627 } 6628 } 6629 6630 // Get the number of parameters in the function prototype, if any. 6631 // We will allocate space for max(Args.size(), NumParams) arguments 6632 // in the call expression. 6633 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6634 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6635 6636 CallExpr *TheCall; 6637 if (Config) { 6638 assert(UsesADL == ADLCallKind::NotADL && 6639 "CUDAKernelCallExpr should not use ADL"); 6640 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6641 Args, ResultTy, VK_RValue, RParenLoc, 6642 CurFPFeatureOverrides(), NumParams); 6643 } else { 6644 TheCall = 6645 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6646 CurFPFeatureOverrides(), NumParams, UsesADL); 6647 } 6648 6649 if (!Context.isDependenceAllowed()) { 6650 // Forget about the nulled arguments since typo correction 6651 // do not handle them well. 6652 TheCall->shrinkNumArgs(Args.size()); 6653 // C cannot always handle TypoExpr nodes in builtin calls and direct 6654 // function calls as their argument checking don't necessarily handle 6655 // dependent types properly, so make sure any TypoExprs have been 6656 // dealt with. 6657 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6658 if (!Result.isUsable()) return ExprError(); 6659 CallExpr *TheOldCall = TheCall; 6660 TheCall = dyn_cast<CallExpr>(Result.get()); 6661 bool CorrectedTypos = TheCall != TheOldCall; 6662 if (!TheCall) return Result; 6663 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6664 6665 // A new call expression node was created if some typos were corrected. 6666 // However it may not have been constructed with enough storage. In this 6667 // case, rebuild the node with enough storage. The waste of space is 6668 // immaterial since this only happens when some typos were corrected. 6669 if (CorrectedTypos && Args.size() < NumParams) { 6670 if (Config) 6671 TheCall = CUDAKernelCallExpr::Create( 6672 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6673 RParenLoc, CurFPFeatureOverrides(), NumParams); 6674 else 6675 TheCall = 6676 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6677 CurFPFeatureOverrides(), NumParams, UsesADL); 6678 } 6679 // We can now handle the nulled arguments for the default arguments. 6680 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6681 } 6682 6683 // Bail out early if calling a builtin with custom type checking. 6684 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6685 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6686 6687 if (getLangOpts().CUDA) { 6688 if (Config) { 6689 // CUDA: Kernel calls must be to global functions 6690 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6691 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6692 << FDecl << Fn->getSourceRange()); 6693 6694 // CUDA: Kernel function must have 'void' return type 6695 if (!FuncT->getReturnType()->isVoidType() && 6696 !FuncT->getReturnType()->getAs<AutoType>() && 6697 !FuncT->getReturnType()->isInstantiationDependentType()) 6698 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6699 << Fn->getType() << Fn->getSourceRange()); 6700 } else { 6701 // CUDA: Calls to global functions must be configured 6702 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6703 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6704 << FDecl << Fn->getSourceRange()); 6705 } 6706 } 6707 6708 // Check for a valid return type 6709 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6710 FDecl)) 6711 return ExprError(); 6712 6713 // We know the result type of the call, set it. 6714 TheCall->setType(FuncT->getCallResultType(Context)); 6715 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6716 6717 if (Proto) { 6718 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6719 IsExecConfig)) 6720 return ExprError(); 6721 } else { 6722 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6723 6724 if (FDecl) { 6725 // Check if we have too few/too many template arguments, based 6726 // on our knowledge of the function definition. 6727 const FunctionDecl *Def = nullptr; 6728 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6729 Proto = Def->getType()->getAs<FunctionProtoType>(); 6730 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6731 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6732 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6733 } 6734 6735 // If the function we're calling isn't a function prototype, but we have 6736 // a function prototype from a prior declaratiom, use that prototype. 6737 if (!FDecl->hasPrototype()) 6738 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6739 } 6740 6741 // Promote the arguments (C99 6.5.2.2p6). 6742 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6743 Expr *Arg = Args[i]; 6744 6745 if (Proto && i < Proto->getNumParams()) { 6746 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6747 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6748 ExprResult ArgE = 6749 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6750 if (ArgE.isInvalid()) 6751 return true; 6752 6753 Arg = ArgE.getAs<Expr>(); 6754 6755 } else { 6756 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6757 6758 if (ArgE.isInvalid()) 6759 return true; 6760 6761 Arg = ArgE.getAs<Expr>(); 6762 } 6763 6764 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6765 diag::err_call_incomplete_argument, Arg)) 6766 return ExprError(); 6767 6768 TheCall->setArg(i, Arg); 6769 } 6770 } 6771 6772 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6773 if (!Method->isStatic()) 6774 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6775 << Fn->getSourceRange()); 6776 6777 // Check for sentinels 6778 if (NDecl) 6779 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6780 6781 // Warn for unions passing across security boundary (CMSE). 6782 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6783 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6784 if (const auto *RT = 6785 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6786 if (RT->getDecl()->isOrContainsUnion()) 6787 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6788 << 0 << i; 6789 } 6790 } 6791 } 6792 6793 // Do special checking on direct calls to functions. 6794 if (FDecl) { 6795 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6796 return ExprError(); 6797 6798 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6799 6800 if (BuiltinID) 6801 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6802 } else if (NDecl) { 6803 if (CheckPointerCall(NDecl, TheCall, Proto)) 6804 return ExprError(); 6805 } else { 6806 if (CheckOtherCall(TheCall, Proto)) 6807 return ExprError(); 6808 } 6809 6810 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6811 } 6812 6813 ExprResult 6814 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6815 SourceLocation RParenLoc, Expr *InitExpr) { 6816 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6817 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6818 6819 TypeSourceInfo *TInfo; 6820 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6821 if (!TInfo) 6822 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6823 6824 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6825 } 6826 6827 ExprResult 6828 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6829 SourceLocation RParenLoc, Expr *LiteralExpr) { 6830 QualType literalType = TInfo->getType(); 6831 6832 if (literalType->isArrayType()) { 6833 if (RequireCompleteSizedType( 6834 LParenLoc, Context.getBaseElementType(literalType), 6835 diag::err_array_incomplete_or_sizeless_type, 6836 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6837 return ExprError(); 6838 if (literalType->isVariableArrayType()) 6839 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6840 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6841 } else if (!literalType->isDependentType() && 6842 RequireCompleteType(LParenLoc, literalType, 6843 diag::err_typecheck_decl_incomplete_type, 6844 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6845 return ExprError(); 6846 6847 InitializedEntity Entity 6848 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6849 InitializationKind Kind 6850 = InitializationKind::CreateCStyleCast(LParenLoc, 6851 SourceRange(LParenLoc, RParenLoc), 6852 /*InitList=*/true); 6853 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6854 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6855 &literalType); 6856 if (Result.isInvalid()) 6857 return ExprError(); 6858 LiteralExpr = Result.get(); 6859 6860 bool isFileScope = !CurContext->isFunctionOrMethod(); 6861 6862 // In C, compound literals are l-values for some reason. 6863 // For GCC compatibility, in C++, file-scope array compound literals with 6864 // constant initializers are also l-values, and compound literals are 6865 // otherwise prvalues. 6866 // 6867 // (GCC also treats C++ list-initialized file-scope array prvalues with 6868 // constant initializers as l-values, but that's non-conforming, so we don't 6869 // follow it there.) 6870 // 6871 // FIXME: It would be better to handle the lvalue cases as materializing and 6872 // lifetime-extending a temporary object, but our materialized temporaries 6873 // representation only supports lifetime extension from a variable, not "out 6874 // of thin air". 6875 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6876 // is bound to the result of applying array-to-pointer decay to the compound 6877 // literal. 6878 // FIXME: GCC supports compound literals of reference type, which should 6879 // obviously have a value kind derived from the kind of reference involved. 6880 ExprValueKind VK = 6881 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6882 ? VK_RValue 6883 : VK_LValue; 6884 6885 if (isFileScope) 6886 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6887 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6888 Expr *Init = ILE->getInit(i); 6889 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6890 } 6891 6892 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6893 VK, LiteralExpr, isFileScope); 6894 if (isFileScope) { 6895 if (!LiteralExpr->isTypeDependent() && 6896 !LiteralExpr->isValueDependent() && 6897 !literalType->isDependentType()) // C99 6.5.2.5p3 6898 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6899 return ExprError(); 6900 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6901 literalType.getAddressSpace() != LangAS::Default) { 6902 // Embedded-C extensions to C99 6.5.2.5: 6903 // "If the compound literal occurs inside the body of a function, the 6904 // type name shall not be qualified by an address-space qualifier." 6905 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6906 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6907 return ExprError(); 6908 } 6909 6910 if (!isFileScope && !getLangOpts().CPlusPlus) { 6911 // Compound literals that have automatic storage duration are destroyed at 6912 // the end of the scope in C; in C++, they're just temporaries. 6913 6914 // Emit diagnostics if it is or contains a C union type that is non-trivial 6915 // to destruct. 6916 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6917 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6918 NTCUC_CompoundLiteral, NTCUK_Destruct); 6919 6920 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6921 if (literalType.isDestructedType()) { 6922 Cleanup.setExprNeedsCleanups(true); 6923 ExprCleanupObjects.push_back(E); 6924 getCurFunction()->setHasBranchProtectedScope(); 6925 } 6926 } 6927 6928 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6929 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6930 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6931 E->getInitializer()->getExprLoc()); 6932 6933 return MaybeBindToTemporary(E); 6934 } 6935 6936 ExprResult 6937 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6938 SourceLocation RBraceLoc) { 6939 // Only produce each kind of designated initialization diagnostic once. 6940 SourceLocation FirstDesignator; 6941 bool DiagnosedArrayDesignator = false; 6942 bool DiagnosedNestedDesignator = false; 6943 bool DiagnosedMixedDesignator = false; 6944 6945 // Check that any designated initializers are syntactically valid in the 6946 // current language mode. 6947 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6948 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6949 if (FirstDesignator.isInvalid()) 6950 FirstDesignator = DIE->getBeginLoc(); 6951 6952 if (!getLangOpts().CPlusPlus) 6953 break; 6954 6955 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6956 DiagnosedNestedDesignator = true; 6957 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6958 << DIE->getDesignatorsSourceRange(); 6959 } 6960 6961 for (auto &Desig : DIE->designators()) { 6962 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6963 DiagnosedArrayDesignator = true; 6964 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6965 << Desig.getSourceRange(); 6966 } 6967 } 6968 6969 if (!DiagnosedMixedDesignator && 6970 !isa<DesignatedInitExpr>(InitArgList[0])) { 6971 DiagnosedMixedDesignator = true; 6972 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6973 << DIE->getSourceRange(); 6974 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6975 << InitArgList[0]->getSourceRange(); 6976 } 6977 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6978 isa<DesignatedInitExpr>(InitArgList[0])) { 6979 DiagnosedMixedDesignator = true; 6980 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6981 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6982 << DIE->getSourceRange(); 6983 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6984 << InitArgList[I]->getSourceRange(); 6985 } 6986 } 6987 6988 if (FirstDesignator.isValid()) { 6989 // Only diagnose designated initiaization as a C++20 extension if we didn't 6990 // already diagnose use of (non-C++20) C99 designator syntax. 6991 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6992 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6993 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6994 ? diag::warn_cxx17_compat_designated_init 6995 : diag::ext_cxx_designated_init); 6996 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6997 Diag(FirstDesignator, diag::ext_designated_init); 6998 } 6999 } 7000 7001 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7002 } 7003 7004 ExprResult 7005 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7006 SourceLocation RBraceLoc) { 7007 // Semantic analysis for initializers is done by ActOnDeclarator() and 7008 // CheckInitializer() - it requires knowledge of the object being initialized. 7009 7010 // Immediately handle non-overload placeholders. Overloads can be 7011 // resolved contextually, but everything else here can't. 7012 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7013 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7014 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7015 7016 // Ignore failures; dropping the entire initializer list because 7017 // of one failure would be terrible for indexing/etc. 7018 if (result.isInvalid()) continue; 7019 7020 InitArgList[I] = result.get(); 7021 } 7022 } 7023 7024 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7025 RBraceLoc); 7026 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7027 return E; 7028 } 7029 7030 /// Do an explicit extend of the given block pointer if we're in ARC. 7031 void Sema::maybeExtendBlockObject(ExprResult &E) { 7032 assert(E.get()->getType()->isBlockPointerType()); 7033 assert(E.get()->isRValue()); 7034 7035 // Only do this in an r-value context. 7036 if (!getLangOpts().ObjCAutoRefCount) return; 7037 7038 E = ImplicitCastExpr::Create( 7039 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7040 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7041 Cleanup.setExprNeedsCleanups(true); 7042 } 7043 7044 /// Prepare a conversion of the given expression to an ObjC object 7045 /// pointer type. 7046 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7047 QualType type = E.get()->getType(); 7048 if (type->isObjCObjectPointerType()) { 7049 return CK_BitCast; 7050 } else if (type->isBlockPointerType()) { 7051 maybeExtendBlockObject(E); 7052 return CK_BlockPointerToObjCPointerCast; 7053 } else { 7054 assert(type->isPointerType()); 7055 return CK_CPointerToObjCPointerCast; 7056 } 7057 } 7058 7059 /// Prepares for a scalar cast, performing all the necessary stages 7060 /// except the final cast and returning the kind required. 7061 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7062 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7063 // Also, callers should have filtered out the invalid cases with 7064 // pointers. Everything else should be possible. 7065 7066 QualType SrcTy = Src.get()->getType(); 7067 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7068 return CK_NoOp; 7069 7070 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7071 case Type::STK_MemberPointer: 7072 llvm_unreachable("member pointer type in C"); 7073 7074 case Type::STK_CPointer: 7075 case Type::STK_BlockPointer: 7076 case Type::STK_ObjCObjectPointer: 7077 switch (DestTy->getScalarTypeKind()) { 7078 case Type::STK_CPointer: { 7079 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7080 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7081 if (SrcAS != DestAS) 7082 return CK_AddressSpaceConversion; 7083 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7084 return CK_NoOp; 7085 return CK_BitCast; 7086 } 7087 case Type::STK_BlockPointer: 7088 return (SrcKind == Type::STK_BlockPointer 7089 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7090 case Type::STK_ObjCObjectPointer: 7091 if (SrcKind == Type::STK_ObjCObjectPointer) 7092 return CK_BitCast; 7093 if (SrcKind == Type::STK_CPointer) 7094 return CK_CPointerToObjCPointerCast; 7095 maybeExtendBlockObject(Src); 7096 return CK_BlockPointerToObjCPointerCast; 7097 case Type::STK_Bool: 7098 return CK_PointerToBoolean; 7099 case Type::STK_Integral: 7100 return CK_PointerToIntegral; 7101 case Type::STK_Floating: 7102 case Type::STK_FloatingComplex: 7103 case Type::STK_IntegralComplex: 7104 case Type::STK_MemberPointer: 7105 case Type::STK_FixedPoint: 7106 llvm_unreachable("illegal cast from pointer"); 7107 } 7108 llvm_unreachable("Should have returned before this"); 7109 7110 case Type::STK_FixedPoint: 7111 switch (DestTy->getScalarTypeKind()) { 7112 case Type::STK_FixedPoint: 7113 return CK_FixedPointCast; 7114 case Type::STK_Bool: 7115 return CK_FixedPointToBoolean; 7116 case Type::STK_Integral: 7117 return CK_FixedPointToIntegral; 7118 case Type::STK_Floating: 7119 return CK_FixedPointToFloating; 7120 case Type::STK_IntegralComplex: 7121 case Type::STK_FloatingComplex: 7122 Diag(Src.get()->getExprLoc(), 7123 diag::err_unimplemented_conversion_with_fixed_point_type) 7124 << DestTy; 7125 return CK_IntegralCast; 7126 case Type::STK_CPointer: 7127 case Type::STK_ObjCObjectPointer: 7128 case Type::STK_BlockPointer: 7129 case Type::STK_MemberPointer: 7130 llvm_unreachable("illegal cast to pointer type"); 7131 } 7132 llvm_unreachable("Should have returned before this"); 7133 7134 case Type::STK_Bool: // casting from bool is like casting from an integer 7135 case Type::STK_Integral: 7136 switch (DestTy->getScalarTypeKind()) { 7137 case Type::STK_CPointer: 7138 case Type::STK_ObjCObjectPointer: 7139 case Type::STK_BlockPointer: 7140 if (Src.get()->isNullPointerConstant(Context, 7141 Expr::NPC_ValueDependentIsNull)) 7142 return CK_NullToPointer; 7143 return CK_IntegralToPointer; 7144 case Type::STK_Bool: 7145 return CK_IntegralToBoolean; 7146 case Type::STK_Integral: 7147 return CK_IntegralCast; 7148 case Type::STK_Floating: 7149 return CK_IntegralToFloating; 7150 case Type::STK_IntegralComplex: 7151 Src = ImpCastExprToType(Src.get(), 7152 DestTy->castAs<ComplexType>()->getElementType(), 7153 CK_IntegralCast); 7154 return CK_IntegralRealToComplex; 7155 case Type::STK_FloatingComplex: 7156 Src = ImpCastExprToType(Src.get(), 7157 DestTy->castAs<ComplexType>()->getElementType(), 7158 CK_IntegralToFloating); 7159 return CK_FloatingRealToComplex; 7160 case Type::STK_MemberPointer: 7161 llvm_unreachable("member pointer type in C"); 7162 case Type::STK_FixedPoint: 7163 return CK_IntegralToFixedPoint; 7164 } 7165 llvm_unreachable("Should have returned before this"); 7166 7167 case Type::STK_Floating: 7168 switch (DestTy->getScalarTypeKind()) { 7169 case Type::STK_Floating: 7170 return CK_FloatingCast; 7171 case Type::STK_Bool: 7172 return CK_FloatingToBoolean; 7173 case Type::STK_Integral: 7174 return CK_FloatingToIntegral; 7175 case Type::STK_FloatingComplex: 7176 Src = ImpCastExprToType(Src.get(), 7177 DestTy->castAs<ComplexType>()->getElementType(), 7178 CK_FloatingCast); 7179 return CK_FloatingRealToComplex; 7180 case Type::STK_IntegralComplex: 7181 Src = ImpCastExprToType(Src.get(), 7182 DestTy->castAs<ComplexType>()->getElementType(), 7183 CK_FloatingToIntegral); 7184 return CK_IntegralRealToComplex; 7185 case Type::STK_CPointer: 7186 case Type::STK_ObjCObjectPointer: 7187 case Type::STK_BlockPointer: 7188 llvm_unreachable("valid float->pointer cast?"); 7189 case Type::STK_MemberPointer: 7190 llvm_unreachable("member pointer type in C"); 7191 case Type::STK_FixedPoint: 7192 return CK_FloatingToFixedPoint; 7193 } 7194 llvm_unreachable("Should have returned before this"); 7195 7196 case Type::STK_FloatingComplex: 7197 switch (DestTy->getScalarTypeKind()) { 7198 case Type::STK_FloatingComplex: 7199 return CK_FloatingComplexCast; 7200 case Type::STK_IntegralComplex: 7201 return CK_FloatingComplexToIntegralComplex; 7202 case Type::STK_Floating: { 7203 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7204 if (Context.hasSameType(ET, DestTy)) 7205 return CK_FloatingComplexToReal; 7206 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7207 return CK_FloatingCast; 7208 } 7209 case Type::STK_Bool: 7210 return CK_FloatingComplexToBoolean; 7211 case Type::STK_Integral: 7212 Src = ImpCastExprToType(Src.get(), 7213 SrcTy->castAs<ComplexType>()->getElementType(), 7214 CK_FloatingComplexToReal); 7215 return CK_FloatingToIntegral; 7216 case Type::STK_CPointer: 7217 case Type::STK_ObjCObjectPointer: 7218 case Type::STK_BlockPointer: 7219 llvm_unreachable("valid complex float->pointer cast?"); 7220 case Type::STK_MemberPointer: 7221 llvm_unreachable("member pointer type in C"); 7222 case Type::STK_FixedPoint: 7223 Diag(Src.get()->getExprLoc(), 7224 diag::err_unimplemented_conversion_with_fixed_point_type) 7225 << SrcTy; 7226 return CK_IntegralCast; 7227 } 7228 llvm_unreachable("Should have returned before this"); 7229 7230 case Type::STK_IntegralComplex: 7231 switch (DestTy->getScalarTypeKind()) { 7232 case Type::STK_FloatingComplex: 7233 return CK_IntegralComplexToFloatingComplex; 7234 case Type::STK_IntegralComplex: 7235 return CK_IntegralComplexCast; 7236 case Type::STK_Integral: { 7237 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7238 if (Context.hasSameType(ET, DestTy)) 7239 return CK_IntegralComplexToReal; 7240 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7241 return CK_IntegralCast; 7242 } 7243 case Type::STK_Bool: 7244 return CK_IntegralComplexToBoolean; 7245 case Type::STK_Floating: 7246 Src = ImpCastExprToType(Src.get(), 7247 SrcTy->castAs<ComplexType>()->getElementType(), 7248 CK_IntegralComplexToReal); 7249 return CK_IntegralToFloating; 7250 case Type::STK_CPointer: 7251 case Type::STK_ObjCObjectPointer: 7252 case Type::STK_BlockPointer: 7253 llvm_unreachable("valid complex int->pointer cast?"); 7254 case Type::STK_MemberPointer: 7255 llvm_unreachable("member pointer type in C"); 7256 case Type::STK_FixedPoint: 7257 Diag(Src.get()->getExprLoc(), 7258 diag::err_unimplemented_conversion_with_fixed_point_type) 7259 << SrcTy; 7260 return CK_IntegralCast; 7261 } 7262 llvm_unreachable("Should have returned before this"); 7263 } 7264 7265 llvm_unreachable("Unhandled scalar cast"); 7266 } 7267 7268 static bool breakDownVectorType(QualType type, uint64_t &len, 7269 QualType &eltType) { 7270 // Vectors are simple. 7271 if (const VectorType *vecType = type->getAs<VectorType>()) { 7272 len = vecType->getNumElements(); 7273 eltType = vecType->getElementType(); 7274 assert(eltType->isScalarType()); 7275 return true; 7276 } 7277 7278 // We allow lax conversion to and from non-vector types, but only if 7279 // they're real types (i.e. non-complex, non-pointer scalar types). 7280 if (!type->isRealType()) return false; 7281 7282 len = 1; 7283 eltType = type; 7284 return true; 7285 } 7286 7287 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7288 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7289 /// allowed? 7290 /// 7291 /// This will also return false if the two given types do not make sense from 7292 /// the perspective of SVE bitcasts. 7293 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7294 assert(srcTy->isVectorType() || destTy->isVectorType()); 7295 7296 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7297 if (!FirstType->isSizelessBuiltinType()) 7298 return false; 7299 7300 const auto *VecTy = SecondType->getAs<VectorType>(); 7301 return VecTy && 7302 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7303 }; 7304 7305 return ValidScalableConversion(srcTy, destTy) || 7306 ValidScalableConversion(destTy, srcTy); 7307 } 7308 7309 /// Are the two types lax-compatible vector types? That is, given 7310 /// that one of them is a vector, do they have equal storage sizes, 7311 /// where the storage size is the number of elements times the element 7312 /// size? 7313 /// 7314 /// This will also return false if either of the types is neither a 7315 /// vector nor a real type. 7316 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7317 assert(destTy->isVectorType() || srcTy->isVectorType()); 7318 7319 // Disallow lax conversions between scalars and ExtVectors (these 7320 // conversions are allowed for other vector types because common headers 7321 // depend on them). Most scalar OP ExtVector cases are handled by the 7322 // splat path anyway, which does what we want (convert, not bitcast). 7323 // What this rules out for ExtVectors is crazy things like char4*float. 7324 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7325 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7326 7327 uint64_t srcLen, destLen; 7328 QualType srcEltTy, destEltTy; 7329 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7330 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7331 7332 // ASTContext::getTypeSize will return the size rounded up to a 7333 // power of 2, so instead of using that, we need to use the raw 7334 // element size multiplied by the element count. 7335 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7336 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7337 7338 return (srcLen * srcEltSize == destLen * destEltSize); 7339 } 7340 7341 /// Is this a legal conversion between two types, one of which is 7342 /// known to be a vector type? 7343 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7344 assert(destTy->isVectorType() || srcTy->isVectorType()); 7345 7346 switch (Context.getLangOpts().getLaxVectorConversions()) { 7347 case LangOptions::LaxVectorConversionKind::None: 7348 return false; 7349 7350 case LangOptions::LaxVectorConversionKind::Integer: 7351 if (!srcTy->isIntegralOrEnumerationType()) { 7352 auto *Vec = srcTy->getAs<VectorType>(); 7353 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7354 return false; 7355 } 7356 if (!destTy->isIntegralOrEnumerationType()) { 7357 auto *Vec = destTy->getAs<VectorType>(); 7358 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7359 return false; 7360 } 7361 // OK, integer (vector) -> integer (vector) bitcast. 7362 break; 7363 7364 case LangOptions::LaxVectorConversionKind::All: 7365 break; 7366 } 7367 7368 return areLaxCompatibleVectorTypes(srcTy, destTy); 7369 } 7370 7371 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7372 CastKind &Kind) { 7373 assert(VectorTy->isVectorType() && "Not a vector type!"); 7374 7375 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7376 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7377 return Diag(R.getBegin(), 7378 Ty->isVectorType() ? 7379 diag::err_invalid_conversion_between_vectors : 7380 diag::err_invalid_conversion_between_vector_and_integer) 7381 << VectorTy << Ty << R; 7382 } else 7383 return Diag(R.getBegin(), 7384 diag::err_invalid_conversion_between_vector_and_scalar) 7385 << VectorTy << Ty << R; 7386 7387 Kind = CK_BitCast; 7388 return false; 7389 } 7390 7391 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7392 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7393 7394 if (DestElemTy == SplattedExpr->getType()) 7395 return SplattedExpr; 7396 7397 assert(DestElemTy->isFloatingType() || 7398 DestElemTy->isIntegralOrEnumerationType()); 7399 7400 CastKind CK; 7401 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7402 // OpenCL requires that we convert `true` boolean expressions to -1, but 7403 // only when splatting vectors. 7404 if (DestElemTy->isFloatingType()) { 7405 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7406 // in two steps: boolean to signed integral, then to floating. 7407 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7408 CK_BooleanToSignedIntegral); 7409 SplattedExpr = CastExprRes.get(); 7410 CK = CK_IntegralToFloating; 7411 } else { 7412 CK = CK_BooleanToSignedIntegral; 7413 } 7414 } else { 7415 ExprResult CastExprRes = SplattedExpr; 7416 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7417 if (CastExprRes.isInvalid()) 7418 return ExprError(); 7419 SplattedExpr = CastExprRes.get(); 7420 } 7421 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7422 } 7423 7424 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7425 Expr *CastExpr, CastKind &Kind) { 7426 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7427 7428 QualType SrcTy = CastExpr->getType(); 7429 7430 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7431 // an ExtVectorType. 7432 // In OpenCL, casts between vectors of different types are not allowed. 7433 // (See OpenCL 6.2). 7434 if (SrcTy->isVectorType()) { 7435 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7436 (getLangOpts().OpenCL && 7437 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7438 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7439 << DestTy << SrcTy << R; 7440 return ExprError(); 7441 } 7442 Kind = CK_BitCast; 7443 return CastExpr; 7444 } 7445 7446 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7447 // conversion will take place first from scalar to elt type, and then 7448 // splat from elt type to vector. 7449 if (SrcTy->isPointerType()) 7450 return Diag(R.getBegin(), 7451 diag::err_invalid_conversion_between_vector_and_scalar) 7452 << DestTy << SrcTy << R; 7453 7454 Kind = CK_VectorSplat; 7455 return prepareVectorSplat(DestTy, CastExpr); 7456 } 7457 7458 ExprResult 7459 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7460 Declarator &D, ParsedType &Ty, 7461 SourceLocation RParenLoc, Expr *CastExpr) { 7462 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7463 "ActOnCastExpr(): missing type or expr"); 7464 7465 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7466 if (D.isInvalidType()) 7467 return ExprError(); 7468 7469 if (getLangOpts().CPlusPlus) { 7470 // Check that there are no default arguments (C++ only). 7471 CheckExtraCXXDefaultArguments(D); 7472 } else { 7473 // Make sure any TypoExprs have been dealt with. 7474 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7475 if (!Res.isUsable()) 7476 return ExprError(); 7477 CastExpr = Res.get(); 7478 } 7479 7480 checkUnusedDeclAttributes(D); 7481 7482 QualType castType = castTInfo->getType(); 7483 Ty = CreateParsedType(castType, castTInfo); 7484 7485 bool isVectorLiteral = false; 7486 7487 // Check for an altivec or OpenCL literal, 7488 // i.e. all the elements are integer constants. 7489 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7490 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7491 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7492 && castType->isVectorType() && (PE || PLE)) { 7493 if (PLE && PLE->getNumExprs() == 0) { 7494 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7495 return ExprError(); 7496 } 7497 if (PE || PLE->getNumExprs() == 1) { 7498 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7499 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7500 isVectorLiteral = true; 7501 } 7502 else 7503 isVectorLiteral = true; 7504 } 7505 7506 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7507 // then handle it as such. 7508 if (isVectorLiteral) 7509 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7510 7511 // If the Expr being casted is a ParenListExpr, handle it specially. 7512 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7513 // sequence of BinOp comma operators. 7514 if (isa<ParenListExpr>(CastExpr)) { 7515 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7516 if (Result.isInvalid()) return ExprError(); 7517 CastExpr = Result.get(); 7518 } 7519 7520 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7521 !getSourceManager().isInSystemMacro(LParenLoc)) 7522 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7523 7524 CheckTollFreeBridgeCast(castType, CastExpr); 7525 7526 CheckObjCBridgeRelatedCast(castType, CastExpr); 7527 7528 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7529 7530 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7531 } 7532 7533 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7534 SourceLocation RParenLoc, Expr *E, 7535 TypeSourceInfo *TInfo) { 7536 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7537 "Expected paren or paren list expression"); 7538 7539 Expr **exprs; 7540 unsigned numExprs; 7541 Expr *subExpr; 7542 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7543 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7544 LiteralLParenLoc = PE->getLParenLoc(); 7545 LiteralRParenLoc = PE->getRParenLoc(); 7546 exprs = PE->getExprs(); 7547 numExprs = PE->getNumExprs(); 7548 } else { // isa<ParenExpr> by assertion at function entrance 7549 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7550 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7551 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7552 exprs = &subExpr; 7553 numExprs = 1; 7554 } 7555 7556 QualType Ty = TInfo->getType(); 7557 assert(Ty->isVectorType() && "Expected vector type"); 7558 7559 SmallVector<Expr *, 8> initExprs; 7560 const VectorType *VTy = Ty->castAs<VectorType>(); 7561 unsigned numElems = VTy->getNumElements(); 7562 7563 // '(...)' form of vector initialization in AltiVec: the number of 7564 // initializers must be one or must match the size of the vector. 7565 // If a single value is specified in the initializer then it will be 7566 // replicated to all the components of the vector 7567 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7568 // The number of initializers must be one or must match the size of the 7569 // vector. If a single value is specified in the initializer then it will 7570 // be replicated to all the components of the vector 7571 if (numExprs == 1) { 7572 QualType ElemTy = VTy->getElementType(); 7573 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7574 if (Literal.isInvalid()) 7575 return ExprError(); 7576 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7577 PrepareScalarCast(Literal, ElemTy)); 7578 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7579 } 7580 else if (numExprs < numElems) { 7581 Diag(E->getExprLoc(), 7582 diag::err_incorrect_number_of_vector_initializers); 7583 return ExprError(); 7584 } 7585 else 7586 initExprs.append(exprs, exprs + numExprs); 7587 } 7588 else { 7589 // For OpenCL, when the number of initializers is a single value, 7590 // it will be replicated to all components of the vector. 7591 if (getLangOpts().OpenCL && 7592 VTy->getVectorKind() == VectorType::GenericVector && 7593 numExprs == 1) { 7594 QualType ElemTy = VTy->getElementType(); 7595 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7596 if (Literal.isInvalid()) 7597 return ExprError(); 7598 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7599 PrepareScalarCast(Literal, ElemTy)); 7600 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7601 } 7602 7603 initExprs.append(exprs, exprs + numExprs); 7604 } 7605 // FIXME: This means that pretty-printing the final AST will produce curly 7606 // braces instead of the original commas. 7607 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7608 initExprs, LiteralRParenLoc); 7609 initE->setType(Ty); 7610 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7611 } 7612 7613 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7614 /// the ParenListExpr into a sequence of comma binary operators. 7615 ExprResult 7616 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7617 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7618 if (!E) 7619 return OrigExpr; 7620 7621 ExprResult Result(E->getExpr(0)); 7622 7623 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7624 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7625 E->getExpr(i)); 7626 7627 if (Result.isInvalid()) return ExprError(); 7628 7629 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7630 } 7631 7632 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7633 SourceLocation R, 7634 MultiExprArg Val) { 7635 return ParenListExpr::Create(Context, L, Val, R); 7636 } 7637 7638 /// Emit a specialized diagnostic when one expression is a null pointer 7639 /// constant and the other is not a pointer. Returns true if a diagnostic is 7640 /// emitted. 7641 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7642 SourceLocation QuestionLoc) { 7643 Expr *NullExpr = LHSExpr; 7644 Expr *NonPointerExpr = RHSExpr; 7645 Expr::NullPointerConstantKind NullKind = 7646 NullExpr->isNullPointerConstant(Context, 7647 Expr::NPC_ValueDependentIsNotNull); 7648 7649 if (NullKind == Expr::NPCK_NotNull) { 7650 NullExpr = RHSExpr; 7651 NonPointerExpr = LHSExpr; 7652 NullKind = 7653 NullExpr->isNullPointerConstant(Context, 7654 Expr::NPC_ValueDependentIsNotNull); 7655 } 7656 7657 if (NullKind == Expr::NPCK_NotNull) 7658 return false; 7659 7660 if (NullKind == Expr::NPCK_ZeroExpression) 7661 return false; 7662 7663 if (NullKind == Expr::NPCK_ZeroLiteral) { 7664 // In this case, check to make sure that we got here from a "NULL" 7665 // string in the source code. 7666 NullExpr = NullExpr->IgnoreParenImpCasts(); 7667 SourceLocation loc = NullExpr->getExprLoc(); 7668 if (!findMacroSpelling(loc, "NULL")) 7669 return false; 7670 } 7671 7672 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7673 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7674 << NonPointerExpr->getType() << DiagType 7675 << NonPointerExpr->getSourceRange(); 7676 return true; 7677 } 7678 7679 /// Return false if the condition expression is valid, true otherwise. 7680 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7681 QualType CondTy = Cond->getType(); 7682 7683 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7684 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7685 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7686 << CondTy << Cond->getSourceRange(); 7687 return true; 7688 } 7689 7690 // C99 6.5.15p2 7691 if (CondTy->isScalarType()) return false; 7692 7693 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7694 << CondTy << Cond->getSourceRange(); 7695 return true; 7696 } 7697 7698 /// Handle when one or both operands are void type. 7699 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7700 ExprResult &RHS) { 7701 Expr *LHSExpr = LHS.get(); 7702 Expr *RHSExpr = RHS.get(); 7703 7704 if (!LHSExpr->getType()->isVoidType()) 7705 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7706 << RHSExpr->getSourceRange(); 7707 if (!RHSExpr->getType()->isVoidType()) 7708 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7709 << LHSExpr->getSourceRange(); 7710 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7711 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7712 return S.Context.VoidTy; 7713 } 7714 7715 /// Return false if the NullExpr can be promoted to PointerTy, 7716 /// true otherwise. 7717 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7718 QualType PointerTy) { 7719 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7720 !NullExpr.get()->isNullPointerConstant(S.Context, 7721 Expr::NPC_ValueDependentIsNull)) 7722 return true; 7723 7724 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7725 return false; 7726 } 7727 7728 /// Checks compatibility between two pointers and return the resulting 7729 /// type. 7730 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7731 ExprResult &RHS, 7732 SourceLocation Loc) { 7733 QualType LHSTy = LHS.get()->getType(); 7734 QualType RHSTy = RHS.get()->getType(); 7735 7736 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7737 // Two identical pointers types are always compatible. 7738 return LHSTy; 7739 } 7740 7741 QualType lhptee, rhptee; 7742 7743 // Get the pointee types. 7744 bool IsBlockPointer = false; 7745 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7746 lhptee = LHSBTy->getPointeeType(); 7747 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7748 IsBlockPointer = true; 7749 } else { 7750 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7751 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7752 } 7753 7754 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7755 // differently qualified versions of compatible types, the result type is 7756 // a pointer to an appropriately qualified version of the composite 7757 // type. 7758 7759 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7760 // clause doesn't make sense for our extensions. E.g. address space 2 should 7761 // be incompatible with address space 3: they may live on different devices or 7762 // anything. 7763 Qualifiers lhQual = lhptee.getQualifiers(); 7764 Qualifiers rhQual = rhptee.getQualifiers(); 7765 7766 LangAS ResultAddrSpace = LangAS::Default; 7767 LangAS LAddrSpace = lhQual.getAddressSpace(); 7768 LangAS RAddrSpace = rhQual.getAddressSpace(); 7769 7770 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7771 // spaces is disallowed. 7772 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7773 ResultAddrSpace = LAddrSpace; 7774 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7775 ResultAddrSpace = RAddrSpace; 7776 else { 7777 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7778 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7779 << RHS.get()->getSourceRange(); 7780 return QualType(); 7781 } 7782 7783 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7784 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7785 lhQual.removeCVRQualifiers(); 7786 rhQual.removeCVRQualifiers(); 7787 7788 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7789 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7790 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7791 // qual types are compatible iff 7792 // * corresponded types are compatible 7793 // * CVR qualifiers are equal 7794 // * address spaces are equal 7795 // Thus for conditional operator we merge CVR and address space unqualified 7796 // pointees and if there is a composite type we return a pointer to it with 7797 // merged qualifiers. 7798 LHSCastKind = 7799 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7800 RHSCastKind = 7801 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7802 lhQual.removeAddressSpace(); 7803 rhQual.removeAddressSpace(); 7804 7805 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7806 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7807 7808 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7809 7810 if (CompositeTy.isNull()) { 7811 // In this situation, we assume void* type. No especially good 7812 // reason, but this is what gcc does, and we do have to pick 7813 // to get a consistent AST. 7814 QualType incompatTy; 7815 incompatTy = S.Context.getPointerType( 7816 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7817 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7818 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7819 7820 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7821 // for casts between types with incompatible address space qualifiers. 7822 // For the following code the compiler produces casts between global and 7823 // local address spaces of the corresponded innermost pointees: 7824 // local int *global *a; 7825 // global int *global *b; 7826 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7827 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7828 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7829 << RHS.get()->getSourceRange(); 7830 7831 return incompatTy; 7832 } 7833 7834 // The pointer types are compatible. 7835 // In case of OpenCL ResultTy should have the address space qualifier 7836 // which is a superset of address spaces of both the 2nd and the 3rd 7837 // operands of the conditional operator. 7838 QualType ResultTy = [&, ResultAddrSpace]() { 7839 if (S.getLangOpts().OpenCL) { 7840 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7841 CompositeQuals.setAddressSpace(ResultAddrSpace); 7842 return S.Context 7843 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7844 .withCVRQualifiers(MergedCVRQual); 7845 } 7846 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7847 }(); 7848 if (IsBlockPointer) 7849 ResultTy = S.Context.getBlockPointerType(ResultTy); 7850 else 7851 ResultTy = S.Context.getPointerType(ResultTy); 7852 7853 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7854 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7855 return ResultTy; 7856 } 7857 7858 /// Return the resulting type when the operands are both block pointers. 7859 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7860 ExprResult &LHS, 7861 ExprResult &RHS, 7862 SourceLocation Loc) { 7863 QualType LHSTy = LHS.get()->getType(); 7864 QualType RHSTy = RHS.get()->getType(); 7865 7866 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7867 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7868 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7869 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7870 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7871 return destType; 7872 } 7873 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7874 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7875 << RHS.get()->getSourceRange(); 7876 return QualType(); 7877 } 7878 7879 // We have 2 block pointer types. 7880 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7881 } 7882 7883 /// Return the resulting type when the operands are both pointers. 7884 static QualType 7885 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7886 ExprResult &RHS, 7887 SourceLocation Loc) { 7888 // get the pointer types 7889 QualType LHSTy = LHS.get()->getType(); 7890 QualType RHSTy = RHS.get()->getType(); 7891 7892 // get the "pointed to" types 7893 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7894 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7895 7896 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7897 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7898 // Figure out necessary qualifiers (C99 6.5.15p6) 7899 QualType destPointee 7900 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7901 QualType destType = S.Context.getPointerType(destPointee); 7902 // Add qualifiers if necessary. 7903 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7904 // Promote to void*. 7905 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7906 return destType; 7907 } 7908 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7909 QualType destPointee 7910 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7911 QualType destType = S.Context.getPointerType(destPointee); 7912 // Add qualifiers if necessary. 7913 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7914 // Promote to void*. 7915 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7916 return destType; 7917 } 7918 7919 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7920 } 7921 7922 /// Return false if the first expression is not an integer and the second 7923 /// expression is not a pointer, true otherwise. 7924 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7925 Expr* PointerExpr, SourceLocation Loc, 7926 bool IsIntFirstExpr) { 7927 if (!PointerExpr->getType()->isPointerType() || 7928 !Int.get()->getType()->isIntegerType()) 7929 return false; 7930 7931 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7932 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7933 7934 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7935 << Expr1->getType() << Expr2->getType() 7936 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7937 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7938 CK_IntegralToPointer); 7939 return true; 7940 } 7941 7942 /// Simple conversion between integer and floating point types. 7943 /// 7944 /// Used when handling the OpenCL conditional operator where the 7945 /// condition is a vector while the other operands are scalar. 7946 /// 7947 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7948 /// types are either integer or floating type. Between the two 7949 /// operands, the type with the higher rank is defined as the "result 7950 /// type". The other operand needs to be promoted to the same type. No 7951 /// other type promotion is allowed. We cannot use 7952 /// UsualArithmeticConversions() for this purpose, since it always 7953 /// promotes promotable types. 7954 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7955 ExprResult &RHS, 7956 SourceLocation QuestionLoc) { 7957 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7958 if (LHS.isInvalid()) 7959 return QualType(); 7960 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7961 if (RHS.isInvalid()) 7962 return QualType(); 7963 7964 // For conversion purposes, we ignore any qualifiers. 7965 // For example, "const float" and "float" are equivalent. 7966 QualType LHSType = 7967 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7968 QualType RHSType = 7969 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7970 7971 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7972 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7973 << LHSType << LHS.get()->getSourceRange(); 7974 return QualType(); 7975 } 7976 7977 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7978 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7979 << RHSType << RHS.get()->getSourceRange(); 7980 return QualType(); 7981 } 7982 7983 // If both types are identical, no conversion is needed. 7984 if (LHSType == RHSType) 7985 return LHSType; 7986 7987 // Now handle "real" floating types (i.e. float, double, long double). 7988 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7989 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7990 /*IsCompAssign = */ false); 7991 7992 // Finally, we have two differing integer types. 7993 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7994 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7995 } 7996 7997 /// Convert scalar operands to a vector that matches the 7998 /// condition in length. 7999 /// 8000 /// Used when handling the OpenCL conditional operator where the 8001 /// condition is a vector while the other operands are scalar. 8002 /// 8003 /// We first compute the "result type" for the scalar operands 8004 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8005 /// into a vector of that type where the length matches the condition 8006 /// vector type. s6.11.6 requires that the element types of the result 8007 /// and the condition must have the same number of bits. 8008 static QualType 8009 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8010 QualType CondTy, SourceLocation QuestionLoc) { 8011 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8012 if (ResTy.isNull()) return QualType(); 8013 8014 const VectorType *CV = CondTy->getAs<VectorType>(); 8015 assert(CV); 8016 8017 // Determine the vector result type 8018 unsigned NumElements = CV->getNumElements(); 8019 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8020 8021 // Ensure that all types have the same number of bits 8022 if (S.Context.getTypeSize(CV->getElementType()) 8023 != S.Context.getTypeSize(ResTy)) { 8024 // Since VectorTy is created internally, it does not pretty print 8025 // with an OpenCL name. Instead, we just print a description. 8026 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8027 SmallString<64> Str; 8028 llvm::raw_svector_ostream OS(Str); 8029 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8030 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8031 << CondTy << OS.str(); 8032 return QualType(); 8033 } 8034 8035 // Convert operands to the vector result type 8036 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8037 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8038 8039 return VectorTy; 8040 } 8041 8042 /// Return false if this is a valid OpenCL condition vector 8043 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8044 SourceLocation QuestionLoc) { 8045 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8046 // integral type. 8047 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8048 assert(CondTy); 8049 QualType EleTy = CondTy->getElementType(); 8050 if (EleTy->isIntegerType()) return false; 8051 8052 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8053 << Cond->getType() << Cond->getSourceRange(); 8054 return true; 8055 } 8056 8057 /// Return false if the vector condition type and the vector 8058 /// result type are compatible. 8059 /// 8060 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8061 /// number of elements, and their element types have the same number 8062 /// of bits. 8063 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8064 SourceLocation QuestionLoc) { 8065 const VectorType *CV = CondTy->getAs<VectorType>(); 8066 const VectorType *RV = VecResTy->getAs<VectorType>(); 8067 assert(CV && RV); 8068 8069 if (CV->getNumElements() != RV->getNumElements()) { 8070 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8071 << CondTy << VecResTy; 8072 return true; 8073 } 8074 8075 QualType CVE = CV->getElementType(); 8076 QualType RVE = RV->getElementType(); 8077 8078 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8079 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8080 << CondTy << VecResTy; 8081 return true; 8082 } 8083 8084 return false; 8085 } 8086 8087 /// Return the resulting type for the conditional operator in 8088 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8089 /// s6.3.i) when the condition is a vector type. 8090 static QualType 8091 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8092 ExprResult &LHS, ExprResult &RHS, 8093 SourceLocation QuestionLoc) { 8094 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8095 if (Cond.isInvalid()) 8096 return QualType(); 8097 QualType CondTy = Cond.get()->getType(); 8098 8099 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8100 return QualType(); 8101 8102 // If either operand is a vector then find the vector type of the 8103 // result as specified in OpenCL v1.1 s6.3.i. 8104 if (LHS.get()->getType()->isVectorType() || 8105 RHS.get()->getType()->isVectorType()) { 8106 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8107 /*isCompAssign*/false, 8108 /*AllowBothBool*/true, 8109 /*AllowBoolConversions*/false); 8110 if (VecResTy.isNull()) return QualType(); 8111 // The result type must match the condition type as specified in 8112 // OpenCL v1.1 s6.11.6. 8113 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8114 return QualType(); 8115 return VecResTy; 8116 } 8117 8118 // Both operands are scalar. 8119 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8120 } 8121 8122 /// Return true if the Expr is block type 8123 static bool checkBlockType(Sema &S, const Expr *E) { 8124 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8125 QualType Ty = CE->getCallee()->getType(); 8126 if (Ty->isBlockPointerType()) { 8127 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8128 return true; 8129 } 8130 } 8131 return false; 8132 } 8133 8134 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8135 /// In that case, LHS = cond. 8136 /// C99 6.5.15 8137 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8138 ExprResult &RHS, ExprValueKind &VK, 8139 ExprObjectKind &OK, 8140 SourceLocation QuestionLoc) { 8141 8142 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8143 if (!LHSResult.isUsable()) return QualType(); 8144 LHS = LHSResult; 8145 8146 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8147 if (!RHSResult.isUsable()) return QualType(); 8148 RHS = RHSResult; 8149 8150 // C++ is sufficiently different to merit its own checker. 8151 if (getLangOpts().CPlusPlus) 8152 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8153 8154 VK = VK_RValue; 8155 OK = OK_Ordinary; 8156 8157 if (Context.isDependenceAllowed() && 8158 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8159 RHS.get()->isTypeDependent())) { 8160 assert(!getLangOpts().CPlusPlus); 8161 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8162 RHS.get()->containsErrors()) && 8163 "should only occur in error-recovery path."); 8164 return Context.DependentTy; 8165 } 8166 8167 // The OpenCL operator with a vector condition is sufficiently 8168 // different to merit its own checker. 8169 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8170 Cond.get()->getType()->isExtVectorType()) 8171 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8172 8173 // First, check the condition. 8174 Cond = UsualUnaryConversions(Cond.get()); 8175 if (Cond.isInvalid()) 8176 return QualType(); 8177 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8178 return QualType(); 8179 8180 // Now check the two expressions. 8181 if (LHS.get()->getType()->isVectorType() || 8182 RHS.get()->getType()->isVectorType()) 8183 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8184 /*AllowBothBool*/true, 8185 /*AllowBoolConversions*/false); 8186 8187 QualType ResTy = 8188 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8189 if (LHS.isInvalid() || RHS.isInvalid()) 8190 return QualType(); 8191 8192 QualType LHSTy = LHS.get()->getType(); 8193 QualType RHSTy = RHS.get()->getType(); 8194 8195 // Diagnose attempts to convert between __float128 and long double where 8196 // such conversions currently can't be handled. 8197 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8198 Diag(QuestionLoc, 8199 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8201 return QualType(); 8202 } 8203 8204 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8205 // selection operator (?:). 8206 if (getLangOpts().OpenCL && 8207 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8208 return QualType(); 8209 } 8210 8211 // If both operands have arithmetic type, do the usual arithmetic conversions 8212 // to find a common type: C99 6.5.15p3,5. 8213 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8214 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8215 // different sizes, or between ExtInts and other types. 8216 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8217 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8218 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8219 << RHS.get()->getSourceRange(); 8220 return QualType(); 8221 } 8222 8223 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8224 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8225 8226 return ResTy; 8227 } 8228 8229 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8230 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8231 return LHSTy; 8232 } 8233 8234 // If both operands are the same structure or union type, the result is that 8235 // type. 8236 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8237 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8238 if (LHSRT->getDecl() == RHSRT->getDecl()) 8239 // "If both the operands have structure or union type, the result has 8240 // that type." This implies that CV qualifiers are dropped. 8241 return LHSTy.getUnqualifiedType(); 8242 // FIXME: Type of conditional expression must be complete in C mode. 8243 } 8244 8245 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8246 // The following || allows only one side to be void (a GCC-ism). 8247 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8248 return checkConditionalVoidType(*this, LHS, RHS); 8249 } 8250 8251 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8252 // the type of the other operand." 8253 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8254 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8255 8256 // All objective-c pointer type analysis is done here. 8257 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8258 QuestionLoc); 8259 if (LHS.isInvalid() || RHS.isInvalid()) 8260 return QualType(); 8261 if (!compositeType.isNull()) 8262 return compositeType; 8263 8264 8265 // Handle block pointer types. 8266 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8267 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8268 QuestionLoc); 8269 8270 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8271 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8272 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8273 QuestionLoc); 8274 8275 // GCC compatibility: soften pointer/integer mismatch. Note that 8276 // null pointers have been filtered out by this point. 8277 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8278 /*IsIntFirstExpr=*/true)) 8279 return RHSTy; 8280 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8281 /*IsIntFirstExpr=*/false)) 8282 return LHSTy; 8283 8284 // Allow ?: operations in which both operands have the same 8285 // built-in sizeless type. 8286 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8287 return LHSTy; 8288 8289 // Emit a better diagnostic if one of the expressions is a null pointer 8290 // constant and the other is not a pointer type. In this case, the user most 8291 // likely forgot to take the address of the other expression. 8292 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8293 return QualType(); 8294 8295 // Otherwise, the operands are not compatible. 8296 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8297 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8298 << RHS.get()->getSourceRange(); 8299 return QualType(); 8300 } 8301 8302 /// FindCompositeObjCPointerType - Helper method to find composite type of 8303 /// two objective-c pointer types of the two input expressions. 8304 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8305 SourceLocation QuestionLoc) { 8306 QualType LHSTy = LHS.get()->getType(); 8307 QualType RHSTy = RHS.get()->getType(); 8308 8309 // Handle things like Class and struct objc_class*. Here we case the result 8310 // to the pseudo-builtin, because that will be implicitly cast back to the 8311 // redefinition type if an attempt is made to access its fields. 8312 if (LHSTy->isObjCClassType() && 8313 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8314 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8315 return LHSTy; 8316 } 8317 if (RHSTy->isObjCClassType() && 8318 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8319 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8320 return RHSTy; 8321 } 8322 // And the same for struct objc_object* / id 8323 if (LHSTy->isObjCIdType() && 8324 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8325 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8326 return LHSTy; 8327 } 8328 if (RHSTy->isObjCIdType() && 8329 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8330 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8331 return RHSTy; 8332 } 8333 // And the same for struct objc_selector* / SEL 8334 if (Context.isObjCSelType(LHSTy) && 8335 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8336 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8337 return LHSTy; 8338 } 8339 if (Context.isObjCSelType(RHSTy) && 8340 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8341 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8342 return RHSTy; 8343 } 8344 // Check constraints for Objective-C object pointers types. 8345 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8346 8347 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8348 // Two identical object pointer types are always compatible. 8349 return LHSTy; 8350 } 8351 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8352 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8353 QualType compositeType = LHSTy; 8354 8355 // If both operands are interfaces and either operand can be 8356 // assigned to the other, use that type as the composite 8357 // type. This allows 8358 // xxx ? (A*) a : (B*) b 8359 // where B is a subclass of A. 8360 // 8361 // Additionally, as for assignment, if either type is 'id' 8362 // allow silent coercion. Finally, if the types are 8363 // incompatible then make sure to use 'id' as the composite 8364 // type so the result is acceptable for sending messages to. 8365 8366 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8367 // It could return the composite type. 8368 if (!(compositeType = 8369 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8370 // Nothing more to do. 8371 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8372 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8373 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8374 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8375 } else if ((LHSOPT->isObjCQualifiedIdType() || 8376 RHSOPT->isObjCQualifiedIdType()) && 8377 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8378 true)) { 8379 // Need to handle "id<xx>" explicitly. 8380 // GCC allows qualified id and any Objective-C type to devolve to 8381 // id. Currently localizing to here until clear this should be 8382 // part of ObjCQualifiedIdTypesAreCompatible. 8383 compositeType = Context.getObjCIdType(); 8384 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8385 compositeType = Context.getObjCIdType(); 8386 } else { 8387 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8388 << LHSTy << RHSTy 8389 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8390 QualType incompatTy = Context.getObjCIdType(); 8391 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8392 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8393 return incompatTy; 8394 } 8395 // The object pointer types are compatible. 8396 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8397 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8398 return compositeType; 8399 } 8400 // Check Objective-C object pointer types and 'void *' 8401 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8402 if (getLangOpts().ObjCAutoRefCount) { 8403 // ARC forbids the implicit conversion of object pointers to 'void *', 8404 // so these types are not compatible. 8405 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8406 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8407 LHS = RHS = true; 8408 return QualType(); 8409 } 8410 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8411 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8412 QualType destPointee 8413 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8414 QualType destType = Context.getPointerType(destPointee); 8415 // Add qualifiers if necessary. 8416 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8417 // Promote to void*. 8418 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8419 return destType; 8420 } 8421 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8422 if (getLangOpts().ObjCAutoRefCount) { 8423 // ARC forbids the implicit conversion of object pointers to 'void *', 8424 // so these types are not compatible. 8425 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8426 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8427 LHS = RHS = true; 8428 return QualType(); 8429 } 8430 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8431 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8432 QualType destPointee 8433 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8434 QualType destType = Context.getPointerType(destPointee); 8435 // Add qualifiers if necessary. 8436 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8437 // Promote to void*. 8438 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8439 return destType; 8440 } 8441 return QualType(); 8442 } 8443 8444 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8445 /// ParenRange in parentheses. 8446 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8447 const PartialDiagnostic &Note, 8448 SourceRange ParenRange) { 8449 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8450 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8451 EndLoc.isValid()) { 8452 Self.Diag(Loc, Note) 8453 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8454 << FixItHint::CreateInsertion(EndLoc, ")"); 8455 } else { 8456 // We can't display the parentheses, so just show the bare note. 8457 Self.Diag(Loc, Note) << ParenRange; 8458 } 8459 } 8460 8461 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8462 return BinaryOperator::isAdditiveOp(Opc) || 8463 BinaryOperator::isMultiplicativeOp(Opc) || 8464 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8465 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8466 // not any of the logical operators. Bitwise-xor is commonly used as a 8467 // logical-xor because there is no logical-xor operator. The logical 8468 // operators, including uses of xor, have a high false positive rate for 8469 // precedence warnings. 8470 } 8471 8472 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8473 /// expression, either using a built-in or overloaded operator, 8474 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8475 /// expression. 8476 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8477 Expr **RHSExprs) { 8478 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8479 E = E->IgnoreImpCasts(); 8480 E = E->IgnoreConversionOperatorSingleStep(); 8481 E = E->IgnoreImpCasts(); 8482 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8483 E = MTE->getSubExpr(); 8484 E = E->IgnoreImpCasts(); 8485 } 8486 8487 // Built-in binary operator. 8488 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8489 if (IsArithmeticOp(OP->getOpcode())) { 8490 *Opcode = OP->getOpcode(); 8491 *RHSExprs = OP->getRHS(); 8492 return true; 8493 } 8494 } 8495 8496 // Overloaded operator. 8497 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8498 if (Call->getNumArgs() != 2) 8499 return false; 8500 8501 // Make sure this is really a binary operator that is safe to pass into 8502 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8503 OverloadedOperatorKind OO = Call->getOperator(); 8504 if (OO < OO_Plus || OO > OO_Arrow || 8505 OO == OO_PlusPlus || OO == OO_MinusMinus) 8506 return false; 8507 8508 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8509 if (IsArithmeticOp(OpKind)) { 8510 *Opcode = OpKind; 8511 *RHSExprs = Call->getArg(1); 8512 return true; 8513 } 8514 } 8515 8516 return false; 8517 } 8518 8519 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8520 /// or is a logical expression such as (x==y) which has int type, but is 8521 /// commonly interpreted as boolean. 8522 static bool ExprLooksBoolean(Expr *E) { 8523 E = E->IgnoreParenImpCasts(); 8524 8525 if (E->getType()->isBooleanType()) 8526 return true; 8527 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8528 return OP->isComparisonOp() || OP->isLogicalOp(); 8529 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8530 return OP->getOpcode() == UO_LNot; 8531 if (E->getType()->isPointerType()) 8532 return true; 8533 // FIXME: What about overloaded operator calls returning "unspecified boolean 8534 // type"s (commonly pointer-to-members)? 8535 8536 return false; 8537 } 8538 8539 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8540 /// and binary operator are mixed in a way that suggests the programmer assumed 8541 /// the conditional operator has higher precedence, for example: 8542 /// "int x = a + someBinaryCondition ? 1 : 2". 8543 static void DiagnoseConditionalPrecedence(Sema &Self, 8544 SourceLocation OpLoc, 8545 Expr *Condition, 8546 Expr *LHSExpr, 8547 Expr *RHSExpr) { 8548 BinaryOperatorKind CondOpcode; 8549 Expr *CondRHS; 8550 8551 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8552 return; 8553 if (!ExprLooksBoolean(CondRHS)) 8554 return; 8555 8556 // The condition is an arithmetic binary expression, with a right- 8557 // hand side that looks boolean, so warn. 8558 8559 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8560 ? diag::warn_precedence_bitwise_conditional 8561 : diag::warn_precedence_conditional; 8562 8563 Self.Diag(OpLoc, DiagID) 8564 << Condition->getSourceRange() 8565 << BinaryOperator::getOpcodeStr(CondOpcode); 8566 8567 SuggestParentheses( 8568 Self, OpLoc, 8569 Self.PDiag(diag::note_precedence_silence) 8570 << BinaryOperator::getOpcodeStr(CondOpcode), 8571 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8572 8573 SuggestParentheses(Self, OpLoc, 8574 Self.PDiag(diag::note_precedence_conditional_first), 8575 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8576 } 8577 8578 /// Compute the nullability of a conditional expression. 8579 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8580 QualType LHSTy, QualType RHSTy, 8581 ASTContext &Ctx) { 8582 if (!ResTy->isAnyPointerType()) 8583 return ResTy; 8584 8585 auto GetNullability = [&Ctx](QualType Ty) { 8586 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8587 if (Kind) { 8588 // For our purposes, treat _Nullable_result as _Nullable. 8589 if (*Kind == NullabilityKind::NullableResult) 8590 return NullabilityKind::Nullable; 8591 return *Kind; 8592 } 8593 return NullabilityKind::Unspecified; 8594 }; 8595 8596 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8597 NullabilityKind MergedKind; 8598 8599 // Compute nullability of a binary conditional expression. 8600 if (IsBin) { 8601 if (LHSKind == NullabilityKind::NonNull) 8602 MergedKind = NullabilityKind::NonNull; 8603 else 8604 MergedKind = RHSKind; 8605 // Compute nullability of a normal conditional expression. 8606 } else { 8607 if (LHSKind == NullabilityKind::Nullable || 8608 RHSKind == NullabilityKind::Nullable) 8609 MergedKind = NullabilityKind::Nullable; 8610 else if (LHSKind == NullabilityKind::NonNull) 8611 MergedKind = RHSKind; 8612 else if (RHSKind == NullabilityKind::NonNull) 8613 MergedKind = LHSKind; 8614 else 8615 MergedKind = NullabilityKind::Unspecified; 8616 } 8617 8618 // Return if ResTy already has the correct nullability. 8619 if (GetNullability(ResTy) == MergedKind) 8620 return ResTy; 8621 8622 // Strip all nullability from ResTy. 8623 while (ResTy->getNullability(Ctx)) 8624 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8625 8626 // Create a new AttributedType with the new nullability kind. 8627 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8628 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8629 } 8630 8631 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8632 /// in the case of a the GNU conditional expr extension. 8633 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8634 SourceLocation ColonLoc, 8635 Expr *CondExpr, Expr *LHSExpr, 8636 Expr *RHSExpr) { 8637 if (!Context.isDependenceAllowed()) { 8638 // C cannot handle TypoExpr nodes in the condition because it 8639 // doesn't handle dependent types properly, so make sure any TypoExprs have 8640 // been dealt with before checking the operands. 8641 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8642 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8643 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8644 8645 if (!CondResult.isUsable()) 8646 return ExprError(); 8647 8648 if (LHSExpr) { 8649 if (!LHSResult.isUsable()) 8650 return ExprError(); 8651 } 8652 8653 if (!RHSResult.isUsable()) 8654 return ExprError(); 8655 8656 CondExpr = CondResult.get(); 8657 LHSExpr = LHSResult.get(); 8658 RHSExpr = RHSResult.get(); 8659 } 8660 8661 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8662 // was the condition. 8663 OpaqueValueExpr *opaqueValue = nullptr; 8664 Expr *commonExpr = nullptr; 8665 if (!LHSExpr) { 8666 commonExpr = CondExpr; 8667 // Lower out placeholder types first. This is important so that we don't 8668 // try to capture a placeholder. This happens in few cases in C++; such 8669 // as Objective-C++'s dictionary subscripting syntax. 8670 if (commonExpr->hasPlaceholderType()) { 8671 ExprResult result = CheckPlaceholderExpr(commonExpr); 8672 if (!result.isUsable()) return ExprError(); 8673 commonExpr = result.get(); 8674 } 8675 // We usually want to apply unary conversions *before* saving, except 8676 // in the special case of a C++ l-value conditional. 8677 if (!(getLangOpts().CPlusPlus 8678 && !commonExpr->isTypeDependent() 8679 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8680 && commonExpr->isGLValue() 8681 && commonExpr->isOrdinaryOrBitFieldObject() 8682 && RHSExpr->isOrdinaryOrBitFieldObject() 8683 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8684 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8685 if (commonRes.isInvalid()) 8686 return ExprError(); 8687 commonExpr = commonRes.get(); 8688 } 8689 8690 // If the common expression is a class or array prvalue, materialize it 8691 // so that we can safely refer to it multiple times. 8692 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8693 commonExpr->getType()->isArrayType())) { 8694 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8695 if (MatExpr.isInvalid()) 8696 return ExprError(); 8697 commonExpr = MatExpr.get(); 8698 } 8699 8700 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8701 commonExpr->getType(), 8702 commonExpr->getValueKind(), 8703 commonExpr->getObjectKind(), 8704 commonExpr); 8705 LHSExpr = CondExpr = opaqueValue; 8706 } 8707 8708 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8709 ExprValueKind VK = VK_RValue; 8710 ExprObjectKind OK = OK_Ordinary; 8711 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8712 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8713 VK, OK, QuestionLoc); 8714 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8715 RHS.isInvalid()) 8716 return ExprError(); 8717 8718 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8719 RHS.get()); 8720 8721 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8722 8723 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8724 Context); 8725 8726 if (!commonExpr) 8727 return new (Context) 8728 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8729 RHS.get(), result, VK, OK); 8730 8731 return new (Context) BinaryConditionalOperator( 8732 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8733 ColonLoc, result, VK, OK); 8734 } 8735 8736 // Check if we have a conversion between incompatible cmse function pointer 8737 // types, that is, a conversion between a function pointer with the 8738 // cmse_nonsecure_call attribute and one without. 8739 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8740 QualType ToType) { 8741 if (const auto *ToFn = 8742 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8743 if (const auto *FromFn = 8744 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8745 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8746 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8747 8748 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8749 } 8750 } 8751 return false; 8752 } 8753 8754 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8755 // being closely modeled after the C99 spec:-). The odd characteristic of this 8756 // routine is it effectively iqnores the qualifiers on the top level pointee. 8757 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8758 // FIXME: add a couple examples in this comment. 8759 static Sema::AssignConvertType 8760 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8761 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8762 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8763 8764 // get the "pointed to" type (ignoring qualifiers at the top level) 8765 const Type *lhptee, *rhptee; 8766 Qualifiers lhq, rhq; 8767 std::tie(lhptee, lhq) = 8768 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8769 std::tie(rhptee, rhq) = 8770 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8771 8772 Sema::AssignConvertType ConvTy = Sema::Compatible; 8773 8774 // C99 6.5.16.1p1: This following citation is common to constraints 8775 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8776 // qualifiers of the type *pointed to* by the right; 8777 8778 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8779 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8780 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8781 // Ignore lifetime for further calculation. 8782 lhq.removeObjCLifetime(); 8783 rhq.removeObjCLifetime(); 8784 } 8785 8786 if (!lhq.compatiblyIncludes(rhq)) { 8787 // Treat address-space mismatches as fatal. 8788 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8789 return Sema::IncompatiblePointerDiscardsQualifiers; 8790 8791 // It's okay to add or remove GC or lifetime qualifiers when converting to 8792 // and from void*. 8793 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8794 .compatiblyIncludes( 8795 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8796 && (lhptee->isVoidType() || rhptee->isVoidType())) 8797 ; // keep old 8798 8799 // Treat lifetime mismatches as fatal. 8800 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8801 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8802 8803 // For GCC/MS compatibility, other qualifier mismatches are treated 8804 // as still compatible in C. 8805 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8806 } 8807 8808 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8809 // incomplete type and the other is a pointer to a qualified or unqualified 8810 // version of void... 8811 if (lhptee->isVoidType()) { 8812 if (rhptee->isIncompleteOrObjectType()) 8813 return ConvTy; 8814 8815 // As an extension, we allow cast to/from void* to function pointer. 8816 assert(rhptee->isFunctionType()); 8817 return Sema::FunctionVoidPointer; 8818 } 8819 8820 if (rhptee->isVoidType()) { 8821 if (lhptee->isIncompleteOrObjectType()) 8822 return ConvTy; 8823 8824 // As an extension, we allow cast to/from void* to function pointer. 8825 assert(lhptee->isFunctionType()); 8826 return Sema::FunctionVoidPointer; 8827 } 8828 8829 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8830 // unqualified versions of compatible types, ... 8831 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8832 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8833 // Check if the pointee types are compatible ignoring the sign. 8834 // We explicitly check for char so that we catch "char" vs 8835 // "unsigned char" on systems where "char" is unsigned. 8836 if (lhptee->isCharType()) 8837 ltrans = S.Context.UnsignedCharTy; 8838 else if (lhptee->hasSignedIntegerRepresentation()) 8839 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8840 8841 if (rhptee->isCharType()) 8842 rtrans = S.Context.UnsignedCharTy; 8843 else if (rhptee->hasSignedIntegerRepresentation()) 8844 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8845 8846 if (ltrans == rtrans) { 8847 // Types are compatible ignoring the sign. Qualifier incompatibility 8848 // takes priority over sign incompatibility because the sign 8849 // warning can be disabled. 8850 if (ConvTy != Sema::Compatible) 8851 return ConvTy; 8852 8853 return Sema::IncompatiblePointerSign; 8854 } 8855 8856 // If we are a multi-level pointer, it's possible that our issue is simply 8857 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8858 // the eventual target type is the same and the pointers have the same 8859 // level of indirection, this must be the issue. 8860 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8861 do { 8862 std::tie(lhptee, lhq) = 8863 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8864 std::tie(rhptee, rhq) = 8865 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8866 8867 // Inconsistent address spaces at this point is invalid, even if the 8868 // address spaces would be compatible. 8869 // FIXME: This doesn't catch address space mismatches for pointers of 8870 // different nesting levels, like: 8871 // __local int *** a; 8872 // int ** b = a; 8873 // It's not clear how to actually determine when such pointers are 8874 // invalidly incompatible. 8875 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8876 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8877 8878 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8879 8880 if (lhptee == rhptee) 8881 return Sema::IncompatibleNestedPointerQualifiers; 8882 } 8883 8884 // General pointer incompatibility takes priority over qualifiers. 8885 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8886 return Sema::IncompatibleFunctionPointer; 8887 return Sema::IncompatiblePointer; 8888 } 8889 if (!S.getLangOpts().CPlusPlus && 8890 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8891 return Sema::IncompatibleFunctionPointer; 8892 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8893 return Sema::IncompatibleFunctionPointer; 8894 return ConvTy; 8895 } 8896 8897 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8898 /// block pointer types are compatible or whether a block and normal pointer 8899 /// are compatible. It is more restrict than comparing two function pointer 8900 // types. 8901 static Sema::AssignConvertType 8902 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8903 QualType RHSType) { 8904 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8905 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8906 8907 QualType lhptee, rhptee; 8908 8909 // get the "pointed to" type (ignoring qualifiers at the top level) 8910 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8911 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8912 8913 // In C++, the types have to match exactly. 8914 if (S.getLangOpts().CPlusPlus) 8915 return Sema::IncompatibleBlockPointer; 8916 8917 Sema::AssignConvertType ConvTy = Sema::Compatible; 8918 8919 // For blocks we enforce that qualifiers are identical. 8920 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8921 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8922 if (S.getLangOpts().OpenCL) { 8923 LQuals.removeAddressSpace(); 8924 RQuals.removeAddressSpace(); 8925 } 8926 if (LQuals != RQuals) 8927 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8928 8929 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8930 // assignment. 8931 // The current behavior is similar to C++ lambdas. A block might be 8932 // assigned to a variable iff its return type and parameters are compatible 8933 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8934 // an assignment. Presumably it should behave in way that a function pointer 8935 // assignment does in C, so for each parameter and return type: 8936 // * CVR and address space of LHS should be a superset of CVR and address 8937 // space of RHS. 8938 // * unqualified types should be compatible. 8939 if (S.getLangOpts().OpenCL) { 8940 if (!S.Context.typesAreBlockPointerCompatible( 8941 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8942 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8943 return Sema::IncompatibleBlockPointer; 8944 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8945 return Sema::IncompatibleBlockPointer; 8946 8947 return ConvTy; 8948 } 8949 8950 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8951 /// for assignment compatibility. 8952 static Sema::AssignConvertType 8953 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8954 QualType RHSType) { 8955 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8956 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8957 8958 if (LHSType->isObjCBuiltinType()) { 8959 // Class is not compatible with ObjC object pointers. 8960 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8961 !RHSType->isObjCQualifiedClassType()) 8962 return Sema::IncompatiblePointer; 8963 return Sema::Compatible; 8964 } 8965 if (RHSType->isObjCBuiltinType()) { 8966 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8967 !LHSType->isObjCQualifiedClassType()) 8968 return Sema::IncompatiblePointer; 8969 return Sema::Compatible; 8970 } 8971 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8972 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8973 8974 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8975 // make an exception for id<P> 8976 !LHSType->isObjCQualifiedIdType()) 8977 return Sema::CompatiblePointerDiscardsQualifiers; 8978 8979 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8980 return Sema::Compatible; 8981 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8982 return Sema::IncompatibleObjCQualifiedId; 8983 return Sema::IncompatiblePointer; 8984 } 8985 8986 Sema::AssignConvertType 8987 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8988 QualType LHSType, QualType RHSType) { 8989 // Fake up an opaque expression. We don't actually care about what 8990 // cast operations are required, so if CheckAssignmentConstraints 8991 // adds casts to this they'll be wasted, but fortunately that doesn't 8992 // usually happen on valid code. 8993 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8994 ExprResult RHSPtr = &RHSExpr; 8995 CastKind K; 8996 8997 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8998 } 8999 9000 /// This helper function returns true if QT is a vector type that has element 9001 /// type ElementType. 9002 static bool isVector(QualType QT, QualType ElementType) { 9003 if (const VectorType *VT = QT->getAs<VectorType>()) 9004 return VT->getElementType().getCanonicalType() == ElementType; 9005 return false; 9006 } 9007 9008 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9009 /// has code to accommodate several GCC extensions when type checking 9010 /// pointers. Here are some objectionable examples that GCC considers warnings: 9011 /// 9012 /// int a, *pint; 9013 /// short *pshort; 9014 /// struct foo *pfoo; 9015 /// 9016 /// pint = pshort; // warning: assignment from incompatible pointer type 9017 /// a = pint; // warning: assignment makes integer from pointer without a cast 9018 /// pint = a; // warning: assignment makes pointer from integer without a cast 9019 /// pint = pfoo; // warning: assignment from incompatible pointer type 9020 /// 9021 /// As a result, the code for dealing with pointers is more complex than the 9022 /// C99 spec dictates. 9023 /// 9024 /// Sets 'Kind' for any result kind except Incompatible. 9025 Sema::AssignConvertType 9026 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9027 CastKind &Kind, bool ConvertRHS) { 9028 QualType RHSType = RHS.get()->getType(); 9029 QualType OrigLHSType = LHSType; 9030 9031 // Get canonical types. We're not formatting these types, just comparing 9032 // them. 9033 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9034 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9035 9036 // Common case: no conversion required. 9037 if (LHSType == RHSType) { 9038 Kind = CK_NoOp; 9039 return Compatible; 9040 } 9041 9042 // If we have an atomic type, try a non-atomic assignment, then just add an 9043 // atomic qualification step. 9044 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9045 Sema::AssignConvertType result = 9046 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9047 if (result != Compatible) 9048 return result; 9049 if (Kind != CK_NoOp && ConvertRHS) 9050 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9051 Kind = CK_NonAtomicToAtomic; 9052 return Compatible; 9053 } 9054 9055 // If the left-hand side is a reference type, then we are in a 9056 // (rare!) case where we've allowed the use of references in C, 9057 // e.g., as a parameter type in a built-in function. In this case, 9058 // just make sure that the type referenced is compatible with the 9059 // right-hand side type. The caller is responsible for adjusting 9060 // LHSType so that the resulting expression does not have reference 9061 // type. 9062 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9063 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9064 Kind = CK_LValueBitCast; 9065 return Compatible; 9066 } 9067 return Incompatible; 9068 } 9069 9070 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9071 // to the same ExtVector type. 9072 if (LHSType->isExtVectorType()) { 9073 if (RHSType->isExtVectorType()) 9074 return Incompatible; 9075 if (RHSType->isArithmeticType()) { 9076 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9077 if (ConvertRHS) 9078 RHS = prepareVectorSplat(LHSType, RHS.get()); 9079 Kind = CK_VectorSplat; 9080 return Compatible; 9081 } 9082 } 9083 9084 // Conversions to or from vector type. 9085 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9086 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9087 // Allow assignments of an AltiVec vector type to an equivalent GCC 9088 // vector type and vice versa 9089 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9090 Kind = CK_BitCast; 9091 return Compatible; 9092 } 9093 9094 // If we are allowing lax vector conversions, and LHS and RHS are both 9095 // vectors, the total size only needs to be the same. This is a bitcast; 9096 // no bits are changed but the result type is different. 9097 if (isLaxVectorConversion(RHSType, LHSType)) { 9098 Kind = CK_BitCast; 9099 return IncompatibleVectors; 9100 } 9101 } 9102 9103 // When the RHS comes from another lax conversion (e.g. binops between 9104 // scalars and vectors) the result is canonicalized as a vector. When the 9105 // LHS is also a vector, the lax is allowed by the condition above. Handle 9106 // the case where LHS is a scalar. 9107 if (LHSType->isScalarType()) { 9108 const VectorType *VecType = RHSType->getAs<VectorType>(); 9109 if (VecType && VecType->getNumElements() == 1 && 9110 isLaxVectorConversion(RHSType, LHSType)) { 9111 ExprResult *VecExpr = &RHS; 9112 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9113 Kind = CK_BitCast; 9114 return Compatible; 9115 } 9116 } 9117 9118 // Allow assignments between fixed-length and sizeless SVE vectors. 9119 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9120 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9121 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9122 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9123 Kind = CK_BitCast; 9124 return Compatible; 9125 } 9126 9127 return Incompatible; 9128 } 9129 9130 // Diagnose attempts to convert between __float128 and long double where 9131 // such conversions currently can't be handled. 9132 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9133 return Incompatible; 9134 9135 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9136 // discards the imaginary part. 9137 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9138 !LHSType->getAs<ComplexType>()) 9139 return Incompatible; 9140 9141 // Arithmetic conversions. 9142 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9143 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9144 if (ConvertRHS) 9145 Kind = PrepareScalarCast(RHS, LHSType); 9146 return Compatible; 9147 } 9148 9149 // Conversions to normal pointers. 9150 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9151 // U* -> T* 9152 if (isa<PointerType>(RHSType)) { 9153 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9154 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9155 if (AddrSpaceL != AddrSpaceR) 9156 Kind = CK_AddressSpaceConversion; 9157 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9158 Kind = CK_NoOp; 9159 else 9160 Kind = CK_BitCast; 9161 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9162 } 9163 9164 // int -> T* 9165 if (RHSType->isIntegerType()) { 9166 Kind = CK_IntegralToPointer; // FIXME: null? 9167 return IntToPointer; 9168 } 9169 9170 // C pointers are not compatible with ObjC object pointers, 9171 // with two exceptions: 9172 if (isa<ObjCObjectPointerType>(RHSType)) { 9173 // - conversions to void* 9174 if (LHSPointer->getPointeeType()->isVoidType()) { 9175 Kind = CK_BitCast; 9176 return Compatible; 9177 } 9178 9179 // - conversions from 'Class' to the redefinition type 9180 if (RHSType->isObjCClassType() && 9181 Context.hasSameType(LHSType, 9182 Context.getObjCClassRedefinitionType())) { 9183 Kind = CK_BitCast; 9184 return Compatible; 9185 } 9186 9187 Kind = CK_BitCast; 9188 return IncompatiblePointer; 9189 } 9190 9191 // U^ -> void* 9192 if (RHSType->getAs<BlockPointerType>()) { 9193 if (LHSPointer->getPointeeType()->isVoidType()) { 9194 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9195 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9196 ->getPointeeType() 9197 .getAddressSpace(); 9198 Kind = 9199 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9200 return Compatible; 9201 } 9202 } 9203 9204 return Incompatible; 9205 } 9206 9207 // Conversions to block pointers. 9208 if (isa<BlockPointerType>(LHSType)) { 9209 // U^ -> T^ 9210 if (RHSType->isBlockPointerType()) { 9211 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9212 ->getPointeeType() 9213 .getAddressSpace(); 9214 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9215 ->getPointeeType() 9216 .getAddressSpace(); 9217 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9218 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9219 } 9220 9221 // int or null -> T^ 9222 if (RHSType->isIntegerType()) { 9223 Kind = CK_IntegralToPointer; // FIXME: null 9224 return IntToBlockPointer; 9225 } 9226 9227 // id -> T^ 9228 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9229 Kind = CK_AnyPointerToBlockPointerCast; 9230 return Compatible; 9231 } 9232 9233 // void* -> T^ 9234 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9235 if (RHSPT->getPointeeType()->isVoidType()) { 9236 Kind = CK_AnyPointerToBlockPointerCast; 9237 return Compatible; 9238 } 9239 9240 return Incompatible; 9241 } 9242 9243 // Conversions to Objective-C pointers. 9244 if (isa<ObjCObjectPointerType>(LHSType)) { 9245 // A* -> B* 9246 if (RHSType->isObjCObjectPointerType()) { 9247 Kind = CK_BitCast; 9248 Sema::AssignConvertType result = 9249 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9250 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9251 result == Compatible && 9252 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9253 result = IncompatibleObjCWeakRef; 9254 return result; 9255 } 9256 9257 // int or null -> A* 9258 if (RHSType->isIntegerType()) { 9259 Kind = CK_IntegralToPointer; // FIXME: null 9260 return IntToPointer; 9261 } 9262 9263 // In general, C pointers are not compatible with ObjC object pointers, 9264 // with two exceptions: 9265 if (isa<PointerType>(RHSType)) { 9266 Kind = CK_CPointerToObjCPointerCast; 9267 9268 // - conversions from 'void*' 9269 if (RHSType->isVoidPointerType()) { 9270 return Compatible; 9271 } 9272 9273 // - conversions to 'Class' from its redefinition type 9274 if (LHSType->isObjCClassType() && 9275 Context.hasSameType(RHSType, 9276 Context.getObjCClassRedefinitionType())) { 9277 return Compatible; 9278 } 9279 9280 return IncompatiblePointer; 9281 } 9282 9283 // Only under strict condition T^ is compatible with an Objective-C pointer. 9284 if (RHSType->isBlockPointerType() && 9285 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9286 if (ConvertRHS) 9287 maybeExtendBlockObject(RHS); 9288 Kind = CK_BlockPointerToObjCPointerCast; 9289 return Compatible; 9290 } 9291 9292 return Incompatible; 9293 } 9294 9295 // Conversions from pointers that are not covered by the above. 9296 if (isa<PointerType>(RHSType)) { 9297 // T* -> _Bool 9298 if (LHSType == Context.BoolTy) { 9299 Kind = CK_PointerToBoolean; 9300 return Compatible; 9301 } 9302 9303 // T* -> int 9304 if (LHSType->isIntegerType()) { 9305 Kind = CK_PointerToIntegral; 9306 return PointerToInt; 9307 } 9308 9309 return Incompatible; 9310 } 9311 9312 // Conversions from Objective-C pointers that are not covered by the above. 9313 if (isa<ObjCObjectPointerType>(RHSType)) { 9314 // T* -> _Bool 9315 if (LHSType == Context.BoolTy) { 9316 Kind = CK_PointerToBoolean; 9317 return Compatible; 9318 } 9319 9320 // T* -> int 9321 if (LHSType->isIntegerType()) { 9322 Kind = CK_PointerToIntegral; 9323 return PointerToInt; 9324 } 9325 9326 return Incompatible; 9327 } 9328 9329 // struct A -> struct B 9330 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9331 if (Context.typesAreCompatible(LHSType, RHSType)) { 9332 Kind = CK_NoOp; 9333 return Compatible; 9334 } 9335 } 9336 9337 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9338 Kind = CK_IntToOCLSampler; 9339 return Compatible; 9340 } 9341 9342 return Incompatible; 9343 } 9344 9345 /// Constructs a transparent union from an expression that is 9346 /// used to initialize the transparent union. 9347 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9348 ExprResult &EResult, QualType UnionType, 9349 FieldDecl *Field) { 9350 // Build an initializer list that designates the appropriate member 9351 // of the transparent union. 9352 Expr *E = EResult.get(); 9353 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9354 E, SourceLocation()); 9355 Initializer->setType(UnionType); 9356 Initializer->setInitializedFieldInUnion(Field); 9357 9358 // Build a compound literal constructing a value of the transparent 9359 // union type from this initializer list. 9360 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9361 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9362 VK_RValue, Initializer, false); 9363 } 9364 9365 Sema::AssignConvertType 9366 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9367 ExprResult &RHS) { 9368 QualType RHSType = RHS.get()->getType(); 9369 9370 // If the ArgType is a Union type, we want to handle a potential 9371 // transparent_union GCC extension. 9372 const RecordType *UT = ArgType->getAsUnionType(); 9373 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9374 return Incompatible; 9375 9376 // The field to initialize within the transparent union. 9377 RecordDecl *UD = UT->getDecl(); 9378 FieldDecl *InitField = nullptr; 9379 // It's compatible if the expression matches any of the fields. 9380 for (auto *it : UD->fields()) { 9381 if (it->getType()->isPointerType()) { 9382 // If the transparent union contains a pointer type, we allow: 9383 // 1) void pointer 9384 // 2) null pointer constant 9385 if (RHSType->isPointerType()) 9386 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9387 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9388 InitField = it; 9389 break; 9390 } 9391 9392 if (RHS.get()->isNullPointerConstant(Context, 9393 Expr::NPC_ValueDependentIsNull)) { 9394 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9395 CK_NullToPointer); 9396 InitField = it; 9397 break; 9398 } 9399 } 9400 9401 CastKind Kind; 9402 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9403 == Compatible) { 9404 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9405 InitField = it; 9406 break; 9407 } 9408 } 9409 9410 if (!InitField) 9411 return Incompatible; 9412 9413 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9414 return Compatible; 9415 } 9416 9417 Sema::AssignConvertType 9418 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9419 bool Diagnose, 9420 bool DiagnoseCFAudited, 9421 bool ConvertRHS) { 9422 // We need to be able to tell the caller whether we diagnosed a problem, if 9423 // they ask us to issue diagnostics. 9424 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9425 9426 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9427 // we can't avoid *all* modifications at the moment, so we need some somewhere 9428 // to put the updated value. 9429 ExprResult LocalRHS = CallerRHS; 9430 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9431 9432 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9433 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9434 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9435 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9436 Diag(RHS.get()->getExprLoc(), 9437 diag::warn_noderef_to_dereferenceable_pointer) 9438 << RHS.get()->getSourceRange(); 9439 } 9440 } 9441 } 9442 9443 if (getLangOpts().CPlusPlus) { 9444 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9445 // C++ 5.17p3: If the left operand is not of class type, the 9446 // expression is implicitly converted (C++ 4) to the 9447 // cv-unqualified type of the left operand. 9448 QualType RHSType = RHS.get()->getType(); 9449 if (Diagnose) { 9450 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9451 AA_Assigning); 9452 } else { 9453 ImplicitConversionSequence ICS = 9454 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9455 /*SuppressUserConversions=*/false, 9456 AllowedExplicit::None, 9457 /*InOverloadResolution=*/false, 9458 /*CStyle=*/false, 9459 /*AllowObjCWritebackConversion=*/false); 9460 if (ICS.isFailure()) 9461 return Incompatible; 9462 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9463 ICS, AA_Assigning); 9464 } 9465 if (RHS.isInvalid()) 9466 return Incompatible; 9467 Sema::AssignConvertType result = Compatible; 9468 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9469 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9470 result = IncompatibleObjCWeakRef; 9471 return result; 9472 } 9473 9474 // FIXME: Currently, we fall through and treat C++ classes like C 9475 // structures. 9476 // FIXME: We also fall through for atomics; not sure what should 9477 // happen there, though. 9478 } else if (RHS.get()->getType() == Context.OverloadTy) { 9479 // As a set of extensions to C, we support overloading on functions. These 9480 // functions need to be resolved here. 9481 DeclAccessPair DAP; 9482 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9483 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9484 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9485 else 9486 return Incompatible; 9487 } 9488 9489 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9490 // a null pointer constant. 9491 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9492 LHSType->isBlockPointerType()) && 9493 RHS.get()->isNullPointerConstant(Context, 9494 Expr::NPC_ValueDependentIsNull)) { 9495 if (Diagnose || ConvertRHS) { 9496 CastKind Kind; 9497 CXXCastPath Path; 9498 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9499 /*IgnoreBaseAccess=*/false, Diagnose); 9500 if (ConvertRHS) 9501 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9502 } 9503 return Compatible; 9504 } 9505 9506 // OpenCL queue_t type assignment. 9507 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9508 Context, Expr::NPC_ValueDependentIsNull)) { 9509 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9510 return Compatible; 9511 } 9512 9513 // This check seems unnatural, however it is necessary to ensure the proper 9514 // conversion of functions/arrays. If the conversion were done for all 9515 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9516 // expressions that suppress this implicit conversion (&, sizeof). 9517 // 9518 // Suppress this for references: C++ 8.5.3p5. 9519 if (!LHSType->isReferenceType()) { 9520 // FIXME: We potentially allocate here even if ConvertRHS is false. 9521 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9522 if (RHS.isInvalid()) 9523 return Incompatible; 9524 } 9525 CastKind Kind; 9526 Sema::AssignConvertType result = 9527 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9528 9529 // C99 6.5.16.1p2: The value of the right operand is converted to the 9530 // type of the assignment expression. 9531 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9532 // so that we can use references in built-in functions even in C. 9533 // The getNonReferenceType() call makes sure that the resulting expression 9534 // does not have reference type. 9535 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9536 QualType Ty = LHSType.getNonLValueExprType(Context); 9537 Expr *E = RHS.get(); 9538 9539 // Check for various Objective-C errors. If we are not reporting 9540 // diagnostics and just checking for errors, e.g., during overload 9541 // resolution, return Incompatible to indicate the failure. 9542 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9543 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9544 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9545 if (!Diagnose) 9546 return Incompatible; 9547 } 9548 if (getLangOpts().ObjC && 9549 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9550 E->getType(), E, Diagnose) || 9551 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9552 if (!Diagnose) 9553 return Incompatible; 9554 // Replace the expression with a corrected version and continue so we 9555 // can find further errors. 9556 RHS = E; 9557 return Compatible; 9558 } 9559 9560 if (ConvertRHS) 9561 RHS = ImpCastExprToType(E, Ty, Kind); 9562 } 9563 9564 return result; 9565 } 9566 9567 namespace { 9568 /// The original operand to an operator, prior to the application of the usual 9569 /// arithmetic conversions and converting the arguments of a builtin operator 9570 /// candidate. 9571 struct OriginalOperand { 9572 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9573 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9574 Op = MTE->getSubExpr(); 9575 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9576 Op = BTE->getSubExpr(); 9577 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9578 Orig = ICE->getSubExprAsWritten(); 9579 Conversion = ICE->getConversionFunction(); 9580 } 9581 } 9582 9583 QualType getType() const { return Orig->getType(); } 9584 9585 Expr *Orig; 9586 NamedDecl *Conversion; 9587 }; 9588 } 9589 9590 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9591 ExprResult &RHS) { 9592 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9593 9594 Diag(Loc, diag::err_typecheck_invalid_operands) 9595 << OrigLHS.getType() << OrigRHS.getType() 9596 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9597 9598 // If a user-defined conversion was applied to either of the operands prior 9599 // to applying the built-in operator rules, tell the user about it. 9600 if (OrigLHS.Conversion) { 9601 Diag(OrigLHS.Conversion->getLocation(), 9602 diag::note_typecheck_invalid_operands_converted) 9603 << 0 << LHS.get()->getType(); 9604 } 9605 if (OrigRHS.Conversion) { 9606 Diag(OrigRHS.Conversion->getLocation(), 9607 diag::note_typecheck_invalid_operands_converted) 9608 << 1 << RHS.get()->getType(); 9609 } 9610 9611 return QualType(); 9612 } 9613 9614 // Diagnose cases where a scalar was implicitly converted to a vector and 9615 // diagnose the underlying types. Otherwise, diagnose the error 9616 // as invalid vector logical operands for non-C++ cases. 9617 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9618 ExprResult &RHS) { 9619 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9620 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9621 9622 bool LHSNatVec = LHSType->isVectorType(); 9623 bool RHSNatVec = RHSType->isVectorType(); 9624 9625 if (!(LHSNatVec && RHSNatVec)) { 9626 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9627 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9628 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9629 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9630 << Vector->getSourceRange(); 9631 return QualType(); 9632 } 9633 9634 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9635 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9636 << RHS.get()->getSourceRange(); 9637 9638 return QualType(); 9639 } 9640 9641 /// Try to convert a value of non-vector type to a vector type by converting 9642 /// the type to the element type of the vector and then performing a splat. 9643 /// If the language is OpenCL, we only use conversions that promote scalar 9644 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9645 /// for float->int. 9646 /// 9647 /// OpenCL V2.0 6.2.6.p2: 9648 /// An error shall occur if any scalar operand type has greater rank 9649 /// than the type of the vector element. 9650 /// 9651 /// \param scalar - if non-null, actually perform the conversions 9652 /// \return true if the operation fails (but without diagnosing the failure) 9653 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9654 QualType scalarTy, 9655 QualType vectorEltTy, 9656 QualType vectorTy, 9657 unsigned &DiagID) { 9658 // The conversion to apply to the scalar before splatting it, 9659 // if necessary. 9660 CastKind scalarCast = CK_NoOp; 9661 9662 if (vectorEltTy->isIntegralType(S.Context)) { 9663 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9664 (scalarTy->isIntegerType() && 9665 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9666 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9667 return true; 9668 } 9669 if (!scalarTy->isIntegralType(S.Context)) 9670 return true; 9671 scalarCast = CK_IntegralCast; 9672 } else if (vectorEltTy->isRealFloatingType()) { 9673 if (scalarTy->isRealFloatingType()) { 9674 if (S.getLangOpts().OpenCL && 9675 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9676 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9677 return true; 9678 } 9679 scalarCast = CK_FloatingCast; 9680 } 9681 else if (scalarTy->isIntegralType(S.Context)) 9682 scalarCast = CK_IntegralToFloating; 9683 else 9684 return true; 9685 } else { 9686 return true; 9687 } 9688 9689 // Adjust scalar if desired. 9690 if (scalar) { 9691 if (scalarCast != CK_NoOp) 9692 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9693 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9694 } 9695 return false; 9696 } 9697 9698 /// Convert vector E to a vector with the same number of elements but different 9699 /// element type. 9700 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9701 const auto *VecTy = E->getType()->getAs<VectorType>(); 9702 assert(VecTy && "Expression E must be a vector"); 9703 QualType NewVecTy = S.Context.getVectorType(ElementType, 9704 VecTy->getNumElements(), 9705 VecTy->getVectorKind()); 9706 9707 // Look through the implicit cast. Return the subexpression if its type is 9708 // NewVecTy. 9709 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9710 if (ICE->getSubExpr()->getType() == NewVecTy) 9711 return ICE->getSubExpr(); 9712 9713 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9714 return S.ImpCastExprToType(E, NewVecTy, Cast); 9715 } 9716 9717 /// Test if a (constant) integer Int can be casted to another integer type 9718 /// IntTy without losing precision. 9719 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9720 QualType OtherIntTy) { 9721 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9722 9723 // Reject cases where the value of the Int is unknown as that would 9724 // possibly cause truncation, but accept cases where the scalar can be 9725 // demoted without loss of precision. 9726 Expr::EvalResult EVResult; 9727 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9728 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9729 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9730 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9731 9732 if (CstInt) { 9733 // If the scalar is constant and is of a higher order and has more active 9734 // bits that the vector element type, reject it. 9735 llvm::APSInt Result = EVResult.Val.getInt(); 9736 unsigned NumBits = IntSigned 9737 ? (Result.isNegative() ? Result.getMinSignedBits() 9738 : Result.getActiveBits()) 9739 : Result.getActiveBits(); 9740 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9741 return true; 9742 9743 // If the signedness of the scalar type and the vector element type 9744 // differs and the number of bits is greater than that of the vector 9745 // element reject it. 9746 return (IntSigned != OtherIntSigned && 9747 NumBits > S.Context.getIntWidth(OtherIntTy)); 9748 } 9749 9750 // Reject cases where the value of the scalar is not constant and it's 9751 // order is greater than that of the vector element type. 9752 return (Order < 0); 9753 } 9754 9755 /// Test if a (constant) integer Int can be casted to floating point type 9756 /// FloatTy without losing precision. 9757 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9758 QualType FloatTy) { 9759 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9760 9761 // Determine if the integer constant can be expressed as a floating point 9762 // number of the appropriate type. 9763 Expr::EvalResult EVResult; 9764 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9765 9766 uint64_t Bits = 0; 9767 if (CstInt) { 9768 // Reject constants that would be truncated if they were converted to 9769 // the floating point type. Test by simple to/from conversion. 9770 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9771 // could be avoided if there was a convertFromAPInt method 9772 // which could signal back if implicit truncation occurred. 9773 llvm::APSInt Result = EVResult.Val.getInt(); 9774 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9775 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9776 llvm::APFloat::rmTowardZero); 9777 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9778 !IntTy->hasSignedIntegerRepresentation()); 9779 bool Ignored = false; 9780 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9781 &Ignored); 9782 if (Result != ConvertBack) 9783 return true; 9784 } else { 9785 // Reject types that cannot be fully encoded into the mantissa of 9786 // the float. 9787 Bits = S.Context.getTypeSize(IntTy); 9788 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9789 S.Context.getFloatTypeSemantics(FloatTy)); 9790 if (Bits > FloatPrec) 9791 return true; 9792 } 9793 9794 return false; 9795 } 9796 9797 /// Attempt to convert and splat Scalar into a vector whose types matches 9798 /// Vector following GCC conversion rules. The rule is that implicit 9799 /// conversion can occur when Scalar can be casted to match Vector's element 9800 /// type without causing truncation of Scalar. 9801 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9802 ExprResult *Vector) { 9803 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9804 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9805 const VectorType *VT = VectorTy->getAs<VectorType>(); 9806 9807 assert(!isa<ExtVectorType>(VT) && 9808 "ExtVectorTypes should not be handled here!"); 9809 9810 QualType VectorEltTy = VT->getElementType(); 9811 9812 // Reject cases where the vector element type or the scalar element type are 9813 // not integral or floating point types. 9814 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9815 return true; 9816 9817 // The conversion to apply to the scalar before splatting it, 9818 // if necessary. 9819 CastKind ScalarCast = CK_NoOp; 9820 9821 // Accept cases where the vector elements are integers and the scalar is 9822 // an integer. 9823 // FIXME: Notionally if the scalar was a floating point value with a precise 9824 // integral representation, we could cast it to an appropriate integer 9825 // type and then perform the rest of the checks here. GCC will perform 9826 // this conversion in some cases as determined by the input language. 9827 // We should accept it on a language independent basis. 9828 if (VectorEltTy->isIntegralType(S.Context) && 9829 ScalarTy->isIntegralType(S.Context) && 9830 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9831 9832 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9833 return true; 9834 9835 ScalarCast = CK_IntegralCast; 9836 } else if (VectorEltTy->isIntegralType(S.Context) && 9837 ScalarTy->isRealFloatingType()) { 9838 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9839 ScalarCast = CK_FloatingToIntegral; 9840 else 9841 return true; 9842 } else if (VectorEltTy->isRealFloatingType()) { 9843 if (ScalarTy->isRealFloatingType()) { 9844 9845 // Reject cases where the scalar type is not a constant and has a higher 9846 // Order than the vector element type. 9847 llvm::APFloat Result(0.0); 9848 9849 // Determine whether this is a constant scalar. In the event that the 9850 // value is dependent (and thus cannot be evaluated by the constant 9851 // evaluator), skip the evaluation. This will then diagnose once the 9852 // expression is instantiated. 9853 bool CstScalar = Scalar->get()->isValueDependent() || 9854 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9855 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9856 if (!CstScalar && Order < 0) 9857 return true; 9858 9859 // If the scalar cannot be safely casted to the vector element type, 9860 // reject it. 9861 if (CstScalar) { 9862 bool Truncated = false; 9863 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9864 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9865 if (Truncated) 9866 return true; 9867 } 9868 9869 ScalarCast = CK_FloatingCast; 9870 } else if (ScalarTy->isIntegralType(S.Context)) { 9871 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9872 return true; 9873 9874 ScalarCast = CK_IntegralToFloating; 9875 } else 9876 return true; 9877 } else if (ScalarTy->isEnumeralType()) 9878 return true; 9879 9880 // Adjust scalar if desired. 9881 if (Scalar) { 9882 if (ScalarCast != CK_NoOp) 9883 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9884 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9885 } 9886 return false; 9887 } 9888 9889 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9890 SourceLocation Loc, bool IsCompAssign, 9891 bool AllowBothBool, 9892 bool AllowBoolConversions) { 9893 if (!IsCompAssign) { 9894 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9895 if (LHS.isInvalid()) 9896 return QualType(); 9897 } 9898 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9899 if (RHS.isInvalid()) 9900 return QualType(); 9901 9902 // For conversion purposes, we ignore any qualifiers. 9903 // For example, "const float" and "float" are equivalent. 9904 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9905 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9906 9907 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9908 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9909 assert(LHSVecType || RHSVecType); 9910 9911 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9912 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9913 return InvalidOperands(Loc, LHS, RHS); 9914 9915 // AltiVec-style "vector bool op vector bool" combinations are allowed 9916 // for some operators but not others. 9917 if (!AllowBothBool && 9918 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9919 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9920 return InvalidOperands(Loc, LHS, RHS); 9921 9922 // If the vector types are identical, return. 9923 if (Context.hasSameType(LHSType, RHSType)) 9924 return LHSType; 9925 9926 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9927 if (LHSVecType && RHSVecType && 9928 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9929 if (isa<ExtVectorType>(LHSVecType)) { 9930 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9931 return LHSType; 9932 } 9933 9934 if (!IsCompAssign) 9935 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9936 return RHSType; 9937 } 9938 9939 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9940 // can be mixed, with the result being the non-bool type. The non-bool 9941 // operand must have integer element type. 9942 if (AllowBoolConversions && LHSVecType && RHSVecType && 9943 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9944 (Context.getTypeSize(LHSVecType->getElementType()) == 9945 Context.getTypeSize(RHSVecType->getElementType()))) { 9946 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9947 LHSVecType->getElementType()->isIntegerType() && 9948 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9949 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9950 return LHSType; 9951 } 9952 if (!IsCompAssign && 9953 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9954 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9955 RHSVecType->getElementType()->isIntegerType()) { 9956 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9957 return RHSType; 9958 } 9959 } 9960 9961 // Expressions containing fixed-length and sizeless SVE vectors are invalid 9962 // since the ambiguity can affect the ABI. 9963 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9964 const VectorType *VecType = SecondType->getAs<VectorType>(); 9965 return FirstType->isSizelessBuiltinType() && VecType && 9966 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9967 VecType->getVectorKind() == 9968 VectorType::SveFixedLengthPredicateVector); 9969 }; 9970 9971 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9972 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 9973 return QualType(); 9974 } 9975 9976 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 9977 // since the ambiguity can affect the ABI. 9978 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 9979 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 9980 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 9981 9982 if (FirstVecType && SecondVecType) 9983 return FirstVecType->getVectorKind() == VectorType::GenericVector && 9984 (SecondVecType->getVectorKind() == 9985 VectorType::SveFixedLengthDataVector || 9986 SecondVecType->getVectorKind() == 9987 VectorType::SveFixedLengthPredicateVector); 9988 9989 return FirstType->isSizelessBuiltinType() && SecondVecType && 9990 SecondVecType->getVectorKind() == VectorType::GenericVector; 9991 }; 9992 9993 if (IsSveGnuConversion(LHSType, RHSType) || 9994 IsSveGnuConversion(RHSType, LHSType)) { 9995 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 9996 return QualType(); 9997 } 9998 9999 // If there's a vector type and a scalar, try to convert the scalar to 10000 // the vector element type and splat. 10001 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10002 if (!RHSVecType) { 10003 if (isa<ExtVectorType>(LHSVecType)) { 10004 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10005 LHSVecType->getElementType(), LHSType, 10006 DiagID)) 10007 return LHSType; 10008 } else { 10009 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10010 return LHSType; 10011 } 10012 } 10013 if (!LHSVecType) { 10014 if (isa<ExtVectorType>(RHSVecType)) { 10015 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10016 LHSType, RHSVecType->getElementType(), 10017 RHSType, DiagID)) 10018 return RHSType; 10019 } else { 10020 if (LHS.get()->getValueKind() == VK_LValue || 10021 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10022 return RHSType; 10023 } 10024 } 10025 10026 // FIXME: The code below also handles conversion between vectors and 10027 // non-scalars, we should break this down into fine grained specific checks 10028 // and emit proper diagnostics. 10029 QualType VecType = LHSVecType ? LHSType : RHSType; 10030 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10031 QualType OtherType = LHSVecType ? RHSType : LHSType; 10032 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10033 if (isLaxVectorConversion(OtherType, VecType)) { 10034 // If we're allowing lax vector conversions, only the total (data) size 10035 // needs to be the same. For non compound assignment, if one of the types is 10036 // scalar, the result is always the vector type. 10037 if (!IsCompAssign) { 10038 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10039 return VecType; 10040 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10041 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10042 // type. Note that this is already done by non-compound assignments in 10043 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10044 // <1 x T> -> T. The result is also a vector type. 10045 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10046 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10047 ExprResult *RHSExpr = &RHS; 10048 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10049 return VecType; 10050 } 10051 } 10052 10053 // Okay, the expression is invalid. 10054 10055 // If there's a non-vector, non-real operand, diagnose that. 10056 if ((!RHSVecType && !RHSType->isRealType()) || 10057 (!LHSVecType && !LHSType->isRealType())) { 10058 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10059 << LHSType << RHSType 10060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10061 return QualType(); 10062 } 10063 10064 // OpenCL V1.1 6.2.6.p1: 10065 // If the operands are of more than one vector type, then an error shall 10066 // occur. Implicit conversions between vector types are not permitted, per 10067 // section 6.2.1. 10068 if (getLangOpts().OpenCL && 10069 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10070 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10071 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10072 << RHSType; 10073 return QualType(); 10074 } 10075 10076 10077 // If there is a vector type that is not a ExtVector and a scalar, we reach 10078 // this point if scalar could not be converted to the vector's element type 10079 // without truncation. 10080 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10081 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10082 QualType Scalar = LHSVecType ? RHSType : LHSType; 10083 QualType Vector = LHSVecType ? LHSType : RHSType; 10084 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10085 Diag(Loc, 10086 diag::err_typecheck_vector_not_convertable_implict_truncation) 10087 << ScalarOrVector << Scalar << Vector; 10088 10089 return QualType(); 10090 } 10091 10092 // Otherwise, use the generic diagnostic. 10093 Diag(Loc, DiagID) 10094 << LHSType << RHSType 10095 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10096 return QualType(); 10097 } 10098 10099 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10100 // expression. These are mainly cases where the null pointer is used as an 10101 // integer instead of a pointer. 10102 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10103 SourceLocation Loc, bool IsCompare) { 10104 // The canonical way to check for a GNU null is with isNullPointerConstant, 10105 // but we use a bit of a hack here for speed; this is a relatively 10106 // hot path, and isNullPointerConstant is slow. 10107 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10108 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10109 10110 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10111 10112 // Avoid analyzing cases where the result will either be invalid (and 10113 // diagnosed as such) or entirely valid and not something to warn about. 10114 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10115 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10116 return; 10117 10118 // Comparison operations would not make sense with a null pointer no matter 10119 // what the other expression is. 10120 if (!IsCompare) { 10121 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10122 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10123 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10124 return; 10125 } 10126 10127 // The rest of the operations only make sense with a null pointer 10128 // if the other expression is a pointer. 10129 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10130 NonNullType->canDecayToPointerType()) 10131 return; 10132 10133 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10134 << LHSNull /* LHS is NULL */ << NonNullType 10135 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10136 } 10137 10138 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10139 SourceLocation Loc) { 10140 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10141 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10142 if (!LUE || !RUE) 10143 return; 10144 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10145 RUE->getKind() != UETT_SizeOf) 10146 return; 10147 10148 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10149 QualType LHSTy = LHSArg->getType(); 10150 QualType RHSTy; 10151 10152 if (RUE->isArgumentType()) 10153 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10154 else 10155 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10156 10157 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10158 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10159 return; 10160 10161 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10162 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10163 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10164 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10165 << LHSArgDecl; 10166 } 10167 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10168 QualType ArrayElemTy = ArrayTy->getElementType(); 10169 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10170 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10171 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10172 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10173 return; 10174 S.Diag(Loc, diag::warn_division_sizeof_array) 10175 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10176 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10177 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10178 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10179 << LHSArgDecl; 10180 } 10181 10182 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10183 } 10184 } 10185 10186 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10187 ExprResult &RHS, 10188 SourceLocation Loc, bool IsDiv) { 10189 // Check for division/remainder by zero. 10190 Expr::EvalResult RHSValue; 10191 if (!RHS.get()->isValueDependent() && 10192 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10193 RHSValue.Val.getInt() == 0) 10194 S.DiagRuntimeBehavior(Loc, RHS.get(), 10195 S.PDiag(diag::warn_remainder_division_by_zero) 10196 << IsDiv << RHS.get()->getSourceRange()); 10197 } 10198 10199 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10200 SourceLocation Loc, 10201 bool IsCompAssign, bool IsDiv) { 10202 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10203 10204 QualType LHSTy = LHS.get()->getType(); 10205 QualType RHSTy = RHS.get()->getType(); 10206 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10207 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10208 /*AllowBothBool*/getLangOpts().AltiVec, 10209 /*AllowBoolConversions*/false); 10210 if (!IsDiv && 10211 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10212 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10213 // For division, only matrix-by-scalar is supported. Other combinations with 10214 // matrix types are invalid. 10215 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10216 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10217 10218 QualType compType = UsualArithmeticConversions( 10219 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10220 if (LHS.isInvalid() || RHS.isInvalid()) 10221 return QualType(); 10222 10223 10224 if (compType.isNull() || !compType->isArithmeticType()) 10225 return InvalidOperands(Loc, LHS, RHS); 10226 if (IsDiv) { 10227 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10228 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10229 } 10230 return compType; 10231 } 10232 10233 QualType Sema::CheckRemainderOperands( 10234 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10235 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10236 10237 if (LHS.get()->getType()->isVectorType() || 10238 RHS.get()->getType()->isVectorType()) { 10239 if (LHS.get()->getType()->hasIntegerRepresentation() && 10240 RHS.get()->getType()->hasIntegerRepresentation()) 10241 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10242 /*AllowBothBool*/getLangOpts().AltiVec, 10243 /*AllowBoolConversions*/false); 10244 return InvalidOperands(Loc, LHS, RHS); 10245 } 10246 10247 QualType compType = UsualArithmeticConversions( 10248 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10249 if (LHS.isInvalid() || RHS.isInvalid()) 10250 return QualType(); 10251 10252 if (compType.isNull() || !compType->isIntegerType()) 10253 return InvalidOperands(Loc, LHS, RHS); 10254 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10255 return compType; 10256 } 10257 10258 /// Diagnose invalid arithmetic on two void pointers. 10259 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10260 Expr *LHSExpr, Expr *RHSExpr) { 10261 S.Diag(Loc, S.getLangOpts().CPlusPlus 10262 ? diag::err_typecheck_pointer_arith_void_type 10263 : diag::ext_gnu_void_ptr) 10264 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10265 << RHSExpr->getSourceRange(); 10266 } 10267 10268 /// Diagnose invalid arithmetic on a void pointer. 10269 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10270 Expr *Pointer) { 10271 S.Diag(Loc, S.getLangOpts().CPlusPlus 10272 ? diag::err_typecheck_pointer_arith_void_type 10273 : diag::ext_gnu_void_ptr) 10274 << 0 /* one pointer */ << Pointer->getSourceRange(); 10275 } 10276 10277 /// Diagnose invalid arithmetic on a null pointer. 10278 /// 10279 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10280 /// idiom, which we recognize as a GNU extension. 10281 /// 10282 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10283 Expr *Pointer, bool IsGNUIdiom) { 10284 if (IsGNUIdiom) 10285 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10286 << Pointer->getSourceRange(); 10287 else 10288 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10289 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10290 } 10291 10292 /// Diagnose invalid arithmetic on two function pointers. 10293 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10294 Expr *LHS, Expr *RHS) { 10295 assert(LHS->getType()->isAnyPointerType()); 10296 assert(RHS->getType()->isAnyPointerType()); 10297 S.Diag(Loc, S.getLangOpts().CPlusPlus 10298 ? diag::err_typecheck_pointer_arith_function_type 10299 : diag::ext_gnu_ptr_func_arith) 10300 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10301 // We only show the second type if it differs from the first. 10302 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10303 RHS->getType()) 10304 << RHS->getType()->getPointeeType() 10305 << LHS->getSourceRange() << RHS->getSourceRange(); 10306 } 10307 10308 /// Diagnose invalid arithmetic on a function pointer. 10309 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10310 Expr *Pointer) { 10311 assert(Pointer->getType()->isAnyPointerType()); 10312 S.Diag(Loc, S.getLangOpts().CPlusPlus 10313 ? diag::err_typecheck_pointer_arith_function_type 10314 : diag::ext_gnu_ptr_func_arith) 10315 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10316 << 0 /* one pointer, so only one type */ 10317 << Pointer->getSourceRange(); 10318 } 10319 10320 /// Emit error if Operand is incomplete pointer type 10321 /// 10322 /// \returns True if pointer has incomplete type 10323 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10324 Expr *Operand) { 10325 QualType ResType = Operand->getType(); 10326 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10327 ResType = ResAtomicType->getValueType(); 10328 10329 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10330 QualType PointeeTy = ResType->getPointeeType(); 10331 return S.RequireCompleteSizedType( 10332 Loc, PointeeTy, 10333 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10334 Operand->getSourceRange()); 10335 } 10336 10337 /// Check the validity of an arithmetic pointer operand. 10338 /// 10339 /// If the operand has pointer type, this code will check for pointer types 10340 /// which are invalid in arithmetic operations. These will be diagnosed 10341 /// appropriately, including whether or not the use is supported as an 10342 /// extension. 10343 /// 10344 /// \returns True when the operand is valid to use (even if as an extension). 10345 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10346 Expr *Operand) { 10347 QualType ResType = Operand->getType(); 10348 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10349 ResType = ResAtomicType->getValueType(); 10350 10351 if (!ResType->isAnyPointerType()) return true; 10352 10353 QualType PointeeTy = ResType->getPointeeType(); 10354 if (PointeeTy->isVoidType()) { 10355 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10356 return !S.getLangOpts().CPlusPlus; 10357 } 10358 if (PointeeTy->isFunctionType()) { 10359 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10360 return !S.getLangOpts().CPlusPlus; 10361 } 10362 10363 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10364 10365 return true; 10366 } 10367 10368 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10369 /// operands. 10370 /// 10371 /// This routine will diagnose any invalid arithmetic on pointer operands much 10372 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10373 /// for emitting a single diagnostic even for operations where both LHS and RHS 10374 /// are (potentially problematic) pointers. 10375 /// 10376 /// \returns True when the operand is valid to use (even if as an extension). 10377 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10378 Expr *LHSExpr, Expr *RHSExpr) { 10379 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10380 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10381 if (!isLHSPointer && !isRHSPointer) return true; 10382 10383 QualType LHSPointeeTy, RHSPointeeTy; 10384 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10385 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10386 10387 // if both are pointers check if operation is valid wrt address spaces 10388 if (isLHSPointer && isRHSPointer) { 10389 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10390 S.Diag(Loc, 10391 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10392 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10393 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10394 return false; 10395 } 10396 } 10397 10398 // Check for arithmetic on pointers to incomplete types. 10399 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10400 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10401 if (isLHSVoidPtr || isRHSVoidPtr) { 10402 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10403 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10404 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10405 10406 return !S.getLangOpts().CPlusPlus; 10407 } 10408 10409 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10410 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10411 if (isLHSFuncPtr || isRHSFuncPtr) { 10412 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10413 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10414 RHSExpr); 10415 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10416 10417 return !S.getLangOpts().CPlusPlus; 10418 } 10419 10420 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10421 return false; 10422 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10423 return false; 10424 10425 return true; 10426 } 10427 10428 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10429 /// literal. 10430 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10431 Expr *LHSExpr, Expr *RHSExpr) { 10432 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10433 Expr* IndexExpr = RHSExpr; 10434 if (!StrExpr) { 10435 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10436 IndexExpr = LHSExpr; 10437 } 10438 10439 bool IsStringPlusInt = StrExpr && 10440 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10441 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10442 return; 10443 10444 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10445 Self.Diag(OpLoc, diag::warn_string_plus_int) 10446 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10447 10448 // Only print a fixit for "str" + int, not for int + "str". 10449 if (IndexExpr == RHSExpr) { 10450 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10451 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10452 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10453 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10454 << FixItHint::CreateInsertion(EndLoc, "]"); 10455 } else 10456 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10457 } 10458 10459 /// Emit a warning when adding a char literal to a string. 10460 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10461 Expr *LHSExpr, Expr *RHSExpr) { 10462 const Expr *StringRefExpr = LHSExpr; 10463 const CharacterLiteral *CharExpr = 10464 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10465 10466 if (!CharExpr) { 10467 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10468 StringRefExpr = RHSExpr; 10469 } 10470 10471 if (!CharExpr || !StringRefExpr) 10472 return; 10473 10474 const QualType StringType = StringRefExpr->getType(); 10475 10476 // Return if not a PointerType. 10477 if (!StringType->isAnyPointerType()) 10478 return; 10479 10480 // Return if not a CharacterType. 10481 if (!StringType->getPointeeType()->isAnyCharacterType()) 10482 return; 10483 10484 ASTContext &Ctx = Self.getASTContext(); 10485 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10486 10487 const QualType CharType = CharExpr->getType(); 10488 if (!CharType->isAnyCharacterType() && 10489 CharType->isIntegerType() && 10490 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10491 Self.Diag(OpLoc, diag::warn_string_plus_char) 10492 << DiagRange << Ctx.CharTy; 10493 } else { 10494 Self.Diag(OpLoc, diag::warn_string_plus_char) 10495 << DiagRange << CharExpr->getType(); 10496 } 10497 10498 // Only print a fixit for str + char, not for char + str. 10499 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10500 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10501 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10502 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10503 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10504 << FixItHint::CreateInsertion(EndLoc, "]"); 10505 } else { 10506 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10507 } 10508 } 10509 10510 /// Emit error when two pointers are incompatible. 10511 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10512 Expr *LHSExpr, Expr *RHSExpr) { 10513 assert(LHSExpr->getType()->isAnyPointerType()); 10514 assert(RHSExpr->getType()->isAnyPointerType()); 10515 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10516 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10517 << RHSExpr->getSourceRange(); 10518 } 10519 10520 // C99 6.5.6 10521 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10522 SourceLocation Loc, BinaryOperatorKind Opc, 10523 QualType* CompLHSTy) { 10524 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10525 10526 if (LHS.get()->getType()->isVectorType() || 10527 RHS.get()->getType()->isVectorType()) { 10528 QualType compType = CheckVectorOperands( 10529 LHS, RHS, Loc, CompLHSTy, 10530 /*AllowBothBool*/getLangOpts().AltiVec, 10531 /*AllowBoolConversions*/getLangOpts().ZVector); 10532 if (CompLHSTy) *CompLHSTy = compType; 10533 return compType; 10534 } 10535 10536 if (LHS.get()->getType()->isConstantMatrixType() || 10537 RHS.get()->getType()->isConstantMatrixType()) { 10538 QualType compType = 10539 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10540 if (CompLHSTy) 10541 *CompLHSTy = compType; 10542 return compType; 10543 } 10544 10545 QualType compType = UsualArithmeticConversions( 10546 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10547 if (LHS.isInvalid() || RHS.isInvalid()) 10548 return QualType(); 10549 10550 // Diagnose "string literal" '+' int and string '+' "char literal". 10551 if (Opc == BO_Add) { 10552 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10553 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10554 } 10555 10556 // handle the common case first (both operands are arithmetic). 10557 if (!compType.isNull() && compType->isArithmeticType()) { 10558 if (CompLHSTy) *CompLHSTy = compType; 10559 return compType; 10560 } 10561 10562 // Type-checking. Ultimately the pointer's going to be in PExp; 10563 // note that we bias towards the LHS being the pointer. 10564 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10565 10566 bool isObjCPointer; 10567 if (PExp->getType()->isPointerType()) { 10568 isObjCPointer = false; 10569 } else if (PExp->getType()->isObjCObjectPointerType()) { 10570 isObjCPointer = true; 10571 } else { 10572 std::swap(PExp, IExp); 10573 if (PExp->getType()->isPointerType()) { 10574 isObjCPointer = false; 10575 } else if (PExp->getType()->isObjCObjectPointerType()) { 10576 isObjCPointer = true; 10577 } else { 10578 return InvalidOperands(Loc, LHS, RHS); 10579 } 10580 } 10581 assert(PExp->getType()->isAnyPointerType()); 10582 10583 if (!IExp->getType()->isIntegerType()) 10584 return InvalidOperands(Loc, LHS, RHS); 10585 10586 // Adding to a null pointer results in undefined behavior. 10587 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10588 Context, Expr::NPC_ValueDependentIsNotNull)) { 10589 // In C++ adding zero to a null pointer is defined. 10590 Expr::EvalResult KnownVal; 10591 if (!getLangOpts().CPlusPlus || 10592 (!IExp->isValueDependent() && 10593 (!IExp->EvaluateAsInt(KnownVal, Context) || 10594 KnownVal.Val.getInt() != 0))) { 10595 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10596 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10597 Context, BO_Add, PExp, IExp); 10598 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10599 } 10600 } 10601 10602 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10603 return QualType(); 10604 10605 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10606 return QualType(); 10607 10608 // Check array bounds for pointer arithemtic 10609 CheckArrayAccess(PExp, IExp); 10610 10611 if (CompLHSTy) { 10612 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10613 if (LHSTy.isNull()) { 10614 LHSTy = LHS.get()->getType(); 10615 if (LHSTy->isPromotableIntegerType()) 10616 LHSTy = Context.getPromotedIntegerType(LHSTy); 10617 } 10618 *CompLHSTy = LHSTy; 10619 } 10620 10621 return PExp->getType(); 10622 } 10623 10624 // C99 6.5.6 10625 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10626 SourceLocation Loc, 10627 QualType* CompLHSTy) { 10628 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10629 10630 if (LHS.get()->getType()->isVectorType() || 10631 RHS.get()->getType()->isVectorType()) { 10632 QualType compType = CheckVectorOperands( 10633 LHS, RHS, Loc, CompLHSTy, 10634 /*AllowBothBool*/getLangOpts().AltiVec, 10635 /*AllowBoolConversions*/getLangOpts().ZVector); 10636 if (CompLHSTy) *CompLHSTy = compType; 10637 return compType; 10638 } 10639 10640 if (LHS.get()->getType()->isConstantMatrixType() || 10641 RHS.get()->getType()->isConstantMatrixType()) { 10642 QualType compType = 10643 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10644 if (CompLHSTy) 10645 *CompLHSTy = compType; 10646 return compType; 10647 } 10648 10649 QualType compType = UsualArithmeticConversions( 10650 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10651 if (LHS.isInvalid() || RHS.isInvalid()) 10652 return QualType(); 10653 10654 // Enforce type constraints: C99 6.5.6p3. 10655 10656 // Handle the common case first (both operands are arithmetic). 10657 if (!compType.isNull() && compType->isArithmeticType()) { 10658 if (CompLHSTy) *CompLHSTy = compType; 10659 return compType; 10660 } 10661 10662 // Either ptr - int or ptr - ptr. 10663 if (LHS.get()->getType()->isAnyPointerType()) { 10664 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10665 10666 // Diagnose bad cases where we step over interface counts. 10667 if (LHS.get()->getType()->isObjCObjectPointerType() && 10668 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10669 return QualType(); 10670 10671 // The result type of a pointer-int computation is the pointer type. 10672 if (RHS.get()->getType()->isIntegerType()) { 10673 // Subtracting from a null pointer should produce a warning. 10674 // The last argument to the diagnose call says this doesn't match the 10675 // GNU int-to-pointer idiom. 10676 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10677 Expr::NPC_ValueDependentIsNotNull)) { 10678 // In C++ adding zero to a null pointer is defined. 10679 Expr::EvalResult KnownVal; 10680 if (!getLangOpts().CPlusPlus || 10681 (!RHS.get()->isValueDependent() && 10682 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10683 KnownVal.Val.getInt() != 0))) { 10684 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10685 } 10686 } 10687 10688 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10689 return QualType(); 10690 10691 // Check array bounds for pointer arithemtic 10692 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10693 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10694 10695 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10696 return LHS.get()->getType(); 10697 } 10698 10699 // Handle pointer-pointer subtractions. 10700 if (const PointerType *RHSPTy 10701 = RHS.get()->getType()->getAs<PointerType>()) { 10702 QualType rpointee = RHSPTy->getPointeeType(); 10703 10704 if (getLangOpts().CPlusPlus) { 10705 // Pointee types must be the same: C++ [expr.add] 10706 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10707 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10708 } 10709 } else { 10710 // Pointee types must be compatible C99 6.5.6p3 10711 if (!Context.typesAreCompatible( 10712 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10713 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10714 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10715 return QualType(); 10716 } 10717 } 10718 10719 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10720 LHS.get(), RHS.get())) 10721 return QualType(); 10722 10723 // FIXME: Add warnings for nullptr - ptr. 10724 10725 // The pointee type may have zero size. As an extension, a structure or 10726 // union may have zero size or an array may have zero length. In this 10727 // case subtraction does not make sense. 10728 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10729 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10730 if (ElementSize.isZero()) { 10731 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10732 << rpointee.getUnqualifiedType() 10733 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10734 } 10735 } 10736 10737 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10738 return Context.getPointerDiffType(); 10739 } 10740 } 10741 10742 return InvalidOperands(Loc, LHS, RHS); 10743 } 10744 10745 static bool isScopedEnumerationType(QualType T) { 10746 if (const EnumType *ET = T->getAs<EnumType>()) 10747 return ET->getDecl()->isScoped(); 10748 return false; 10749 } 10750 10751 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10752 SourceLocation Loc, BinaryOperatorKind Opc, 10753 QualType LHSType) { 10754 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10755 // so skip remaining warnings as we don't want to modify values within Sema. 10756 if (S.getLangOpts().OpenCL) 10757 return; 10758 10759 // Check right/shifter operand 10760 Expr::EvalResult RHSResult; 10761 if (RHS.get()->isValueDependent() || 10762 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10763 return; 10764 llvm::APSInt Right = RHSResult.Val.getInt(); 10765 10766 if (Right.isNegative()) { 10767 S.DiagRuntimeBehavior(Loc, RHS.get(), 10768 S.PDiag(diag::warn_shift_negative) 10769 << RHS.get()->getSourceRange()); 10770 return; 10771 } 10772 10773 QualType LHSExprType = LHS.get()->getType(); 10774 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10775 if (LHSExprType->isExtIntType()) 10776 LeftSize = S.Context.getIntWidth(LHSExprType); 10777 else if (LHSExprType->isFixedPointType()) { 10778 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10779 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10780 } 10781 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10782 if (Right.uge(LeftBits)) { 10783 S.DiagRuntimeBehavior(Loc, RHS.get(), 10784 S.PDiag(diag::warn_shift_gt_typewidth) 10785 << RHS.get()->getSourceRange()); 10786 return; 10787 } 10788 10789 // FIXME: We probably need to handle fixed point types specially here. 10790 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10791 return; 10792 10793 // When left shifting an ICE which is signed, we can check for overflow which 10794 // according to C++ standards prior to C++2a has undefined behavior 10795 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10796 // more than the maximum value representable in the result type, so never 10797 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10798 // expression is still probably a bug.) 10799 Expr::EvalResult LHSResult; 10800 if (LHS.get()->isValueDependent() || 10801 LHSType->hasUnsignedIntegerRepresentation() || 10802 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10803 return; 10804 llvm::APSInt Left = LHSResult.Val.getInt(); 10805 10806 // If LHS does not have a signed type and non-negative value 10807 // then, the behavior is undefined before C++2a. Warn about it. 10808 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10809 !S.getLangOpts().CPlusPlus20) { 10810 S.DiagRuntimeBehavior(Loc, LHS.get(), 10811 S.PDiag(diag::warn_shift_lhs_negative) 10812 << LHS.get()->getSourceRange()); 10813 return; 10814 } 10815 10816 llvm::APInt ResultBits = 10817 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10818 if (LeftBits.uge(ResultBits)) 10819 return; 10820 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10821 Result = Result.shl(Right); 10822 10823 // Print the bit representation of the signed integer as an unsigned 10824 // hexadecimal number. 10825 SmallString<40> HexResult; 10826 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10827 10828 // If we are only missing a sign bit, this is less likely to result in actual 10829 // bugs -- if the result is cast back to an unsigned type, it will have the 10830 // expected value. Thus we place this behind a different warning that can be 10831 // turned off separately if needed. 10832 if (LeftBits == ResultBits - 1) { 10833 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10834 << HexResult << LHSType 10835 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10836 return; 10837 } 10838 10839 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10840 << HexResult.str() << Result.getMinSignedBits() << LHSType 10841 << Left.getBitWidth() << LHS.get()->getSourceRange() 10842 << RHS.get()->getSourceRange(); 10843 } 10844 10845 /// Return the resulting type when a vector is shifted 10846 /// by a scalar or vector shift amount. 10847 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10848 SourceLocation Loc, bool IsCompAssign) { 10849 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10850 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10851 !LHS.get()->getType()->isVectorType()) { 10852 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10853 << RHS.get()->getType() << LHS.get()->getType() 10854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10855 return QualType(); 10856 } 10857 10858 if (!IsCompAssign) { 10859 LHS = S.UsualUnaryConversions(LHS.get()); 10860 if (LHS.isInvalid()) return QualType(); 10861 } 10862 10863 RHS = S.UsualUnaryConversions(RHS.get()); 10864 if (RHS.isInvalid()) return QualType(); 10865 10866 QualType LHSType = LHS.get()->getType(); 10867 // Note that LHS might be a scalar because the routine calls not only in 10868 // OpenCL case. 10869 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10870 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10871 10872 // Note that RHS might not be a vector. 10873 QualType RHSType = RHS.get()->getType(); 10874 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10875 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10876 10877 // The operands need to be integers. 10878 if (!LHSEleType->isIntegerType()) { 10879 S.Diag(Loc, diag::err_typecheck_expect_int) 10880 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10881 return QualType(); 10882 } 10883 10884 if (!RHSEleType->isIntegerType()) { 10885 S.Diag(Loc, diag::err_typecheck_expect_int) 10886 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10887 return QualType(); 10888 } 10889 10890 if (!LHSVecTy) { 10891 assert(RHSVecTy); 10892 if (IsCompAssign) 10893 return RHSType; 10894 if (LHSEleType != RHSEleType) { 10895 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10896 LHSEleType = RHSEleType; 10897 } 10898 QualType VecTy = 10899 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10900 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10901 LHSType = VecTy; 10902 } else if (RHSVecTy) { 10903 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10904 // are applied component-wise. So if RHS is a vector, then ensure 10905 // that the number of elements is the same as LHS... 10906 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10907 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10908 << LHS.get()->getType() << RHS.get()->getType() 10909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10910 return QualType(); 10911 } 10912 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10913 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10914 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10915 if (LHSBT != RHSBT && 10916 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10917 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10918 << LHS.get()->getType() << RHS.get()->getType() 10919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10920 } 10921 } 10922 } else { 10923 // ...else expand RHS to match the number of elements in LHS. 10924 QualType VecTy = 10925 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10926 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10927 } 10928 10929 return LHSType; 10930 } 10931 10932 // C99 6.5.7 10933 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10934 SourceLocation Loc, BinaryOperatorKind Opc, 10935 bool IsCompAssign) { 10936 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10937 10938 // Vector shifts promote their scalar inputs to vector type. 10939 if (LHS.get()->getType()->isVectorType() || 10940 RHS.get()->getType()->isVectorType()) { 10941 if (LangOpts.ZVector) { 10942 // The shift operators for the z vector extensions work basically 10943 // like general shifts, except that neither the LHS nor the RHS is 10944 // allowed to be a "vector bool". 10945 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10946 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10947 return InvalidOperands(Loc, LHS, RHS); 10948 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10949 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10950 return InvalidOperands(Loc, LHS, RHS); 10951 } 10952 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10953 } 10954 10955 // Shifts don't perform usual arithmetic conversions, they just do integer 10956 // promotions on each operand. C99 6.5.7p3 10957 10958 // For the LHS, do usual unary conversions, but then reset them away 10959 // if this is a compound assignment. 10960 ExprResult OldLHS = LHS; 10961 LHS = UsualUnaryConversions(LHS.get()); 10962 if (LHS.isInvalid()) 10963 return QualType(); 10964 QualType LHSType = LHS.get()->getType(); 10965 if (IsCompAssign) LHS = OldLHS; 10966 10967 // The RHS is simpler. 10968 RHS = UsualUnaryConversions(RHS.get()); 10969 if (RHS.isInvalid()) 10970 return QualType(); 10971 QualType RHSType = RHS.get()->getType(); 10972 10973 // C99 6.5.7p2: Each of the operands shall have integer type. 10974 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10975 if ((!LHSType->isFixedPointOrIntegerType() && 10976 !LHSType->hasIntegerRepresentation()) || 10977 !RHSType->hasIntegerRepresentation()) 10978 return InvalidOperands(Loc, LHS, RHS); 10979 10980 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10981 // hasIntegerRepresentation() above instead of this. 10982 if (isScopedEnumerationType(LHSType) || 10983 isScopedEnumerationType(RHSType)) { 10984 return InvalidOperands(Loc, LHS, RHS); 10985 } 10986 // Sanity-check shift operands 10987 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10988 10989 // "The type of the result is that of the promoted left operand." 10990 return LHSType; 10991 } 10992 10993 /// Diagnose bad pointer comparisons. 10994 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10995 ExprResult &LHS, ExprResult &RHS, 10996 bool IsError) { 10997 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10998 : diag::ext_typecheck_comparison_of_distinct_pointers) 10999 << LHS.get()->getType() << RHS.get()->getType() 11000 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11001 } 11002 11003 /// Returns false if the pointers are converted to a composite type, 11004 /// true otherwise. 11005 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11006 ExprResult &LHS, ExprResult &RHS) { 11007 // C++ [expr.rel]p2: 11008 // [...] Pointer conversions (4.10) and qualification 11009 // conversions (4.4) are performed on pointer operands (or on 11010 // a pointer operand and a null pointer constant) to bring 11011 // them to their composite pointer type. [...] 11012 // 11013 // C++ [expr.eq]p1 uses the same notion for (in)equality 11014 // comparisons of pointers. 11015 11016 QualType LHSType = LHS.get()->getType(); 11017 QualType RHSType = RHS.get()->getType(); 11018 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11019 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11020 11021 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11022 if (T.isNull()) { 11023 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11024 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11025 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11026 else 11027 S.InvalidOperands(Loc, LHS, RHS); 11028 return true; 11029 } 11030 11031 return false; 11032 } 11033 11034 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11035 ExprResult &LHS, 11036 ExprResult &RHS, 11037 bool IsError) { 11038 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11039 : diag::ext_typecheck_comparison_of_fptr_to_void) 11040 << LHS.get()->getType() << RHS.get()->getType() 11041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11042 } 11043 11044 static bool isObjCObjectLiteral(ExprResult &E) { 11045 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11046 case Stmt::ObjCArrayLiteralClass: 11047 case Stmt::ObjCDictionaryLiteralClass: 11048 case Stmt::ObjCStringLiteralClass: 11049 case Stmt::ObjCBoxedExprClass: 11050 return true; 11051 default: 11052 // Note that ObjCBoolLiteral is NOT an object literal! 11053 return false; 11054 } 11055 } 11056 11057 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11058 const ObjCObjectPointerType *Type = 11059 LHS->getType()->getAs<ObjCObjectPointerType>(); 11060 11061 // If this is not actually an Objective-C object, bail out. 11062 if (!Type) 11063 return false; 11064 11065 // Get the LHS object's interface type. 11066 QualType InterfaceType = Type->getPointeeType(); 11067 11068 // If the RHS isn't an Objective-C object, bail out. 11069 if (!RHS->getType()->isObjCObjectPointerType()) 11070 return false; 11071 11072 // Try to find the -isEqual: method. 11073 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11074 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11075 InterfaceType, 11076 /*IsInstance=*/true); 11077 if (!Method) { 11078 if (Type->isObjCIdType()) { 11079 // For 'id', just check the global pool. 11080 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11081 /*receiverId=*/true); 11082 } else { 11083 // Check protocols. 11084 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11085 /*IsInstance=*/true); 11086 } 11087 } 11088 11089 if (!Method) 11090 return false; 11091 11092 QualType T = Method->parameters()[0]->getType(); 11093 if (!T->isObjCObjectPointerType()) 11094 return false; 11095 11096 QualType R = Method->getReturnType(); 11097 if (!R->isScalarType()) 11098 return false; 11099 11100 return true; 11101 } 11102 11103 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11104 FromE = FromE->IgnoreParenImpCasts(); 11105 switch (FromE->getStmtClass()) { 11106 default: 11107 break; 11108 case Stmt::ObjCStringLiteralClass: 11109 // "string literal" 11110 return LK_String; 11111 case Stmt::ObjCArrayLiteralClass: 11112 // "array literal" 11113 return LK_Array; 11114 case Stmt::ObjCDictionaryLiteralClass: 11115 // "dictionary literal" 11116 return LK_Dictionary; 11117 case Stmt::BlockExprClass: 11118 return LK_Block; 11119 case Stmt::ObjCBoxedExprClass: { 11120 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11121 switch (Inner->getStmtClass()) { 11122 case Stmt::IntegerLiteralClass: 11123 case Stmt::FloatingLiteralClass: 11124 case Stmt::CharacterLiteralClass: 11125 case Stmt::ObjCBoolLiteralExprClass: 11126 case Stmt::CXXBoolLiteralExprClass: 11127 // "numeric literal" 11128 return LK_Numeric; 11129 case Stmt::ImplicitCastExprClass: { 11130 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11131 // Boolean literals can be represented by implicit casts. 11132 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11133 return LK_Numeric; 11134 break; 11135 } 11136 default: 11137 break; 11138 } 11139 return LK_Boxed; 11140 } 11141 } 11142 return LK_None; 11143 } 11144 11145 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11146 ExprResult &LHS, ExprResult &RHS, 11147 BinaryOperator::Opcode Opc){ 11148 Expr *Literal; 11149 Expr *Other; 11150 if (isObjCObjectLiteral(LHS)) { 11151 Literal = LHS.get(); 11152 Other = RHS.get(); 11153 } else { 11154 Literal = RHS.get(); 11155 Other = LHS.get(); 11156 } 11157 11158 // Don't warn on comparisons against nil. 11159 Other = Other->IgnoreParenCasts(); 11160 if (Other->isNullPointerConstant(S.getASTContext(), 11161 Expr::NPC_ValueDependentIsNotNull)) 11162 return; 11163 11164 // This should be kept in sync with warn_objc_literal_comparison. 11165 // LK_String should always be after the other literals, since it has its own 11166 // warning flag. 11167 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11168 assert(LiteralKind != Sema::LK_Block); 11169 if (LiteralKind == Sema::LK_None) { 11170 llvm_unreachable("Unknown Objective-C object literal kind"); 11171 } 11172 11173 if (LiteralKind == Sema::LK_String) 11174 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11175 << Literal->getSourceRange(); 11176 else 11177 S.Diag(Loc, diag::warn_objc_literal_comparison) 11178 << LiteralKind << Literal->getSourceRange(); 11179 11180 if (BinaryOperator::isEqualityOp(Opc) && 11181 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11182 SourceLocation Start = LHS.get()->getBeginLoc(); 11183 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11184 CharSourceRange OpRange = 11185 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11186 11187 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11188 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11189 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11190 << FixItHint::CreateInsertion(End, "]"); 11191 } 11192 } 11193 11194 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11195 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11196 ExprResult &RHS, SourceLocation Loc, 11197 BinaryOperatorKind Opc) { 11198 // Check that left hand side is !something. 11199 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11200 if (!UO || UO->getOpcode() != UO_LNot) return; 11201 11202 // Only check if the right hand side is non-bool arithmetic type. 11203 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11204 11205 // Make sure that the something in !something is not bool. 11206 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11207 if (SubExpr->isKnownToHaveBooleanValue()) return; 11208 11209 // Emit warning. 11210 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11211 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11212 << Loc << IsBitwiseOp; 11213 11214 // First note suggest !(x < y) 11215 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11216 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11217 FirstClose = S.getLocForEndOfToken(FirstClose); 11218 if (FirstClose.isInvalid()) 11219 FirstOpen = SourceLocation(); 11220 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11221 << IsBitwiseOp 11222 << FixItHint::CreateInsertion(FirstOpen, "(") 11223 << FixItHint::CreateInsertion(FirstClose, ")"); 11224 11225 // Second note suggests (!x) < y 11226 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11227 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11228 SecondClose = S.getLocForEndOfToken(SecondClose); 11229 if (SecondClose.isInvalid()) 11230 SecondOpen = SourceLocation(); 11231 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11232 << FixItHint::CreateInsertion(SecondOpen, "(") 11233 << FixItHint::CreateInsertion(SecondClose, ")"); 11234 } 11235 11236 // Returns true if E refers to a non-weak array. 11237 static bool checkForArray(const Expr *E) { 11238 const ValueDecl *D = nullptr; 11239 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11240 D = DR->getDecl(); 11241 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11242 if (Mem->isImplicitAccess()) 11243 D = Mem->getMemberDecl(); 11244 } 11245 if (!D) 11246 return false; 11247 return D->getType()->isArrayType() && !D->isWeak(); 11248 } 11249 11250 /// Diagnose some forms of syntactically-obvious tautological comparison. 11251 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11252 Expr *LHS, Expr *RHS, 11253 BinaryOperatorKind Opc) { 11254 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11255 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11256 11257 QualType LHSType = LHS->getType(); 11258 QualType RHSType = RHS->getType(); 11259 if (LHSType->hasFloatingRepresentation() || 11260 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11261 S.inTemplateInstantiation()) 11262 return; 11263 11264 // Comparisons between two array types are ill-formed for operator<=>, so 11265 // we shouldn't emit any additional warnings about it. 11266 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11267 return; 11268 11269 // For non-floating point types, check for self-comparisons of the form 11270 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11271 // often indicate logic errors in the program. 11272 // 11273 // NOTE: Don't warn about comparison expressions resulting from macro 11274 // expansion. Also don't warn about comparisons which are only self 11275 // comparisons within a template instantiation. The warnings should catch 11276 // obvious cases in the definition of the template anyways. The idea is to 11277 // warn when the typed comparison operator will always evaluate to the same 11278 // result. 11279 11280 // Used for indexing into %select in warn_comparison_always 11281 enum { 11282 AlwaysConstant, 11283 AlwaysTrue, 11284 AlwaysFalse, 11285 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11286 }; 11287 11288 // C++2a [depr.array.comp]: 11289 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11290 // operands of array type are deprecated. 11291 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11292 RHSStripped->getType()->isArrayType()) { 11293 S.Diag(Loc, diag::warn_depr_array_comparison) 11294 << LHS->getSourceRange() << RHS->getSourceRange() 11295 << LHSStripped->getType() << RHSStripped->getType(); 11296 // Carry on to produce the tautological comparison warning, if this 11297 // expression is potentially-evaluated, we can resolve the array to a 11298 // non-weak declaration, and so on. 11299 } 11300 11301 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11302 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11303 unsigned Result; 11304 switch (Opc) { 11305 case BO_EQ: 11306 case BO_LE: 11307 case BO_GE: 11308 Result = AlwaysTrue; 11309 break; 11310 case BO_NE: 11311 case BO_LT: 11312 case BO_GT: 11313 Result = AlwaysFalse; 11314 break; 11315 case BO_Cmp: 11316 Result = AlwaysEqual; 11317 break; 11318 default: 11319 Result = AlwaysConstant; 11320 break; 11321 } 11322 S.DiagRuntimeBehavior(Loc, nullptr, 11323 S.PDiag(diag::warn_comparison_always) 11324 << 0 /*self-comparison*/ 11325 << Result); 11326 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11327 // What is it always going to evaluate to? 11328 unsigned Result; 11329 switch (Opc) { 11330 case BO_EQ: // e.g. array1 == array2 11331 Result = AlwaysFalse; 11332 break; 11333 case BO_NE: // e.g. array1 != array2 11334 Result = AlwaysTrue; 11335 break; 11336 default: // e.g. array1 <= array2 11337 // The best we can say is 'a constant' 11338 Result = AlwaysConstant; 11339 break; 11340 } 11341 S.DiagRuntimeBehavior(Loc, nullptr, 11342 S.PDiag(diag::warn_comparison_always) 11343 << 1 /*array comparison*/ 11344 << Result); 11345 } 11346 } 11347 11348 if (isa<CastExpr>(LHSStripped)) 11349 LHSStripped = LHSStripped->IgnoreParenCasts(); 11350 if (isa<CastExpr>(RHSStripped)) 11351 RHSStripped = RHSStripped->IgnoreParenCasts(); 11352 11353 // Warn about comparisons against a string constant (unless the other 11354 // operand is null); the user probably wants string comparison function. 11355 Expr *LiteralString = nullptr; 11356 Expr *LiteralStringStripped = nullptr; 11357 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11358 !RHSStripped->isNullPointerConstant(S.Context, 11359 Expr::NPC_ValueDependentIsNull)) { 11360 LiteralString = LHS; 11361 LiteralStringStripped = LHSStripped; 11362 } else if ((isa<StringLiteral>(RHSStripped) || 11363 isa<ObjCEncodeExpr>(RHSStripped)) && 11364 !LHSStripped->isNullPointerConstant(S.Context, 11365 Expr::NPC_ValueDependentIsNull)) { 11366 LiteralString = RHS; 11367 LiteralStringStripped = RHSStripped; 11368 } 11369 11370 if (LiteralString) { 11371 S.DiagRuntimeBehavior(Loc, nullptr, 11372 S.PDiag(diag::warn_stringcompare) 11373 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11374 << LiteralString->getSourceRange()); 11375 } 11376 } 11377 11378 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11379 switch (CK) { 11380 default: { 11381 #ifndef NDEBUG 11382 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11383 << "\n"; 11384 #endif 11385 llvm_unreachable("unhandled cast kind"); 11386 } 11387 case CK_UserDefinedConversion: 11388 return ICK_Identity; 11389 case CK_LValueToRValue: 11390 return ICK_Lvalue_To_Rvalue; 11391 case CK_ArrayToPointerDecay: 11392 return ICK_Array_To_Pointer; 11393 case CK_FunctionToPointerDecay: 11394 return ICK_Function_To_Pointer; 11395 case CK_IntegralCast: 11396 return ICK_Integral_Conversion; 11397 case CK_FloatingCast: 11398 return ICK_Floating_Conversion; 11399 case CK_IntegralToFloating: 11400 case CK_FloatingToIntegral: 11401 return ICK_Floating_Integral; 11402 case CK_IntegralComplexCast: 11403 case CK_FloatingComplexCast: 11404 case CK_FloatingComplexToIntegralComplex: 11405 case CK_IntegralComplexToFloatingComplex: 11406 return ICK_Complex_Conversion; 11407 case CK_FloatingComplexToReal: 11408 case CK_FloatingRealToComplex: 11409 case CK_IntegralComplexToReal: 11410 case CK_IntegralRealToComplex: 11411 return ICK_Complex_Real; 11412 } 11413 } 11414 11415 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11416 QualType FromType, 11417 SourceLocation Loc) { 11418 // Check for a narrowing implicit conversion. 11419 StandardConversionSequence SCS; 11420 SCS.setAsIdentityConversion(); 11421 SCS.setToType(0, FromType); 11422 SCS.setToType(1, ToType); 11423 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11424 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11425 11426 APValue PreNarrowingValue; 11427 QualType PreNarrowingType; 11428 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11429 PreNarrowingType, 11430 /*IgnoreFloatToIntegralConversion*/ true)) { 11431 case NK_Dependent_Narrowing: 11432 // Implicit conversion to a narrower type, but the expression is 11433 // value-dependent so we can't tell whether it's actually narrowing. 11434 case NK_Not_Narrowing: 11435 return false; 11436 11437 case NK_Constant_Narrowing: 11438 // Implicit conversion to a narrower type, and the value is not a constant 11439 // expression. 11440 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11441 << /*Constant*/ 1 11442 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11443 return true; 11444 11445 case NK_Variable_Narrowing: 11446 // Implicit conversion to a narrower type, and the value is not a constant 11447 // expression. 11448 case NK_Type_Narrowing: 11449 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11450 << /*Constant*/ 0 << FromType << ToType; 11451 // TODO: It's not a constant expression, but what if the user intended it 11452 // to be? Can we produce notes to help them figure out why it isn't? 11453 return true; 11454 } 11455 llvm_unreachable("unhandled case in switch"); 11456 } 11457 11458 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11459 ExprResult &LHS, 11460 ExprResult &RHS, 11461 SourceLocation Loc) { 11462 QualType LHSType = LHS.get()->getType(); 11463 QualType RHSType = RHS.get()->getType(); 11464 // Dig out the original argument type and expression before implicit casts 11465 // were applied. These are the types/expressions we need to check the 11466 // [expr.spaceship] requirements against. 11467 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11468 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11469 QualType LHSStrippedType = LHSStripped.get()->getType(); 11470 QualType RHSStrippedType = RHSStripped.get()->getType(); 11471 11472 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11473 // other is not, the program is ill-formed. 11474 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11475 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11476 return QualType(); 11477 } 11478 11479 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11480 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11481 RHSStrippedType->isEnumeralType(); 11482 if (NumEnumArgs == 1) { 11483 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11484 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11485 if (OtherTy->hasFloatingRepresentation()) { 11486 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11487 return QualType(); 11488 } 11489 } 11490 if (NumEnumArgs == 2) { 11491 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11492 // type E, the operator yields the result of converting the operands 11493 // to the underlying type of E and applying <=> to the converted operands. 11494 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11495 S.InvalidOperands(Loc, LHS, RHS); 11496 return QualType(); 11497 } 11498 QualType IntType = 11499 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11500 assert(IntType->isArithmeticType()); 11501 11502 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11503 // promote the boolean type, and all other promotable integer types, to 11504 // avoid this. 11505 if (IntType->isPromotableIntegerType()) 11506 IntType = S.Context.getPromotedIntegerType(IntType); 11507 11508 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11509 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11510 LHSType = RHSType = IntType; 11511 } 11512 11513 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11514 // usual arithmetic conversions are applied to the operands. 11515 QualType Type = 11516 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11517 if (LHS.isInvalid() || RHS.isInvalid()) 11518 return QualType(); 11519 if (Type.isNull()) 11520 return S.InvalidOperands(Loc, LHS, RHS); 11521 11522 Optional<ComparisonCategoryType> CCT = 11523 getComparisonCategoryForBuiltinCmp(Type); 11524 if (!CCT) 11525 return S.InvalidOperands(Loc, LHS, RHS); 11526 11527 bool HasNarrowing = checkThreeWayNarrowingConversion( 11528 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11529 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11530 RHS.get()->getBeginLoc()); 11531 if (HasNarrowing) 11532 return QualType(); 11533 11534 assert(!Type.isNull() && "composite type for <=> has not been set"); 11535 11536 return S.CheckComparisonCategoryType( 11537 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11538 } 11539 11540 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11541 ExprResult &RHS, 11542 SourceLocation Loc, 11543 BinaryOperatorKind Opc) { 11544 if (Opc == BO_Cmp) 11545 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11546 11547 // C99 6.5.8p3 / C99 6.5.9p4 11548 QualType Type = 11549 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11550 if (LHS.isInvalid() || RHS.isInvalid()) 11551 return QualType(); 11552 if (Type.isNull()) 11553 return S.InvalidOperands(Loc, LHS, RHS); 11554 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11555 11556 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11557 return S.InvalidOperands(Loc, LHS, RHS); 11558 11559 // Check for comparisons of floating point operands using != and ==. 11560 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11561 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11562 11563 // The result of comparisons is 'bool' in C++, 'int' in C. 11564 return S.Context.getLogicalOperationType(); 11565 } 11566 11567 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11568 if (!NullE.get()->getType()->isAnyPointerType()) 11569 return; 11570 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11571 if (!E.get()->getType()->isAnyPointerType() && 11572 E.get()->isNullPointerConstant(Context, 11573 Expr::NPC_ValueDependentIsNotNull) == 11574 Expr::NPCK_ZeroExpression) { 11575 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11576 if (CL->getValue() == 0) 11577 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11578 << NullValue 11579 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11580 NullValue ? "NULL" : "(void *)0"); 11581 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11582 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11583 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11584 if (T == Context.CharTy) 11585 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11586 << NullValue 11587 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11588 NullValue ? "NULL" : "(void *)0"); 11589 } 11590 } 11591 } 11592 11593 // C99 6.5.8, C++ [expr.rel] 11594 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11595 SourceLocation Loc, 11596 BinaryOperatorKind Opc) { 11597 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11598 bool IsThreeWay = Opc == BO_Cmp; 11599 bool IsOrdered = IsRelational || IsThreeWay; 11600 auto IsAnyPointerType = [](ExprResult E) { 11601 QualType Ty = E.get()->getType(); 11602 return Ty->isPointerType() || Ty->isMemberPointerType(); 11603 }; 11604 11605 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11606 // type, array-to-pointer, ..., conversions are performed on both operands to 11607 // bring them to their composite type. 11608 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11609 // any type-related checks. 11610 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11611 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11612 if (LHS.isInvalid()) 11613 return QualType(); 11614 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11615 if (RHS.isInvalid()) 11616 return QualType(); 11617 } else { 11618 LHS = DefaultLvalueConversion(LHS.get()); 11619 if (LHS.isInvalid()) 11620 return QualType(); 11621 RHS = DefaultLvalueConversion(RHS.get()); 11622 if (RHS.isInvalid()) 11623 return QualType(); 11624 } 11625 11626 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11627 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11628 CheckPtrComparisonWithNullChar(LHS, RHS); 11629 CheckPtrComparisonWithNullChar(RHS, LHS); 11630 } 11631 11632 // Handle vector comparisons separately. 11633 if (LHS.get()->getType()->isVectorType() || 11634 RHS.get()->getType()->isVectorType()) 11635 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11636 11637 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11638 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11639 11640 QualType LHSType = LHS.get()->getType(); 11641 QualType RHSType = RHS.get()->getType(); 11642 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11643 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11644 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11645 11646 const Expr::NullPointerConstantKind LHSNullKind = 11647 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11648 const Expr::NullPointerConstantKind RHSNullKind = 11649 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11650 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11651 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11652 11653 auto computeResultTy = [&]() { 11654 if (Opc != BO_Cmp) 11655 return Context.getLogicalOperationType(); 11656 assert(getLangOpts().CPlusPlus); 11657 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11658 11659 QualType CompositeTy = LHS.get()->getType(); 11660 assert(!CompositeTy->isReferenceType()); 11661 11662 Optional<ComparisonCategoryType> CCT = 11663 getComparisonCategoryForBuiltinCmp(CompositeTy); 11664 if (!CCT) 11665 return InvalidOperands(Loc, LHS, RHS); 11666 11667 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11668 // P0946R0: Comparisons between a null pointer constant and an object 11669 // pointer result in std::strong_equality, which is ill-formed under 11670 // P1959R0. 11671 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11672 << (LHSIsNull ? LHS.get()->getSourceRange() 11673 : RHS.get()->getSourceRange()); 11674 return QualType(); 11675 } 11676 11677 return CheckComparisonCategoryType( 11678 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11679 }; 11680 11681 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11682 bool IsEquality = Opc == BO_EQ; 11683 if (RHSIsNull) 11684 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11685 RHS.get()->getSourceRange()); 11686 else 11687 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11688 LHS.get()->getSourceRange()); 11689 } 11690 11691 if ((LHSType->isIntegerType() && !LHSIsNull) || 11692 (RHSType->isIntegerType() && !RHSIsNull)) { 11693 // Skip normal pointer conversion checks in this case; we have better 11694 // diagnostics for this below. 11695 } else if (getLangOpts().CPlusPlus) { 11696 // Equality comparison of a function pointer to a void pointer is invalid, 11697 // but we allow it as an extension. 11698 // FIXME: If we really want to allow this, should it be part of composite 11699 // pointer type computation so it works in conditionals too? 11700 if (!IsOrdered && 11701 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11702 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11703 // This is a gcc extension compatibility comparison. 11704 // In a SFINAE context, we treat this as a hard error to maintain 11705 // conformance with the C++ standard. 11706 diagnoseFunctionPointerToVoidComparison( 11707 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11708 11709 if (isSFINAEContext()) 11710 return QualType(); 11711 11712 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11713 return computeResultTy(); 11714 } 11715 11716 // C++ [expr.eq]p2: 11717 // If at least one operand is a pointer [...] bring them to their 11718 // composite pointer type. 11719 // C++ [expr.spaceship]p6 11720 // If at least one of the operands is of pointer type, [...] bring them 11721 // to their composite pointer type. 11722 // C++ [expr.rel]p2: 11723 // If both operands are pointers, [...] bring them to their composite 11724 // pointer type. 11725 // For <=>, the only valid non-pointer types are arrays and functions, and 11726 // we already decayed those, so this is really the same as the relational 11727 // comparison rule. 11728 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11729 (IsOrdered ? 2 : 1) && 11730 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11731 RHSType->isObjCObjectPointerType()))) { 11732 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11733 return QualType(); 11734 return computeResultTy(); 11735 } 11736 } else if (LHSType->isPointerType() && 11737 RHSType->isPointerType()) { // C99 6.5.8p2 11738 // All of the following pointer-related warnings are GCC extensions, except 11739 // when handling null pointer constants. 11740 QualType LCanPointeeTy = 11741 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11742 QualType RCanPointeeTy = 11743 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11744 11745 // C99 6.5.9p2 and C99 6.5.8p2 11746 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11747 RCanPointeeTy.getUnqualifiedType())) { 11748 if (IsRelational) { 11749 // Pointers both need to point to complete or incomplete types 11750 if ((LCanPointeeTy->isIncompleteType() != 11751 RCanPointeeTy->isIncompleteType()) && 11752 !getLangOpts().C11) { 11753 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11755 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11756 << RCanPointeeTy->isIncompleteType(); 11757 } 11758 if (LCanPointeeTy->isFunctionType()) { 11759 // Valid unless a relational comparison of function pointers 11760 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11761 << LHSType << RHSType << LHS.get()->getSourceRange() 11762 << RHS.get()->getSourceRange(); 11763 } 11764 } 11765 } else if (!IsRelational && 11766 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11767 // Valid unless comparison between non-null pointer and function pointer 11768 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11769 && !LHSIsNull && !RHSIsNull) 11770 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11771 /*isError*/false); 11772 } else { 11773 // Invalid 11774 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11775 } 11776 if (LCanPointeeTy != RCanPointeeTy) { 11777 // Treat NULL constant as a special case in OpenCL. 11778 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11779 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11780 Diag(Loc, 11781 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11782 << LHSType << RHSType << 0 /* comparison */ 11783 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11784 } 11785 } 11786 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11787 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11788 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11789 : CK_BitCast; 11790 if (LHSIsNull && !RHSIsNull) 11791 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11792 else 11793 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11794 } 11795 return computeResultTy(); 11796 } 11797 11798 if (getLangOpts().CPlusPlus) { 11799 // C++ [expr.eq]p4: 11800 // Two operands of type std::nullptr_t or one operand of type 11801 // std::nullptr_t and the other a null pointer constant compare equal. 11802 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11803 if (LHSType->isNullPtrType()) { 11804 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11805 return computeResultTy(); 11806 } 11807 if (RHSType->isNullPtrType()) { 11808 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11809 return computeResultTy(); 11810 } 11811 } 11812 11813 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11814 // These aren't covered by the composite pointer type rules. 11815 if (!IsOrdered && RHSType->isNullPtrType() && 11816 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11817 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11818 return computeResultTy(); 11819 } 11820 if (!IsOrdered && LHSType->isNullPtrType() && 11821 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11822 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11823 return computeResultTy(); 11824 } 11825 11826 if (IsRelational && 11827 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11828 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11829 // HACK: Relational comparison of nullptr_t against a pointer type is 11830 // invalid per DR583, but we allow it within std::less<> and friends, 11831 // since otherwise common uses of it break. 11832 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11833 // friends to have std::nullptr_t overload candidates. 11834 DeclContext *DC = CurContext; 11835 if (isa<FunctionDecl>(DC)) 11836 DC = DC->getParent(); 11837 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11838 if (CTSD->isInStdNamespace() && 11839 llvm::StringSwitch<bool>(CTSD->getName()) 11840 .Cases("less", "less_equal", "greater", "greater_equal", true) 11841 .Default(false)) { 11842 if (RHSType->isNullPtrType()) 11843 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11844 else 11845 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11846 return computeResultTy(); 11847 } 11848 } 11849 } 11850 11851 // C++ [expr.eq]p2: 11852 // If at least one operand is a pointer to member, [...] bring them to 11853 // their composite pointer type. 11854 if (!IsOrdered && 11855 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11856 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11857 return QualType(); 11858 else 11859 return computeResultTy(); 11860 } 11861 } 11862 11863 // Handle block pointer types. 11864 if (!IsOrdered && LHSType->isBlockPointerType() && 11865 RHSType->isBlockPointerType()) { 11866 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11867 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11868 11869 if (!LHSIsNull && !RHSIsNull && 11870 !Context.typesAreCompatible(lpointee, rpointee)) { 11871 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11872 << LHSType << RHSType << LHS.get()->getSourceRange() 11873 << RHS.get()->getSourceRange(); 11874 } 11875 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11876 return computeResultTy(); 11877 } 11878 11879 // Allow block pointers to be compared with null pointer constants. 11880 if (!IsOrdered 11881 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11882 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11883 if (!LHSIsNull && !RHSIsNull) { 11884 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11885 ->getPointeeType()->isVoidType()) 11886 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11887 ->getPointeeType()->isVoidType()))) 11888 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11889 << LHSType << RHSType << LHS.get()->getSourceRange() 11890 << RHS.get()->getSourceRange(); 11891 } 11892 if (LHSIsNull && !RHSIsNull) 11893 LHS = ImpCastExprToType(LHS.get(), RHSType, 11894 RHSType->isPointerType() ? CK_BitCast 11895 : CK_AnyPointerToBlockPointerCast); 11896 else 11897 RHS = ImpCastExprToType(RHS.get(), LHSType, 11898 LHSType->isPointerType() ? CK_BitCast 11899 : CK_AnyPointerToBlockPointerCast); 11900 return computeResultTy(); 11901 } 11902 11903 if (LHSType->isObjCObjectPointerType() || 11904 RHSType->isObjCObjectPointerType()) { 11905 const PointerType *LPT = LHSType->getAs<PointerType>(); 11906 const PointerType *RPT = RHSType->getAs<PointerType>(); 11907 if (LPT || RPT) { 11908 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11909 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11910 11911 if (!LPtrToVoid && !RPtrToVoid && 11912 !Context.typesAreCompatible(LHSType, RHSType)) { 11913 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11914 /*isError*/false); 11915 } 11916 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11917 // the RHS, but we have test coverage for this behavior. 11918 // FIXME: Consider using convertPointersToCompositeType in C++. 11919 if (LHSIsNull && !RHSIsNull) { 11920 Expr *E = LHS.get(); 11921 if (getLangOpts().ObjCAutoRefCount) 11922 CheckObjCConversion(SourceRange(), RHSType, E, 11923 CCK_ImplicitConversion); 11924 LHS = ImpCastExprToType(E, RHSType, 11925 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11926 } 11927 else { 11928 Expr *E = RHS.get(); 11929 if (getLangOpts().ObjCAutoRefCount) 11930 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11931 /*Diagnose=*/true, 11932 /*DiagnoseCFAudited=*/false, Opc); 11933 RHS = ImpCastExprToType(E, LHSType, 11934 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11935 } 11936 return computeResultTy(); 11937 } 11938 if (LHSType->isObjCObjectPointerType() && 11939 RHSType->isObjCObjectPointerType()) { 11940 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11941 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11942 /*isError*/false); 11943 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11944 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11945 11946 if (LHSIsNull && !RHSIsNull) 11947 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11948 else 11949 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11950 return computeResultTy(); 11951 } 11952 11953 if (!IsOrdered && LHSType->isBlockPointerType() && 11954 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11955 LHS = ImpCastExprToType(LHS.get(), RHSType, 11956 CK_BlockPointerToObjCPointerCast); 11957 return computeResultTy(); 11958 } else if (!IsOrdered && 11959 LHSType->isBlockCompatibleObjCPointerType(Context) && 11960 RHSType->isBlockPointerType()) { 11961 RHS = ImpCastExprToType(RHS.get(), LHSType, 11962 CK_BlockPointerToObjCPointerCast); 11963 return computeResultTy(); 11964 } 11965 } 11966 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11967 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11968 unsigned DiagID = 0; 11969 bool isError = false; 11970 if (LangOpts.DebuggerSupport) { 11971 // Under a debugger, allow the comparison of pointers to integers, 11972 // since users tend to want to compare addresses. 11973 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11974 (RHSIsNull && RHSType->isIntegerType())) { 11975 if (IsOrdered) { 11976 isError = getLangOpts().CPlusPlus; 11977 DiagID = 11978 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11979 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11980 } 11981 } else if (getLangOpts().CPlusPlus) { 11982 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11983 isError = true; 11984 } else if (IsOrdered) 11985 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11986 else 11987 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11988 11989 if (DiagID) { 11990 Diag(Loc, DiagID) 11991 << LHSType << RHSType << LHS.get()->getSourceRange() 11992 << RHS.get()->getSourceRange(); 11993 if (isError) 11994 return QualType(); 11995 } 11996 11997 if (LHSType->isIntegerType()) 11998 LHS = ImpCastExprToType(LHS.get(), RHSType, 11999 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12000 else 12001 RHS = ImpCastExprToType(RHS.get(), LHSType, 12002 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12003 return computeResultTy(); 12004 } 12005 12006 // Handle block pointers. 12007 if (!IsOrdered && RHSIsNull 12008 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12009 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12010 return computeResultTy(); 12011 } 12012 if (!IsOrdered && LHSIsNull 12013 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12014 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12015 return computeResultTy(); 12016 } 12017 12018 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12019 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12020 return computeResultTy(); 12021 } 12022 12023 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12024 return computeResultTy(); 12025 } 12026 12027 if (LHSIsNull && RHSType->isQueueT()) { 12028 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12029 return computeResultTy(); 12030 } 12031 12032 if (LHSType->isQueueT() && RHSIsNull) { 12033 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12034 return computeResultTy(); 12035 } 12036 } 12037 12038 return InvalidOperands(Loc, LHS, RHS); 12039 } 12040 12041 // Return a signed ext_vector_type that is of identical size and number of 12042 // elements. For floating point vectors, return an integer type of identical 12043 // size and number of elements. In the non ext_vector_type case, search from 12044 // the largest type to the smallest type to avoid cases where long long == long, 12045 // where long gets picked over long long. 12046 QualType Sema::GetSignedVectorType(QualType V) { 12047 const VectorType *VTy = V->castAs<VectorType>(); 12048 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12049 12050 if (isa<ExtVectorType>(VTy)) { 12051 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12052 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12053 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12054 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12055 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12056 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12057 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12058 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12059 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12060 "Unhandled vector element size in vector compare"); 12061 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12062 } 12063 12064 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12065 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12066 VectorType::GenericVector); 12067 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12068 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12069 VectorType::GenericVector); 12070 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12071 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12072 VectorType::GenericVector); 12073 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12074 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12075 VectorType::GenericVector); 12076 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12077 "Unhandled vector element size in vector compare"); 12078 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12079 VectorType::GenericVector); 12080 } 12081 12082 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12083 /// operates on extended vector types. Instead of producing an IntTy result, 12084 /// like a scalar comparison, a vector comparison produces a vector of integer 12085 /// types. 12086 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12087 SourceLocation Loc, 12088 BinaryOperatorKind Opc) { 12089 if (Opc == BO_Cmp) { 12090 Diag(Loc, diag::err_three_way_vector_comparison); 12091 return QualType(); 12092 } 12093 12094 // Check to make sure we're operating on vectors of the same type and width, 12095 // Allowing one side to be a scalar of element type. 12096 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12097 /*AllowBothBool*/true, 12098 /*AllowBoolConversions*/getLangOpts().ZVector); 12099 if (vType.isNull()) 12100 return vType; 12101 12102 QualType LHSType = LHS.get()->getType(); 12103 12104 // If AltiVec, the comparison results in a numeric type, i.e. 12105 // bool for C++, int for C 12106 if (getLangOpts().AltiVec && 12107 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12108 return Context.getLogicalOperationType(); 12109 12110 // For non-floating point types, check for self-comparisons of the form 12111 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12112 // often indicate logic errors in the program. 12113 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12114 12115 // Check for comparisons of floating point operands using != and ==. 12116 if (BinaryOperator::isEqualityOp(Opc) && 12117 LHSType->hasFloatingRepresentation()) { 12118 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12119 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12120 } 12121 12122 // Return a signed type for the vector. 12123 return GetSignedVectorType(vType); 12124 } 12125 12126 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12127 const ExprResult &XorRHS, 12128 const SourceLocation Loc) { 12129 // Do not diagnose macros. 12130 if (Loc.isMacroID()) 12131 return; 12132 12133 // Do not diagnose if both LHS and RHS are macros. 12134 if (XorLHS.get()->getExprLoc().isMacroID() && 12135 XorRHS.get()->getExprLoc().isMacroID()) 12136 return; 12137 12138 bool Negative = false; 12139 bool ExplicitPlus = false; 12140 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12141 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12142 12143 if (!LHSInt) 12144 return; 12145 if (!RHSInt) { 12146 // Check negative literals. 12147 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12148 UnaryOperatorKind Opc = UO->getOpcode(); 12149 if (Opc != UO_Minus && Opc != UO_Plus) 12150 return; 12151 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12152 if (!RHSInt) 12153 return; 12154 Negative = (Opc == UO_Minus); 12155 ExplicitPlus = !Negative; 12156 } else { 12157 return; 12158 } 12159 } 12160 12161 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12162 llvm::APInt RightSideValue = RHSInt->getValue(); 12163 if (LeftSideValue != 2 && LeftSideValue != 10) 12164 return; 12165 12166 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12167 return; 12168 12169 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12170 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12171 llvm::StringRef ExprStr = 12172 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12173 12174 CharSourceRange XorRange = 12175 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12176 llvm::StringRef XorStr = 12177 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12178 // Do not diagnose if xor keyword/macro is used. 12179 if (XorStr == "xor") 12180 return; 12181 12182 std::string LHSStr = std::string(Lexer::getSourceText( 12183 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12184 S.getSourceManager(), S.getLangOpts())); 12185 std::string RHSStr = std::string(Lexer::getSourceText( 12186 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12187 S.getSourceManager(), S.getLangOpts())); 12188 12189 if (Negative) { 12190 RightSideValue = -RightSideValue; 12191 RHSStr = "-" + RHSStr; 12192 } else if (ExplicitPlus) { 12193 RHSStr = "+" + RHSStr; 12194 } 12195 12196 StringRef LHSStrRef = LHSStr; 12197 StringRef RHSStrRef = RHSStr; 12198 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12199 // literals. 12200 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12201 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12202 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12203 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12204 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12205 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12206 LHSStrRef.find('\'') != StringRef::npos || 12207 RHSStrRef.find('\'') != StringRef::npos) 12208 return; 12209 12210 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12211 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12212 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12213 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12214 std::string SuggestedExpr = "1 << " + RHSStr; 12215 bool Overflow = false; 12216 llvm::APInt One = (LeftSideValue - 1); 12217 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12218 if (Overflow) { 12219 if (RightSideIntValue < 64) 12220 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12221 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12222 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12223 else if (RightSideIntValue == 64) 12224 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12225 else 12226 return; 12227 } else { 12228 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12229 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12230 << PowValue.toString(10, true) 12231 << FixItHint::CreateReplacement( 12232 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12233 } 12234 12235 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12236 } else if (LeftSideValue == 10) { 12237 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12238 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12239 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12240 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12241 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12242 } 12243 } 12244 12245 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12246 SourceLocation Loc) { 12247 // Ensure that either both operands are of the same vector type, or 12248 // one operand is of a vector type and the other is of its element type. 12249 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12250 /*AllowBothBool*/true, 12251 /*AllowBoolConversions*/false); 12252 if (vType.isNull()) 12253 return InvalidOperands(Loc, LHS, RHS); 12254 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12255 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12256 return InvalidOperands(Loc, LHS, RHS); 12257 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12258 // usage of the logical operators && and || with vectors in C. This 12259 // check could be notionally dropped. 12260 if (!getLangOpts().CPlusPlus && 12261 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12262 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12263 12264 return GetSignedVectorType(LHS.get()->getType()); 12265 } 12266 12267 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12268 SourceLocation Loc, 12269 bool IsCompAssign) { 12270 if (!IsCompAssign) { 12271 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12272 if (LHS.isInvalid()) 12273 return QualType(); 12274 } 12275 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12276 if (RHS.isInvalid()) 12277 return QualType(); 12278 12279 // For conversion purposes, we ignore any qualifiers. 12280 // For example, "const float" and "float" are equivalent. 12281 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12282 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12283 12284 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12285 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12286 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12287 12288 if (Context.hasSameType(LHSType, RHSType)) 12289 return LHSType; 12290 12291 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12292 // case we have to return InvalidOperands. 12293 ExprResult OriginalLHS = LHS; 12294 ExprResult OriginalRHS = RHS; 12295 if (LHSMatType && !RHSMatType) { 12296 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12297 if (!RHS.isInvalid()) 12298 return LHSType; 12299 12300 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12301 } 12302 12303 if (!LHSMatType && RHSMatType) { 12304 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12305 if (!LHS.isInvalid()) 12306 return RHSType; 12307 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12308 } 12309 12310 return InvalidOperands(Loc, LHS, RHS); 12311 } 12312 12313 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12314 SourceLocation Loc, 12315 bool IsCompAssign) { 12316 if (!IsCompAssign) { 12317 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12318 if (LHS.isInvalid()) 12319 return QualType(); 12320 } 12321 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12322 if (RHS.isInvalid()) 12323 return QualType(); 12324 12325 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12326 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12327 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12328 12329 if (LHSMatType && RHSMatType) { 12330 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12331 return InvalidOperands(Loc, LHS, RHS); 12332 12333 if (!Context.hasSameType(LHSMatType->getElementType(), 12334 RHSMatType->getElementType())) 12335 return InvalidOperands(Loc, LHS, RHS); 12336 12337 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12338 LHSMatType->getNumRows(), 12339 RHSMatType->getNumColumns()); 12340 } 12341 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12342 } 12343 12344 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12345 SourceLocation Loc, 12346 BinaryOperatorKind Opc) { 12347 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12348 12349 bool IsCompAssign = 12350 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12351 12352 if (LHS.get()->getType()->isVectorType() || 12353 RHS.get()->getType()->isVectorType()) { 12354 if (LHS.get()->getType()->hasIntegerRepresentation() && 12355 RHS.get()->getType()->hasIntegerRepresentation()) 12356 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12357 /*AllowBothBool*/true, 12358 /*AllowBoolConversions*/getLangOpts().ZVector); 12359 return InvalidOperands(Loc, LHS, RHS); 12360 } 12361 12362 if (Opc == BO_And) 12363 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12364 12365 if (LHS.get()->getType()->hasFloatingRepresentation() || 12366 RHS.get()->getType()->hasFloatingRepresentation()) 12367 return InvalidOperands(Loc, LHS, RHS); 12368 12369 ExprResult LHSResult = LHS, RHSResult = RHS; 12370 QualType compType = UsualArithmeticConversions( 12371 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12372 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12373 return QualType(); 12374 LHS = LHSResult.get(); 12375 RHS = RHSResult.get(); 12376 12377 if (Opc == BO_Xor) 12378 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12379 12380 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12381 return compType; 12382 return InvalidOperands(Loc, LHS, RHS); 12383 } 12384 12385 // C99 6.5.[13,14] 12386 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12387 SourceLocation Loc, 12388 BinaryOperatorKind Opc) { 12389 // Check vector operands differently. 12390 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12391 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12392 12393 bool EnumConstantInBoolContext = false; 12394 for (const ExprResult &HS : {LHS, RHS}) { 12395 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12396 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12397 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12398 EnumConstantInBoolContext = true; 12399 } 12400 } 12401 12402 if (EnumConstantInBoolContext) 12403 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12404 12405 // Diagnose cases where the user write a logical and/or but probably meant a 12406 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12407 // is a constant. 12408 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12409 !LHS.get()->getType()->isBooleanType() && 12410 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12411 // Don't warn in macros or template instantiations. 12412 !Loc.isMacroID() && !inTemplateInstantiation()) { 12413 // If the RHS can be constant folded, and if it constant folds to something 12414 // that isn't 0 or 1 (which indicate a potential logical operation that 12415 // happened to fold to true/false) then warn. 12416 // Parens on the RHS are ignored. 12417 Expr::EvalResult EVResult; 12418 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12419 llvm::APSInt Result = EVResult.Val.getInt(); 12420 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12421 !RHS.get()->getExprLoc().isMacroID()) || 12422 (Result != 0 && Result != 1)) { 12423 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12424 << RHS.get()->getSourceRange() 12425 << (Opc == BO_LAnd ? "&&" : "||"); 12426 // Suggest replacing the logical operator with the bitwise version 12427 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12428 << (Opc == BO_LAnd ? "&" : "|") 12429 << FixItHint::CreateReplacement(SourceRange( 12430 Loc, getLocForEndOfToken(Loc)), 12431 Opc == BO_LAnd ? "&" : "|"); 12432 if (Opc == BO_LAnd) 12433 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12434 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12435 << FixItHint::CreateRemoval( 12436 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12437 RHS.get()->getEndLoc())); 12438 } 12439 } 12440 } 12441 12442 if (!Context.getLangOpts().CPlusPlus) { 12443 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12444 // not operate on the built-in scalar and vector float types. 12445 if (Context.getLangOpts().OpenCL && 12446 Context.getLangOpts().OpenCLVersion < 120) { 12447 if (LHS.get()->getType()->isFloatingType() || 12448 RHS.get()->getType()->isFloatingType()) 12449 return InvalidOperands(Loc, LHS, RHS); 12450 } 12451 12452 LHS = UsualUnaryConversions(LHS.get()); 12453 if (LHS.isInvalid()) 12454 return QualType(); 12455 12456 RHS = UsualUnaryConversions(RHS.get()); 12457 if (RHS.isInvalid()) 12458 return QualType(); 12459 12460 if (!LHS.get()->getType()->isScalarType() || 12461 !RHS.get()->getType()->isScalarType()) 12462 return InvalidOperands(Loc, LHS, RHS); 12463 12464 return Context.IntTy; 12465 } 12466 12467 // The following is safe because we only use this method for 12468 // non-overloadable operands. 12469 12470 // C++ [expr.log.and]p1 12471 // C++ [expr.log.or]p1 12472 // The operands are both contextually converted to type bool. 12473 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12474 if (LHSRes.isInvalid()) 12475 return InvalidOperands(Loc, LHS, RHS); 12476 LHS = LHSRes; 12477 12478 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12479 if (RHSRes.isInvalid()) 12480 return InvalidOperands(Loc, LHS, RHS); 12481 RHS = RHSRes; 12482 12483 // C++ [expr.log.and]p2 12484 // C++ [expr.log.or]p2 12485 // The result is a bool. 12486 return Context.BoolTy; 12487 } 12488 12489 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12490 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12491 if (!ME) return false; 12492 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12493 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12494 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12495 if (!Base) return false; 12496 return Base->getMethodDecl() != nullptr; 12497 } 12498 12499 /// Is the given expression (which must be 'const') a reference to a 12500 /// variable which was originally non-const, but which has become 12501 /// 'const' due to being captured within a block? 12502 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12503 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12504 assert(E->isLValue() && E->getType().isConstQualified()); 12505 E = E->IgnoreParens(); 12506 12507 // Must be a reference to a declaration from an enclosing scope. 12508 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12509 if (!DRE) return NCCK_None; 12510 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12511 12512 // The declaration must be a variable which is not declared 'const'. 12513 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12514 if (!var) return NCCK_None; 12515 if (var->getType().isConstQualified()) return NCCK_None; 12516 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12517 12518 // Decide whether the first capture was for a block or a lambda. 12519 DeclContext *DC = S.CurContext, *Prev = nullptr; 12520 // Decide whether the first capture was for a block or a lambda. 12521 while (DC) { 12522 // For init-capture, it is possible that the variable belongs to the 12523 // template pattern of the current context. 12524 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12525 if (var->isInitCapture() && 12526 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12527 break; 12528 if (DC == var->getDeclContext()) 12529 break; 12530 Prev = DC; 12531 DC = DC->getParent(); 12532 } 12533 // Unless we have an init-capture, we've gone one step too far. 12534 if (!var->isInitCapture()) 12535 DC = Prev; 12536 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12537 } 12538 12539 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12540 Ty = Ty.getNonReferenceType(); 12541 if (IsDereference && Ty->isPointerType()) 12542 Ty = Ty->getPointeeType(); 12543 return !Ty.isConstQualified(); 12544 } 12545 12546 // Update err_typecheck_assign_const and note_typecheck_assign_const 12547 // when this enum is changed. 12548 enum { 12549 ConstFunction, 12550 ConstVariable, 12551 ConstMember, 12552 ConstMethod, 12553 NestedConstMember, 12554 ConstUnknown, // Keep as last element 12555 }; 12556 12557 /// Emit the "read-only variable not assignable" error and print notes to give 12558 /// more information about why the variable is not assignable, such as pointing 12559 /// to the declaration of a const variable, showing that a method is const, or 12560 /// that the function is returning a const reference. 12561 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12562 SourceLocation Loc) { 12563 SourceRange ExprRange = E->getSourceRange(); 12564 12565 // Only emit one error on the first const found. All other consts will emit 12566 // a note to the error. 12567 bool DiagnosticEmitted = false; 12568 12569 // Track if the current expression is the result of a dereference, and if the 12570 // next checked expression is the result of a dereference. 12571 bool IsDereference = false; 12572 bool NextIsDereference = false; 12573 12574 // Loop to process MemberExpr chains. 12575 while (true) { 12576 IsDereference = NextIsDereference; 12577 12578 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12579 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12580 NextIsDereference = ME->isArrow(); 12581 const ValueDecl *VD = ME->getMemberDecl(); 12582 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12583 // Mutable fields can be modified even if the class is const. 12584 if (Field->isMutable()) { 12585 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12586 break; 12587 } 12588 12589 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12590 if (!DiagnosticEmitted) { 12591 S.Diag(Loc, diag::err_typecheck_assign_const) 12592 << ExprRange << ConstMember << false /*static*/ << Field 12593 << Field->getType(); 12594 DiagnosticEmitted = true; 12595 } 12596 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12597 << ConstMember << false /*static*/ << Field << Field->getType() 12598 << Field->getSourceRange(); 12599 } 12600 E = ME->getBase(); 12601 continue; 12602 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12603 if (VDecl->getType().isConstQualified()) { 12604 if (!DiagnosticEmitted) { 12605 S.Diag(Loc, diag::err_typecheck_assign_const) 12606 << ExprRange << ConstMember << true /*static*/ << VDecl 12607 << VDecl->getType(); 12608 DiagnosticEmitted = true; 12609 } 12610 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12611 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12612 << VDecl->getSourceRange(); 12613 } 12614 // Static fields do not inherit constness from parents. 12615 break; 12616 } 12617 break; // End MemberExpr 12618 } else if (const ArraySubscriptExpr *ASE = 12619 dyn_cast<ArraySubscriptExpr>(E)) { 12620 E = ASE->getBase()->IgnoreParenImpCasts(); 12621 continue; 12622 } else if (const ExtVectorElementExpr *EVE = 12623 dyn_cast<ExtVectorElementExpr>(E)) { 12624 E = EVE->getBase()->IgnoreParenImpCasts(); 12625 continue; 12626 } 12627 break; 12628 } 12629 12630 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12631 // Function calls 12632 const FunctionDecl *FD = CE->getDirectCallee(); 12633 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12634 if (!DiagnosticEmitted) { 12635 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12636 << ConstFunction << FD; 12637 DiagnosticEmitted = true; 12638 } 12639 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12640 diag::note_typecheck_assign_const) 12641 << ConstFunction << FD << FD->getReturnType() 12642 << FD->getReturnTypeSourceRange(); 12643 } 12644 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12645 // Point to variable declaration. 12646 if (const ValueDecl *VD = DRE->getDecl()) { 12647 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12648 if (!DiagnosticEmitted) { 12649 S.Diag(Loc, diag::err_typecheck_assign_const) 12650 << ExprRange << ConstVariable << VD << VD->getType(); 12651 DiagnosticEmitted = true; 12652 } 12653 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12654 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12655 } 12656 } 12657 } else if (isa<CXXThisExpr>(E)) { 12658 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12659 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12660 if (MD->isConst()) { 12661 if (!DiagnosticEmitted) { 12662 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12663 << ConstMethod << MD; 12664 DiagnosticEmitted = true; 12665 } 12666 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12667 << ConstMethod << MD << MD->getSourceRange(); 12668 } 12669 } 12670 } 12671 } 12672 12673 if (DiagnosticEmitted) 12674 return; 12675 12676 // Can't determine a more specific message, so display the generic error. 12677 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12678 } 12679 12680 enum OriginalExprKind { 12681 OEK_Variable, 12682 OEK_Member, 12683 OEK_LValue 12684 }; 12685 12686 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12687 const RecordType *Ty, 12688 SourceLocation Loc, SourceRange Range, 12689 OriginalExprKind OEK, 12690 bool &DiagnosticEmitted) { 12691 std::vector<const RecordType *> RecordTypeList; 12692 RecordTypeList.push_back(Ty); 12693 unsigned NextToCheckIndex = 0; 12694 // We walk the record hierarchy breadth-first to ensure that we print 12695 // diagnostics in field nesting order. 12696 while (RecordTypeList.size() > NextToCheckIndex) { 12697 bool IsNested = NextToCheckIndex > 0; 12698 for (const FieldDecl *Field : 12699 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12700 // First, check every field for constness. 12701 QualType FieldTy = Field->getType(); 12702 if (FieldTy.isConstQualified()) { 12703 if (!DiagnosticEmitted) { 12704 S.Diag(Loc, diag::err_typecheck_assign_const) 12705 << Range << NestedConstMember << OEK << VD 12706 << IsNested << Field; 12707 DiagnosticEmitted = true; 12708 } 12709 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12710 << NestedConstMember << IsNested << Field 12711 << FieldTy << Field->getSourceRange(); 12712 } 12713 12714 // Then we append it to the list to check next in order. 12715 FieldTy = FieldTy.getCanonicalType(); 12716 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12717 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12718 RecordTypeList.push_back(FieldRecTy); 12719 } 12720 } 12721 ++NextToCheckIndex; 12722 } 12723 } 12724 12725 /// Emit an error for the case where a record we are trying to assign to has a 12726 /// const-qualified field somewhere in its hierarchy. 12727 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12728 SourceLocation Loc) { 12729 QualType Ty = E->getType(); 12730 assert(Ty->isRecordType() && "lvalue was not record?"); 12731 SourceRange Range = E->getSourceRange(); 12732 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12733 bool DiagEmitted = false; 12734 12735 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12736 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12737 Range, OEK_Member, DiagEmitted); 12738 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12739 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12740 Range, OEK_Variable, DiagEmitted); 12741 else 12742 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12743 Range, OEK_LValue, DiagEmitted); 12744 if (!DiagEmitted) 12745 DiagnoseConstAssignment(S, E, Loc); 12746 } 12747 12748 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12749 /// emit an error and return true. If so, return false. 12750 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12751 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12752 12753 S.CheckShadowingDeclModification(E, Loc); 12754 12755 SourceLocation OrigLoc = Loc; 12756 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12757 &Loc); 12758 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12759 IsLV = Expr::MLV_InvalidMessageExpression; 12760 if (IsLV == Expr::MLV_Valid) 12761 return false; 12762 12763 unsigned DiagID = 0; 12764 bool NeedType = false; 12765 switch (IsLV) { // C99 6.5.16p2 12766 case Expr::MLV_ConstQualified: 12767 // Use a specialized diagnostic when we're assigning to an object 12768 // from an enclosing function or block. 12769 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12770 if (NCCK == NCCK_Block) 12771 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12772 else 12773 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12774 break; 12775 } 12776 12777 // In ARC, use some specialized diagnostics for occasions where we 12778 // infer 'const'. These are always pseudo-strong variables. 12779 if (S.getLangOpts().ObjCAutoRefCount) { 12780 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12781 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12782 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12783 12784 // Use the normal diagnostic if it's pseudo-__strong but the 12785 // user actually wrote 'const'. 12786 if (var->isARCPseudoStrong() && 12787 (!var->getTypeSourceInfo() || 12788 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12789 // There are three pseudo-strong cases: 12790 // - self 12791 ObjCMethodDecl *method = S.getCurMethodDecl(); 12792 if (method && var == method->getSelfDecl()) { 12793 DiagID = method->isClassMethod() 12794 ? diag::err_typecheck_arc_assign_self_class_method 12795 : diag::err_typecheck_arc_assign_self; 12796 12797 // - Objective-C externally_retained attribute. 12798 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12799 isa<ParmVarDecl>(var)) { 12800 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12801 12802 // - fast enumeration variables 12803 } else { 12804 DiagID = diag::err_typecheck_arr_assign_enumeration; 12805 } 12806 12807 SourceRange Assign; 12808 if (Loc != OrigLoc) 12809 Assign = SourceRange(OrigLoc, OrigLoc); 12810 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12811 // We need to preserve the AST regardless, so migration tool 12812 // can do its job. 12813 return false; 12814 } 12815 } 12816 } 12817 12818 // If none of the special cases above are triggered, then this is a 12819 // simple const assignment. 12820 if (DiagID == 0) { 12821 DiagnoseConstAssignment(S, E, Loc); 12822 return true; 12823 } 12824 12825 break; 12826 case Expr::MLV_ConstAddrSpace: 12827 DiagnoseConstAssignment(S, E, Loc); 12828 return true; 12829 case Expr::MLV_ConstQualifiedField: 12830 DiagnoseRecursiveConstFields(S, E, Loc); 12831 return true; 12832 case Expr::MLV_ArrayType: 12833 case Expr::MLV_ArrayTemporary: 12834 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12835 NeedType = true; 12836 break; 12837 case Expr::MLV_NotObjectType: 12838 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12839 NeedType = true; 12840 break; 12841 case Expr::MLV_LValueCast: 12842 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12843 break; 12844 case Expr::MLV_Valid: 12845 llvm_unreachable("did not take early return for MLV_Valid"); 12846 case Expr::MLV_InvalidExpression: 12847 case Expr::MLV_MemberFunction: 12848 case Expr::MLV_ClassTemporary: 12849 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12850 break; 12851 case Expr::MLV_IncompleteType: 12852 case Expr::MLV_IncompleteVoidType: 12853 return S.RequireCompleteType(Loc, E->getType(), 12854 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12855 case Expr::MLV_DuplicateVectorComponents: 12856 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12857 break; 12858 case Expr::MLV_NoSetterProperty: 12859 llvm_unreachable("readonly properties should be processed differently"); 12860 case Expr::MLV_InvalidMessageExpression: 12861 DiagID = diag::err_readonly_message_assignment; 12862 break; 12863 case Expr::MLV_SubObjCPropertySetting: 12864 DiagID = diag::err_no_subobject_property_setting; 12865 break; 12866 } 12867 12868 SourceRange Assign; 12869 if (Loc != OrigLoc) 12870 Assign = SourceRange(OrigLoc, OrigLoc); 12871 if (NeedType) 12872 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12873 else 12874 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12875 return true; 12876 } 12877 12878 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12879 SourceLocation Loc, 12880 Sema &Sema) { 12881 if (Sema.inTemplateInstantiation()) 12882 return; 12883 if (Sema.isUnevaluatedContext()) 12884 return; 12885 if (Loc.isInvalid() || Loc.isMacroID()) 12886 return; 12887 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12888 return; 12889 12890 // C / C++ fields 12891 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12892 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12893 if (ML && MR) { 12894 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12895 return; 12896 const ValueDecl *LHSDecl = 12897 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12898 const ValueDecl *RHSDecl = 12899 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12900 if (LHSDecl != RHSDecl) 12901 return; 12902 if (LHSDecl->getType().isVolatileQualified()) 12903 return; 12904 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12905 if (RefTy->getPointeeType().isVolatileQualified()) 12906 return; 12907 12908 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12909 } 12910 12911 // Objective-C instance variables 12912 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12913 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12914 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12915 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12916 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12917 if (RL && RR && RL->getDecl() == RR->getDecl()) 12918 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12919 } 12920 } 12921 12922 // C99 6.5.16.1 12923 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12924 SourceLocation Loc, 12925 QualType CompoundType) { 12926 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12927 12928 // Verify that LHS is a modifiable lvalue, and emit error if not. 12929 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12930 return QualType(); 12931 12932 QualType LHSType = LHSExpr->getType(); 12933 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12934 CompoundType; 12935 // OpenCL v1.2 s6.1.1.1 p2: 12936 // The half data type can only be used to declare a pointer to a buffer that 12937 // contains half values 12938 if (getLangOpts().OpenCL && 12939 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 12940 LHSType->isHalfType()) { 12941 Diag(Loc, diag::err_opencl_half_load_store) << 1 12942 << LHSType.getUnqualifiedType(); 12943 return QualType(); 12944 } 12945 12946 AssignConvertType ConvTy; 12947 if (CompoundType.isNull()) { 12948 Expr *RHSCheck = RHS.get(); 12949 12950 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12951 12952 QualType LHSTy(LHSType); 12953 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12954 if (RHS.isInvalid()) 12955 return QualType(); 12956 // Special case of NSObject attributes on c-style pointer types. 12957 if (ConvTy == IncompatiblePointer && 12958 ((Context.isObjCNSObjectType(LHSType) && 12959 RHSType->isObjCObjectPointerType()) || 12960 (Context.isObjCNSObjectType(RHSType) && 12961 LHSType->isObjCObjectPointerType()))) 12962 ConvTy = Compatible; 12963 12964 if (ConvTy == Compatible && 12965 LHSType->isObjCObjectType()) 12966 Diag(Loc, diag::err_objc_object_assignment) 12967 << LHSType; 12968 12969 // If the RHS is a unary plus or minus, check to see if they = and + are 12970 // right next to each other. If so, the user may have typo'd "x =+ 4" 12971 // instead of "x += 4". 12972 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12973 RHSCheck = ICE->getSubExpr(); 12974 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12975 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12976 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12977 // Only if the two operators are exactly adjacent. 12978 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12979 // And there is a space or other character before the subexpr of the 12980 // unary +/-. We don't want to warn on "x=-1". 12981 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12982 UO->getSubExpr()->getBeginLoc().isFileID()) { 12983 Diag(Loc, diag::warn_not_compound_assign) 12984 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12985 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12986 } 12987 } 12988 12989 if (ConvTy == Compatible) { 12990 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12991 // Warn about retain cycles where a block captures the LHS, but 12992 // not if the LHS is a simple variable into which the block is 12993 // being stored...unless that variable can be captured by reference! 12994 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12995 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12996 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12997 checkRetainCycles(LHSExpr, RHS.get()); 12998 } 12999 13000 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13001 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13002 // It is safe to assign a weak reference into a strong variable. 13003 // Although this code can still have problems: 13004 // id x = self.weakProp; 13005 // id y = self.weakProp; 13006 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13007 // paths through the function. This should be revisited if 13008 // -Wrepeated-use-of-weak is made flow-sensitive. 13009 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13010 // variable, which will be valid for the current autorelease scope. 13011 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13012 RHS.get()->getBeginLoc())) 13013 getCurFunction()->markSafeWeakUse(RHS.get()); 13014 13015 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13016 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13017 } 13018 } 13019 } else { 13020 // Compound assignment "x += y" 13021 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13022 } 13023 13024 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13025 RHS.get(), AA_Assigning)) 13026 return QualType(); 13027 13028 CheckForNullPointerDereference(*this, LHSExpr); 13029 13030 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13031 if (CompoundType.isNull()) { 13032 // C++2a [expr.ass]p5: 13033 // A simple-assignment whose left operand is of a volatile-qualified 13034 // type is deprecated unless the assignment is either a discarded-value 13035 // expression or an unevaluated operand 13036 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13037 } else { 13038 // C++2a [expr.ass]p6: 13039 // [Compound-assignment] expressions are deprecated if E1 has 13040 // volatile-qualified type 13041 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13042 } 13043 } 13044 13045 // C99 6.5.16p3: The type of an assignment expression is the type of the 13046 // left operand unless the left operand has qualified type, in which case 13047 // it is the unqualified version of the type of the left operand. 13048 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13049 // is converted to the type of the assignment expression (above). 13050 // C++ 5.17p1: the type of the assignment expression is that of its left 13051 // operand. 13052 return (getLangOpts().CPlusPlus 13053 ? LHSType : LHSType.getUnqualifiedType()); 13054 } 13055 13056 // Only ignore explicit casts to void. 13057 static bool IgnoreCommaOperand(const Expr *E) { 13058 E = E->IgnoreParens(); 13059 13060 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13061 if (CE->getCastKind() == CK_ToVoid) { 13062 return true; 13063 } 13064 13065 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13066 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13067 CE->getSubExpr()->getType()->isDependentType()) { 13068 return true; 13069 } 13070 } 13071 13072 return false; 13073 } 13074 13075 // Look for instances where it is likely the comma operator is confused with 13076 // another operator. There is an explicit list of acceptable expressions for 13077 // the left hand side of the comma operator, otherwise emit a warning. 13078 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13079 // No warnings in macros 13080 if (Loc.isMacroID()) 13081 return; 13082 13083 // Don't warn in template instantiations. 13084 if (inTemplateInstantiation()) 13085 return; 13086 13087 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13088 // instead, skip more than needed, then call back into here with the 13089 // CommaVisitor in SemaStmt.cpp. 13090 // The listed locations are the initialization and increment portions 13091 // of a for loop. The additional checks are on the condition of 13092 // if statements, do/while loops, and for loops. 13093 // Differences in scope flags for C89 mode requires the extra logic. 13094 const unsigned ForIncrementFlags = 13095 getLangOpts().C99 || getLangOpts().CPlusPlus 13096 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13097 : Scope::ContinueScope | Scope::BreakScope; 13098 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13099 const unsigned ScopeFlags = getCurScope()->getFlags(); 13100 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13101 (ScopeFlags & ForInitFlags) == ForInitFlags) 13102 return; 13103 13104 // If there are multiple comma operators used together, get the RHS of the 13105 // of the comma operator as the LHS. 13106 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13107 if (BO->getOpcode() != BO_Comma) 13108 break; 13109 LHS = BO->getRHS(); 13110 } 13111 13112 // Only allow some expressions on LHS to not warn. 13113 if (IgnoreCommaOperand(LHS)) 13114 return; 13115 13116 Diag(Loc, diag::warn_comma_operator); 13117 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13118 << LHS->getSourceRange() 13119 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13120 LangOpts.CPlusPlus ? "static_cast<void>(" 13121 : "(void)(") 13122 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13123 ")"); 13124 } 13125 13126 // C99 6.5.17 13127 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13128 SourceLocation Loc) { 13129 LHS = S.CheckPlaceholderExpr(LHS.get()); 13130 RHS = S.CheckPlaceholderExpr(RHS.get()); 13131 if (LHS.isInvalid() || RHS.isInvalid()) 13132 return QualType(); 13133 13134 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13135 // operands, but not unary promotions. 13136 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13137 13138 // So we treat the LHS as a ignored value, and in C++ we allow the 13139 // containing site to determine what should be done with the RHS. 13140 LHS = S.IgnoredValueConversions(LHS.get()); 13141 if (LHS.isInvalid()) 13142 return QualType(); 13143 13144 S.DiagnoseUnusedExprResult(LHS.get()); 13145 13146 if (!S.getLangOpts().CPlusPlus) { 13147 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13148 if (RHS.isInvalid()) 13149 return QualType(); 13150 if (!RHS.get()->getType()->isVoidType()) 13151 S.RequireCompleteType(Loc, RHS.get()->getType(), 13152 diag::err_incomplete_type); 13153 } 13154 13155 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13156 S.DiagnoseCommaOperator(LHS.get(), Loc); 13157 13158 return RHS.get()->getType(); 13159 } 13160 13161 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13162 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13163 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13164 ExprValueKind &VK, 13165 ExprObjectKind &OK, 13166 SourceLocation OpLoc, 13167 bool IsInc, bool IsPrefix) { 13168 if (Op->isTypeDependent()) 13169 return S.Context.DependentTy; 13170 13171 QualType ResType = Op->getType(); 13172 // Atomic types can be used for increment / decrement where the non-atomic 13173 // versions can, so ignore the _Atomic() specifier for the purpose of 13174 // checking. 13175 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13176 ResType = ResAtomicType->getValueType(); 13177 13178 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13179 13180 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13181 // Decrement of bool is not allowed. 13182 if (!IsInc) { 13183 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13184 return QualType(); 13185 } 13186 // Increment of bool sets it to true, but is deprecated. 13187 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13188 : diag::warn_increment_bool) 13189 << Op->getSourceRange(); 13190 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13191 // Error on enum increments and decrements in C++ mode 13192 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13193 return QualType(); 13194 } else if (ResType->isRealType()) { 13195 // OK! 13196 } else if (ResType->isPointerType()) { 13197 // C99 6.5.2.4p2, 6.5.6p2 13198 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13199 return QualType(); 13200 } else if (ResType->isObjCObjectPointerType()) { 13201 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13202 // Otherwise, we just need a complete type. 13203 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13204 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13205 return QualType(); 13206 } else if (ResType->isAnyComplexType()) { 13207 // C99 does not support ++/-- on complex types, we allow as an extension. 13208 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13209 << ResType << Op->getSourceRange(); 13210 } else if (ResType->isPlaceholderType()) { 13211 ExprResult PR = S.CheckPlaceholderExpr(Op); 13212 if (PR.isInvalid()) return QualType(); 13213 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13214 IsInc, IsPrefix); 13215 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13216 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13217 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13218 (ResType->castAs<VectorType>()->getVectorKind() != 13219 VectorType::AltiVecBool)) { 13220 // The z vector extensions allow ++ and -- for non-bool vectors. 13221 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13222 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13223 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13224 } else { 13225 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13226 << ResType << int(IsInc) << Op->getSourceRange(); 13227 return QualType(); 13228 } 13229 // At this point, we know we have a real, complex or pointer type. 13230 // Now make sure the operand is a modifiable lvalue. 13231 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13232 return QualType(); 13233 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13234 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13235 // An operand with volatile-qualified type is deprecated 13236 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13237 << IsInc << ResType; 13238 } 13239 // In C++, a prefix increment is the same type as the operand. Otherwise 13240 // (in C or with postfix), the increment is the unqualified type of the 13241 // operand. 13242 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13243 VK = VK_LValue; 13244 OK = Op->getObjectKind(); 13245 return ResType; 13246 } else { 13247 VK = VK_RValue; 13248 return ResType.getUnqualifiedType(); 13249 } 13250 } 13251 13252 13253 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13254 /// This routine allows us to typecheck complex/recursive expressions 13255 /// where the declaration is needed for type checking. We only need to 13256 /// handle cases when the expression references a function designator 13257 /// or is an lvalue. Here are some examples: 13258 /// - &(x) => x 13259 /// - &*****f => f for f a function designator. 13260 /// - &s.xx => s 13261 /// - &s.zz[1].yy -> s, if zz is an array 13262 /// - *(x + 1) -> x, if x is an array 13263 /// - &"123"[2] -> 0 13264 /// - & __real__ x -> x 13265 /// 13266 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13267 /// members. 13268 static ValueDecl *getPrimaryDecl(Expr *E) { 13269 switch (E->getStmtClass()) { 13270 case Stmt::DeclRefExprClass: 13271 return cast<DeclRefExpr>(E)->getDecl(); 13272 case Stmt::MemberExprClass: 13273 // If this is an arrow operator, the address is an offset from 13274 // the base's value, so the object the base refers to is 13275 // irrelevant. 13276 if (cast<MemberExpr>(E)->isArrow()) 13277 return nullptr; 13278 // Otherwise, the expression refers to a part of the base 13279 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13280 case Stmt::ArraySubscriptExprClass: { 13281 // FIXME: This code shouldn't be necessary! We should catch the implicit 13282 // promotion of register arrays earlier. 13283 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13284 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13285 if (ICE->getSubExpr()->getType()->isArrayType()) 13286 return getPrimaryDecl(ICE->getSubExpr()); 13287 } 13288 return nullptr; 13289 } 13290 case Stmt::UnaryOperatorClass: { 13291 UnaryOperator *UO = cast<UnaryOperator>(E); 13292 13293 switch(UO->getOpcode()) { 13294 case UO_Real: 13295 case UO_Imag: 13296 case UO_Extension: 13297 return getPrimaryDecl(UO->getSubExpr()); 13298 default: 13299 return nullptr; 13300 } 13301 } 13302 case Stmt::ParenExprClass: 13303 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13304 case Stmt::ImplicitCastExprClass: 13305 // If the result of an implicit cast is an l-value, we care about 13306 // the sub-expression; otherwise, the result here doesn't matter. 13307 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13308 case Stmt::CXXUuidofExprClass: 13309 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13310 default: 13311 return nullptr; 13312 } 13313 } 13314 13315 namespace { 13316 enum { 13317 AO_Bit_Field = 0, 13318 AO_Vector_Element = 1, 13319 AO_Property_Expansion = 2, 13320 AO_Register_Variable = 3, 13321 AO_Matrix_Element = 4, 13322 AO_No_Error = 5 13323 }; 13324 } 13325 /// Diagnose invalid operand for address of operations. 13326 /// 13327 /// \param Type The type of operand which cannot have its address taken. 13328 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13329 Expr *E, unsigned Type) { 13330 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13331 } 13332 13333 /// CheckAddressOfOperand - The operand of & must be either a function 13334 /// designator or an lvalue designating an object. If it is an lvalue, the 13335 /// object cannot be declared with storage class register or be a bit field. 13336 /// Note: The usual conversions are *not* applied to the operand of the & 13337 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13338 /// In C++, the operand might be an overloaded function name, in which case 13339 /// we allow the '&' but retain the overloaded-function type. 13340 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13341 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13342 if (PTy->getKind() == BuiltinType::Overload) { 13343 Expr *E = OrigOp.get()->IgnoreParens(); 13344 if (!isa<OverloadExpr>(E)) { 13345 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13346 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13347 << OrigOp.get()->getSourceRange(); 13348 return QualType(); 13349 } 13350 13351 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13352 if (isa<UnresolvedMemberExpr>(Ovl)) 13353 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13354 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13355 << OrigOp.get()->getSourceRange(); 13356 return QualType(); 13357 } 13358 13359 return Context.OverloadTy; 13360 } 13361 13362 if (PTy->getKind() == BuiltinType::UnknownAny) 13363 return Context.UnknownAnyTy; 13364 13365 if (PTy->getKind() == BuiltinType::BoundMember) { 13366 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13367 << OrigOp.get()->getSourceRange(); 13368 return QualType(); 13369 } 13370 13371 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13372 if (OrigOp.isInvalid()) return QualType(); 13373 } 13374 13375 if (OrigOp.get()->isTypeDependent()) 13376 return Context.DependentTy; 13377 13378 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13379 13380 // Make sure to ignore parentheses in subsequent checks 13381 Expr *op = OrigOp.get()->IgnoreParens(); 13382 13383 // In OpenCL captures for blocks called as lambda functions 13384 // are located in the private address space. Blocks used in 13385 // enqueue_kernel can be located in a different address space 13386 // depending on a vendor implementation. Thus preventing 13387 // taking an address of the capture to avoid invalid AS casts. 13388 if (LangOpts.OpenCL) { 13389 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13390 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13391 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13392 return QualType(); 13393 } 13394 } 13395 13396 if (getLangOpts().C99) { 13397 // Implement C99-only parts of addressof rules. 13398 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13399 if (uOp->getOpcode() == UO_Deref) 13400 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13401 // (assuming the deref expression is valid). 13402 return uOp->getSubExpr()->getType(); 13403 } 13404 // Technically, there should be a check for array subscript 13405 // expressions here, but the result of one is always an lvalue anyway. 13406 } 13407 ValueDecl *dcl = getPrimaryDecl(op); 13408 13409 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13410 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13411 op->getBeginLoc())) 13412 return QualType(); 13413 13414 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13415 unsigned AddressOfError = AO_No_Error; 13416 13417 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13418 bool sfinae = (bool)isSFINAEContext(); 13419 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13420 : diag::ext_typecheck_addrof_temporary) 13421 << op->getType() << op->getSourceRange(); 13422 if (sfinae) 13423 return QualType(); 13424 // Materialize the temporary as an lvalue so that we can take its address. 13425 OrigOp = op = 13426 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13427 } else if (isa<ObjCSelectorExpr>(op)) { 13428 return Context.getPointerType(op->getType()); 13429 } else if (lval == Expr::LV_MemberFunction) { 13430 // If it's an instance method, make a member pointer. 13431 // The expression must have exactly the form &A::foo. 13432 13433 // If the underlying expression isn't a decl ref, give up. 13434 if (!isa<DeclRefExpr>(op)) { 13435 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13436 << OrigOp.get()->getSourceRange(); 13437 return QualType(); 13438 } 13439 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13440 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13441 13442 // The id-expression was parenthesized. 13443 if (OrigOp.get() != DRE) { 13444 Diag(OpLoc, diag::err_parens_pointer_member_function) 13445 << OrigOp.get()->getSourceRange(); 13446 13447 // The method was named without a qualifier. 13448 } else if (!DRE->getQualifier()) { 13449 if (MD->getParent()->getName().empty()) 13450 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13451 << op->getSourceRange(); 13452 else { 13453 SmallString<32> Str; 13454 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13455 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13456 << op->getSourceRange() 13457 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13458 } 13459 } 13460 13461 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13462 if (isa<CXXDestructorDecl>(MD)) 13463 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13464 13465 QualType MPTy = Context.getMemberPointerType( 13466 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13467 // Under the MS ABI, lock down the inheritance model now. 13468 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13469 (void)isCompleteType(OpLoc, MPTy); 13470 return MPTy; 13471 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13472 // C99 6.5.3.2p1 13473 // The operand must be either an l-value or a function designator 13474 if (!op->getType()->isFunctionType()) { 13475 // Use a special diagnostic for loads from property references. 13476 if (isa<PseudoObjectExpr>(op)) { 13477 AddressOfError = AO_Property_Expansion; 13478 } else { 13479 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13480 << op->getType() << op->getSourceRange(); 13481 return QualType(); 13482 } 13483 } 13484 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13485 // The operand cannot be a bit-field 13486 AddressOfError = AO_Bit_Field; 13487 } else if (op->getObjectKind() == OK_VectorComponent) { 13488 // The operand cannot be an element of a vector 13489 AddressOfError = AO_Vector_Element; 13490 } else if (op->getObjectKind() == OK_MatrixComponent) { 13491 // The operand cannot be an element of a matrix. 13492 AddressOfError = AO_Matrix_Element; 13493 } else if (dcl) { // C99 6.5.3.2p1 13494 // We have an lvalue with a decl. Make sure the decl is not declared 13495 // with the register storage-class specifier. 13496 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13497 // in C++ it is not error to take address of a register 13498 // variable (c++03 7.1.1P3) 13499 if (vd->getStorageClass() == SC_Register && 13500 !getLangOpts().CPlusPlus) { 13501 AddressOfError = AO_Register_Variable; 13502 } 13503 } else if (isa<MSPropertyDecl>(dcl)) { 13504 AddressOfError = AO_Property_Expansion; 13505 } else if (isa<FunctionTemplateDecl>(dcl)) { 13506 return Context.OverloadTy; 13507 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13508 // Okay: we can take the address of a field. 13509 // Could be a pointer to member, though, if there is an explicit 13510 // scope qualifier for the class. 13511 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13512 DeclContext *Ctx = dcl->getDeclContext(); 13513 if (Ctx && Ctx->isRecord()) { 13514 if (dcl->getType()->isReferenceType()) { 13515 Diag(OpLoc, 13516 diag::err_cannot_form_pointer_to_member_of_reference_type) 13517 << dcl->getDeclName() << dcl->getType(); 13518 return QualType(); 13519 } 13520 13521 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13522 Ctx = Ctx->getParent(); 13523 13524 QualType MPTy = Context.getMemberPointerType( 13525 op->getType(), 13526 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13527 // Under the MS ABI, lock down the inheritance model now. 13528 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13529 (void)isCompleteType(OpLoc, MPTy); 13530 return MPTy; 13531 } 13532 } 13533 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13534 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13535 llvm_unreachable("Unknown/unexpected decl type"); 13536 } 13537 13538 if (AddressOfError != AO_No_Error) { 13539 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13540 return QualType(); 13541 } 13542 13543 if (lval == Expr::LV_IncompleteVoidType) { 13544 // Taking the address of a void variable is technically illegal, but we 13545 // allow it in cases which are otherwise valid. 13546 // Example: "extern void x; void* y = &x;". 13547 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13548 } 13549 13550 // If the operand has type "type", the result has type "pointer to type". 13551 if (op->getType()->isObjCObjectType()) 13552 return Context.getObjCObjectPointerType(op->getType()); 13553 13554 CheckAddressOfPackedMember(op); 13555 13556 return Context.getPointerType(op->getType()); 13557 } 13558 13559 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13560 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13561 if (!DRE) 13562 return; 13563 const Decl *D = DRE->getDecl(); 13564 if (!D) 13565 return; 13566 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13567 if (!Param) 13568 return; 13569 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13570 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13571 return; 13572 if (FunctionScopeInfo *FD = S.getCurFunction()) 13573 if (!FD->ModifiedNonNullParams.count(Param)) 13574 FD->ModifiedNonNullParams.insert(Param); 13575 } 13576 13577 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13578 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13579 SourceLocation OpLoc) { 13580 if (Op->isTypeDependent()) 13581 return S.Context.DependentTy; 13582 13583 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13584 if (ConvResult.isInvalid()) 13585 return QualType(); 13586 Op = ConvResult.get(); 13587 QualType OpTy = Op->getType(); 13588 QualType Result; 13589 13590 if (isa<CXXReinterpretCastExpr>(Op)) { 13591 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13592 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13593 Op->getSourceRange()); 13594 } 13595 13596 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13597 { 13598 Result = PT->getPointeeType(); 13599 } 13600 else if (const ObjCObjectPointerType *OPT = 13601 OpTy->getAs<ObjCObjectPointerType>()) 13602 Result = OPT->getPointeeType(); 13603 else { 13604 ExprResult PR = S.CheckPlaceholderExpr(Op); 13605 if (PR.isInvalid()) return QualType(); 13606 if (PR.get() != Op) 13607 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13608 } 13609 13610 if (Result.isNull()) { 13611 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13612 << OpTy << Op->getSourceRange(); 13613 return QualType(); 13614 } 13615 13616 // Note that per both C89 and C99, indirection is always legal, even if Result 13617 // is an incomplete type or void. It would be possible to warn about 13618 // dereferencing a void pointer, but it's completely well-defined, and such a 13619 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13620 // for pointers to 'void' but is fine for any other pointer type: 13621 // 13622 // C++ [expr.unary.op]p1: 13623 // [...] the expression to which [the unary * operator] is applied shall 13624 // be a pointer to an object type, or a pointer to a function type 13625 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13626 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13627 << OpTy << Op->getSourceRange(); 13628 13629 // Dereferences are usually l-values... 13630 VK = VK_LValue; 13631 13632 // ...except that certain expressions are never l-values in C. 13633 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13634 VK = VK_RValue; 13635 13636 return Result; 13637 } 13638 13639 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13640 BinaryOperatorKind Opc; 13641 switch (Kind) { 13642 default: llvm_unreachable("Unknown binop!"); 13643 case tok::periodstar: Opc = BO_PtrMemD; break; 13644 case tok::arrowstar: Opc = BO_PtrMemI; break; 13645 case tok::star: Opc = BO_Mul; break; 13646 case tok::slash: Opc = BO_Div; break; 13647 case tok::percent: Opc = BO_Rem; break; 13648 case tok::plus: Opc = BO_Add; break; 13649 case tok::minus: Opc = BO_Sub; break; 13650 case tok::lessless: Opc = BO_Shl; break; 13651 case tok::greatergreater: Opc = BO_Shr; break; 13652 case tok::lessequal: Opc = BO_LE; break; 13653 case tok::less: Opc = BO_LT; break; 13654 case tok::greaterequal: Opc = BO_GE; break; 13655 case tok::greater: Opc = BO_GT; break; 13656 case tok::exclaimequal: Opc = BO_NE; break; 13657 case tok::equalequal: Opc = BO_EQ; break; 13658 case tok::spaceship: Opc = BO_Cmp; break; 13659 case tok::amp: Opc = BO_And; break; 13660 case tok::caret: Opc = BO_Xor; break; 13661 case tok::pipe: Opc = BO_Or; break; 13662 case tok::ampamp: Opc = BO_LAnd; break; 13663 case tok::pipepipe: Opc = BO_LOr; break; 13664 case tok::equal: Opc = BO_Assign; break; 13665 case tok::starequal: Opc = BO_MulAssign; break; 13666 case tok::slashequal: Opc = BO_DivAssign; break; 13667 case tok::percentequal: Opc = BO_RemAssign; break; 13668 case tok::plusequal: Opc = BO_AddAssign; break; 13669 case tok::minusequal: Opc = BO_SubAssign; break; 13670 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13671 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13672 case tok::ampequal: Opc = BO_AndAssign; break; 13673 case tok::caretequal: Opc = BO_XorAssign; break; 13674 case tok::pipeequal: Opc = BO_OrAssign; break; 13675 case tok::comma: Opc = BO_Comma; break; 13676 } 13677 return Opc; 13678 } 13679 13680 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13681 tok::TokenKind Kind) { 13682 UnaryOperatorKind Opc; 13683 switch (Kind) { 13684 default: llvm_unreachable("Unknown unary op!"); 13685 case tok::plusplus: Opc = UO_PreInc; break; 13686 case tok::minusminus: Opc = UO_PreDec; break; 13687 case tok::amp: Opc = UO_AddrOf; break; 13688 case tok::star: Opc = UO_Deref; break; 13689 case tok::plus: Opc = UO_Plus; break; 13690 case tok::minus: Opc = UO_Minus; break; 13691 case tok::tilde: Opc = UO_Not; break; 13692 case tok::exclaim: Opc = UO_LNot; break; 13693 case tok::kw___real: Opc = UO_Real; break; 13694 case tok::kw___imag: Opc = UO_Imag; break; 13695 case tok::kw___extension__: Opc = UO_Extension; break; 13696 } 13697 return Opc; 13698 } 13699 13700 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13701 /// This warning suppressed in the event of macro expansions. 13702 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13703 SourceLocation OpLoc, bool IsBuiltin) { 13704 if (S.inTemplateInstantiation()) 13705 return; 13706 if (S.isUnevaluatedContext()) 13707 return; 13708 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13709 return; 13710 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13711 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13712 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13713 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13714 if (!LHSDeclRef || !RHSDeclRef || 13715 LHSDeclRef->getLocation().isMacroID() || 13716 RHSDeclRef->getLocation().isMacroID()) 13717 return; 13718 const ValueDecl *LHSDecl = 13719 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13720 const ValueDecl *RHSDecl = 13721 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13722 if (LHSDecl != RHSDecl) 13723 return; 13724 if (LHSDecl->getType().isVolatileQualified()) 13725 return; 13726 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13727 if (RefTy->getPointeeType().isVolatileQualified()) 13728 return; 13729 13730 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13731 : diag::warn_self_assignment_overloaded) 13732 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13733 << RHSExpr->getSourceRange(); 13734 } 13735 13736 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13737 /// is usually indicative of introspection within the Objective-C pointer. 13738 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13739 SourceLocation OpLoc) { 13740 if (!S.getLangOpts().ObjC) 13741 return; 13742 13743 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13744 const Expr *LHS = L.get(); 13745 const Expr *RHS = R.get(); 13746 13747 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13748 ObjCPointerExpr = LHS; 13749 OtherExpr = RHS; 13750 } 13751 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13752 ObjCPointerExpr = RHS; 13753 OtherExpr = LHS; 13754 } 13755 13756 // This warning is deliberately made very specific to reduce false 13757 // positives with logic that uses '&' for hashing. This logic mainly 13758 // looks for code trying to introspect into tagged pointers, which 13759 // code should generally never do. 13760 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13761 unsigned Diag = diag::warn_objc_pointer_masking; 13762 // Determine if we are introspecting the result of performSelectorXXX. 13763 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13764 // Special case messages to -performSelector and friends, which 13765 // can return non-pointer values boxed in a pointer value. 13766 // Some clients may wish to silence warnings in this subcase. 13767 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13768 Selector S = ME->getSelector(); 13769 StringRef SelArg0 = S.getNameForSlot(0); 13770 if (SelArg0.startswith("performSelector")) 13771 Diag = diag::warn_objc_pointer_masking_performSelector; 13772 } 13773 13774 S.Diag(OpLoc, Diag) 13775 << ObjCPointerExpr->getSourceRange(); 13776 } 13777 } 13778 13779 static NamedDecl *getDeclFromExpr(Expr *E) { 13780 if (!E) 13781 return nullptr; 13782 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13783 return DRE->getDecl(); 13784 if (auto *ME = dyn_cast<MemberExpr>(E)) 13785 return ME->getMemberDecl(); 13786 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13787 return IRE->getDecl(); 13788 return nullptr; 13789 } 13790 13791 // This helper function promotes a binary operator's operands (which are of a 13792 // half vector type) to a vector of floats and then truncates the result to 13793 // a vector of either half or short. 13794 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13795 BinaryOperatorKind Opc, QualType ResultTy, 13796 ExprValueKind VK, ExprObjectKind OK, 13797 bool IsCompAssign, SourceLocation OpLoc, 13798 FPOptionsOverride FPFeatures) { 13799 auto &Context = S.getASTContext(); 13800 assert((isVector(ResultTy, Context.HalfTy) || 13801 isVector(ResultTy, Context.ShortTy)) && 13802 "Result must be a vector of half or short"); 13803 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13804 isVector(RHS.get()->getType(), Context.HalfTy) && 13805 "both operands expected to be a half vector"); 13806 13807 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13808 QualType BinOpResTy = RHS.get()->getType(); 13809 13810 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13811 // change BinOpResTy to a vector of ints. 13812 if (isVector(ResultTy, Context.ShortTy)) 13813 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13814 13815 if (IsCompAssign) 13816 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13817 ResultTy, VK, OK, OpLoc, FPFeatures, 13818 BinOpResTy, BinOpResTy); 13819 13820 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13821 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13822 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13823 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13824 } 13825 13826 static std::pair<ExprResult, ExprResult> 13827 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13828 Expr *RHSExpr) { 13829 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13830 if (!S.Context.isDependenceAllowed()) { 13831 // C cannot handle TypoExpr nodes on either side of a binop because it 13832 // doesn't handle dependent types properly, so make sure any TypoExprs have 13833 // been dealt with before checking the operands. 13834 LHS = S.CorrectDelayedTyposInExpr(LHS); 13835 RHS = S.CorrectDelayedTyposInExpr( 13836 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13837 [Opc, LHS](Expr *E) { 13838 if (Opc != BO_Assign) 13839 return ExprResult(E); 13840 // Avoid correcting the RHS to the same Expr as the LHS. 13841 Decl *D = getDeclFromExpr(E); 13842 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13843 }); 13844 } 13845 return std::make_pair(LHS, RHS); 13846 } 13847 13848 /// Returns true if conversion between vectors of halfs and vectors of floats 13849 /// is needed. 13850 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13851 Expr *E0, Expr *E1 = nullptr) { 13852 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13853 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13854 return false; 13855 13856 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13857 QualType Ty = E->IgnoreImplicit()->getType(); 13858 13859 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13860 // to vectors of floats. Although the element type of the vectors is __fp16, 13861 // the vectors shouldn't be treated as storage-only types. See the 13862 // discussion here: https://reviews.llvm.org/rG825235c140e7 13863 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13864 if (VT->getVectorKind() == VectorType::NeonVector) 13865 return false; 13866 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13867 } 13868 return false; 13869 }; 13870 13871 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13872 } 13873 13874 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13875 /// operator @p Opc at location @c TokLoc. This routine only supports 13876 /// built-in operations; ActOnBinOp handles overloaded operators. 13877 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13878 BinaryOperatorKind Opc, 13879 Expr *LHSExpr, Expr *RHSExpr) { 13880 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13881 // The syntax only allows initializer lists on the RHS of assignment, 13882 // so we don't need to worry about accepting invalid code for 13883 // non-assignment operators. 13884 // C++11 5.17p9: 13885 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13886 // of x = {} is x = T(). 13887 InitializationKind Kind = InitializationKind::CreateDirectList( 13888 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13889 InitializedEntity Entity = 13890 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13891 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13892 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13893 if (Init.isInvalid()) 13894 return Init; 13895 RHSExpr = Init.get(); 13896 } 13897 13898 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13899 QualType ResultTy; // Result type of the binary operator. 13900 // The following two variables are used for compound assignment operators 13901 QualType CompLHSTy; // Type of LHS after promotions for computation 13902 QualType CompResultTy; // Type of computation result 13903 ExprValueKind VK = VK_RValue; 13904 ExprObjectKind OK = OK_Ordinary; 13905 bool ConvertHalfVec = false; 13906 13907 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13908 if (!LHS.isUsable() || !RHS.isUsable()) 13909 return ExprError(); 13910 13911 if (getLangOpts().OpenCL) { 13912 QualType LHSTy = LHSExpr->getType(); 13913 QualType RHSTy = RHSExpr->getType(); 13914 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13915 // the ATOMIC_VAR_INIT macro. 13916 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13917 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13918 if (BO_Assign == Opc) 13919 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13920 else 13921 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13922 return ExprError(); 13923 } 13924 13925 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13926 // only with a builtin functions and therefore should be disallowed here. 13927 if (LHSTy->isImageType() || RHSTy->isImageType() || 13928 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13929 LHSTy->isPipeType() || RHSTy->isPipeType() || 13930 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13931 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13932 return ExprError(); 13933 } 13934 } 13935 13936 switch (Opc) { 13937 case BO_Assign: 13938 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13939 if (getLangOpts().CPlusPlus && 13940 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13941 VK = LHS.get()->getValueKind(); 13942 OK = LHS.get()->getObjectKind(); 13943 } 13944 if (!ResultTy.isNull()) { 13945 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13946 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13947 13948 // Avoid copying a block to the heap if the block is assigned to a local 13949 // auto variable that is declared in the same scope as the block. This 13950 // optimization is unsafe if the local variable is declared in an outer 13951 // scope. For example: 13952 // 13953 // BlockTy b; 13954 // { 13955 // b = ^{...}; 13956 // } 13957 // // It is unsafe to invoke the block here if it wasn't copied to the 13958 // // heap. 13959 // b(); 13960 13961 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13962 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13963 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13964 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13965 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13966 13967 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13968 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13969 NTCUC_Assignment, NTCUK_Copy); 13970 } 13971 RecordModifiableNonNullParam(*this, LHS.get()); 13972 break; 13973 case BO_PtrMemD: 13974 case BO_PtrMemI: 13975 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13976 Opc == BO_PtrMemI); 13977 break; 13978 case BO_Mul: 13979 case BO_Div: 13980 ConvertHalfVec = true; 13981 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13982 Opc == BO_Div); 13983 break; 13984 case BO_Rem: 13985 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13986 break; 13987 case BO_Add: 13988 ConvertHalfVec = true; 13989 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13990 break; 13991 case BO_Sub: 13992 ConvertHalfVec = true; 13993 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13994 break; 13995 case BO_Shl: 13996 case BO_Shr: 13997 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13998 break; 13999 case BO_LE: 14000 case BO_LT: 14001 case BO_GE: 14002 case BO_GT: 14003 ConvertHalfVec = true; 14004 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14005 break; 14006 case BO_EQ: 14007 case BO_NE: 14008 ConvertHalfVec = true; 14009 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14010 break; 14011 case BO_Cmp: 14012 ConvertHalfVec = true; 14013 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14014 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14015 break; 14016 case BO_And: 14017 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14018 LLVM_FALLTHROUGH; 14019 case BO_Xor: 14020 case BO_Or: 14021 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14022 break; 14023 case BO_LAnd: 14024 case BO_LOr: 14025 ConvertHalfVec = true; 14026 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14027 break; 14028 case BO_MulAssign: 14029 case BO_DivAssign: 14030 ConvertHalfVec = true; 14031 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14032 Opc == BO_DivAssign); 14033 CompLHSTy = CompResultTy; 14034 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14035 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14036 break; 14037 case BO_RemAssign: 14038 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14039 CompLHSTy = CompResultTy; 14040 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14041 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14042 break; 14043 case BO_AddAssign: 14044 ConvertHalfVec = true; 14045 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14046 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14047 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14048 break; 14049 case BO_SubAssign: 14050 ConvertHalfVec = true; 14051 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14052 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14053 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14054 break; 14055 case BO_ShlAssign: 14056 case BO_ShrAssign: 14057 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14058 CompLHSTy = CompResultTy; 14059 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14060 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14061 break; 14062 case BO_AndAssign: 14063 case BO_OrAssign: // fallthrough 14064 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14065 LLVM_FALLTHROUGH; 14066 case BO_XorAssign: 14067 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14068 CompLHSTy = CompResultTy; 14069 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14070 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14071 break; 14072 case BO_Comma: 14073 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14074 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14075 VK = RHS.get()->getValueKind(); 14076 OK = RHS.get()->getObjectKind(); 14077 } 14078 break; 14079 } 14080 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14081 return ExprError(); 14082 14083 // Some of the binary operations require promoting operands of half vector to 14084 // float vectors and truncating the result back to half vector. For now, we do 14085 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14086 // arm64). 14087 assert( 14088 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14089 isVector(LHS.get()->getType(), Context.HalfTy)) && 14090 "both sides are half vectors or neither sides are"); 14091 ConvertHalfVec = 14092 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14093 14094 // Check for array bounds violations for both sides of the BinaryOperator 14095 CheckArrayAccess(LHS.get()); 14096 CheckArrayAccess(RHS.get()); 14097 14098 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14099 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14100 &Context.Idents.get("object_setClass"), 14101 SourceLocation(), LookupOrdinaryName); 14102 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14103 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14104 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14105 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14106 "object_setClass(") 14107 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14108 ",") 14109 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14110 } 14111 else 14112 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14113 } 14114 else if (const ObjCIvarRefExpr *OIRE = 14115 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14116 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14117 14118 // Opc is not a compound assignment if CompResultTy is null. 14119 if (CompResultTy.isNull()) { 14120 if (ConvertHalfVec) 14121 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14122 OpLoc, CurFPFeatureOverrides()); 14123 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14124 VK, OK, OpLoc, CurFPFeatureOverrides()); 14125 } 14126 14127 // Handle compound assignments. 14128 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14129 OK_ObjCProperty) { 14130 VK = VK_LValue; 14131 OK = LHS.get()->getObjectKind(); 14132 } 14133 14134 // The LHS is not converted to the result type for fixed-point compound 14135 // assignment as the common type is computed on demand. Reset the CompLHSTy 14136 // to the LHS type we would have gotten after unary conversions. 14137 if (CompResultTy->isFixedPointType()) 14138 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14139 14140 if (ConvertHalfVec) 14141 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14142 OpLoc, CurFPFeatureOverrides()); 14143 14144 return CompoundAssignOperator::Create( 14145 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14146 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14147 } 14148 14149 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14150 /// operators are mixed in a way that suggests that the programmer forgot that 14151 /// comparison operators have higher precedence. The most typical example of 14152 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14153 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14154 SourceLocation OpLoc, Expr *LHSExpr, 14155 Expr *RHSExpr) { 14156 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14157 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14158 14159 // Check that one of the sides is a comparison operator and the other isn't. 14160 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14161 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14162 if (isLeftComp == isRightComp) 14163 return; 14164 14165 // Bitwise operations are sometimes used as eager logical ops. 14166 // Don't diagnose this. 14167 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14168 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14169 if (isLeftBitwise || isRightBitwise) 14170 return; 14171 14172 SourceRange DiagRange = isLeftComp 14173 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14174 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14175 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14176 SourceRange ParensRange = 14177 isLeftComp 14178 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14179 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14180 14181 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14182 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14183 SuggestParentheses(Self, OpLoc, 14184 Self.PDiag(diag::note_precedence_silence) << OpStr, 14185 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14186 SuggestParentheses(Self, OpLoc, 14187 Self.PDiag(diag::note_precedence_bitwise_first) 14188 << BinaryOperator::getOpcodeStr(Opc), 14189 ParensRange); 14190 } 14191 14192 /// It accepts a '&&' expr that is inside a '||' one. 14193 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14194 /// in parentheses. 14195 static void 14196 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14197 BinaryOperator *Bop) { 14198 assert(Bop->getOpcode() == BO_LAnd); 14199 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14200 << Bop->getSourceRange() << OpLoc; 14201 SuggestParentheses(Self, Bop->getOperatorLoc(), 14202 Self.PDiag(diag::note_precedence_silence) 14203 << Bop->getOpcodeStr(), 14204 Bop->getSourceRange()); 14205 } 14206 14207 /// Returns true if the given expression can be evaluated as a constant 14208 /// 'true'. 14209 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14210 bool Res; 14211 return !E->isValueDependent() && 14212 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14213 } 14214 14215 /// Returns true if the given expression can be evaluated as a constant 14216 /// 'false'. 14217 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14218 bool Res; 14219 return !E->isValueDependent() && 14220 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14221 } 14222 14223 /// Look for '&&' in the left hand of a '||' expr. 14224 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14225 Expr *LHSExpr, Expr *RHSExpr) { 14226 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14227 if (Bop->getOpcode() == BO_LAnd) { 14228 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14229 if (EvaluatesAsFalse(S, RHSExpr)) 14230 return; 14231 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14232 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14233 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14234 } else if (Bop->getOpcode() == BO_LOr) { 14235 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14236 // If it's "a || b && 1 || c" we didn't warn earlier for 14237 // "a || b && 1", but warn now. 14238 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14239 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14240 } 14241 } 14242 } 14243 } 14244 14245 /// Look for '&&' in the right hand of a '||' expr. 14246 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14247 Expr *LHSExpr, Expr *RHSExpr) { 14248 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14249 if (Bop->getOpcode() == BO_LAnd) { 14250 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14251 if (EvaluatesAsFalse(S, LHSExpr)) 14252 return; 14253 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14254 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14255 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14256 } 14257 } 14258 } 14259 14260 /// Look for bitwise op in the left or right hand of a bitwise op with 14261 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14262 /// the '&' expression in parentheses. 14263 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14264 SourceLocation OpLoc, Expr *SubExpr) { 14265 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14266 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14267 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14268 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14269 << Bop->getSourceRange() << OpLoc; 14270 SuggestParentheses(S, Bop->getOperatorLoc(), 14271 S.PDiag(diag::note_precedence_silence) 14272 << Bop->getOpcodeStr(), 14273 Bop->getSourceRange()); 14274 } 14275 } 14276 } 14277 14278 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14279 Expr *SubExpr, StringRef Shift) { 14280 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14281 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14282 StringRef Op = Bop->getOpcodeStr(); 14283 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14284 << Bop->getSourceRange() << OpLoc << Shift << Op; 14285 SuggestParentheses(S, Bop->getOperatorLoc(), 14286 S.PDiag(diag::note_precedence_silence) << Op, 14287 Bop->getSourceRange()); 14288 } 14289 } 14290 } 14291 14292 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14293 Expr *LHSExpr, Expr *RHSExpr) { 14294 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14295 if (!OCE) 14296 return; 14297 14298 FunctionDecl *FD = OCE->getDirectCallee(); 14299 if (!FD || !FD->isOverloadedOperator()) 14300 return; 14301 14302 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14303 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14304 return; 14305 14306 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14307 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14308 << (Kind == OO_LessLess); 14309 SuggestParentheses(S, OCE->getOperatorLoc(), 14310 S.PDiag(diag::note_precedence_silence) 14311 << (Kind == OO_LessLess ? "<<" : ">>"), 14312 OCE->getSourceRange()); 14313 SuggestParentheses( 14314 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14315 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14316 } 14317 14318 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14319 /// precedence. 14320 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14321 SourceLocation OpLoc, Expr *LHSExpr, 14322 Expr *RHSExpr){ 14323 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14324 if (BinaryOperator::isBitwiseOp(Opc)) 14325 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14326 14327 // Diagnose "arg1 & arg2 | arg3" 14328 if ((Opc == BO_Or || Opc == BO_Xor) && 14329 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14330 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14331 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14332 } 14333 14334 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14335 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14336 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14337 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14338 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14339 } 14340 14341 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14342 || Opc == BO_Shr) { 14343 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14344 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14345 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14346 } 14347 14348 // Warn on overloaded shift operators and comparisons, such as: 14349 // cout << 5 == 4; 14350 if (BinaryOperator::isComparisonOp(Opc)) 14351 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14352 } 14353 14354 // Binary Operators. 'Tok' is the token for the operator. 14355 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14356 tok::TokenKind Kind, 14357 Expr *LHSExpr, Expr *RHSExpr) { 14358 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14359 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14360 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14361 14362 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14363 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14364 14365 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14366 } 14367 14368 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14369 UnresolvedSetImpl &Functions) { 14370 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14371 if (OverOp != OO_None && OverOp != OO_Equal) 14372 LookupOverloadedOperatorName(OverOp, S, Functions); 14373 14374 // In C++20 onwards, we may have a second operator to look up. 14375 if (getLangOpts().CPlusPlus20) { 14376 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14377 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14378 } 14379 } 14380 14381 /// Build an overloaded binary operator expression in the given scope. 14382 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14383 BinaryOperatorKind Opc, 14384 Expr *LHS, Expr *RHS) { 14385 switch (Opc) { 14386 case BO_Assign: 14387 case BO_DivAssign: 14388 case BO_RemAssign: 14389 case BO_SubAssign: 14390 case BO_AndAssign: 14391 case BO_OrAssign: 14392 case BO_XorAssign: 14393 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14394 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14395 break; 14396 default: 14397 break; 14398 } 14399 14400 // Find all of the overloaded operators visible from this point. 14401 UnresolvedSet<16> Functions; 14402 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14403 14404 // Build the (potentially-overloaded, potentially-dependent) 14405 // binary operation. 14406 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14407 } 14408 14409 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14410 BinaryOperatorKind Opc, 14411 Expr *LHSExpr, Expr *RHSExpr) { 14412 ExprResult LHS, RHS; 14413 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14414 if (!LHS.isUsable() || !RHS.isUsable()) 14415 return ExprError(); 14416 LHSExpr = LHS.get(); 14417 RHSExpr = RHS.get(); 14418 14419 // We want to end up calling one of checkPseudoObjectAssignment 14420 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14421 // both expressions are overloadable or either is type-dependent), 14422 // or CreateBuiltinBinOp (in any other case). We also want to get 14423 // any placeholder types out of the way. 14424 14425 // Handle pseudo-objects in the LHS. 14426 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14427 // Assignments with a pseudo-object l-value need special analysis. 14428 if (pty->getKind() == BuiltinType::PseudoObject && 14429 BinaryOperator::isAssignmentOp(Opc)) 14430 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14431 14432 // Don't resolve overloads if the other type is overloadable. 14433 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14434 // We can't actually test that if we still have a placeholder, 14435 // though. Fortunately, none of the exceptions we see in that 14436 // code below are valid when the LHS is an overload set. Note 14437 // that an overload set can be dependently-typed, but it never 14438 // instantiates to having an overloadable type. 14439 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14440 if (resolvedRHS.isInvalid()) return ExprError(); 14441 RHSExpr = resolvedRHS.get(); 14442 14443 if (RHSExpr->isTypeDependent() || 14444 RHSExpr->getType()->isOverloadableType()) 14445 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14446 } 14447 14448 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14449 // template, diagnose the missing 'template' keyword instead of diagnosing 14450 // an invalid use of a bound member function. 14451 // 14452 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14453 // to C++1z [over.over]/1.4, but we already checked for that case above. 14454 if (Opc == BO_LT && inTemplateInstantiation() && 14455 (pty->getKind() == BuiltinType::BoundMember || 14456 pty->getKind() == BuiltinType::Overload)) { 14457 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14458 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14459 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14460 return isa<FunctionTemplateDecl>(ND); 14461 })) { 14462 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14463 : OE->getNameLoc(), 14464 diag::err_template_kw_missing) 14465 << OE->getName().getAsString() << ""; 14466 return ExprError(); 14467 } 14468 } 14469 14470 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14471 if (LHS.isInvalid()) return ExprError(); 14472 LHSExpr = LHS.get(); 14473 } 14474 14475 // Handle pseudo-objects in the RHS. 14476 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14477 // An overload in the RHS can potentially be resolved by the type 14478 // being assigned to. 14479 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14480 if (getLangOpts().CPlusPlus && 14481 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14482 LHSExpr->getType()->isOverloadableType())) 14483 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14484 14485 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14486 } 14487 14488 // Don't resolve overloads if the other type is overloadable. 14489 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14490 LHSExpr->getType()->isOverloadableType()) 14491 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14492 14493 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14494 if (!resolvedRHS.isUsable()) return ExprError(); 14495 RHSExpr = resolvedRHS.get(); 14496 } 14497 14498 if (getLangOpts().CPlusPlus) { 14499 // If either expression is type-dependent, always build an 14500 // overloaded op. 14501 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14502 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14503 14504 // Otherwise, build an overloaded op if either expression has an 14505 // overloadable type. 14506 if (LHSExpr->getType()->isOverloadableType() || 14507 RHSExpr->getType()->isOverloadableType()) 14508 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14509 } 14510 14511 if (getLangOpts().RecoveryAST && 14512 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14513 assert(!getLangOpts().CPlusPlus); 14514 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14515 "Should only occur in error-recovery path."); 14516 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14517 // C [6.15.16] p3: 14518 // An assignment expression has the value of the left operand after the 14519 // assignment, but is not an lvalue. 14520 return CompoundAssignOperator::Create( 14521 Context, LHSExpr, RHSExpr, Opc, 14522 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14523 OpLoc, CurFPFeatureOverrides()); 14524 QualType ResultType; 14525 switch (Opc) { 14526 case BO_Assign: 14527 ResultType = LHSExpr->getType().getUnqualifiedType(); 14528 break; 14529 case BO_LT: 14530 case BO_GT: 14531 case BO_LE: 14532 case BO_GE: 14533 case BO_EQ: 14534 case BO_NE: 14535 case BO_LAnd: 14536 case BO_LOr: 14537 // These operators have a fixed result type regardless of operands. 14538 ResultType = Context.IntTy; 14539 break; 14540 case BO_Comma: 14541 ResultType = RHSExpr->getType(); 14542 break; 14543 default: 14544 ResultType = Context.DependentTy; 14545 break; 14546 } 14547 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14548 VK_RValue, OK_Ordinary, OpLoc, 14549 CurFPFeatureOverrides()); 14550 } 14551 14552 // Build a built-in binary operation. 14553 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14554 } 14555 14556 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14557 if (T.isNull() || T->isDependentType()) 14558 return false; 14559 14560 if (!T->isPromotableIntegerType()) 14561 return true; 14562 14563 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14564 } 14565 14566 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14567 UnaryOperatorKind Opc, 14568 Expr *InputExpr) { 14569 ExprResult Input = InputExpr; 14570 ExprValueKind VK = VK_RValue; 14571 ExprObjectKind OK = OK_Ordinary; 14572 QualType resultType; 14573 bool CanOverflow = false; 14574 14575 bool ConvertHalfVec = false; 14576 if (getLangOpts().OpenCL) { 14577 QualType Ty = InputExpr->getType(); 14578 // The only legal unary operation for atomics is '&'. 14579 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14580 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14581 // only with a builtin functions and therefore should be disallowed here. 14582 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14583 || Ty->isBlockPointerType())) { 14584 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14585 << InputExpr->getType() 14586 << Input.get()->getSourceRange()); 14587 } 14588 } 14589 14590 switch (Opc) { 14591 case UO_PreInc: 14592 case UO_PreDec: 14593 case UO_PostInc: 14594 case UO_PostDec: 14595 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14596 OpLoc, 14597 Opc == UO_PreInc || 14598 Opc == UO_PostInc, 14599 Opc == UO_PreInc || 14600 Opc == UO_PreDec); 14601 CanOverflow = isOverflowingIntegerType(Context, resultType); 14602 break; 14603 case UO_AddrOf: 14604 resultType = CheckAddressOfOperand(Input, OpLoc); 14605 CheckAddressOfNoDeref(InputExpr); 14606 RecordModifiableNonNullParam(*this, InputExpr); 14607 break; 14608 case UO_Deref: { 14609 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14610 if (Input.isInvalid()) return ExprError(); 14611 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14612 break; 14613 } 14614 case UO_Plus: 14615 case UO_Minus: 14616 CanOverflow = Opc == UO_Minus && 14617 isOverflowingIntegerType(Context, Input.get()->getType()); 14618 Input = UsualUnaryConversions(Input.get()); 14619 if (Input.isInvalid()) return ExprError(); 14620 // Unary plus and minus require promoting an operand of half vector to a 14621 // float vector and truncating the result back to a half vector. For now, we 14622 // do this only when HalfArgsAndReturns is set (that is, when the target is 14623 // arm or arm64). 14624 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14625 14626 // If the operand is a half vector, promote it to a float vector. 14627 if (ConvertHalfVec) 14628 Input = convertVector(Input.get(), Context.FloatTy, *this); 14629 resultType = Input.get()->getType(); 14630 if (resultType->isDependentType()) 14631 break; 14632 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14633 break; 14634 else if (resultType->isVectorType() && 14635 // The z vector extensions don't allow + or - with bool vectors. 14636 (!Context.getLangOpts().ZVector || 14637 resultType->castAs<VectorType>()->getVectorKind() != 14638 VectorType::AltiVecBool)) 14639 break; 14640 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14641 Opc == UO_Plus && 14642 resultType->isPointerType()) 14643 break; 14644 14645 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14646 << resultType << Input.get()->getSourceRange()); 14647 14648 case UO_Not: // bitwise complement 14649 Input = UsualUnaryConversions(Input.get()); 14650 if (Input.isInvalid()) 14651 return ExprError(); 14652 resultType = Input.get()->getType(); 14653 if (resultType->isDependentType()) 14654 break; 14655 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14656 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14657 // C99 does not support '~' for complex conjugation. 14658 Diag(OpLoc, diag::ext_integer_complement_complex) 14659 << resultType << Input.get()->getSourceRange(); 14660 else if (resultType->hasIntegerRepresentation()) 14661 break; 14662 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14663 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14664 // on vector float types. 14665 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14666 if (!T->isIntegerType()) 14667 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14668 << resultType << Input.get()->getSourceRange()); 14669 } else { 14670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14671 << resultType << Input.get()->getSourceRange()); 14672 } 14673 break; 14674 14675 case UO_LNot: // logical negation 14676 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14677 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14678 if (Input.isInvalid()) return ExprError(); 14679 resultType = Input.get()->getType(); 14680 14681 // Though we still have to promote half FP to float... 14682 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14683 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14684 resultType = Context.FloatTy; 14685 } 14686 14687 if (resultType->isDependentType()) 14688 break; 14689 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14690 // C99 6.5.3.3p1: ok, fallthrough; 14691 if (Context.getLangOpts().CPlusPlus) { 14692 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14693 // operand contextually converted to bool. 14694 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14695 ScalarTypeToBooleanCastKind(resultType)); 14696 } else if (Context.getLangOpts().OpenCL && 14697 Context.getLangOpts().OpenCLVersion < 120) { 14698 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14699 // operate on scalar float types. 14700 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14701 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14702 << resultType << Input.get()->getSourceRange()); 14703 } 14704 } else if (resultType->isExtVectorType()) { 14705 if (Context.getLangOpts().OpenCL && 14706 Context.getLangOpts().OpenCLVersion < 120 && 14707 !Context.getLangOpts().OpenCLCPlusPlus) { 14708 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14709 // operate on vector float types. 14710 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14711 if (!T->isIntegerType()) 14712 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14713 << resultType << Input.get()->getSourceRange()); 14714 } 14715 // Vector logical not returns the signed variant of the operand type. 14716 resultType = GetSignedVectorType(resultType); 14717 break; 14718 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14719 const VectorType *VTy = resultType->castAs<VectorType>(); 14720 if (VTy->getVectorKind() != VectorType::GenericVector) 14721 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14722 << resultType << Input.get()->getSourceRange()); 14723 14724 // Vector logical not returns the signed variant of the operand type. 14725 resultType = GetSignedVectorType(resultType); 14726 break; 14727 } else { 14728 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14729 << resultType << Input.get()->getSourceRange()); 14730 } 14731 14732 // LNot always has type int. C99 6.5.3.3p5. 14733 // In C++, it's bool. C++ 5.3.1p8 14734 resultType = Context.getLogicalOperationType(); 14735 break; 14736 case UO_Real: 14737 case UO_Imag: 14738 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14739 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14740 // complex l-values to ordinary l-values and all other values to r-values. 14741 if (Input.isInvalid()) return ExprError(); 14742 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14743 if (Input.get()->getValueKind() != VK_RValue && 14744 Input.get()->getObjectKind() == OK_Ordinary) 14745 VK = Input.get()->getValueKind(); 14746 } else if (!getLangOpts().CPlusPlus) { 14747 // In C, a volatile scalar is read by __imag. In C++, it is not. 14748 Input = DefaultLvalueConversion(Input.get()); 14749 } 14750 break; 14751 case UO_Extension: 14752 resultType = Input.get()->getType(); 14753 VK = Input.get()->getValueKind(); 14754 OK = Input.get()->getObjectKind(); 14755 break; 14756 case UO_Coawait: 14757 // It's unnecessary to represent the pass-through operator co_await in the 14758 // AST; just return the input expression instead. 14759 assert(!Input.get()->getType()->isDependentType() && 14760 "the co_await expression must be non-dependant before " 14761 "building operator co_await"); 14762 return Input; 14763 } 14764 if (resultType.isNull() || Input.isInvalid()) 14765 return ExprError(); 14766 14767 // Check for array bounds violations in the operand of the UnaryOperator, 14768 // except for the '*' and '&' operators that have to be handled specially 14769 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14770 // that are explicitly defined as valid by the standard). 14771 if (Opc != UO_AddrOf && Opc != UO_Deref) 14772 CheckArrayAccess(Input.get()); 14773 14774 auto *UO = 14775 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14776 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14777 14778 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14779 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14780 !isUnevaluatedContext()) 14781 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14782 14783 // Convert the result back to a half vector. 14784 if (ConvertHalfVec) 14785 return convertVector(UO, Context.HalfTy, *this); 14786 return UO; 14787 } 14788 14789 /// Determine whether the given expression is a qualified member 14790 /// access expression, of a form that could be turned into a pointer to member 14791 /// with the address-of operator. 14792 bool Sema::isQualifiedMemberAccess(Expr *E) { 14793 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14794 if (!DRE->getQualifier()) 14795 return false; 14796 14797 ValueDecl *VD = DRE->getDecl(); 14798 if (!VD->isCXXClassMember()) 14799 return false; 14800 14801 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14802 return true; 14803 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14804 return Method->isInstance(); 14805 14806 return false; 14807 } 14808 14809 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14810 if (!ULE->getQualifier()) 14811 return false; 14812 14813 for (NamedDecl *D : ULE->decls()) { 14814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14815 if (Method->isInstance()) 14816 return true; 14817 } else { 14818 // Overload set does not contain methods. 14819 break; 14820 } 14821 } 14822 14823 return false; 14824 } 14825 14826 return false; 14827 } 14828 14829 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14830 UnaryOperatorKind Opc, Expr *Input) { 14831 // First things first: handle placeholders so that the 14832 // overloaded-operator check considers the right type. 14833 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14834 // Increment and decrement of pseudo-object references. 14835 if (pty->getKind() == BuiltinType::PseudoObject && 14836 UnaryOperator::isIncrementDecrementOp(Opc)) 14837 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14838 14839 // extension is always a builtin operator. 14840 if (Opc == UO_Extension) 14841 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14842 14843 // & gets special logic for several kinds of placeholder. 14844 // The builtin code knows what to do. 14845 if (Opc == UO_AddrOf && 14846 (pty->getKind() == BuiltinType::Overload || 14847 pty->getKind() == BuiltinType::UnknownAny || 14848 pty->getKind() == BuiltinType::BoundMember)) 14849 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14850 14851 // Anything else needs to be handled now. 14852 ExprResult Result = CheckPlaceholderExpr(Input); 14853 if (Result.isInvalid()) return ExprError(); 14854 Input = Result.get(); 14855 } 14856 14857 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14858 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14859 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14860 // Find all of the overloaded operators visible from this point. 14861 UnresolvedSet<16> Functions; 14862 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14863 if (S && OverOp != OO_None) 14864 LookupOverloadedOperatorName(OverOp, S, Functions); 14865 14866 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14867 } 14868 14869 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14870 } 14871 14872 // Unary Operators. 'Tok' is the token for the operator. 14873 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14874 tok::TokenKind Op, Expr *Input) { 14875 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14876 } 14877 14878 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14879 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14880 LabelDecl *TheDecl) { 14881 TheDecl->markUsed(Context); 14882 // Create the AST node. The address of a label always has type 'void*'. 14883 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14884 Context.getPointerType(Context.VoidTy)); 14885 } 14886 14887 void Sema::ActOnStartStmtExpr() { 14888 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14889 } 14890 14891 void Sema::ActOnStmtExprError() { 14892 // Note that function is also called by TreeTransform when leaving a 14893 // StmtExpr scope without rebuilding anything. 14894 14895 DiscardCleanupsInEvaluationContext(); 14896 PopExpressionEvaluationContext(); 14897 } 14898 14899 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14900 SourceLocation RPLoc) { 14901 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14902 } 14903 14904 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14905 SourceLocation RPLoc, unsigned TemplateDepth) { 14906 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14907 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14908 14909 if (hasAnyUnrecoverableErrorsInThisFunction()) 14910 DiscardCleanupsInEvaluationContext(); 14911 assert(!Cleanup.exprNeedsCleanups() && 14912 "cleanups within StmtExpr not correctly bound!"); 14913 PopExpressionEvaluationContext(); 14914 14915 // FIXME: there are a variety of strange constraints to enforce here, for 14916 // example, it is not possible to goto into a stmt expression apparently. 14917 // More semantic analysis is needed. 14918 14919 // If there are sub-stmts in the compound stmt, take the type of the last one 14920 // as the type of the stmtexpr. 14921 QualType Ty = Context.VoidTy; 14922 bool StmtExprMayBindToTemp = false; 14923 if (!Compound->body_empty()) { 14924 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14925 if (const auto *LastStmt = 14926 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14927 if (const Expr *Value = LastStmt->getExprStmt()) { 14928 StmtExprMayBindToTemp = true; 14929 Ty = Value->getType(); 14930 } 14931 } 14932 } 14933 14934 // FIXME: Check that expression type is complete/non-abstract; statement 14935 // expressions are not lvalues. 14936 Expr *ResStmtExpr = 14937 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14938 if (StmtExprMayBindToTemp) 14939 return MaybeBindToTemporary(ResStmtExpr); 14940 return ResStmtExpr; 14941 } 14942 14943 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14944 if (ER.isInvalid()) 14945 return ExprError(); 14946 14947 // Do function/array conversion on the last expression, but not 14948 // lvalue-to-rvalue. However, initialize an unqualified type. 14949 ER = DefaultFunctionArrayConversion(ER.get()); 14950 if (ER.isInvalid()) 14951 return ExprError(); 14952 Expr *E = ER.get(); 14953 14954 if (E->isTypeDependent()) 14955 return E; 14956 14957 // In ARC, if the final expression ends in a consume, splice 14958 // the consume out and bind it later. In the alternate case 14959 // (when dealing with a retainable type), the result 14960 // initialization will create a produce. In both cases the 14961 // result will be +1, and we'll need to balance that out with 14962 // a bind. 14963 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14964 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14965 return Cast->getSubExpr(); 14966 14967 // FIXME: Provide a better location for the initialization. 14968 return PerformCopyInitialization( 14969 InitializedEntity::InitializeStmtExprResult( 14970 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14971 SourceLocation(), E); 14972 } 14973 14974 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14975 TypeSourceInfo *TInfo, 14976 ArrayRef<OffsetOfComponent> Components, 14977 SourceLocation RParenLoc) { 14978 QualType ArgTy = TInfo->getType(); 14979 bool Dependent = ArgTy->isDependentType(); 14980 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14981 14982 // We must have at least one component that refers to the type, and the first 14983 // one is known to be a field designator. Verify that the ArgTy represents 14984 // a struct/union/class. 14985 if (!Dependent && !ArgTy->isRecordType()) 14986 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14987 << ArgTy << TypeRange); 14988 14989 // Type must be complete per C99 7.17p3 because a declaring a variable 14990 // with an incomplete type would be ill-formed. 14991 if (!Dependent 14992 && RequireCompleteType(BuiltinLoc, ArgTy, 14993 diag::err_offsetof_incomplete_type, TypeRange)) 14994 return ExprError(); 14995 14996 bool DidWarnAboutNonPOD = false; 14997 QualType CurrentType = ArgTy; 14998 SmallVector<OffsetOfNode, 4> Comps; 14999 SmallVector<Expr*, 4> Exprs; 15000 for (const OffsetOfComponent &OC : Components) { 15001 if (OC.isBrackets) { 15002 // Offset of an array sub-field. TODO: Should we allow vector elements? 15003 if (!CurrentType->isDependentType()) { 15004 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15005 if(!AT) 15006 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15007 << CurrentType); 15008 CurrentType = AT->getElementType(); 15009 } else 15010 CurrentType = Context.DependentTy; 15011 15012 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15013 if (IdxRval.isInvalid()) 15014 return ExprError(); 15015 Expr *Idx = IdxRval.get(); 15016 15017 // The expression must be an integral expression. 15018 // FIXME: An integral constant expression? 15019 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15020 !Idx->getType()->isIntegerType()) 15021 return ExprError( 15022 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15023 << Idx->getSourceRange()); 15024 15025 // Record this array index. 15026 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15027 Exprs.push_back(Idx); 15028 continue; 15029 } 15030 15031 // Offset of a field. 15032 if (CurrentType->isDependentType()) { 15033 // We have the offset of a field, but we can't look into the dependent 15034 // type. Just record the identifier of the field. 15035 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15036 CurrentType = Context.DependentTy; 15037 continue; 15038 } 15039 15040 // We need to have a complete type to look into. 15041 if (RequireCompleteType(OC.LocStart, CurrentType, 15042 diag::err_offsetof_incomplete_type)) 15043 return ExprError(); 15044 15045 // Look for the designated field. 15046 const RecordType *RC = CurrentType->getAs<RecordType>(); 15047 if (!RC) 15048 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15049 << CurrentType); 15050 RecordDecl *RD = RC->getDecl(); 15051 15052 // C++ [lib.support.types]p5: 15053 // The macro offsetof accepts a restricted set of type arguments in this 15054 // International Standard. type shall be a POD structure or a POD union 15055 // (clause 9). 15056 // C++11 [support.types]p4: 15057 // If type is not a standard-layout class (Clause 9), the results are 15058 // undefined. 15059 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15060 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15061 unsigned DiagID = 15062 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15063 : diag::ext_offsetof_non_pod_type; 15064 15065 if (!IsSafe && !DidWarnAboutNonPOD && 15066 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15067 PDiag(DiagID) 15068 << SourceRange(Components[0].LocStart, OC.LocEnd) 15069 << CurrentType)) 15070 DidWarnAboutNonPOD = true; 15071 } 15072 15073 // Look for the field. 15074 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15075 LookupQualifiedName(R, RD); 15076 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15077 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15078 if (!MemberDecl) { 15079 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15080 MemberDecl = IndirectMemberDecl->getAnonField(); 15081 } 15082 15083 if (!MemberDecl) 15084 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15085 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15086 OC.LocEnd)); 15087 15088 // C99 7.17p3: 15089 // (If the specified member is a bit-field, the behavior is undefined.) 15090 // 15091 // We diagnose this as an error. 15092 if (MemberDecl->isBitField()) { 15093 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15094 << MemberDecl->getDeclName() 15095 << SourceRange(BuiltinLoc, RParenLoc); 15096 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15097 return ExprError(); 15098 } 15099 15100 RecordDecl *Parent = MemberDecl->getParent(); 15101 if (IndirectMemberDecl) 15102 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15103 15104 // If the member was found in a base class, introduce OffsetOfNodes for 15105 // the base class indirections. 15106 CXXBasePaths Paths; 15107 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15108 Paths)) { 15109 if (Paths.getDetectedVirtual()) { 15110 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15111 << MemberDecl->getDeclName() 15112 << SourceRange(BuiltinLoc, RParenLoc); 15113 return ExprError(); 15114 } 15115 15116 CXXBasePath &Path = Paths.front(); 15117 for (const CXXBasePathElement &B : Path) 15118 Comps.push_back(OffsetOfNode(B.Base)); 15119 } 15120 15121 if (IndirectMemberDecl) { 15122 for (auto *FI : IndirectMemberDecl->chain()) { 15123 assert(isa<FieldDecl>(FI)); 15124 Comps.push_back(OffsetOfNode(OC.LocStart, 15125 cast<FieldDecl>(FI), OC.LocEnd)); 15126 } 15127 } else 15128 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15129 15130 CurrentType = MemberDecl->getType().getNonReferenceType(); 15131 } 15132 15133 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15134 Comps, Exprs, RParenLoc); 15135 } 15136 15137 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15138 SourceLocation BuiltinLoc, 15139 SourceLocation TypeLoc, 15140 ParsedType ParsedArgTy, 15141 ArrayRef<OffsetOfComponent> Components, 15142 SourceLocation RParenLoc) { 15143 15144 TypeSourceInfo *ArgTInfo; 15145 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15146 if (ArgTy.isNull()) 15147 return ExprError(); 15148 15149 if (!ArgTInfo) 15150 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15151 15152 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15153 } 15154 15155 15156 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15157 Expr *CondExpr, 15158 Expr *LHSExpr, Expr *RHSExpr, 15159 SourceLocation RPLoc) { 15160 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15161 15162 ExprValueKind VK = VK_RValue; 15163 ExprObjectKind OK = OK_Ordinary; 15164 QualType resType; 15165 bool CondIsTrue = false; 15166 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15167 resType = Context.DependentTy; 15168 } else { 15169 // The conditional expression is required to be a constant expression. 15170 llvm::APSInt condEval(32); 15171 ExprResult CondICE = VerifyIntegerConstantExpression( 15172 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15173 if (CondICE.isInvalid()) 15174 return ExprError(); 15175 CondExpr = CondICE.get(); 15176 CondIsTrue = condEval.getZExtValue(); 15177 15178 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15179 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15180 15181 resType = ActiveExpr->getType(); 15182 VK = ActiveExpr->getValueKind(); 15183 OK = ActiveExpr->getObjectKind(); 15184 } 15185 15186 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15187 resType, VK, OK, RPLoc, CondIsTrue); 15188 } 15189 15190 //===----------------------------------------------------------------------===// 15191 // Clang Extensions. 15192 //===----------------------------------------------------------------------===// 15193 15194 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15195 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15196 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15197 15198 if (LangOpts.CPlusPlus) { 15199 MangleNumberingContext *MCtx; 15200 Decl *ManglingContextDecl; 15201 std::tie(MCtx, ManglingContextDecl) = 15202 getCurrentMangleNumberContext(Block->getDeclContext()); 15203 if (MCtx) { 15204 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15205 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15206 } 15207 } 15208 15209 PushBlockScope(CurScope, Block); 15210 CurContext->addDecl(Block); 15211 if (CurScope) 15212 PushDeclContext(CurScope, Block); 15213 else 15214 CurContext = Block; 15215 15216 getCurBlock()->HasImplicitReturnType = true; 15217 15218 // Enter a new evaluation context to insulate the block from any 15219 // cleanups from the enclosing full-expression. 15220 PushExpressionEvaluationContext( 15221 ExpressionEvaluationContext::PotentiallyEvaluated); 15222 } 15223 15224 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15225 Scope *CurScope) { 15226 assert(ParamInfo.getIdentifier() == nullptr && 15227 "block-id should have no identifier!"); 15228 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15229 BlockScopeInfo *CurBlock = getCurBlock(); 15230 15231 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15232 QualType T = Sig->getType(); 15233 15234 // FIXME: We should allow unexpanded parameter packs here, but that would, 15235 // in turn, make the block expression contain unexpanded parameter packs. 15236 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15237 // Drop the parameters. 15238 FunctionProtoType::ExtProtoInfo EPI; 15239 EPI.HasTrailingReturn = false; 15240 EPI.TypeQuals.addConst(); 15241 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15242 Sig = Context.getTrivialTypeSourceInfo(T); 15243 } 15244 15245 // GetTypeForDeclarator always produces a function type for a block 15246 // literal signature. Furthermore, it is always a FunctionProtoType 15247 // unless the function was written with a typedef. 15248 assert(T->isFunctionType() && 15249 "GetTypeForDeclarator made a non-function block signature"); 15250 15251 // Look for an explicit signature in that function type. 15252 FunctionProtoTypeLoc ExplicitSignature; 15253 15254 if ((ExplicitSignature = Sig->getTypeLoc() 15255 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15256 15257 // Check whether that explicit signature was synthesized by 15258 // GetTypeForDeclarator. If so, don't save that as part of the 15259 // written signature. 15260 if (ExplicitSignature.getLocalRangeBegin() == 15261 ExplicitSignature.getLocalRangeEnd()) { 15262 // This would be much cheaper if we stored TypeLocs instead of 15263 // TypeSourceInfos. 15264 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15265 unsigned Size = Result.getFullDataSize(); 15266 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15267 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15268 15269 ExplicitSignature = FunctionProtoTypeLoc(); 15270 } 15271 } 15272 15273 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15274 CurBlock->FunctionType = T; 15275 15276 const auto *Fn = T->castAs<FunctionType>(); 15277 QualType RetTy = Fn->getReturnType(); 15278 bool isVariadic = 15279 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15280 15281 CurBlock->TheDecl->setIsVariadic(isVariadic); 15282 15283 // Context.DependentTy is used as a placeholder for a missing block 15284 // return type. TODO: what should we do with declarators like: 15285 // ^ * { ... } 15286 // If the answer is "apply template argument deduction".... 15287 if (RetTy != Context.DependentTy) { 15288 CurBlock->ReturnType = RetTy; 15289 CurBlock->TheDecl->setBlockMissingReturnType(false); 15290 CurBlock->HasImplicitReturnType = false; 15291 } 15292 15293 // Push block parameters from the declarator if we had them. 15294 SmallVector<ParmVarDecl*, 8> Params; 15295 if (ExplicitSignature) { 15296 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15297 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15298 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15299 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15300 // Diagnose this as an extension in C17 and earlier. 15301 if (!getLangOpts().C2x) 15302 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15303 } 15304 Params.push_back(Param); 15305 } 15306 15307 // Fake up parameter variables if we have a typedef, like 15308 // ^ fntype { ... } 15309 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15310 for (const auto &I : Fn->param_types()) { 15311 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15312 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15313 Params.push_back(Param); 15314 } 15315 } 15316 15317 // Set the parameters on the block decl. 15318 if (!Params.empty()) { 15319 CurBlock->TheDecl->setParams(Params); 15320 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15321 /*CheckParameterNames=*/false); 15322 } 15323 15324 // Finally we can process decl attributes. 15325 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15326 15327 // Put the parameter variables in scope. 15328 for (auto AI : CurBlock->TheDecl->parameters()) { 15329 AI->setOwningFunction(CurBlock->TheDecl); 15330 15331 // If this has an identifier, add it to the scope stack. 15332 if (AI->getIdentifier()) { 15333 CheckShadow(CurBlock->TheScope, AI); 15334 15335 PushOnScopeChains(AI, CurBlock->TheScope); 15336 } 15337 } 15338 } 15339 15340 /// ActOnBlockError - If there is an error parsing a block, this callback 15341 /// is invoked to pop the information about the block from the action impl. 15342 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15343 // Leave the expression-evaluation context. 15344 DiscardCleanupsInEvaluationContext(); 15345 PopExpressionEvaluationContext(); 15346 15347 // Pop off CurBlock, handle nested blocks. 15348 PopDeclContext(); 15349 PopFunctionScopeInfo(); 15350 } 15351 15352 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15353 /// literal was successfully completed. ^(int x){...} 15354 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15355 Stmt *Body, Scope *CurScope) { 15356 // If blocks are disabled, emit an error. 15357 if (!LangOpts.Blocks) 15358 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15359 15360 // Leave the expression-evaluation context. 15361 if (hasAnyUnrecoverableErrorsInThisFunction()) 15362 DiscardCleanupsInEvaluationContext(); 15363 assert(!Cleanup.exprNeedsCleanups() && 15364 "cleanups within block not correctly bound!"); 15365 PopExpressionEvaluationContext(); 15366 15367 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15368 BlockDecl *BD = BSI->TheDecl; 15369 15370 if (BSI->HasImplicitReturnType) 15371 deduceClosureReturnType(*BSI); 15372 15373 QualType RetTy = Context.VoidTy; 15374 if (!BSI->ReturnType.isNull()) 15375 RetTy = BSI->ReturnType; 15376 15377 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15378 QualType BlockTy; 15379 15380 // If the user wrote a function type in some form, try to use that. 15381 if (!BSI->FunctionType.isNull()) { 15382 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15383 15384 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15385 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15386 15387 // Turn protoless block types into nullary block types. 15388 if (isa<FunctionNoProtoType>(FTy)) { 15389 FunctionProtoType::ExtProtoInfo EPI; 15390 EPI.ExtInfo = Ext; 15391 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15392 15393 // Otherwise, if we don't need to change anything about the function type, 15394 // preserve its sugar structure. 15395 } else if (FTy->getReturnType() == RetTy && 15396 (!NoReturn || FTy->getNoReturnAttr())) { 15397 BlockTy = BSI->FunctionType; 15398 15399 // Otherwise, make the minimal modifications to the function type. 15400 } else { 15401 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15402 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15403 EPI.TypeQuals = Qualifiers(); 15404 EPI.ExtInfo = Ext; 15405 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15406 } 15407 15408 // If we don't have a function type, just build one from nothing. 15409 } else { 15410 FunctionProtoType::ExtProtoInfo EPI; 15411 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15412 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15413 } 15414 15415 DiagnoseUnusedParameters(BD->parameters()); 15416 BlockTy = Context.getBlockPointerType(BlockTy); 15417 15418 // If needed, diagnose invalid gotos and switches in the block. 15419 if (getCurFunction()->NeedsScopeChecking() && 15420 !PP.isCodeCompletionEnabled()) 15421 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15422 15423 BD->setBody(cast<CompoundStmt>(Body)); 15424 15425 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15426 DiagnoseUnguardedAvailabilityViolations(BD); 15427 15428 // Try to apply the named return value optimization. We have to check again 15429 // if we can do this, though, because blocks keep return statements around 15430 // to deduce an implicit return type. 15431 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15432 !BD->isDependentContext()) 15433 computeNRVO(Body, BSI); 15434 15435 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15436 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15437 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15438 NTCUK_Destruct|NTCUK_Copy); 15439 15440 PopDeclContext(); 15441 15442 // Set the captured variables on the block. 15443 SmallVector<BlockDecl::Capture, 4> Captures; 15444 for (Capture &Cap : BSI->Captures) { 15445 if (Cap.isInvalid() || Cap.isThisCapture()) 15446 continue; 15447 15448 VarDecl *Var = Cap.getVariable(); 15449 Expr *CopyExpr = nullptr; 15450 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15451 if (const RecordType *Record = 15452 Cap.getCaptureType()->getAs<RecordType>()) { 15453 // The capture logic needs the destructor, so make sure we mark it. 15454 // Usually this is unnecessary because most local variables have 15455 // their destructors marked at declaration time, but parameters are 15456 // an exception because it's technically only the call site that 15457 // actually requires the destructor. 15458 if (isa<ParmVarDecl>(Var)) 15459 FinalizeVarWithDestructor(Var, Record); 15460 15461 // Enter a separate potentially-evaluated context while building block 15462 // initializers to isolate their cleanups from those of the block 15463 // itself. 15464 // FIXME: Is this appropriate even when the block itself occurs in an 15465 // unevaluated operand? 15466 EnterExpressionEvaluationContext EvalContext( 15467 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15468 15469 SourceLocation Loc = Cap.getLocation(); 15470 15471 ExprResult Result = BuildDeclarationNameExpr( 15472 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15473 15474 // According to the blocks spec, the capture of a variable from 15475 // the stack requires a const copy constructor. This is not true 15476 // of the copy/move done to move a __block variable to the heap. 15477 if (!Result.isInvalid() && 15478 !Result.get()->getType().isConstQualified()) { 15479 Result = ImpCastExprToType(Result.get(), 15480 Result.get()->getType().withConst(), 15481 CK_NoOp, VK_LValue); 15482 } 15483 15484 if (!Result.isInvalid()) { 15485 Result = PerformCopyInitialization( 15486 InitializedEntity::InitializeBlock(Var->getLocation(), 15487 Cap.getCaptureType(), false), 15488 Loc, Result.get()); 15489 } 15490 15491 // Build a full-expression copy expression if initialization 15492 // succeeded and used a non-trivial constructor. Recover from 15493 // errors by pretending that the copy isn't necessary. 15494 if (!Result.isInvalid() && 15495 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15496 ->isTrivial()) { 15497 Result = MaybeCreateExprWithCleanups(Result); 15498 CopyExpr = Result.get(); 15499 } 15500 } 15501 } 15502 15503 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15504 CopyExpr); 15505 Captures.push_back(NewCap); 15506 } 15507 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15508 15509 // Pop the block scope now but keep it alive to the end of this function. 15510 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15511 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15512 15513 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15514 15515 // If the block isn't obviously global, i.e. it captures anything at 15516 // all, then we need to do a few things in the surrounding context: 15517 if (Result->getBlockDecl()->hasCaptures()) { 15518 // First, this expression has a new cleanup object. 15519 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15520 Cleanup.setExprNeedsCleanups(true); 15521 15522 // It also gets a branch-protected scope if any of the captured 15523 // variables needs destruction. 15524 for (const auto &CI : Result->getBlockDecl()->captures()) { 15525 const VarDecl *var = CI.getVariable(); 15526 if (var->getType().isDestructedType() != QualType::DK_none) { 15527 setFunctionHasBranchProtectedScope(); 15528 break; 15529 } 15530 } 15531 } 15532 15533 if (getCurFunction()) 15534 getCurFunction()->addBlock(BD); 15535 15536 return Result; 15537 } 15538 15539 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15540 SourceLocation RPLoc) { 15541 TypeSourceInfo *TInfo; 15542 GetTypeFromParser(Ty, &TInfo); 15543 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15544 } 15545 15546 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15547 Expr *E, TypeSourceInfo *TInfo, 15548 SourceLocation RPLoc) { 15549 Expr *OrigExpr = E; 15550 bool IsMS = false; 15551 15552 // CUDA device code does not support varargs. 15553 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15554 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15555 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15556 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15557 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15558 } 15559 } 15560 15561 // NVPTX does not support va_arg expression. 15562 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15563 Context.getTargetInfo().getTriple().isNVPTX()) 15564 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15565 15566 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15567 // as Microsoft ABI on an actual Microsoft platform, where 15568 // __builtin_ms_va_list and __builtin_va_list are the same.) 15569 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15570 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15571 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15572 if (Context.hasSameType(MSVaListType, E->getType())) { 15573 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15574 return ExprError(); 15575 IsMS = true; 15576 } 15577 } 15578 15579 // Get the va_list type 15580 QualType VaListType = Context.getBuiltinVaListType(); 15581 if (!IsMS) { 15582 if (VaListType->isArrayType()) { 15583 // Deal with implicit array decay; for example, on x86-64, 15584 // va_list is an array, but it's supposed to decay to 15585 // a pointer for va_arg. 15586 VaListType = Context.getArrayDecayedType(VaListType); 15587 // Make sure the input expression also decays appropriately. 15588 ExprResult Result = UsualUnaryConversions(E); 15589 if (Result.isInvalid()) 15590 return ExprError(); 15591 E = Result.get(); 15592 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15593 // If va_list is a record type and we are compiling in C++ mode, 15594 // check the argument using reference binding. 15595 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15596 Context, Context.getLValueReferenceType(VaListType), false); 15597 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15598 if (Init.isInvalid()) 15599 return ExprError(); 15600 E = Init.getAs<Expr>(); 15601 } else { 15602 // Otherwise, the va_list argument must be an l-value because 15603 // it is modified by va_arg. 15604 if (!E->isTypeDependent() && 15605 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15606 return ExprError(); 15607 } 15608 } 15609 15610 if (!IsMS && !E->isTypeDependent() && 15611 !Context.hasSameType(VaListType, E->getType())) 15612 return ExprError( 15613 Diag(E->getBeginLoc(), 15614 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15615 << OrigExpr->getType() << E->getSourceRange()); 15616 15617 if (!TInfo->getType()->isDependentType()) { 15618 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15619 diag::err_second_parameter_to_va_arg_incomplete, 15620 TInfo->getTypeLoc())) 15621 return ExprError(); 15622 15623 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15624 TInfo->getType(), 15625 diag::err_second_parameter_to_va_arg_abstract, 15626 TInfo->getTypeLoc())) 15627 return ExprError(); 15628 15629 if (!TInfo->getType().isPODType(Context)) { 15630 Diag(TInfo->getTypeLoc().getBeginLoc(), 15631 TInfo->getType()->isObjCLifetimeType() 15632 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15633 : diag::warn_second_parameter_to_va_arg_not_pod) 15634 << TInfo->getType() 15635 << TInfo->getTypeLoc().getSourceRange(); 15636 } 15637 15638 // Check for va_arg where arguments of the given type will be promoted 15639 // (i.e. this va_arg is guaranteed to have undefined behavior). 15640 QualType PromoteType; 15641 if (TInfo->getType()->isPromotableIntegerType()) { 15642 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15643 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15644 PromoteType = QualType(); 15645 } 15646 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15647 PromoteType = Context.DoubleTy; 15648 if (!PromoteType.isNull()) 15649 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15650 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15651 << TInfo->getType() 15652 << PromoteType 15653 << TInfo->getTypeLoc().getSourceRange()); 15654 } 15655 15656 QualType T = TInfo->getType().getNonLValueExprType(Context); 15657 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15658 } 15659 15660 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15661 // The type of __null will be int or long, depending on the size of 15662 // pointers on the target. 15663 QualType Ty; 15664 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15665 if (pw == Context.getTargetInfo().getIntWidth()) 15666 Ty = Context.IntTy; 15667 else if (pw == Context.getTargetInfo().getLongWidth()) 15668 Ty = Context.LongTy; 15669 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15670 Ty = Context.LongLongTy; 15671 else { 15672 llvm_unreachable("I don't know size of pointer!"); 15673 } 15674 15675 return new (Context) GNUNullExpr(Ty, TokenLoc); 15676 } 15677 15678 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15679 SourceLocation BuiltinLoc, 15680 SourceLocation RPLoc) { 15681 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15682 } 15683 15684 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15685 SourceLocation BuiltinLoc, 15686 SourceLocation RPLoc, 15687 DeclContext *ParentContext) { 15688 return new (Context) 15689 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15690 } 15691 15692 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15693 bool Diagnose) { 15694 if (!getLangOpts().ObjC) 15695 return false; 15696 15697 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15698 if (!PT) 15699 return false; 15700 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15701 15702 // Ignore any parens, implicit casts (should only be 15703 // array-to-pointer decays), and not-so-opaque values. The last is 15704 // important for making this trigger for property assignments. 15705 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15706 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15707 if (OV->getSourceExpr()) 15708 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15709 15710 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15711 if (!PT->isObjCIdType() && 15712 !(ID && ID->getIdentifier()->isStr("NSString"))) 15713 return false; 15714 if (!SL->isAscii()) 15715 return false; 15716 15717 if (Diagnose) { 15718 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15719 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15720 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15721 } 15722 return true; 15723 } 15724 15725 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15726 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15727 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15728 !SrcExpr->isNullPointerConstant( 15729 getASTContext(), Expr::NPC_NeverValueDependent)) { 15730 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15731 return false; 15732 if (Diagnose) { 15733 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15734 << /*number*/1 15735 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15736 Expr *NumLit = 15737 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15738 if (NumLit) 15739 Exp = NumLit; 15740 } 15741 return true; 15742 } 15743 15744 return false; 15745 } 15746 15747 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15748 const Expr *SrcExpr) { 15749 if (!DstType->isFunctionPointerType() || 15750 !SrcExpr->getType()->isFunctionType()) 15751 return false; 15752 15753 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15754 if (!DRE) 15755 return false; 15756 15757 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15758 if (!FD) 15759 return false; 15760 15761 return !S.checkAddressOfFunctionIsAvailable(FD, 15762 /*Complain=*/true, 15763 SrcExpr->getBeginLoc()); 15764 } 15765 15766 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15767 SourceLocation Loc, 15768 QualType DstType, QualType SrcType, 15769 Expr *SrcExpr, AssignmentAction Action, 15770 bool *Complained) { 15771 if (Complained) 15772 *Complained = false; 15773 15774 // Decode the result (notice that AST's are still created for extensions). 15775 bool CheckInferredResultType = false; 15776 bool isInvalid = false; 15777 unsigned DiagKind = 0; 15778 ConversionFixItGenerator ConvHints; 15779 bool MayHaveConvFixit = false; 15780 bool MayHaveFunctionDiff = false; 15781 const ObjCInterfaceDecl *IFace = nullptr; 15782 const ObjCProtocolDecl *PDecl = nullptr; 15783 15784 switch (ConvTy) { 15785 case Compatible: 15786 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15787 return false; 15788 15789 case PointerToInt: 15790 if (getLangOpts().CPlusPlus) { 15791 DiagKind = diag::err_typecheck_convert_pointer_int; 15792 isInvalid = true; 15793 } else { 15794 DiagKind = diag::ext_typecheck_convert_pointer_int; 15795 } 15796 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15797 MayHaveConvFixit = true; 15798 break; 15799 case IntToPointer: 15800 if (getLangOpts().CPlusPlus) { 15801 DiagKind = diag::err_typecheck_convert_int_pointer; 15802 isInvalid = true; 15803 } else { 15804 DiagKind = diag::ext_typecheck_convert_int_pointer; 15805 } 15806 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15807 MayHaveConvFixit = true; 15808 break; 15809 case IncompatibleFunctionPointer: 15810 if (getLangOpts().CPlusPlus) { 15811 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15812 isInvalid = true; 15813 } else { 15814 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15815 } 15816 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15817 MayHaveConvFixit = true; 15818 break; 15819 case IncompatiblePointer: 15820 if (Action == AA_Passing_CFAudited) { 15821 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15822 } else if (getLangOpts().CPlusPlus) { 15823 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15824 isInvalid = true; 15825 } else { 15826 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15827 } 15828 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15829 SrcType->isObjCObjectPointerType(); 15830 if (!CheckInferredResultType) { 15831 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15832 } else if (CheckInferredResultType) { 15833 SrcType = SrcType.getUnqualifiedType(); 15834 DstType = DstType.getUnqualifiedType(); 15835 } 15836 MayHaveConvFixit = true; 15837 break; 15838 case IncompatiblePointerSign: 15839 if (getLangOpts().CPlusPlus) { 15840 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15841 isInvalid = true; 15842 } else { 15843 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15844 } 15845 break; 15846 case FunctionVoidPointer: 15847 if (getLangOpts().CPlusPlus) { 15848 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15849 isInvalid = true; 15850 } else { 15851 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15852 } 15853 break; 15854 case IncompatiblePointerDiscardsQualifiers: { 15855 // Perform array-to-pointer decay if necessary. 15856 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15857 15858 isInvalid = true; 15859 15860 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15861 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15862 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15863 DiagKind = diag::err_typecheck_incompatible_address_space; 15864 break; 15865 15866 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15867 DiagKind = diag::err_typecheck_incompatible_ownership; 15868 break; 15869 } 15870 15871 llvm_unreachable("unknown error case for discarding qualifiers!"); 15872 // fallthrough 15873 } 15874 case CompatiblePointerDiscardsQualifiers: 15875 // If the qualifiers lost were because we were applying the 15876 // (deprecated) C++ conversion from a string literal to a char* 15877 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15878 // Ideally, this check would be performed in 15879 // checkPointerTypesForAssignment. However, that would require a 15880 // bit of refactoring (so that the second argument is an 15881 // expression, rather than a type), which should be done as part 15882 // of a larger effort to fix checkPointerTypesForAssignment for 15883 // C++ semantics. 15884 if (getLangOpts().CPlusPlus && 15885 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15886 return false; 15887 if (getLangOpts().CPlusPlus) { 15888 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15889 isInvalid = true; 15890 } else { 15891 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15892 } 15893 15894 break; 15895 case IncompatibleNestedPointerQualifiers: 15896 if (getLangOpts().CPlusPlus) { 15897 isInvalid = true; 15898 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15899 } else { 15900 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15901 } 15902 break; 15903 case IncompatibleNestedPointerAddressSpaceMismatch: 15904 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15905 isInvalid = true; 15906 break; 15907 case IntToBlockPointer: 15908 DiagKind = diag::err_int_to_block_pointer; 15909 isInvalid = true; 15910 break; 15911 case IncompatibleBlockPointer: 15912 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15913 isInvalid = true; 15914 break; 15915 case IncompatibleObjCQualifiedId: { 15916 if (SrcType->isObjCQualifiedIdType()) { 15917 const ObjCObjectPointerType *srcOPT = 15918 SrcType->castAs<ObjCObjectPointerType>(); 15919 for (auto *srcProto : srcOPT->quals()) { 15920 PDecl = srcProto; 15921 break; 15922 } 15923 if (const ObjCInterfaceType *IFaceT = 15924 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15925 IFace = IFaceT->getDecl(); 15926 } 15927 else if (DstType->isObjCQualifiedIdType()) { 15928 const ObjCObjectPointerType *dstOPT = 15929 DstType->castAs<ObjCObjectPointerType>(); 15930 for (auto *dstProto : dstOPT->quals()) { 15931 PDecl = dstProto; 15932 break; 15933 } 15934 if (const ObjCInterfaceType *IFaceT = 15935 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15936 IFace = IFaceT->getDecl(); 15937 } 15938 if (getLangOpts().CPlusPlus) { 15939 DiagKind = diag::err_incompatible_qualified_id; 15940 isInvalid = true; 15941 } else { 15942 DiagKind = diag::warn_incompatible_qualified_id; 15943 } 15944 break; 15945 } 15946 case IncompatibleVectors: 15947 if (getLangOpts().CPlusPlus) { 15948 DiagKind = diag::err_incompatible_vectors; 15949 isInvalid = true; 15950 } else { 15951 DiagKind = diag::warn_incompatible_vectors; 15952 } 15953 break; 15954 case IncompatibleObjCWeakRef: 15955 DiagKind = diag::err_arc_weak_unavailable_assign; 15956 isInvalid = true; 15957 break; 15958 case Incompatible: 15959 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15960 if (Complained) 15961 *Complained = true; 15962 return true; 15963 } 15964 15965 DiagKind = diag::err_typecheck_convert_incompatible; 15966 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15967 MayHaveConvFixit = true; 15968 isInvalid = true; 15969 MayHaveFunctionDiff = true; 15970 break; 15971 } 15972 15973 QualType FirstType, SecondType; 15974 switch (Action) { 15975 case AA_Assigning: 15976 case AA_Initializing: 15977 // The destination type comes first. 15978 FirstType = DstType; 15979 SecondType = SrcType; 15980 break; 15981 15982 case AA_Returning: 15983 case AA_Passing: 15984 case AA_Passing_CFAudited: 15985 case AA_Converting: 15986 case AA_Sending: 15987 case AA_Casting: 15988 // The source type comes first. 15989 FirstType = SrcType; 15990 SecondType = DstType; 15991 break; 15992 } 15993 15994 PartialDiagnostic FDiag = PDiag(DiagKind); 15995 if (Action == AA_Passing_CFAudited) 15996 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15997 else 15998 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15999 16000 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16001 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16002 auto isPlainChar = [](const clang::Type *Type) { 16003 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16004 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16005 }; 16006 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16007 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16008 } 16009 16010 // If we can fix the conversion, suggest the FixIts. 16011 if (!ConvHints.isNull()) { 16012 for (FixItHint &H : ConvHints.Hints) 16013 FDiag << H; 16014 } 16015 16016 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16017 16018 if (MayHaveFunctionDiff) 16019 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16020 16021 Diag(Loc, FDiag); 16022 if ((DiagKind == diag::warn_incompatible_qualified_id || 16023 DiagKind == diag::err_incompatible_qualified_id) && 16024 PDecl && IFace && !IFace->hasDefinition()) 16025 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16026 << IFace << PDecl; 16027 16028 if (SecondType == Context.OverloadTy) 16029 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16030 FirstType, /*TakingAddress=*/true); 16031 16032 if (CheckInferredResultType) 16033 EmitRelatedResultTypeNote(SrcExpr); 16034 16035 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16036 EmitRelatedResultTypeNoteForReturn(DstType); 16037 16038 if (Complained) 16039 *Complained = true; 16040 return isInvalid; 16041 } 16042 16043 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16044 llvm::APSInt *Result, 16045 AllowFoldKind CanFold) { 16046 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16047 public: 16048 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16049 QualType T) override { 16050 return S.Diag(Loc, diag::err_ice_not_integral) 16051 << T << S.LangOpts.CPlusPlus; 16052 } 16053 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16054 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16055 } 16056 } Diagnoser; 16057 16058 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16059 } 16060 16061 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16062 llvm::APSInt *Result, 16063 unsigned DiagID, 16064 AllowFoldKind CanFold) { 16065 class IDDiagnoser : public VerifyICEDiagnoser { 16066 unsigned DiagID; 16067 16068 public: 16069 IDDiagnoser(unsigned DiagID) 16070 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16071 16072 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16073 return S.Diag(Loc, DiagID); 16074 } 16075 } Diagnoser(DiagID); 16076 16077 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16078 } 16079 16080 Sema::SemaDiagnosticBuilder 16081 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16082 QualType T) { 16083 return diagnoseNotICE(S, Loc); 16084 } 16085 16086 Sema::SemaDiagnosticBuilder 16087 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16088 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16089 } 16090 16091 ExprResult 16092 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16093 VerifyICEDiagnoser &Diagnoser, 16094 AllowFoldKind CanFold) { 16095 SourceLocation DiagLoc = E->getBeginLoc(); 16096 16097 if (getLangOpts().CPlusPlus11) { 16098 // C++11 [expr.const]p5: 16099 // If an expression of literal class type is used in a context where an 16100 // integral constant expression is required, then that class type shall 16101 // have a single non-explicit conversion function to an integral or 16102 // unscoped enumeration type 16103 ExprResult Converted; 16104 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16105 VerifyICEDiagnoser &BaseDiagnoser; 16106 public: 16107 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16108 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16109 BaseDiagnoser.Suppress, true), 16110 BaseDiagnoser(BaseDiagnoser) {} 16111 16112 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16113 QualType T) override { 16114 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16115 } 16116 16117 SemaDiagnosticBuilder diagnoseIncomplete( 16118 Sema &S, SourceLocation Loc, QualType T) override { 16119 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16120 } 16121 16122 SemaDiagnosticBuilder diagnoseExplicitConv( 16123 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16124 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16125 } 16126 16127 SemaDiagnosticBuilder noteExplicitConv( 16128 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16129 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16130 << ConvTy->isEnumeralType() << ConvTy; 16131 } 16132 16133 SemaDiagnosticBuilder diagnoseAmbiguous( 16134 Sema &S, SourceLocation Loc, QualType T) override { 16135 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16136 } 16137 16138 SemaDiagnosticBuilder noteAmbiguous( 16139 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16140 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16141 << ConvTy->isEnumeralType() << ConvTy; 16142 } 16143 16144 SemaDiagnosticBuilder diagnoseConversion( 16145 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16146 llvm_unreachable("conversion functions are permitted"); 16147 } 16148 } ConvertDiagnoser(Diagnoser); 16149 16150 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16151 ConvertDiagnoser); 16152 if (Converted.isInvalid()) 16153 return Converted; 16154 E = Converted.get(); 16155 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16156 return ExprError(); 16157 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16158 // An ICE must be of integral or unscoped enumeration type. 16159 if (!Diagnoser.Suppress) 16160 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16161 << E->getSourceRange(); 16162 return ExprError(); 16163 } 16164 16165 ExprResult RValueExpr = DefaultLvalueConversion(E); 16166 if (RValueExpr.isInvalid()) 16167 return ExprError(); 16168 16169 E = RValueExpr.get(); 16170 16171 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16172 // in the non-ICE case. 16173 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16174 if (Result) 16175 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16176 if (!isa<ConstantExpr>(E)) 16177 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16178 : ConstantExpr::Create(Context, E); 16179 return E; 16180 } 16181 16182 Expr::EvalResult EvalResult; 16183 SmallVector<PartialDiagnosticAt, 8> Notes; 16184 EvalResult.Diag = &Notes; 16185 16186 // Try to evaluate the expression, and produce diagnostics explaining why it's 16187 // not a constant expression as a side-effect. 16188 bool Folded = 16189 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16190 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16191 16192 if (!isa<ConstantExpr>(E)) 16193 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16194 16195 // In C++11, we can rely on diagnostics being produced for any expression 16196 // which is not a constant expression. If no diagnostics were produced, then 16197 // this is a constant expression. 16198 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16199 if (Result) 16200 *Result = EvalResult.Val.getInt(); 16201 return E; 16202 } 16203 16204 // If our only note is the usual "invalid subexpression" note, just point 16205 // the caret at its location rather than producing an essentially 16206 // redundant note. 16207 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16208 diag::note_invalid_subexpr_in_const_expr) { 16209 DiagLoc = Notes[0].first; 16210 Notes.clear(); 16211 } 16212 16213 if (!Folded || !CanFold) { 16214 if (!Diagnoser.Suppress) { 16215 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16216 for (const PartialDiagnosticAt &Note : Notes) 16217 Diag(Note.first, Note.second); 16218 } 16219 16220 return ExprError(); 16221 } 16222 16223 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16224 for (const PartialDiagnosticAt &Note : Notes) 16225 Diag(Note.first, Note.second); 16226 16227 if (Result) 16228 *Result = EvalResult.Val.getInt(); 16229 return E; 16230 } 16231 16232 namespace { 16233 // Handle the case where we conclude a expression which we speculatively 16234 // considered to be unevaluated is actually evaluated. 16235 class TransformToPE : public TreeTransform<TransformToPE> { 16236 typedef TreeTransform<TransformToPE> BaseTransform; 16237 16238 public: 16239 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16240 16241 // Make sure we redo semantic analysis 16242 bool AlwaysRebuild() { return true; } 16243 bool ReplacingOriginal() { return true; } 16244 16245 // We need to special-case DeclRefExprs referring to FieldDecls which 16246 // are not part of a member pointer formation; normal TreeTransforming 16247 // doesn't catch this case because of the way we represent them in the AST. 16248 // FIXME: This is a bit ugly; is it really the best way to handle this 16249 // case? 16250 // 16251 // Error on DeclRefExprs referring to FieldDecls. 16252 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16253 if (isa<FieldDecl>(E->getDecl()) && 16254 !SemaRef.isUnevaluatedContext()) 16255 return SemaRef.Diag(E->getLocation(), 16256 diag::err_invalid_non_static_member_use) 16257 << E->getDecl() << E->getSourceRange(); 16258 16259 return BaseTransform::TransformDeclRefExpr(E); 16260 } 16261 16262 // Exception: filter out member pointer formation 16263 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16264 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16265 return E; 16266 16267 return BaseTransform::TransformUnaryOperator(E); 16268 } 16269 16270 // The body of a lambda-expression is in a separate expression evaluation 16271 // context so never needs to be transformed. 16272 // FIXME: Ideally we wouldn't transform the closure type either, and would 16273 // just recreate the capture expressions and lambda expression. 16274 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16275 return SkipLambdaBody(E, Body); 16276 } 16277 }; 16278 } 16279 16280 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16281 assert(isUnevaluatedContext() && 16282 "Should only transform unevaluated expressions"); 16283 ExprEvalContexts.back().Context = 16284 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16285 if (isUnevaluatedContext()) 16286 return E; 16287 return TransformToPE(*this).TransformExpr(E); 16288 } 16289 16290 void 16291 Sema::PushExpressionEvaluationContext( 16292 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16293 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16294 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16295 LambdaContextDecl, ExprContext); 16296 Cleanup.reset(); 16297 if (!MaybeODRUseExprs.empty()) 16298 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16299 } 16300 16301 void 16302 Sema::PushExpressionEvaluationContext( 16303 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16304 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16305 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16306 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16307 } 16308 16309 namespace { 16310 16311 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16312 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16313 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16314 if (E->getOpcode() == UO_Deref) 16315 return CheckPossibleDeref(S, E->getSubExpr()); 16316 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16317 return CheckPossibleDeref(S, E->getBase()); 16318 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16319 return CheckPossibleDeref(S, E->getBase()); 16320 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16321 QualType Inner; 16322 QualType Ty = E->getType(); 16323 if (const auto *Ptr = Ty->getAs<PointerType>()) 16324 Inner = Ptr->getPointeeType(); 16325 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16326 Inner = Arr->getElementType(); 16327 else 16328 return nullptr; 16329 16330 if (Inner->hasAttr(attr::NoDeref)) 16331 return E; 16332 } 16333 return nullptr; 16334 } 16335 16336 } // namespace 16337 16338 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16339 for (const Expr *E : Rec.PossibleDerefs) { 16340 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16341 if (DeclRef) { 16342 const ValueDecl *Decl = DeclRef->getDecl(); 16343 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16344 << Decl->getName() << E->getSourceRange(); 16345 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16346 } else { 16347 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16348 << E->getSourceRange(); 16349 } 16350 } 16351 Rec.PossibleDerefs.clear(); 16352 } 16353 16354 /// Check whether E, which is either a discarded-value expression or an 16355 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16356 /// and if so, remove it from the list of volatile-qualified assignments that 16357 /// we are going to warn are deprecated. 16358 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16359 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16360 return; 16361 16362 // Note: ignoring parens here is not justified by the standard rules, but 16363 // ignoring parentheses seems like a more reasonable approach, and this only 16364 // drives a deprecation warning so doesn't affect conformance. 16365 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16366 if (BO->getOpcode() == BO_Assign) { 16367 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16368 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16369 LHSs.end()); 16370 } 16371 } 16372 } 16373 16374 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16375 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16376 RebuildingImmediateInvocation) 16377 return E; 16378 16379 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16380 /// It's OK if this fails; we'll also remove this in 16381 /// HandleImmediateInvocations, but catching it here allows us to avoid 16382 /// walking the AST looking for it in simple cases. 16383 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16384 if (auto *DeclRef = 16385 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16386 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16387 16388 E = MaybeCreateExprWithCleanups(E); 16389 16390 ConstantExpr *Res = ConstantExpr::Create( 16391 getASTContext(), E.get(), 16392 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16393 getASTContext()), 16394 /*IsImmediateInvocation*/ true); 16395 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16396 return Res; 16397 } 16398 16399 static void EvaluateAndDiagnoseImmediateInvocation( 16400 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16401 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16402 Expr::EvalResult Eval; 16403 Eval.Diag = &Notes; 16404 ConstantExpr *CE = Candidate.getPointer(); 16405 bool Result = CE->EvaluateAsConstantExpr( 16406 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16407 if (!Result || !Notes.empty()) { 16408 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16409 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16410 InnerExpr = FunctionalCast->getSubExpr(); 16411 FunctionDecl *FD = nullptr; 16412 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16413 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16414 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16415 FD = Call->getConstructor(); 16416 else 16417 llvm_unreachable("unhandled decl kind"); 16418 assert(FD->isConsteval()); 16419 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16420 for (auto &Note : Notes) 16421 SemaRef.Diag(Note.first, Note.second); 16422 return; 16423 } 16424 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16425 } 16426 16427 static void RemoveNestedImmediateInvocation( 16428 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16429 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16430 struct ComplexRemove : TreeTransform<ComplexRemove> { 16431 using Base = TreeTransform<ComplexRemove>; 16432 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16433 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16434 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16435 CurrentII; 16436 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16437 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16438 SmallVector<Sema::ImmediateInvocationCandidate, 16439 4>::reverse_iterator Current) 16440 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16441 void RemoveImmediateInvocation(ConstantExpr* E) { 16442 auto It = std::find_if(CurrentII, IISet.rend(), 16443 [E](Sema::ImmediateInvocationCandidate Elem) { 16444 return Elem.getPointer() == E; 16445 }); 16446 assert(It != IISet.rend() && 16447 "ConstantExpr marked IsImmediateInvocation should " 16448 "be present"); 16449 It->setInt(1); // Mark as deleted 16450 } 16451 ExprResult TransformConstantExpr(ConstantExpr *E) { 16452 if (!E->isImmediateInvocation()) 16453 return Base::TransformConstantExpr(E); 16454 RemoveImmediateInvocation(E); 16455 return Base::TransformExpr(E->getSubExpr()); 16456 } 16457 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16458 /// we need to remove its DeclRefExpr from the DRSet. 16459 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16460 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16461 return Base::TransformCXXOperatorCallExpr(E); 16462 } 16463 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16464 /// here. 16465 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16466 if (!Init) 16467 return Init; 16468 /// ConstantExpr are the first layer of implicit node to be removed so if 16469 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16470 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16471 if (CE->isImmediateInvocation()) 16472 RemoveImmediateInvocation(CE); 16473 return Base::TransformInitializer(Init, NotCopyInit); 16474 } 16475 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16476 DRSet.erase(E); 16477 return E; 16478 } 16479 bool AlwaysRebuild() { return false; } 16480 bool ReplacingOriginal() { return true; } 16481 bool AllowSkippingCXXConstructExpr() { 16482 bool Res = AllowSkippingFirstCXXConstructExpr; 16483 AllowSkippingFirstCXXConstructExpr = true; 16484 return Res; 16485 } 16486 bool AllowSkippingFirstCXXConstructExpr = true; 16487 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16488 Rec.ImmediateInvocationCandidates, It); 16489 16490 /// CXXConstructExpr with a single argument are getting skipped by 16491 /// TreeTransform in some situtation because they could be implicit. This 16492 /// can only occur for the top-level CXXConstructExpr because it is used 16493 /// nowhere in the expression being transformed therefore will not be rebuilt. 16494 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16495 /// skipping the first CXXConstructExpr. 16496 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16497 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16498 16499 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16500 assert(Res.isUsable()); 16501 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16502 It->getPointer()->setSubExpr(Res.get()); 16503 } 16504 16505 static void 16506 HandleImmediateInvocations(Sema &SemaRef, 16507 Sema::ExpressionEvaluationContextRecord &Rec) { 16508 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16509 Rec.ReferenceToConsteval.size() == 0) || 16510 SemaRef.RebuildingImmediateInvocation) 16511 return; 16512 16513 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16514 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16515 /// need to remove ReferenceToConsteval in the immediate invocation. 16516 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16517 16518 /// Prevent sema calls during the tree transform from adding pointers that 16519 /// are already in the sets. 16520 llvm::SaveAndRestore<bool> DisableIITracking( 16521 SemaRef.RebuildingImmediateInvocation, true); 16522 16523 /// Prevent diagnostic during tree transfrom as they are duplicates 16524 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16525 16526 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16527 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16528 if (!It->getInt()) 16529 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16530 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16531 Rec.ReferenceToConsteval.size()) { 16532 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16533 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16534 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16535 bool VisitDeclRefExpr(DeclRefExpr *E) { 16536 DRSet.erase(E); 16537 return DRSet.size(); 16538 } 16539 } Visitor(Rec.ReferenceToConsteval); 16540 Visitor.TraverseStmt( 16541 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16542 } 16543 for (auto CE : Rec.ImmediateInvocationCandidates) 16544 if (!CE.getInt()) 16545 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16546 for (auto DR : Rec.ReferenceToConsteval) { 16547 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16548 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16549 << FD; 16550 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16551 } 16552 } 16553 16554 void Sema::PopExpressionEvaluationContext() { 16555 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16556 unsigned NumTypos = Rec.NumTypos; 16557 16558 if (!Rec.Lambdas.empty()) { 16559 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16560 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16561 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16562 unsigned D; 16563 if (Rec.isUnevaluated()) { 16564 // C++11 [expr.prim.lambda]p2: 16565 // A lambda-expression shall not appear in an unevaluated operand 16566 // (Clause 5). 16567 D = diag::err_lambda_unevaluated_operand; 16568 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16569 // C++1y [expr.const]p2: 16570 // A conditional-expression e is a core constant expression unless the 16571 // evaluation of e, following the rules of the abstract machine, would 16572 // evaluate [...] a lambda-expression. 16573 D = diag::err_lambda_in_constant_expression; 16574 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16575 // C++17 [expr.prim.lamda]p2: 16576 // A lambda-expression shall not appear [...] in a template-argument. 16577 D = diag::err_lambda_in_invalid_context; 16578 } else 16579 llvm_unreachable("Couldn't infer lambda error message."); 16580 16581 for (const auto *L : Rec.Lambdas) 16582 Diag(L->getBeginLoc(), D); 16583 } 16584 } 16585 16586 WarnOnPendingNoDerefs(Rec); 16587 HandleImmediateInvocations(*this, Rec); 16588 16589 // Warn on any volatile-qualified simple-assignments that are not discarded- 16590 // value expressions nor unevaluated operands (those cases get removed from 16591 // this list by CheckUnusedVolatileAssignment). 16592 for (auto *BO : Rec.VolatileAssignmentLHSs) 16593 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16594 << BO->getType(); 16595 16596 // When are coming out of an unevaluated context, clear out any 16597 // temporaries that we may have created as part of the evaluation of 16598 // the expression in that context: they aren't relevant because they 16599 // will never be constructed. 16600 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16601 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16602 ExprCleanupObjects.end()); 16603 Cleanup = Rec.ParentCleanup; 16604 CleanupVarDeclMarking(); 16605 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16606 // Otherwise, merge the contexts together. 16607 } else { 16608 Cleanup.mergeFrom(Rec.ParentCleanup); 16609 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16610 Rec.SavedMaybeODRUseExprs.end()); 16611 } 16612 16613 // Pop the current expression evaluation context off the stack. 16614 ExprEvalContexts.pop_back(); 16615 16616 // The global expression evaluation context record is never popped. 16617 ExprEvalContexts.back().NumTypos += NumTypos; 16618 } 16619 16620 void Sema::DiscardCleanupsInEvaluationContext() { 16621 ExprCleanupObjects.erase( 16622 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16623 ExprCleanupObjects.end()); 16624 Cleanup.reset(); 16625 MaybeODRUseExprs.clear(); 16626 } 16627 16628 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16629 ExprResult Result = CheckPlaceholderExpr(E); 16630 if (Result.isInvalid()) 16631 return ExprError(); 16632 E = Result.get(); 16633 if (!E->getType()->isVariablyModifiedType()) 16634 return E; 16635 return TransformToPotentiallyEvaluated(E); 16636 } 16637 16638 /// Are we in a context that is potentially constant evaluated per C++20 16639 /// [expr.const]p12? 16640 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16641 /// C++2a [expr.const]p12: 16642 // An expression or conversion is potentially constant evaluated if it is 16643 switch (SemaRef.ExprEvalContexts.back().Context) { 16644 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16645 // -- a manifestly constant-evaluated expression, 16646 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16647 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16648 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16649 // -- a potentially-evaluated expression, 16650 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16651 // -- an immediate subexpression of a braced-init-list, 16652 16653 // -- [FIXME] an expression of the form & cast-expression that occurs 16654 // within a templated entity 16655 // -- a subexpression of one of the above that is not a subexpression of 16656 // a nested unevaluated operand. 16657 return true; 16658 16659 case Sema::ExpressionEvaluationContext::Unevaluated: 16660 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16661 // Expressions in this context are never evaluated. 16662 return false; 16663 } 16664 llvm_unreachable("Invalid context"); 16665 } 16666 16667 /// Return true if this function has a calling convention that requires mangling 16668 /// in the size of the parameter pack. 16669 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16670 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16671 // we don't need parameter type sizes. 16672 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16673 if (!TT.isOSWindows() || !TT.isX86()) 16674 return false; 16675 16676 // If this is C++ and this isn't an extern "C" function, parameters do not 16677 // need to be complete. In this case, C++ mangling will apply, which doesn't 16678 // use the size of the parameters. 16679 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16680 return false; 16681 16682 // Stdcall, fastcall, and vectorcall need this special treatment. 16683 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16684 switch (CC) { 16685 case CC_X86StdCall: 16686 case CC_X86FastCall: 16687 case CC_X86VectorCall: 16688 return true; 16689 default: 16690 break; 16691 } 16692 return false; 16693 } 16694 16695 /// Require that all of the parameter types of function be complete. Normally, 16696 /// parameter types are only required to be complete when a function is called 16697 /// or defined, but to mangle functions with certain calling conventions, the 16698 /// mangler needs to know the size of the parameter list. In this situation, 16699 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16700 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16701 /// result in a linker error. Clang doesn't implement this behavior, and instead 16702 /// attempts to error at compile time. 16703 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16704 SourceLocation Loc) { 16705 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16706 FunctionDecl *FD; 16707 ParmVarDecl *Param; 16708 16709 public: 16710 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16711 : FD(FD), Param(Param) {} 16712 16713 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16714 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16715 StringRef CCName; 16716 switch (CC) { 16717 case CC_X86StdCall: 16718 CCName = "stdcall"; 16719 break; 16720 case CC_X86FastCall: 16721 CCName = "fastcall"; 16722 break; 16723 case CC_X86VectorCall: 16724 CCName = "vectorcall"; 16725 break; 16726 default: 16727 llvm_unreachable("CC does not need mangling"); 16728 } 16729 16730 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16731 << Param->getDeclName() << FD->getDeclName() << CCName; 16732 } 16733 }; 16734 16735 for (ParmVarDecl *Param : FD->parameters()) { 16736 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16737 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16738 } 16739 } 16740 16741 namespace { 16742 enum class OdrUseContext { 16743 /// Declarations in this context are not odr-used. 16744 None, 16745 /// Declarations in this context are formally odr-used, but this is a 16746 /// dependent context. 16747 Dependent, 16748 /// Declarations in this context are odr-used but not actually used (yet). 16749 FormallyOdrUsed, 16750 /// Declarations in this context are used. 16751 Used 16752 }; 16753 } 16754 16755 /// Are we within a context in which references to resolved functions or to 16756 /// variables result in odr-use? 16757 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16758 OdrUseContext Result; 16759 16760 switch (SemaRef.ExprEvalContexts.back().Context) { 16761 case Sema::ExpressionEvaluationContext::Unevaluated: 16762 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16763 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16764 return OdrUseContext::None; 16765 16766 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16767 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16768 Result = OdrUseContext::Used; 16769 break; 16770 16771 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16772 Result = OdrUseContext::FormallyOdrUsed; 16773 break; 16774 16775 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16776 // A default argument formally results in odr-use, but doesn't actually 16777 // result in a use in any real sense until it itself is used. 16778 Result = OdrUseContext::FormallyOdrUsed; 16779 break; 16780 } 16781 16782 if (SemaRef.CurContext->isDependentContext()) 16783 return OdrUseContext::Dependent; 16784 16785 return Result; 16786 } 16787 16788 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16789 if (!Func->isConstexpr()) 16790 return false; 16791 16792 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16793 return true; 16794 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16795 return CCD && CCD->getInheritedConstructor(); 16796 } 16797 16798 /// Mark a function referenced, and check whether it is odr-used 16799 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16800 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16801 bool MightBeOdrUse) { 16802 assert(Func && "No function?"); 16803 16804 Func->setReferenced(); 16805 16806 // Recursive functions aren't really used until they're used from some other 16807 // context. 16808 bool IsRecursiveCall = CurContext == Func; 16809 16810 // C++11 [basic.def.odr]p3: 16811 // A function whose name appears as a potentially-evaluated expression is 16812 // odr-used if it is the unique lookup result or the selected member of a 16813 // set of overloaded functions [...]. 16814 // 16815 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16816 // can just check that here. 16817 OdrUseContext OdrUse = 16818 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16819 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16820 OdrUse = OdrUseContext::FormallyOdrUsed; 16821 16822 // Trivial default constructors and destructors are never actually used. 16823 // FIXME: What about other special members? 16824 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16825 OdrUse == OdrUseContext::Used) { 16826 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16827 if (Constructor->isDefaultConstructor()) 16828 OdrUse = OdrUseContext::FormallyOdrUsed; 16829 if (isa<CXXDestructorDecl>(Func)) 16830 OdrUse = OdrUseContext::FormallyOdrUsed; 16831 } 16832 16833 // C++20 [expr.const]p12: 16834 // A function [...] is needed for constant evaluation if it is [...] a 16835 // constexpr function that is named by an expression that is potentially 16836 // constant evaluated 16837 bool NeededForConstantEvaluation = 16838 isPotentiallyConstantEvaluatedContext(*this) && 16839 isImplicitlyDefinableConstexprFunction(Func); 16840 16841 // Determine whether we require a function definition to exist, per 16842 // C++11 [temp.inst]p3: 16843 // Unless a function template specialization has been explicitly 16844 // instantiated or explicitly specialized, the function template 16845 // specialization is implicitly instantiated when the specialization is 16846 // referenced in a context that requires a function definition to exist. 16847 // C++20 [temp.inst]p7: 16848 // The existence of a definition of a [...] function is considered to 16849 // affect the semantics of the program if the [...] function is needed for 16850 // constant evaluation by an expression 16851 // C++20 [basic.def.odr]p10: 16852 // Every program shall contain exactly one definition of every non-inline 16853 // function or variable that is odr-used in that program outside of a 16854 // discarded statement 16855 // C++20 [special]p1: 16856 // The implementation will implicitly define [defaulted special members] 16857 // if they are odr-used or needed for constant evaluation. 16858 // 16859 // Note that we skip the implicit instantiation of templates that are only 16860 // used in unused default arguments or by recursive calls to themselves. 16861 // This is formally non-conforming, but seems reasonable in practice. 16862 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16863 NeededForConstantEvaluation); 16864 16865 // C++14 [temp.expl.spec]p6: 16866 // If a template [...] is explicitly specialized then that specialization 16867 // shall be declared before the first use of that specialization that would 16868 // cause an implicit instantiation to take place, in every translation unit 16869 // in which such a use occurs 16870 if (NeedDefinition && 16871 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16872 Func->getMemberSpecializationInfo())) 16873 checkSpecializationVisibility(Loc, Func); 16874 16875 if (getLangOpts().CUDA) 16876 CheckCUDACall(Loc, Func); 16877 16878 if (getLangOpts().SYCLIsDevice) 16879 checkSYCLDeviceFunction(Loc, Func); 16880 16881 // If we need a definition, try to create one. 16882 if (NeedDefinition && !Func->getBody()) { 16883 runWithSufficientStackSpace(Loc, [&] { 16884 if (CXXConstructorDecl *Constructor = 16885 dyn_cast<CXXConstructorDecl>(Func)) { 16886 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16887 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16888 if (Constructor->isDefaultConstructor()) { 16889 if (Constructor->isTrivial() && 16890 !Constructor->hasAttr<DLLExportAttr>()) 16891 return; 16892 DefineImplicitDefaultConstructor(Loc, Constructor); 16893 } else if (Constructor->isCopyConstructor()) { 16894 DefineImplicitCopyConstructor(Loc, Constructor); 16895 } else if (Constructor->isMoveConstructor()) { 16896 DefineImplicitMoveConstructor(Loc, Constructor); 16897 } 16898 } else if (Constructor->getInheritedConstructor()) { 16899 DefineInheritingConstructor(Loc, Constructor); 16900 } 16901 } else if (CXXDestructorDecl *Destructor = 16902 dyn_cast<CXXDestructorDecl>(Func)) { 16903 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16904 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16905 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16906 return; 16907 DefineImplicitDestructor(Loc, Destructor); 16908 } 16909 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16910 MarkVTableUsed(Loc, Destructor->getParent()); 16911 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16912 if (MethodDecl->isOverloadedOperator() && 16913 MethodDecl->getOverloadedOperator() == OO_Equal) { 16914 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16915 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16916 if (MethodDecl->isCopyAssignmentOperator()) 16917 DefineImplicitCopyAssignment(Loc, MethodDecl); 16918 else if (MethodDecl->isMoveAssignmentOperator()) 16919 DefineImplicitMoveAssignment(Loc, MethodDecl); 16920 } 16921 } else if (isa<CXXConversionDecl>(MethodDecl) && 16922 MethodDecl->getParent()->isLambda()) { 16923 CXXConversionDecl *Conversion = 16924 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16925 if (Conversion->isLambdaToBlockPointerConversion()) 16926 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16927 else 16928 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16929 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16930 MarkVTableUsed(Loc, MethodDecl->getParent()); 16931 } 16932 16933 if (Func->isDefaulted() && !Func->isDeleted()) { 16934 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16935 if (DCK != DefaultedComparisonKind::None) 16936 DefineDefaultedComparison(Loc, Func, DCK); 16937 } 16938 16939 // Implicit instantiation of function templates and member functions of 16940 // class templates. 16941 if (Func->isImplicitlyInstantiable()) { 16942 TemplateSpecializationKind TSK = 16943 Func->getTemplateSpecializationKindForInstantiation(); 16944 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16945 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16946 if (FirstInstantiation) { 16947 PointOfInstantiation = Loc; 16948 if (auto *MSI = Func->getMemberSpecializationInfo()) 16949 MSI->setPointOfInstantiation(Loc); 16950 // FIXME: Notify listener. 16951 else 16952 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16953 } else if (TSK != TSK_ImplicitInstantiation) { 16954 // Use the point of use as the point of instantiation, instead of the 16955 // point of explicit instantiation (which we track as the actual point 16956 // of instantiation). This gives better backtraces in diagnostics. 16957 PointOfInstantiation = Loc; 16958 } 16959 16960 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16961 Func->isConstexpr()) { 16962 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16963 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16964 CodeSynthesisContexts.size()) 16965 PendingLocalImplicitInstantiations.push_back( 16966 std::make_pair(Func, PointOfInstantiation)); 16967 else if (Func->isConstexpr()) 16968 // Do not defer instantiations of constexpr functions, to avoid the 16969 // expression evaluator needing to call back into Sema if it sees a 16970 // call to such a function. 16971 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16972 else { 16973 Func->setInstantiationIsPending(true); 16974 PendingInstantiations.push_back( 16975 std::make_pair(Func, PointOfInstantiation)); 16976 // Notify the consumer that a function was implicitly instantiated. 16977 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16978 } 16979 } 16980 } else { 16981 // Walk redefinitions, as some of them may be instantiable. 16982 for (auto i : Func->redecls()) { 16983 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16984 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16985 } 16986 } 16987 }); 16988 } 16989 16990 // C++14 [except.spec]p17: 16991 // An exception-specification is considered to be needed when: 16992 // - the function is odr-used or, if it appears in an unevaluated operand, 16993 // would be odr-used if the expression were potentially-evaluated; 16994 // 16995 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16996 // function is a pure virtual function we're calling, and in that case the 16997 // function was selected by overload resolution and we need to resolve its 16998 // exception specification for a different reason. 16999 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17000 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17001 ResolveExceptionSpec(Loc, FPT); 17002 17003 // If this is the first "real" use, act on that. 17004 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17005 // Keep track of used but undefined functions. 17006 if (!Func->isDefined()) { 17007 if (mightHaveNonExternalLinkage(Func)) 17008 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17009 else if (Func->getMostRecentDecl()->isInlined() && 17010 !LangOpts.GNUInline && 17011 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17012 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17013 else if (isExternalWithNoLinkageType(Func)) 17014 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17015 } 17016 17017 // Some x86 Windows calling conventions mangle the size of the parameter 17018 // pack into the name. Computing the size of the parameters requires the 17019 // parameter types to be complete. Check that now. 17020 if (funcHasParameterSizeMangling(*this, Func)) 17021 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17022 17023 // In the MS C++ ABI, the compiler emits destructor variants where they are 17024 // used. If the destructor is used here but defined elsewhere, mark the 17025 // virtual base destructors referenced. If those virtual base destructors 17026 // are inline, this will ensure they are defined when emitting the complete 17027 // destructor variant. This checking may be redundant if the destructor is 17028 // provided later in this TU. 17029 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17030 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17031 CXXRecordDecl *Parent = Dtor->getParent(); 17032 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17033 CheckCompleteDestructorVariant(Loc, Dtor); 17034 } 17035 } 17036 17037 Func->markUsed(Context); 17038 } 17039 } 17040 17041 /// Directly mark a variable odr-used. Given a choice, prefer to use 17042 /// MarkVariableReferenced since it does additional checks and then 17043 /// calls MarkVarDeclODRUsed. 17044 /// If the variable must be captured: 17045 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17046 /// - else capture it in the DeclContext that maps to the 17047 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17048 static void 17049 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17050 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17051 // Keep track of used but undefined variables. 17052 // FIXME: We shouldn't suppress this warning for static data members. 17053 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17054 (!Var->isExternallyVisible() || Var->isInline() || 17055 SemaRef.isExternalWithNoLinkageType(Var)) && 17056 !(Var->isStaticDataMember() && Var->hasInit())) { 17057 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17058 if (old.isInvalid()) 17059 old = Loc; 17060 } 17061 QualType CaptureType, DeclRefType; 17062 if (SemaRef.LangOpts.OpenMP) 17063 SemaRef.tryCaptureOpenMPLambdas(Var); 17064 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17065 /*EllipsisLoc*/ SourceLocation(), 17066 /*BuildAndDiagnose*/ true, 17067 CaptureType, DeclRefType, 17068 FunctionScopeIndexToStopAt); 17069 17070 Var->markUsed(SemaRef.Context); 17071 } 17072 17073 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17074 SourceLocation Loc, 17075 unsigned CapturingScopeIndex) { 17076 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17077 } 17078 17079 static void 17080 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17081 ValueDecl *var, DeclContext *DC) { 17082 DeclContext *VarDC = var->getDeclContext(); 17083 17084 // If the parameter still belongs to the translation unit, then 17085 // we're actually just using one parameter in the declaration of 17086 // the next. 17087 if (isa<ParmVarDecl>(var) && 17088 isa<TranslationUnitDecl>(VarDC)) 17089 return; 17090 17091 // For C code, don't diagnose about capture if we're not actually in code 17092 // right now; it's impossible to write a non-constant expression outside of 17093 // function context, so we'll get other (more useful) diagnostics later. 17094 // 17095 // For C++, things get a bit more nasty... it would be nice to suppress this 17096 // diagnostic for certain cases like using a local variable in an array bound 17097 // for a member of a local class, but the correct predicate is not obvious. 17098 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17099 return; 17100 17101 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17102 unsigned ContextKind = 3; // unknown 17103 if (isa<CXXMethodDecl>(VarDC) && 17104 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17105 ContextKind = 2; 17106 } else if (isa<FunctionDecl>(VarDC)) { 17107 ContextKind = 0; 17108 } else if (isa<BlockDecl>(VarDC)) { 17109 ContextKind = 1; 17110 } 17111 17112 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17113 << var << ValueKind << ContextKind << VarDC; 17114 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17115 << var; 17116 17117 // FIXME: Add additional diagnostic info about class etc. which prevents 17118 // capture. 17119 } 17120 17121 17122 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17123 bool &SubCapturesAreNested, 17124 QualType &CaptureType, 17125 QualType &DeclRefType) { 17126 // Check whether we've already captured it. 17127 if (CSI->CaptureMap.count(Var)) { 17128 // If we found a capture, any subcaptures are nested. 17129 SubCapturesAreNested = true; 17130 17131 // Retrieve the capture type for this variable. 17132 CaptureType = CSI->getCapture(Var).getCaptureType(); 17133 17134 // Compute the type of an expression that refers to this variable. 17135 DeclRefType = CaptureType.getNonReferenceType(); 17136 17137 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17138 // are mutable in the sense that user can change their value - they are 17139 // private instances of the captured declarations. 17140 const Capture &Cap = CSI->getCapture(Var); 17141 if (Cap.isCopyCapture() && 17142 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17143 !(isa<CapturedRegionScopeInfo>(CSI) && 17144 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17145 DeclRefType.addConst(); 17146 return true; 17147 } 17148 return false; 17149 } 17150 17151 // Only block literals, captured statements, and lambda expressions can 17152 // capture; other scopes don't work. 17153 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17154 SourceLocation Loc, 17155 const bool Diagnose, Sema &S) { 17156 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17157 return getLambdaAwareParentOfDeclContext(DC); 17158 else if (Var->hasLocalStorage()) { 17159 if (Diagnose) 17160 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17161 } 17162 return nullptr; 17163 } 17164 17165 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17166 // certain types of variables (unnamed, variably modified types etc.) 17167 // so check for eligibility. 17168 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17169 SourceLocation Loc, 17170 const bool Diagnose, Sema &S) { 17171 17172 bool IsBlock = isa<BlockScopeInfo>(CSI); 17173 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17174 17175 // Lambdas are not allowed to capture unnamed variables 17176 // (e.g. anonymous unions). 17177 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17178 // assuming that's the intent. 17179 if (IsLambda && !Var->getDeclName()) { 17180 if (Diagnose) { 17181 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17182 S.Diag(Var->getLocation(), diag::note_declared_at); 17183 } 17184 return false; 17185 } 17186 17187 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17188 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17189 if (Diagnose) { 17190 S.Diag(Loc, diag::err_ref_vm_type); 17191 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17192 } 17193 return false; 17194 } 17195 // Prohibit structs with flexible array members too. 17196 // We cannot capture what is in the tail end of the struct. 17197 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17198 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17199 if (Diagnose) { 17200 if (IsBlock) 17201 S.Diag(Loc, diag::err_ref_flexarray_type); 17202 else 17203 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17204 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17205 } 17206 return false; 17207 } 17208 } 17209 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17210 // Lambdas and captured statements are not allowed to capture __block 17211 // variables; they don't support the expected semantics. 17212 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17213 if (Diagnose) { 17214 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17215 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17216 } 17217 return false; 17218 } 17219 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17220 if (S.getLangOpts().OpenCL && IsBlock && 17221 Var->getType()->isBlockPointerType()) { 17222 if (Diagnose) 17223 S.Diag(Loc, diag::err_opencl_block_ref_block); 17224 return false; 17225 } 17226 17227 return true; 17228 } 17229 17230 // Returns true if the capture by block was successful. 17231 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17232 SourceLocation Loc, 17233 const bool BuildAndDiagnose, 17234 QualType &CaptureType, 17235 QualType &DeclRefType, 17236 const bool Nested, 17237 Sema &S, bool Invalid) { 17238 bool ByRef = false; 17239 17240 // Blocks are not allowed to capture arrays, excepting OpenCL. 17241 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17242 // (decayed to pointers). 17243 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17244 if (BuildAndDiagnose) { 17245 S.Diag(Loc, diag::err_ref_array_type); 17246 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17247 Invalid = true; 17248 } else { 17249 return false; 17250 } 17251 } 17252 17253 // Forbid the block-capture of autoreleasing variables. 17254 if (!Invalid && 17255 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17256 if (BuildAndDiagnose) { 17257 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17258 << /*block*/ 0; 17259 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17260 Invalid = true; 17261 } else { 17262 return false; 17263 } 17264 } 17265 17266 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17267 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17268 QualType PointeeTy = PT->getPointeeType(); 17269 17270 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17271 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17272 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17273 if (BuildAndDiagnose) { 17274 SourceLocation VarLoc = Var->getLocation(); 17275 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17276 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17277 } 17278 } 17279 } 17280 17281 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17282 if (HasBlocksAttr || CaptureType->isReferenceType() || 17283 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17284 // Block capture by reference does not change the capture or 17285 // declaration reference types. 17286 ByRef = true; 17287 } else { 17288 // Block capture by copy introduces 'const'. 17289 CaptureType = CaptureType.getNonReferenceType().withConst(); 17290 DeclRefType = CaptureType; 17291 } 17292 17293 // Actually capture the variable. 17294 if (BuildAndDiagnose) 17295 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17296 CaptureType, Invalid); 17297 17298 return !Invalid; 17299 } 17300 17301 17302 /// Capture the given variable in the captured region. 17303 static bool captureInCapturedRegion( 17304 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17305 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17306 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17307 bool IsTopScope, Sema &S, bool Invalid) { 17308 // By default, capture variables by reference. 17309 bool ByRef = true; 17310 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17311 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17312 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17313 // Using an LValue reference type is consistent with Lambdas (see below). 17314 if (S.isOpenMPCapturedDecl(Var)) { 17315 bool HasConst = DeclRefType.isConstQualified(); 17316 DeclRefType = DeclRefType.getUnqualifiedType(); 17317 // Don't lose diagnostics about assignments to const. 17318 if (HasConst) 17319 DeclRefType.addConst(); 17320 } 17321 // Do not capture firstprivates in tasks. 17322 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17323 OMPC_unknown) 17324 return true; 17325 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17326 RSI->OpenMPCaptureLevel); 17327 } 17328 17329 if (ByRef) 17330 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17331 else 17332 CaptureType = DeclRefType; 17333 17334 // Actually capture the variable. 17335 if (BuildAndDiagnose) 17336 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17337 Loc, SourceLocation(), CaptureType, Invalid); 17338 17339 return !Invalid; 17340 } 17341 17342 /// Capture the given variable in the lambda. 17343 static bool captureInLambda(LambdaScopeInfo *LSI, 17344 VarDecl *Var, 17345 SourceLocation Loc, 17346 const bool BuildAndDiagnose, 17347 QualType &CaptureType, 17348 QualType &DeclRefType, 17349 const bool RefersToCapturedVariable, 17350 const Sema::TryCaptureKind Kind, 17351 SourceLocation EllipsisLoc, 17352 const bool IsTopScope, 17353 Sema &S, bool Invalid) { 17354 // Determine whether we are capturing by reference or by value. 17355 bool ByRef = false; 17356 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17357 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17358 } else { 17359 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17360 } 17361 17362 // Compute the type of the field that will capture this variable. 17363 if (ByRef) { 17364 // C++11 [expr.prim.lambda]p15: 17365 // An entity is captured by reference if it is implicitly or 17366 // explicitly captured but not captured by copy. It is 17367 // unspecified whether additional unnamed non-static data 17368 // members are declared in the closure type for entities 17369 // captured by reference. 17370 // 17371 // FIXME: It is not clear whether we want to build an lvalue reference 17372 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17373 // to do the former, while EDG does the latter. Core issue 1249 will 17374 // clarify, but for now we follow GCC because it's a more permissive and 17375 // easily defensible position. 17376 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17377 } else { 17378 // C++11 [expr.prim.lambda]p14: 17379 // For each entity captured by copy, an unnamed non-static 17380 // data member is declared in the closure type. The 17381 // declaration order of these members is unspecified. The type 17382 // of such a data member is the type of the corresponding 17383 // captured entity if the entity is not a reference to an 17384 // object, or the referenced type otherwise. [Note: If the 17385 // captured entity is a reference to a function, the 17386 // corresponding data member is also a reference to a 17387 // function. - end note ] 17388 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17389 if (!RefType->getPointeeType()->isFunctionType()) 17390 CaptureType = RefType->getPointeeType(); 17391 } 17392 17393 // Forbid the lambda copy-capture of autoreleasing variables. 17394 if (!Invalid && 17395 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17396 if (BuildAndDiagnose) { 17397 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17398 S.Diag(Var->getLocation(), diag::note_previous_decl) 17399 << Var->getDeclName(); 17400 Invalid = true; 17401 } else { 17402 return false; 17403 } 17404 } 17405 17406 // Make sure that by-copy captures are of a complete and non-abstract type. 17407 if (!Invalid && BuildAndDiagnose) { 17408 if (!CaptureType->isDependentType() && 17409 S.RequireCompleteSizedType( 17410 Loc, CaptureType, 17411 diag::err_capture_of_incomplete_or_sizeless_type, 17412 Var->getDeclName())) 17413 Invalid = true; 17414 else if (S.RequireNonAbstractType(Loc, CaptureType, 17415 diag::err_capture_of_abstract_type)) 17416 Invalid = true; 17417 } 17418 } 17419 17420 // Compute the type of a reference to this captured variable. 17421 if (ByRef) 17422 DeclRefType = CaptureType.getNonReferenceType(); 17423 else { 17424 // C++ [expr.prim.lambda]p5: 17425 // The closure type for a lambda-expression has a public inline 17426 // function call operator [...]. This function call operator is 17427 // declared const (9.3.1) if and only if the lambda-expression's 17428 // parameter-declaration-clause is not followed by mutable. 17429 DeclRefType = CaptureType.getNonReferenceType(); 17430 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17431 DeclRefType.addConst(); 17432 } 17433 17434 // Add the capture. 17435 if (BuildAndDiagnose) 17436 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17437 Loc, EllipsisLoc, CaptureType, Invalid); 17438 17439 return !Invalid; 17440 } 17441 17442 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17443 // Offer a Copy fix even if the type is dependent. 17444 if (Var->getType()->isDependentType()) 17445 return true; 17446 QualType T = Var->getType().getNonReferenceType(); 17447 if (T.isTriviallyCopyableType(Context)) 17448 return true; 17449 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17450 17451 if (!(RD = RD->getDefinition())) 17452 return false; 17453 if (RD->hasSimpleCopyConstructor()) 17454 return true; 17455 if (RD->hasUserDeclaredCopyConstructor()) 17456 for (CXXConstructorDecl *Ctor : RD->ctors()) 17457 if (Ctor->isCopyConstructor()) 17458 return !Ctor->isDeleted(); 17459 } 17460 return false; 17461 } 17462 17463 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17464 /// default capture. Fixes may be omitted if they aren't allowed by the 17465 /// standard, for example we can't emit a default copy capture fix-it if we 17466 /// already explicitly copy capture capture another variable. 17467 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17468 VarDecl *Var) { 17469 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17470 // Don't offer Capture by copy of default capture by copy fixes if Var is 17471 // known not to be copy constructible. 17472 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17473 17474 SmallString<32> FixBuffer; 17475 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17476 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17477 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17478 if (ShouldOfferCopyFix) { 17479 // Offer fixes to insert an explicit capture for the variable. 17480 // [] -> [VarName] 17481 // [OtherCapture] -> [OtherCapture, VarName] 17482 FixBuffer.assign({Separator, Var->getName()}); 17483 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17484 << Var << /*value*/ 0 17485 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17486 } 17487 // As above but capture by reference. 17488 FixBuffer.assign({Separator, "&", Var->getName()}); 17489 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17490 << Var << /*reference*/ 1 17491 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17492 } 17493 17494 // Only try to offer default capture if there are no captures excluding this 17495 // and init captures. 17496 // [this]: OK. 17497 // [X = Y]: OK. 17498 // [&A, &B]: Don't offer. 17499 // [A, B]: Don't offer. 17500 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17501 return !C.isThisCapture() && !C.isInitCapture(); 17502 })) 17503 return; 17504 17505 // The default capture specifiers, '=' or '&', must appear first in the 17506 // capture body. 17507 SourceLocation DefaultInsertLoc = 17508 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17509 17510 if (ShouldOfferCopyFix) { 17511 bool CanDefaultCopyCapture = true; 17512 // [=, *this] OK since c++17 17513 // [=, this] OK since c++20 17514 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17515 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17516 ? LSI->getCXXThisCapture().isCopyCapture() 17517 : false; 17518 // We can't use default capture by copy if any captures already specified 17519 // capture by copy. 17520 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17521 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17522 })) { 17523 FixBuffer.assign({"=", Separator}); 17524 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17525 << /*value*/ 0 17526 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17527 } 17528 } 17529 17530 // We can't use default capture by reference if any captures already specified 17531 // capture by reference. 17532 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17533 return !C.isInitCapture() && C.isReferenceCapture() && 17534 !C.isThisCapture(); 17535 })) { 17536 FixBuffer.assign({"&", Separator}); 17537 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17538 << /*reference*/ 1 17539 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17540 } 17541 } 17542 17543 bool Sema::tryCaptureVariable( 17544 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17545 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17546 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17547 // An init-capture is notionally from the context surrounding its 17548 // declaration, but its parent DC is the lambda class. 17549 DeclContext *VarDC = Var->getDeclContext(); 17550 if (Var->isInitCapture()) 17551 VarDC = VarDC->getParent(); 17552 17553 DeclContext *DC = CurContext; 17554 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17555 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17556 // We need to sync up the Declaration Context with the 17557 // FunctionScopeIndexToStopAt 17558 if (FunctionScopeIndexToStopAt) { 17559 unsigned FSIndex = FunctionScopes.size() - 1; 17560 while (FSIndex != MaxFunctionScopesIndex) { 17561 DC = getLambdaAwareParentOfDeclContext(DC); 17562 --FSIndex; 17563 } 17564 } 17565 17566 17567 // If the variable is declared in the current context, there is no need to 17568 // capture it. 17569 if (VarDC == DC) return true; 17570 17571 // Capture global variables if it is required to use private copy of this 17572 // variable. 17573 bool IsGlobal = !Var->hasLocalStorage(); 17574 if (IsGlobal && 17575 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17576 MaxFunctionScopesIndex))) 17577 return true; 17578 Var = Var->getCanonicalDecl(); 17579 17580 // Walk up the stack to determine whether we can capture the variable, 17581 // performing the "simple" checks that don't depend on type. We stop when 17582 // we've either hit the declared scope of the variable or find an existing 17583 // capture of that variable. We start from the innermost capturing-entity 17584 // (the DC) and ensure that all intervening capturing-entities 17585 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17586 // declcontext can either capture the variable or have already captured 17587 // the variable. 17588 CaptureType = Var->getType(); 17589 DeclRefType = CaptureType.getNonReferenceType(); 17590 bool Nested = false; 17591 bool Explicit = (Kind != TryCapture_Implicit); 17592 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17593 do { 17594 // Only block literals, captured statements, and lambda expressions can 17595 // capture; other scopes don't work. 17596 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17597 ExprLoc, 17598 BuildAndDiagnose, 17599 *this); 17600 // We need to check for the parent *first* because, if we *have* 17601 // private-captured a global variable, we need to recursively capture it in 17602 // intermediate blocks, lambdas, etc. 17603 if (!ParentDC) { 17604 if (IsGlobal) { 17605 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17606 break; 17607 } 17608 return true; 17609 } 17610 17611 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17612 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17613 17614 17615 // Check whether we've already captured it. 17616 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17617 DeclRefType)) { 17618 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17619 break; 17620 } 17621 // If we are instantiating a generic lambda call operator body, 17622 // we do not want to capture new variables. What was captured 17623 // during either a lambdas transformation or initial parsing 17624 // should be used. 17625 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17626 if (BuildAndDiagnose) { 17627 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17628 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17629 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17630 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17631 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17632 buildLambdaCaptureFixit(*this, LSI, Var); 17633 } else 17634 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17635 } 17636 return true; 17637 } 17638 17639 // Try to capture variable-length arrays types. 17640 if (Var->getType()->isVariablyModifiedType()) { 17641 // We're going to walk down into the type and look for VLA 17642 // expressions. 17643 QualType QTy = Var->getType(); 17644 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17645 QTy = PVD->getOriginalType(); 17646 captureVariablyModifiedType(Context, QTy, CSI); 17647 } 17648 17649 if (getLangOpts().OpenMP) { 17650 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17651 // OpenMP private variables should not be captured in outer scope, so 17652 // just break here. Similarly, global variables that are captured in a 17653 // target region should not be captured outside the scope of the region. 17654 if (RSI->CapRegionKind == CR_OpenMP) { 17655 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17656 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17657 // If the variable is private (i.e. not captured) and has variably 17658 // modified type, we still need to capture the type for correct 17659 // codegen in all regions, associated with the construct. Currently, 17660 // it is captured in the innermost captured region only. 17661 if (IsOpenMPPrivateDecl != OMPC_unknown && 17662 Var->getType()->isVariablyModifiedType()) { 17663 QualType QTy = Var->getType(); 17664 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17665 QTy = PVD->getOriginalType(); 17666 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17667 I < E; ++I) { 17668 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17669 FunctionScopes[FunctionScopesIndex - I]); 17670 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17671 "Wrong number of captured regions associated with the " 17672 "OpenMP construct."); 17673 captureVariablyModifiedType(Context, QTy, OuterRSI); 17674 } 17675 } 17676 bool IsTargetCap = 17677 IsOpenMPPrivateDecl != OMPC_private && 17678 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17679 RSI->OpenMPCaptureLevel); 17680 // Do not capture global if it is not privatized in outer regions. 17681 bool IsGlobalCap = 17682 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17683 RSI->OpenMPCaptureLevel); 17684 17685 // When we detect target captures we are looking from inside the 17686 // target region, therefore we need to propagate the capture from the 17687 // enclosing region. Therefore, the capture is not initially nested. 17688 if (IsTargetCap) 17689 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17690 17691 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17692 (IsGlobal && !IsGlobalCap)) { 17693 Nested = !IsTargetCap; 17694 bool HasConst = DeclRefType.isConstQualified(); 17695 DeclRefType = DeclRefType.getUnqualifiedType(); 17696 // Don't lose diagnostics about assignments to const. 17697 if (HasConst) 17698 DeclRefType.addConst(); 17699 CaptureType = Context.getLValueReferenceType(DeclRefType); 17700 break; 17701 } 17702 } 17703 } 17704 } 17705 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17706 // No capture-default, and this is not an explicit capture 17707 // so cannot capture this variable. 17708 if (BuildAndDiagnose) { 17709 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17710 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17711 auto *LSI = cast<LambdaScopeInfo>(CSI); 17712 if (LSI->Lambda) { 17713 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17714 buildLambdaCaptureFixit(*this, LSI, Var); 17715 } 17716 // FIXME: If we error out because an outer lambda can not implicitly 17717 // capture a variable that an inner lambda explicitly captures, we 17718 // should have the inner lambda do the explicit capture - because 17719 // it makes for cleaner diagnostics later. This would purely be done 17720 // so that the diagnostic does not misleadingly claim that a variable 17721 // can not be captured by a lambda implicitly even though it is captured 17722 // explicitly. Suggestion: 17723 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17724 // at the function head 17725 // - cache the StartingDeclContext - this must be a lambda 17726 // - captureInLambda in the innermost lambda the variable. 17727 } 17728 return true; 17729 } 17730 17731 FunctionScopesIndex--; 17732 DC = ParentDC; 17733 Explicit = false; 17734 } while (!VarDC->Equals(DC)); 17735 17736 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17737 // computing the type of the capture at each step, checking type-specific 17738 // requirements, and adding captures if requested. 17739 // If the variable had already been captured previously, we start capturing 17740 // at the lambda nested within that one. 17741 bool Invalid = false; 17742 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17743 ++I) { 17744 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17745 17746 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17747 // certain types of variables (unnamed, variably modified types etc.) 17748 // so check for eligibility. 17749 if (!Invalid) 17750 Invalid = 17751 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17752 17753 // After encountering an error, if we're actually supposed to capture, keep 17754 // capturing in nested contexts to suppress any follow-on diagnostics. 17755 if (Invalid && !BuildAndDiagnose) 17756 return true; 17757 17758 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17759 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17760 DeclRefType, Nested, *this, Invalid); 17761 Nested = true; 17762 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17763 Invalid = !captureInCapturedRegion( 17764 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17765 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17766 Nested = true; 17767 } else { 17768 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17769 Invalid = 17770 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17771 DeclRefType, Nested, Kind, EllipsisLoc, 17772 /*IsTopScope*/ I == N - 1, *this, Invalid); 17773 Nested = true; 17774 } 17775 17776 if (Invalid && !BuildAndDiagnose) 17777 return true; 17778 } 17779 return Invalid; 17780 } 17781 17782 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17783 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17784 QualType CaptureType; 17785 QualType DeclRefType; 17786 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17787 /*BuildAndDiagnose=*/true, CaptureType, 17788 DeclRefType, nullptr); 17789 } 17790 17791 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17792 QualType CaptureType; 17793 QualType DeclRefType; 17794 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17795 /*BuildAndDiagnose=*/false, CaptureType, 17796 DeclRefType, nullptr); 17797 } 17798 17799 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17800 QualType CaptureType; 17801 QualType DeclRefType; 17802 17803 // Determine whether we can capture this variable. 17804 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17805 /*BuildAndDiagnose=*/false, CaptureType, 17806 DeclRefType, nullptr)) 17807 return QualType(); 17808 17809 return DeclRefType; 17810 } 17811 17812 namespace { 17813 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17814 // The produced TemplateArgumentListInfo* points to data stored within this 17815 // object, so should only be used in contexts where the pointer will not be 17816 // used after the CopiedTemplateArgs object is destroyed. 17817 class CopiedTemplateArgs { 17818 bool HasArgs; 17819 TemplateArgumentListInfo TemplateArgStorage; 17820 public: 17821 template<typename RefExpr> 17822 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17823 if (HasArgs) 17824 E->copyTemplateArgumentsInto(TemplateArgStorage); 17825 } 17826 operator TemplateArgumentListInfo*() 17827 #ifdef __has_cpp_attribute 17828 #if __has_cpp_attribute(clang::lifetimebound) 17829 [[clang::lifetimebound]] 17830 #endif 17831 #endif 17832 { 17833 return HasArgs ? &TemplateArgStorage : nullptr; 17834 } 17835 }; 17836 } 17837 17838 /// Walk the set of potential results of an expression and mark them all as 17839 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17840 /// 17841 /// \return A new expression if we found any potential results, ExprEmpty() if 17842 /// not, and ExprError() if we diagnosed an error. 17843 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17844 NonOdrUseReason NOUR) { 17845 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17846 // an object that satisfies the requirements for appearing in a 17847 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17848 // is immediately applied." This function handles the lvalue-to-rvalue 17849 // conversion part. 17850 // 17851 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17852 // transform it into the relevant kind of non-odr-use node and rebuild the 17853 // tree of nodes leading to it. 17854 // 17855 // This is a mini-TreeTransform that only transforms a restricted subset of 17856 // nodes (and only certain operands of them). 17857 17858 // Rebuild a subexpression. 17859 auto Rebuild = [&](Expr *Sub) { 17860 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17861 }; 17862 17863 // Check whether a potential result satisfies the requirements of NOUR. 17864 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17865 // Any entity other than a VarDecl is always odr-used whenever it's named 17866 // in a potentially-evaluated expression. 17867 auto *VD = dyn_cast<VarDecl>(D); 17868 if (!VD) 17869 return true; 17870 17871 // C++2a [basic.def.odr]p4: 17872 // A variable x whose name appears as a potentially-evalauted expression 17873 // e is odr-used by e unless 17874 // -- x is a reference that is usable in constant expressions, or 17875 // -- x is a variable of non-reference type that is usable in constant 17876 // expressions and has no mutable subobjects, and e is an element of 17877 // the set of potential results of an expression of 17878 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17879 // conversion is applied, or 17880 // -- x is a variable of non-reference type, and e is an element of the 17881 // set of potential results of a discarded-value expression to which 17882 // the lvalue-to-rvalue conversion is not applied 17883 // 17884 // We check the first bullet and the "potentially-evaluated" condition in 17885 // BuildDeclRefExpr. We check the type requirements in the second bullet 17886 // in CheckLValueToRValueConversionOperand below. 17887 switch (NOUR) { 17888 case NOUR_None: 17889 case NOUR_Unevaluated: 17890 llvm_unreachable("unexpected non-odr-use-reason"); 17891 17892 case NOUR_Constant: 17893 // Constant references were handled when they were built. 17894 if (VD->getType()->isReferenceType()) 17895 return true; 17896 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17897 if (RD->hasMutableFields()) 17898 return true; 17899 if (!VD->isUsableInConstantExpressions(S.Context)) 17900 return true; 17901 break; 17902 17903 case NOUR_Discarded: 17904 if (VD->getType()->isReferenceType()) 17905 return true; 17906 break; 17907 } 17908 return false; 17909 }; 17910 17911 // Mark that this expression does not constitute an odr-use. 17912 auto MarkNotOdrUsed = [&] { 17913 S.MaybeODRUseExprs.remove(E); 17914 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17915 LSI->markVariableExprAsNonODRUsed(E); 17916 }; 17917 17918 // C++2a [basic.def.odr]p2: 17919 // The set of potential results of an expression e is defined as follows: 17920 switch (E->getStmtClass()) { 17921 // -- If e is an id-expression, ... 17922 case Expr::DeclRefExprClass: { 17923 auto *DRE = cast<DeclRefExpr>(E); 17924 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17925 break; 17926 17927 // Rebuild as a non-odr-use DeclRefExpr. 17928 MarkNotOdrUsed(); 17929 return DeclRefExpr::Create( 17930 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17931 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17932 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17933 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17934 } 17935 17936 case Expr::FunctionParmPackExprClass: { 17937 auto *FPPE = cast<FunctionParmPackExpr>(E); 17938 // If any of the declarations in the pack is odr-used, then the expression 17939 // as a whole constitutes an odr-use. 17940 for (VarDecl *D : *FPPE) 17941 if (IsPotentialResultOdrUsed(D)) 17942 return ExprEmpty(); 17943 17944 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17945 // nothing cares about whether we marked this as an odr-use, but it might 17946 // be useful for non-compiler tools. 17947 MarkNotOdrUsed(); 17948 break; 17949 } 17950 17951 // -- If e is a subscripting operation with an array operand... 17952 case Expr::ArraySubscriptExprClass: { 17953 auto *ASE = cast<ArraySubscriptExpr>(E); 17954 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17955 if (!OldBase->getType()->isArrayType()) 17956 break; 17957 ExprResult Base = Rebuild(OldBase); 17958 if (!Base.isUsable()) 17959 return Base; 17960 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17961 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17962 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17963 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17964 ASE->getRBracketLoc()); 17965 } 17966 17967 case Expr::MemberExprClass: { 17968 auto *ME = cast<MemberExpr>(E); 17969 // -- If e is a class member access expression [...] naming a non-static 17970 // data member... 17971 if (isa<FieldDecl>(ME->getMemberDecl())) { 17972 ExprResult Base = Rebuild(ME->getBase()); 17973 if (!Base.isUsable()) 17974 return Base; 17975 return MemberExpr::Create( 17976 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17977 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17978 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17979 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17980 ME->getObjectKind(), ME->isNonOdrUse()); 17981 } 17982 17983 if (ME->getMemberDecl()->isCXXInstanceMember()) 17984 break; 17985 17986 // -- If e is a class member access expression naming a static data member, 17987 // ... 17988 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17989 break; 17990 17991 // Rebuild as a non-odr-use MemberExpr. 17992 MarkNotOdrUsed(); 17993 return MemberExpr::Create( 17994 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17995 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17996 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17997 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17998 return ExprEmpty(); 17999 } 18000 18001 case Expr::BinaryOperatorClass: { 18002 auto *BO = cast<BinaryOperator>(E); 18003 Expr *LHS = BO->getLHS(); 18004 Expr *RHS = BO->getRHS(); 18005 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18006 if (BO->getOpcode() == BO_PtrMemD) { 18007 ExprResult Sub = Rebuild(LHS); 18008 if (!Sub.isUsable()) 18009 return Sub; 18010 LHS = Sub.get(); 18011 // -- If e is a comma expression, ... 18012 } else if (BO->getOpcode() == BO_Comma) { 18013 ExprResult Sub = Rebuild(RHS); 18014 if (!Sub.isUsable()) 18015 return Sub; 18016 RHS = Sub.get(); 18017 } else { 18018 break; 18019 } 18020 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18021 LHS, RHS); 18022 } 18023 18024 // -- If e has the form (e1)... 18025 case Expr::ParenExprClass: { 18026 auto *PE = cast<ParenExpr>(E); 18027 ExprResult Sub = Rebuild(PE->getSubExpr()); 18028 if (!Sub.isUsable()) 18029 return Sub; 18030 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18031 } 18032 18033 // -- If e is a glvalue conditional expression, ... 18034 // We don't apply this to a binary conditional operator. FIXME: Should we? 18035 case Expr::ConditionalOperatorClass: { 18036 auto *CO = cast<ConditionalOperator>(E); 18037 ExprResult LHS = Rebuild(CO->getLHS()); 18038 if (LHS.isInvalid()) 18039 return ExprError(); 18040 ExprResult RHS = Rebuild(CO->getRHS()); 18041 if (RHS.isInvalid()) 18042 return ExprError(); 18043 if (!LHS.isUsable() && !RHS.isUsable()) 18044 return ExprEmpty(); 18045 if (!LHS.isUsable()) 18046 LHS = CO->getLHS(); 18047 if (!RHS.isUsable()) 18048 RHS = CO->getRHS(); 18049 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18050 CO->getCond(), LHS.get(), RHS.get()); 18051 } 18052 18053 // [Clang extension] 18054 // -- If e has the form __extension__ e1... 18055 case Expr::UnaryOperatorClass: { 18056 auto *UO = cast<UnaryOperator>(E); 18057 if (UO->getOpcode() != UO_Extension) 18058 break; 18059 ExprResult Sub = Rebuild(UO->getSubExpr()); 18060 if (!Sub.isUsable()) 18061 return Sub; 18062 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18063 Sub.get()); 18064 } 18065 18066 // [Clang extension] 18067 // -- If e has the form _Generic(...), the set of potential results is the 18068 // union of the sets of potential results of the associated expressions. 18069 case Expr::GenericSelectionExprClass: { 18070 auto *GSE = cast<GenericSelectionExpr>(E); 18071 18072 SmallVector<Expr *, 4> AssocExprs; 18073 bool AnyChanged = false; 18074 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18075 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18076 if (AssocExpr.isInvalid()) 18077 return ExprError(); 18078 if (AssocExpr.isUsable()) { 18079 AssocExprs.push_back(AssocExpr.get()); 18080 AnyChanged = true; 18081 } else { 18082 AssocExprs.push_back(OrigAssocExpr); 18083 } 18084 } 18085 18086 return AnyChanged ? S.CreateGenericSelectionExpr( 18087 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18088 GSE->getRParenLoc(), GSE->getControllingExpr(), 18089 GSE->getAssocTypeSourceInfos(), AssocExprs) 18090 : ExprEmpty(); 18091 } 18092 18093 // [Clang extension] 18094 // -- If e has the form __builtin_choose_expr(...), the set of potential 18095 // results is the union of the sets of potential results of the 18096 // second and third subexpressions. 18097 case Expr::ChooseExprClass: { 18098 auto *CE = cast<ChooseExpr>(E); 18099 18100 ExprResult LHS = Rebuild(CE->getLHS()); 18101 if (LHS.isInvalid()) 18102 return ExprError(); 18103 18104 ExprResult RHS = Rebuild(CE->getLHS()); 18105 if (RHS.isInvalid()) 18106 return ExprError(); 18107 18108 if (!LHS.get() && !RHS.get()) 18109 return ExprEmpty(); 18110 if (!LHS.isUsable()) 18111 LHS = CE->getLHS(); 18112 if (!RHS.isUsable()) 18113 RHS = CE->getRHS(); 18114 18115 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18116 RHS.get(), CE->getRParenLoc()); 18117 } 18118 18119 // Step through non-syntactic nodes. 18120 case Expr::ConstantExprClass: { 18121 auto *CE = cast<ConstantExpr>(E); 18122 ExprResult Sub = Rebuild(CE->getSubExpr()); 18123 if (!Sub.isUsable()) 18124 return Sub; 18125 return ConstantExpr::Create(S.Context, Sub.get()); 18126 } 18127 18128 // We could mostly rely on the recursive rebuilding to rebuild implicit 18129 // casts, but not at the top level, so rebuild them here. 18130 case Expr::ImplicitCastExprClass: { 18131 auto *ICE = cast<ImplicitCastExpr>(E); 18132 // Only step through the narrow set of cast kinds we expect to encounter. 18133 // Anything else suggests we've left the region in which potential results 18134 // can be found. 18135 switch (ICE->getCastKind()) { 18136 case CK_NoOp: 18137 case CK_DerivedToBase: 18138 case CK_UncheckedDerivedToBase: { 18139 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18140 if (!Sub.isUsable()) 18141 return Sub; 18142 CXXCastPath Path(ICE->path()); 18143 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18144 ICE->getValueKind(), &Path); 18145 } 18146 18147 default: 18148 break; 18149 } 18150 break; 18151 } 18152 18153 default: 18154 break; 18155 } 18156 18157 // Can't traverse through this node. Nothing to do. 18158 return ExprEmpty(); 18159 } 18160 18161 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18162 // Check whether the operand is or contains an object of non-trivial C union 18163 // type. 18164 if (E->getType().isVolatileQualified() && 18165 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18166 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18167 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18168 Sema::NTCUC_LValueToRValueVolatile, 18169 NTCUK_Destruct|NTCUK_Copy); 18170 18171 // C++2a [basic.def.odr]p4: 18172 // [...] an expression of non-volatile-qualified non-class type to which 18173 // the lvalue-to-rvalue conversion is applied [...] 18174 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18175 return E; 18176 18177 ExprResult Result = 18178 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18179 if (Result.isInvalid()) 18180 return ExprError(); 18181 return Result.get() ? Result : E; 18182 } 18183 18184 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18185 Res = CorrectDelayedTyposInExpr(Res); 18186 18187 if (!Res.isUsable()) 18188 return Res; 18189 18190 // If a constant-expression is a reference to a variable where we delay 18191 // deciding whether it is an odr-use, just assume we will apply the 18192 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18193 // (a non-type template argument), we have special handling anyway. 18194 return CheckLValueToRValueConversionOperand(Res.get()); 18195 } 18196 18197 void Sema::CleanupVarDeclMarking() { 18198 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18199 // call. 18200 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18201 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18202 18203 for (Expr *E : LocalMaybeODRUseExprs) { 18204 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18205 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18206 DRE->getLocation(), *this); 18207 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18208 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18209 *this); 18210 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18211 for (VarDecl *VD : *FP) 18212 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18213 } else { 18214 llvm_unreachable("Unexpected expression"); 18215 } 18216 } 18217 18218 assert(MaybeODRUseExprs.empty() && 18219 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18220 } 18221 18222 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18223 VarDecl *Var, Expr *E) { 18224 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18225 isa<FunctionParmPackExpr>(E)) && 18226 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18227 Var->setReferenced(); 18228 18229 if (Var->isInvalidDecl()) 18230 return; 18231 18232 // Record a CUDA/HIP static device/constant variable if it is referenced 18233 // by host code. This is done conservatively, when the variable is referenced 18234 // in any of the following contexts: 18235 // - a non-function context 18236 // - a host function 18237 // - a host device function 18238 // This also requires the reference of the static device/constant variable by 18239 // host code to be visible in the device compilation for the compiler to be 18240 // able to externalize the static device/constant variable. 18241 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18242 auto *CurContext = SemaRef.CurContext; 18243 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18244 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18245 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18246 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18247 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18248 } 18249 18250 auto *MSI = Var->getMemberSpecializationInfo(); 18251 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18252 : Var->getTemplateSpecializationKind(); 18253 18254 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18255 bool UsableInConstantExpr = 18256 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18257 18258 // C++20 [expr.const]p12: 18259 // A variable [...] is needed for constant evaluation if it is [...] a 18260 // variable whose name appears as a potentially constant evaluated 18261 // expression that is either a contexpr variable or is of non-volatile 18262 // const-qualified integral type or of reference type 18263 bool NeededForConstantEvaluation = 18264 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18265 18266 bool NeedDefinition = 18267 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18268 18269 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18270 "Can't instantiate a partial template specialization."); 18271 18272 // If this might be a member specialization of a static data member, check 18273 // the specialization is visible. We already did the checks for variable 18274 // template specializations when we created them. 18275 if (NeedDefinition && TSK != TSK_Undeclared && 18276 !isa<VarTemplateSpecializationDecl>(Var)) 18277 SemaRef.checkSpecializationVisibility(Loc, Var); 18278 18279 // Perform implicit instantiation of static data members, static data member 18280 // templates of class templates, and variable template specializations. Delay 18281 // instantiations of variable templates, except for those that could be used 18282 // in a constant expression. 18283 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18284 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18285 // instantiation declaration if a variable is usable in a constant 18286 // expression (among other cases). 18287 bool TryInstantiating = 18288 TSK == TSK_ImplicitInstantiation || 18289 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18290 18291 if (TryInstantiating) { 18292 SourceLocation PointOfInstantiation = 18293 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18294 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18295 if (FirstInstantiation) { 18296 PointOfInstantiation = Loc; 18297 if (MSI) 18298 MSI->setPointOfInstantiation(PointOfInstantiation); 18299 // FIXME: Notify listener. 18300 else 18301 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18302 } 18303 18304 if (UsableInConstantExpr) { 18305 // Do not defer instantiations of variables that could be used in a 18306 // constant expression. 18307 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18308 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18309 }); 18310 18311 // Re-set the member to trigger a recomputation of the dependence bits 18312 // for the expression. 18313 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18314 DRE->setDecl(DRE->getDecl()); 18315 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18316 ME->setMemberDecl(ME->getMemberDecl()); 18317 } else if (FirstInstantiation || 18318 isa<VarTemplateSpecializationDecl>(Var)) { 18319 // FIXME: For a specialization of a variable template, we don't 18320 // distinguish between "declaration and type implicitly instantiated" 18321 // and "implicit instantiation of definition requested", so we have 18322 // no direct way to avoid enqueueing the pending instantiation 18323 // multiple times. 18324 SemaRef.PendingInstantiations 18325 .push_back(std::make_pair(Var, PointOfInstantiation)); 18326 } 18327 } 18328 } 18329 18330 // C++2a [basic.def.odr]p4: 18331 // A variable x whose name appears as a potentially-evaluated expression e 18332 // is odr-used by e unless 18333 // -- x is a reference that is usable in constant expressions 18334 // -- x is a variable of non-reference type that is usable in constant 18335 // expressions and has no mutable subobjects [FIXME], and e is an 18336 // element of the set of potential results of an expression of 18337 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18338 // conversion is applied 18339 // -- x is a variable of non-reference type, and e is an element of the set 18340 // of potential results of a discarded-value expression to which the 18341 // lvalue-to-rvalue conversion is not applied [FIXME] 18342 // 18343 // We check the first part of the second bullet here, and 18344 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18345 // FIXME: To get the third bullet right, we need to delay this even for 18346 // variables that are not usable in constant expressions. 18347 18348 // If we already know this isn't an odr-use, there's nothing more to do. 18349 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18350 if (DRE->isNonOdrUse()) 18351 return; 18352 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18353 if (ME->isNonOdrUse()) 18354 return; 18355 18356 switch (OdrUse) { 18357 case OdrUseContext::None: 18358 assert((!E || isa<FunctionParmPackExpr>(E)) && 18359 "missing non-odr-use marking for unevaluated decl ref"); 18360 break; 18361 18362 case OdrUseContext::FormallyOdrUsed: 18363 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18364 // behavior. 18365 break; 18366 18367 case OdrUseContext::Used: 18368 // If we might later find that this expression isn't actually an odr-use, 18369 // delay the marking. 18370 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18371 SemaRef.MaybeODRUseExprs.insert(E); 18372 else 18373 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18374 break; 18375 18376 case OdrUseContext::Dependent: 18377 // If this is a dependent context, we don't need to mark variables as 18378 // odr-used, but we may still need to track them for lambda capture. 18379 // FIXME: Do we also need to do this inside dependent typeid expressions 18380 // (which are modeled as unevaluated at this point)? 18381 const bool RefersToEnclosingScope = 18382 (SemaRef.CurContext != Var->getDeclContext() && 18383 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18384 if (RefersToEnclosingScope) { 18385 LambdaScopeInfo *const LSI = 18386 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18387 if (LSI && (!LSI->CallOperator || 18388 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18389 // If a variable could potentially be odr-used, defer marking it so 18390 // until we finish analyzing the full expression for any 18391 // lvalue-to-rvalue 18392 // or discarded value conversions that would obviate odr-use. 18393 // Add it to the list of potential captures that will be analyzed 18394 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18395 // unless the variable is a reference that was initialized by a constant 18396 // expression (this will never need to be captured or odr-used). 18397 // 18398 // FIXME: We can simplify this a lot after implementing P0588R1. 18399 assert(E && "Capture variable should be used in an expression."); 18400 if (!Var->getType()->isReferenceType() || 18401 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18402 LSI->addPotentialCapture(E->IgnoreParens()); 18403 } 18404 } 18405 break; 18406 } 18407 } 18408 18409 /// Mark a variable referenced, and check whether it is odr-used 18410 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18411 /// used directly for normal expressions referring to VarDecl. 18412 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18413 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18414 } 18415 18416 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18417 Decl *D, Expr *E, bool MightBeOdrUse) { 18418 if (SemaRef.isInOpenMPDeclareTargetContext()) 18419 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18420 18421 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18422 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18423 return; 18424 } 18425 18426 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18427 18428 // If this is a call to a method via a cast, also mark the method in the 18429 // derived class used in case codegen can devirtualize the call. 18430 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18431 if (!ME) 18432 return; 18433 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18434 if (!MD) 18435 return; 18436 // Only attempt to devirtualize if this is truly a virtual call. 18437 bool IsVirtualCall = MD->isVirtual() && 18438 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18439 if (!IsVirtualCall) 18440 return; 18441 18442 // If it's possible to devirtualize the call, mark the called function 18443 // referenced. 18444 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18445 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18446 if (DM) 18447 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18448 } 18449 18450 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18451 /// 18452 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18453 /// handled with care if the DeclRefExpr is not newly-created. 18454 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18455 // TODO: update this with DR# once a defect report is filed. 18456 // C++11 defect. The address of a pure member should not be an ODR use, even 18457 // if it's a qualified reference. 18458 bool OdrUse = true; 18459 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18460 if (Method->isVirtual() && 18461 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18462 OdrUse = false; 18463 18464 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18465 if (!isConstantEvaluated() && FD->isConsteval() && 18466 !RebuildingImmediateInvocation) 18467 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18468 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18469 } 18470 18471 /// Perform reference-marking and odr-use handling for a MemberExpr. 18472 void Sema::MarkMemberReferenced(MemberExpr *E) { 18473 // C++11 [basic.def.odr]p2: 18474 // A non-overloaded function whose name appears as a potentially-evaluated 18475 // expression or a member of a set of candidate functions, if selected by 18476 // overload resolution when referred to from a potentially-evaluated 18477 // expression, is odr-used, unless it is a pure virtual function and its 18478 // name is not explicitly qualified. 18479 bool MightBeOdrUse = true; 18480 if (E->performsVirtualDispatch(getLangOpts())) { 18481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18482 if (Method->isPure()) 18483 MightBeOdrUse = false; 18484 } 18485 SourceLocation Loc = 18486 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18487 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18488 } 18489 18490 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18491 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18492 for (VarDecl *VD : *E) 18493 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18494 } 18495 18496 /// Perform marking for a reference to an arbitrary declaration. It 18497 /// marks the declaration referenced, and performs odr-use checking for 18498 /// functions and variables. This method should not be used when building a 18499 /// normal expression which refers to a variable. 18500 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18501 bool MightBeOdrUse) { 18502 if (MightBeOdrUse) { 18503 if (auto *VD = dyn_cast<VarDecl>(D)) { 18504 MarkVariableReferenced(Loc, VD); 18505 return; 18506 } 18507 } 18508 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18509 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18510 return; 18511 } 18512 D->setReferenced(); 18513 } 18514 18515 namespace { 18516 // Mark all of the declarations used by a type as referenced. 18517 // FIXME: Not fully implemented yet! We need to have a better understanding 18518 // of when we're entering a context we should not recurse into. 18519 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18520 // TreeTransforms rebuilding the type in a new context. Rather than 18521 // duplicating the TreeTransform logic, we should consider reusing it here. 18522 // Currently that causes problems when rebuilding LambdaExprs. 18523 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18524 Sema &S; 18525 SourceLocation Loc; 18526 18527 public: 18528 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18529 18530 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18531 18532 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18533 }; 18534 } 18535 18536 bool MarkReferencedDecls::TraverseTemplateArgument( 18537 const TemplateArgument &Arg) { 18538 { 18539 // A non-type template argument is a constant-evaluated context. 18540 EnterExpressionEvaluationContext Evaluated( 18541 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18542 if (Arg.getKind() == TemplateArgument::Declaration) { 18543 if (Decl *D = Arg.getAsDecl()) 18544 S.MarkAnyDeclReferenced(Loc, D, true); 18545 } else if (Arg.getKind() == TemplateArgument::Expression) { 18546 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18547 } 18548 } 18549 18550 return Inherited::TraverseTemplateArgument(Arg); 18551 } 18552 18553 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18554 MarkReferencedDecls Marker(*this, Loc); 18555 Marker.TraverseType(T); 18556 } 18557 18558 namespace { 18559 /// Helper class that marks all of the declarations referenced by 18560 /// potentially-evaluated subexpressions as "referenced". 18561 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18562 public: 18563 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18564 bool SkipLocalVariables; 18565 18566 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18567 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18568 18569 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18570 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18571 } 18572 18573 void VisitDeclRefExpr(DeclRefExpr *E) { 18574 // If we were asked not to visit local variables, don't. 18575 if (SkipLocalVariables) { 18576 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18577 if (VD->hasLocalStorage()) 18578 return; 18579 } 18580 18581 // FIXME: This can trigger the instantiation of the initializer of a 18582 // variable, which can cause the expression to become value-dependent 18583 // or error-dependent. Do we need to propagate the new dependence bits? 18584 S.MarkDeclRefReferenced(E); 18585 } 18586 18587 void VisitMemberExpr(MemberExpr *E) { 18588 S.MarkMemberReferenced(E); 18589 Visit(E->getBase()); 18590 } 18591 }; 18592 } // namespace 18593 18594 /// Mark any declarations that appear within this expression or any 18595 /// potentially-evaluated subexpressions as "referenced". 18596 /// 18597 /// \param SkipLocalVariables If true, don't mark local variables as 18598 /// 'referenced'. 18599 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18600 bool SkipLocalVariables) { 18601 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18602 } 18603 18604 /// Emit a diagnostic that describes an effect on the run-time behavior 18605 /// of the program being compiled. 18606 /// 18607 /// This routine emits the given diagnostic when the code currently being 18608 /// type-checked is "potentially evaluated", meaning that there is a 18609 /// possibility that the code will actually be executable. Code in sizeof() 18610 /// expressions, code used only during overload resolution, etc., are not 18611 /// potentially evaluated. This routine will suppress such diagnostics or, 18612 /// in the absolutely nutty case of potentially potentially evaluated 18613 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18614 /// later. 18615 /// 18616 /// This routine should be used for all diagnostics that describe the run-time 18617 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18618 /// Failure to do so will likely result in spurious diagnostics or failures 18619 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18620 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18621 const PartialDiagnostic &PD) { 18622 switch (ExprEvalContexts.back().Context) { 18623 case ExpressionEvaluationContext::Unevaluated: 18624 case ExpressionEvaluationContext::UnevaluatedList: 18625 case ExpressionEvaluationContext::UnevaluatedAbstract: 18626 case ExpressionEvaluationContext::DiscardedStatement: 18627 // The argument will never be evaluated, so don't complain. 18628 break; 18629 18630 case ExpressionEvaluationContext::ConstantEvaluated: 18631 // Relevant diagnostics should be produced by constant evaluation. 18632 break; 18633 18634 case ExpressionEvaluationContext::PotentiallyEvaluated: 18635 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18636 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18637 FunctionScopes.back()->PossiblyUnreachableDiags. 18638 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18639 return true; 18640 } 18641 18642 // The initializer of a constexpr variable or of the first declaration of a 18643 // static data member is not syntactically a constant evaluated constant, 18644 // but nonetheless is always required to be a constant expression, so we 18645 // can skip diagnosing. 18646 // FIXME: Using the mangling context here is a hack. 18647 if (auto *VD = dyn_cast_or_null<VarDecl>( 18648 ExprEvalContexts.back().ManglingContextDecl)) { 18649 if (VD->isConstexpr() || 18650 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18651 break; 18652 // FIXME: For any other kind of variable, we should build a CFG for its 18653 // initializer and check whether the context in question is reachable. 18654 } 18655 18656 Diag(Loc, PD); 18657 return true; 18658 } 18659 18660 return false; 18661 } 18662 18663 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18664 const PartialDiagnostic &PD) { 18665 return DiagRuntimeBehavior( 18666 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18667 } 18668 18669 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18670 CallExpr *CE, FunctionDecl *FD) { 18671 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18672 return false; 18673 18674 // If we're inside a decltype's expression, don't check for a valid return 18675 // type or construct temporaries until we know whether this is the last call. 18676 if (ExprEvalContexts.back().ExprContext == 18677 ExpressionEvaluationContextRecord::EK_Decltype) { 18678 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18679 return false; 18680 } 18681 18682 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18683 FunctionDecl *FD; 18684 CallExpr *CE; 18685 18686 public: 18687 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18688 : FD(FD), CE(CE) { } 18689 18690 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18691 if (!FD) { 18692 S.Diag(Loc, diag::err_call_incomplete_return) 18693 << T << CE->getSourceRange(); 18694 return; 18695 } 18696 18697 S.Diag(Loc, diag::err_call_function_incomplete_return) 18698 << CE->getSourceRange() << FD << T; 18699 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18700 << FD->getDeclName(); 18701 } 18702 } Diagnoser(FD, CE); 18703 18704 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18705 return true; 18706 18707 return false; 18708 } 18709 18710 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18711 // will prevent this condition from triggering, which is what we want. 18712 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18713 SourceLocation Loc; 18714 18715 unsigned diagnostic = diag::warn_condition_is_assignment; 18716 bool IsOrAssign = false; 18717 18718 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18719 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18720 return; 18721 18722 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18723 18724 // Greylist some idioms by putting them into a warning subcategory. 18725 if (ObjCMessageExpr *ME 18726 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18727 Selector Sel = ME->getSelector(); 18728 18729 // self = [<foo> init...] 18730 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18731 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18732 18733 // <foo> = [<bar> nextObject] 18734 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18735 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18736 } 18737 18738 Loc = Op->getOperatorLoc(); 18739 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18740 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18741 return; 18742 18743 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18744 Loc = Op->getOperatorLoc(); 18745 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18746 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18747 else { 18748 // Not an assignment. 18749 return; 18750 } 18751 18752 Diag(Loc, diagnostic) << E->getSourceRange(); 18753 18754 SourceLocation Open = E->getBeginLoc(); 18755 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18756 Diag(Loc, diag::note_condition_assign_silence) 18757 << FixItHint::CreateInsertion(Open, "(") 18758 << FixItHint::CreateInsertion(Close, ")"); 18759 18760 if (IsOrAssign) 18761 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18762 << FixItHint::CreateReplacement(Loc, "!="); 18763 else 18764 Diag(Loc, diag::note_condition_assign_to_comparison) 18765 << FixItHint::CreateReplacement(Loc, "=="); 18766 } 18767 18768 /// Redundant parentheses over an equality comparison can indicate 18769 /// that the user intended an assignment used as condition. 18770 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18771 // Don't warn if the parens came from a macro. 18772 SourceLocation parenLoc = ParenE->getBeginLoc(); 18773 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18774 return; 18775 // Don't warn for dependent expressions. 18776 if (ParenE->isTypeDependent()) 18777 return; 18778 18779 Expr *E = ParenE->IgnoreParens(); 18780 18781 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18782 if (opE->getOpcode() == BO_EQ && 18783 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18784 == Expr::MLV_Valid) { 18785 SourceLocation Loc = opE->getOperatorLoc(); 18786 18787 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18788 SourceRange ParenERange = ParenE->getSourceRange(); 18789 Diag(Loc, diag::note_equality_comparison_silence) 18790 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18791 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18792 Diag(Loc, diag::note_equality_comparison_to_assign) 18793 << FixItHint::CreateReplacement(Loc, "="); 18794 } 18795 } 18796 18797 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18798 bool IsConstexpr) { 18799 DiagnoseAssignmentAsCondition(E); 18800 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18801 DiagnoseEqualityWithExtraParens(parenE); 18802 18803 ExprResult result = CheckPlaceholderExpr(E); 18804 if (result.isInvalid()) return ExprError(); 18805 E = result.get(); 18806 18807 if (!E->isTypeDependent()) { 18808 if (getLangOpts().CPlusPlus) 18809 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18810 18811 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18812 if (ERes.isInvalid()) 18813 return ExprError(); 18814 E = ERes.get(); 18815 18816 QualType T = E->getType(); 18817 if (!T->isScalarType()) { // C99 6.8.4.1p1 18818 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18819 << T << E->getSourceRange(); 18820 return ExprError(); 18821 } 18822 CheckBoolLikeConversion(E, Loc); 18823 } 18824 18825 return E; 18826 } 18827 18828 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18829 Expr *SubExpr, ConditionKind CK) { 18830 // Empty conditions are valid in for-statements. 18831 if (!SubExpr) 18832 return ConditionResult(); 18833 18834 ExprResult Cond; 18835 switch (CK) { 18836 case ConditionKind::Boolean: 18837 Cond = CheckBooleanCondition(Loc, SubExpr); 18838 break; 18839 18840 case ConditionKind::ConstexprIf: 18841 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18842 break; 18843 18844 case ConditionKind::Switch: 18845 Cond = CheckSwitchCondition(Loc, SubExpr); 18846 break; 18847 } 18848 if (Cond.isInvalid()) { 18849 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18850 {SubExpr}); 18851 if (!Cond.get()) 18852 return ConditionError(); 18853 } 18854 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18855 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18856 if (!FullExpr.get()) 18857 return ConditionError(); 18858 18859 return ConditionResult(*this, nullptr, FullExpr, 18860 CK == ConditionKind::ConstexprIf); 18861 } 18862 18863 namespace { 18864 /// A visitor for rebuilding a call to an __unknown_any expression 18865 /// to have an appropriate type. 18866 struct RebuildUnknownAnyFunction 18867 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18868 18869 Sema &S; 18870 18871 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18872 18873 ExprResult VisitStmt(Stmt *S) { 18874 llvm_unreachable("unexpected statement!"); 18875 } 18876 18877 ExprResult VisitExpr(Expr *E) { 18878 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18879 << E->getSourceRange(); 18880 return ExprError(); 18881 } 18882 18883 /// Rebuild an expression which simply semantically wraps another 18884 /// expression which it shares the type and value kind of. 18885 template <class T> ExprResult rebuildSugarExpr(T *E) { 18886 ExprResult SubResult = Visit(E->getSubExpr()); 18887 if (SubResult.isInvalid()) return ExprError(); 18888 18889 Expr *SubExpr = SubResult.get(); 18890 E->setSubExpr(SubExpr); 18891 E->setType(SubExpr->getType()); 18892 E->setValueKind(SubExpr->getValueKind()); 18893 assert(E->getObjectKind() == OK_Ordinary); 18894 return E; 18895 } 18896 18897 ExprResult VisitParenExpr(ParenExpr *E) { 18898 return rebuildSugarExpr(E); 18899 } 18900 18901 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18902 return rebuildSugarExpr(E); 18903 } 18904 18905 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18906 ExprResult SubResult = Visit(E->getSubExpr()); 18907 if (SubResult.isInvalid()) return ExprError(); 18908 18909 Expr *SubExpr = SubResult.get(); 18910 E->setSubExpr(SubExpr); 18911 E->setType(S.Context.getPointerType(SubExpr->getType())); 18912 assert(E->getValueKind() == VK_RValue); 18913 assert(E->getObjectKind() == OK_Ordinary); 18914 return E; 18915 } 18916 18917 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18918 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18919 18920 E->setType(VD->getType()); 18921 18922 assert(E->getValueKind() == VK_RValue); 18923 if (S.getLangOpts().CPlusPlus && 18924 !(isa<CXXMethodDecl>(VD) && 18925 cast<CXXMethodDecl>(VD)->isInstance())) 18926 E->setValueKind(VK_LValue); 18927 18928 return E; 18929 } 18930 18931 ExprResult VisitMemberExpr(MemberExpr *E) { 18932 return resolveDecl(E, E->getMemberDecl()); 18933 } 18934 18935 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18936 return resolveDecl(E, E->getDecl()); 18937 } 18938 }; 18939 } 18940 18941 /// Given a function expression of unknown-any type, try to rebuild it 18942 /// to have a function type. 18943 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18944 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18945 if (Result.isInvalid()) return ExprError(); 18946 return S.DefaultFunctionArrayConversion(Result.get()); 18947 } 18948 18949 namespace { 18950 /// A visitor for rebuilding an expression of type __unknown_anytype 18951 /// into one which resolves the type directly on the referring 18952 /// expression. Strict preservation of the original source 18953 /// structure is not a goal. 18954 struct RebuildUnknownAnyExpr 18955 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18956 18957 Sema &S; 18958 18959 /// The current destination type. 18960 QualType DestType; 18961 18962 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18963 : S(S), DestType(CastType) {} 18964 18965 ExprResult VisitStmt(Stmt *S) { 18966 llvm_unreachable("unexpected statement!"); 18967 } 18968 18969 ExprResult VisitExpr(Expr *E) { 18970 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18971 << E->getSourceRange(); 18972 return ExprError(); 18973 } 18974 18975 ExprResult VisitCallExpr(CallExpr *E); 18976 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18977 18978 /// Rebuild an expression which simply semantically wraps another 18979 /// expression which it shares the type and value kind of. 18980 template <class T> ExprResult rebuildSugarExpr(T *E) { 18981 ExprResult SubResult = Visit(E->getSubExpr()); 18982 if (SubResult.isInvalid()) return ExprError(); 18983 Expr *SubExpr = SubResult.get(); 18984 E->setSubExpr(SubExpr); 18985 E->setType(SubExpr->getType()); 18986 E->setValueKind(SubExpr->getValueKind()); 18987 assert(E->getObjectKind() == OK_Ordinary); 18988 return E; 18989 } 18990 18991 ExprResult VisitParenExpr(ParenExpr *E) { 18992 return rebuildSugarExpr(E); 18993 } 18994 18995 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18996 return rebuildSugarExpr(E); 18997 } 18998 18999 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19000 const PointerType *Ptr = DestType->getAs<PointerType>(); 19001 if (!Ptr) { 19002 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19003 << E->getSourceRange(); 19004 return ExprError(); 19005 } 19006 19007 if (isa<CallExpr>(E->getSubExpr())) { 19008 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19009 << E->getSourceRange(); 19010 return ExprError(); 19011 } 19012 19013 assert(E->getValueKind() == VK_RValue); 19014 assert(E->getObjectKind() == OK_Ordinary); 19015 E->setType(DestType); 19016 19017 // Build the sub-expression as if it were an object of the pointee type. 19018 DestType = Ptr->getPointeeType(); 19019 ExprResult SubResult = Visit(E->getSubExpr()); 19020 if (SubResult.isInvalid()) return ExprError(); 19021 E->setSubExpr(SubResult.get()); 19022 return E; 19023 } 19024 19025 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19026 19027 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19028 19029 ExprResult VisitMemberExpr(MemberExpr *E) { 19030 return resolveDecl(E, E->getMemberDecl()); 19031 } 19032 19033 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19034 return resolveDecl(E, E->getDecl()); 19035 } 19036 }; 19037 } 19038 19039 /// Rebuilds a call expression which yielded __unknown_anytype. 19040 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19041 Expr *CalleeExpr = E->getCallee(); 19042 19043 enum FnKind { 19044 FK_MemberFunction, 19045 FK_FunctionPointer, 19046 FK_BlockPointer 19047 }; 19048 19049 FnKind Kind; 19050 QualType CalleeType = CalleeExpr->getType(); 19051 if (CalleeType == S.Context.BoundMemberTy) { 19052 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19053 Kind = FK_MemberFunction; 19054 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19055 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19056 CalleeType = Ptr->getPointeeType(); 19057 Kind = FK_FunctionPointer; 19058 } else { 19059 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19060 Kind = FK_BlockPointer; 19061 } 19062 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19063 19064 // Verify that this is a legal result type of a function. 19065 if (DestType->isArrayType() || DestType->isFunctionType()) { 19066 unsigned diagID = diag::err_func_returning_array_function; 19067 if (Kind == FK_BlockPointer) 19068 diagID = diag::err_block_returning_array_function; 19069 19070 S.Diag(E->getExprLoc(), diagID) 19071 << DestType->isFunctionType() << DestType; 19072 return ExprError(); 19073 } 19074 19075 // Otherwise, go ahead and set DestType as the call's result. 19076 E->setType(DestType.getNonLValueExprType(S.Context)); 19077 E->setValueKind(Expr::getValueKindForType(DestType)); 19078 assert(E->getObjectKind() == OK_Ordinary); 19079 19080 // Rebuild the function type, replacing the result type with DestType. 19081 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19082 if (Proto) { 19083 // __unknown_anytype(...) is a special case used by the debugger when 19084 // it has no idea what a function's signature is. 19085 // 19086 // We want to build this call essentially under the K&R 19087 // unprototyped rules, but making a FunctionNoProtoType in C++ 19088 // would foul up all sorts of assumptions. However, we cannot 19089 // simply pass all arguments as variadic arguments, nor can we 19090 // portably just call the function under a non-variadic type; see 19091 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19092 // However, it turns out that in practice it is generally safe to 19093 // call a function declared as "A foo(B,C,D);" under the prototype 19094 // "A foo(B,C,D,...);". The only known exception is with the 19095 // Windows ABI, where any variadic function is implicitly cdecl 19096 // regardless of its normal CC. Therefore we change the parameter 19097 // types to match the types of the arguments. 19098 // 19099 // This is a hack, but it is far superior to moving the 19100 // corresponding target-specific code from IR-gen to Sema/AST. 19101 19102 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19103 SmallVector<QualType, 8> ArgTypes; 19104 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19105 ArgTypes.reserve(E->getNumArgs()); 19106 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19107 Expr *Arg = E->getArg(i); 19108 QualType ArgType = Arg->getType(); 19109 if (E->isLValue()) { 19110 ArgType = S.Context.getLValueReferenceType(ArgType); 19111 } else if (E->isXValue()) { 19112 ArgType = S.Context.getRValueReferenceType(ArgType); 19113 } 19114 ArgTypes.push_back(ArgType); 19115 } 19116 ParamTypes = ArgTypes; 19117 } 19118 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19119 Proto->getExtProtoInfo()); 19120 } else { 19121 DestType = S.Context.getFunctionNoProtoType(DestType, 19122 FnType->getExtInfo()); 19123 } 19124 19125 // Rebuild the appropriate pointer-to-function type. 19126 switch (Kind) { 19127 case FK_MemberFunction: 19128 // Nothing to do. 19129 break; 19130 19131 case FK_FunctionPointer: 19132 DestType = S.Context.getPointerType(DestType); 19133 break; 19134 19135 case FK_BlockPointer: 19136 DestType = S.Context.getBlockPointerType(DestType); 19137 break; 19138 } 19139 19140 // Finally, we can recurse. 19141 ExprResult CalleeResult = Visit(CalleeExpr); 19142 if (!CalleeResult.isUsable()) return ExprError(); 19143 E->setCallee(CalleeResult.get()); 19144 19145 // Bind a temporary if necessary. 19146 return S.MaybeBindToTemporary(E); 19147 } 19148 19149 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19150 // Verify that this is a legal result type of a call. 19151 if (DestType->isArrayType() || DestType->isFunctionType()) { 19152 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19153 << DestType->isFunctionType() << DestType; 19154 return ExprError(); 19155 } 19156 19157 // Rewrite the method result type if available. 19158 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19159 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19160 Method->setReturnType(DestType); 19161 } 19162 19163 // Change the type of the message. 19164 E->setType(DestType.getNonReferenceType()); 19165 E->setValueKind(Expr::getValueKindForType(DestType)); 19166 19167 return S.MaybeBindToTemporary(E); 19168 } 19169 19170 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19171 // The only case we should ever see here is a function-to-pointer decay. 19172 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19173 assert(E->getValueKind() == VK_RValue); 19174 assert(E->getObjectKind() == OK_Ordinary); 19175 19176 E->setType(DestType); 19177 19178 // Rebuild the sub-expression as the pointee (function) type. 19179 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19180 19181 ExprResult Result = Visit(E->getSubExpr()); 19182 if (!Result.isUsable()) return ExprError(); 19183 19184 E->setSubExpr(Result.get()); 19185 return E; 19186 } else if (E->getCastKind() == CK_LValueToRValue) { 19187 assert(E->getValueKind() == VK_RValue); 19188 assert(E->getObjectKind() == OK_Ordinary); 19189 19190 assert(isa<BlockPointerType>(E->getType())); 19191 19192 E->setType(DestType); 19193 19194 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19195 DestType = S.Context.getLValueReferenceType(DestType); 19196 19197 ExprResult Result = Visit(E->getSubExpr()); 19198 if (!Result.isUsable()) return ExprError(); 19199 19200 E->setSubExpr(Result.get()); 19201 return E; 19202 } else { 19203 llvm_unreachable("Unhandled cast type!"); 19204 } 19205 } 19206 19207 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19208 ExprValueKind ValueKind = VK_LValue; 19209 QualType Type = DestType; 19210 19211 // We know how to make this work for certain kinds of decls: 19212 19213 // - functions 19214 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19215 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19216 DestType = Ptr->getPointeeType(); 19217 ExprResult Result = resolveDecl(E, VD); 19218 if (Result.isInvalid()) return ExprError(); 19219 return S.ImpCastExprToType(Result.get(), Type, 19220 CK_FunctionToPointerDecay, VK_RValue); 19221 } 19222 19223 if (!Type->isFunctionType()) { 19224 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19225 << VD << E->getSourceRange(); 19226 return ExprError(); 19227 } 19228 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19229 // We must match the FunctionDecl's type to the hack introduced in 19230 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19231 // type. See the lengthy commentary in that routine. 19232 QualType FDT = FD->getType(); 19233 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19234 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19235 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19236 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19237 SourceLocation Loc = FD->getLocation(); 19238 FunctionDecl *NewFD = FunctionDecl::Create( 19239 S.Context, FD->getDeclContext(), Loc, Loc, 19240 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19241 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19242 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19243 19244 if (FD->getQualifier()) 19245 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19246 19247 SmallVector<ParmVarDecl*, 16> Params; 19248 for (const auto &AI : FT->param_types()) { 19249 ParmVarDecl *Param = 19250 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19251 Param->setScopeInfo(0, Params.size()); 19252 Params.push_back(Param); 19253 } 19254 NewFD->setParams(Params); 19255 DRE->setDecl(NewFD); 19256 VD = DRE->getDecl(); 19257 } 19258 } 19259 19260 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19261 if (MD->isInstance()) { 19262 ValueKind = VK_RValue; 19263 Type = S.Context.BoundMemberTy; 19264 } 19265 19266 // Function references aren't l-values in C. 19267 if (!S.getLangOpts().CPlusPlus) 19268 ValueKind = VK_RValue; 19269 19270 // - variables 19271 } else if (isa<VarDecl>(VD)) { 19272 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19273 Type = RefTy->getPointeeType(); 19274 } else if (Type->isFunctionType()) { 19275 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19276 << VD << E->getSourceRange(); 19277 return ExprError(); 19278 } 19279 19280 // - nothing else 19281 } else { 19282 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19283 << VD << E->getSourceRange(); 19284 return ExprError(); 19285 } 19286 19287 // Modifying the declaration like this is friendly to IR-gen but 19288 // also really dangerous. 19289 VD->setType(DestType); 19290 E->setType(Type); 19291 E->setValueKind(ValueKind); 19292 return E; 19293 } 19294 19295 /// Check a cast of an unknown-any type. We intentionally only 19296 /// trigger this for C-style casts. 19297 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19298 Expr *CastExpr, CastKind &CastKind, 19299 ExprValueKind &VK, CXXCastPath &Path) { 19300 // The type we're casting to must be either void or complete. 19301 if (!CastType->isVoidType() && 19302 RequireCompleteType(TypeRange.getBegin(), CastType, 19303 diag::err_typecheck_cast_to_incomplete)) 19304 return ExprError(); 19305 19306 // Rewrite the casted expression from scratch. 19307 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19308 if (!result.isUsable()) return ExprError(); 19309 19310 CastExpr = result.get(); 19311 VK = CastExpr->getValueKind(); 19312 CastKind = CK_NoOp; 19313 19314 return CastExpr; 19315 } 19316 19317 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19318 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19319 } 19320 19321 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19322 Expr *arg, QualType ¶mType) { 19323 // If the syntactic form of the argument is not an explicit cast of 19324 // any sort, just do default argument promotion. 19325 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19326 if (!castArg) { 19327 ExprResult result = DefaultArgumentPromotion(arg); 19328 if (result.isInvalid()) return ExprError(); 19329 paramType = result.get()->getType(); 19330 return result; 19331 } 19332 19333 // Otherwise, use the type that was written in the explicit cast. 19334 assert(!arg->hasPlaceholderType()); 19335 paramType = castArg->getTypeAsWritten(); 19336 19337 // Copy-initialize a parameter of that type. 19338 InitializedEntity entity = 19339 InitializedEntity::InitializeParameter(Context, paramType, 19340 /*consumed*/ false); 19341 return PerformCopyInitialization(entity, callLoc, arg); 19342 } 19343 19344 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19345 Expr *orig = E; 19346 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19347 while (true) { 19348 E = E->IgnoreParenImpCasts(); 19349 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19350 E = call->getCallee(); 19351 diagID = diag::err_uncasted_call_of_unknown_any; 19352 } else { 19353 break; 19354 } 19355 } 19356 19357 SourceLocation loc; 19358 NamedDecl *d; 19359 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19360 loc = ref->getLocation(); 19361 d = ref->getDecl(); 19362 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19363 loc = mem->getMemberLoc(); 19364 d = mem->getMemberDecl(); 19365 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19366 diagID = diag::err_uncasted_call_of_unknown_any; 19367 loc = msg->getSelectorStartLoc(); 19368 d = msg->getMethodDecl(); 19369 if (!d) { 19370 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19371 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19372 << orig->getSourceRange(); 19373 return ExprError(); 19374 } 19375 } else { 19376 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19377 << E->getSourceRange(); 19378 return ExprError(); 19379 } 19380 19381 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19382 19383 // Never recoverable. 19384 return ExprError(); 19385 } 19386 19387 /// Check for operands with placeholder types and complain if found. 19388 /// Returns ExprError() if there was an error and no recovery was possible. 19389 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19390 if (!Context.isDependenceAllowed()) { 19391 // C cannot handle TypoExpr nodes on either side of a binop because it 19392 // doesn't handle dependent types properly, so make sure any TypoExprs have 19393 // been dealt with before checking the operands. 19394 ExprResult Result = CorrectDelayedTyposInExpr(E); 19395 if (!Result.isUsable()) return ExprError(); 19396 E = Result.get(); 19397 } 19398 19399 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19400 if (!placeholderType) return E; 19401 19402 switch (placeholderType->getKind()) { 19403 19404 // Overloaded expressions. 19405 case BuiltinType::Overload: { 19406 // Try to resolve a single function template specialization. 19407 // This is obligatory. 19408 ExprResult Result = E; 19409 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19410 return Result; 19411 19412 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19413 // leaves Result unchanged on failure. 19414 Result = E; 19415 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19416 return Result; 19417 19418 // If that failed, try to recover with a call. 19419 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19420 /*complain*/ true); 19421 return Result; 19422 } 19423 19424 // Bound member functions. 19425 case BuiltinType::BoundMember: { 19426 ExprResult result = E; 19427 const Expr *BME = E->IgnoreParens(); 19428 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19429 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19430 if (isa<CXXPseudoDestructorExpr>(BME)) { 19431 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19432 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19433 if (ME->getMemberNameInfo().getName().getNameKind() == 19434 DeclarationName::CXXDestructorName) 19435 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19436 } 19437 tryToRecoverWithCall(result, PD, 19438 /*complain*/ true); 19439 return result; 19440 } 19441 19442 // ARC unbridged casts. 19443 case BuiltinType::ARCUnbridgedCast: { 19444 Expr *realCast = stripARCUnbridgedCast(E); 19445 diagnoseARCUnbridgedCast(realCast); 19446 return realCast; 19447 } 19448 19449 // Expressions of unknown type. 19450 case BuiltinType::UnknownAny: 19451 return diagnoseUnknownAnyExpr(*this, E); 19452 19453 // Pseudo-objects. 19454 case BuiltinType::PseudoObject: 19455 return checkPseudoObjectRValue(E); 19456 19457 case BuiltinType::BuiltinFn: { 19458 // Accept __noop without parens by implicitly converting it to a call expr. 19459 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19460 if (DRE) { 19461 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19462 if (FD->getBuiltinID() == Builtin::BI__noop) { 19463 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19464 CK_BuiltinFnToFnPtr) 19465 .get(); 19466 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19467 VK_RValue, SourceLocation(), 19468 FPOptionsOverride()); 19469 } 19470 } 19471 19472 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19473 return ExprError(); 19474 } 19475 19476 case BuiltinType::IncompleteMatrixIdx: 19477 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19478 ->getRowIdx() 19479 ->getBeginLoc(), 19480 diag::err_matrix_incomplete_index); 19481 return ExprError(); 19482 19483 // Expressions of unknown type. 19484 case BuiltinType::OMPArraySection: 19485 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19486 return ExprError(); 19487 19488 // Expressions of unknown type. 19489 case BuiltinType::OMPArrayShaping: 19490 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19491 19492 case BuiltinType::OMPIterator: 19493 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19494 19495 // Everything else should be impossible. 19496 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19497 case BuiltinType::Id: 19498 #include "clang/Basic/OpenCLImageTypes.def" 19499 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19500 case BuiltinType::Id: 19501 #include "clang/Basic/OpenCLExtensionTypes.def" 19502 #define SVE_TYPE(Name, Id, SingletonId) \ 19503 case BuiltinType::Id: 19504 #include "clang/Basic/AArch64SVEACLETypes.def" 19505 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19506 case BuiltinType::Id: 19507 #include "clang/Basic/PPCTypes.def" 19508 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19509 #include "clang/Basic/RISCVVTypes.def" 19510 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19511 #define PLACEHOLDER_TYPE(Id, SingletonId) 19512 #include "clang/AST/BuiltinTypes.def" 19513 break; 19514 } 19515 19516 llvm_unreachable("invalid placeholder type!"); 19517 } 19518 19519 bool Sema::CheckCaseExpression(Expr *E) { 19520 if (E->isTypeDependent()) 19521 return true; 19522 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19523 return E->getType()->isIntegralOrEnumerationType(); 19524 return false; 19525 } 19526 19527 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19528 ExprResult 19529 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19530 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19531 "Unknown Objective-C Boolean value!"); 19532 QualType BoolT = Context.ObjCBuiltinBoolTy; 19533 if (!Context.getBOOLDecl()) { 19534 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19535 Sema::LookupOrdinaryName); 19536 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19537 NamedDecl *ND = Result.getFoundDecl(); 19538 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19539 Context.setBOOLDecl(TD); 19540 } 19541 } 19542 if (Context.getBOOLDecl()) 19543 BoolT = Context.getBOOLType(); 19544 return new (Context) 19545 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19546 } 19547 19548 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19549 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19550 SourceLocation RParen) { 19551 19552 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19553 19554 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19555 return Spec.getPlatform() == Platform; 19556 }); 19557 19558 VersionTuple Version; 19559 if (Spec != AvailSpecs.end()) 19560 Version = Spec->getVersion(); 19561 19562 // The use of `@available` in the enclosing function should be analyzed to 19563 // warn when it's used inappropriately (i.e. not if(@available)). 19564 if (getCurFunctionOrMethodDecl()) 19565 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19566 else if (getCurBlock() || getCurLambda()) 19567 getCurFunction()->HasPotentialAvailabilityViolations = true; 19568 19569 return new (Context) 19570 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19571 } 19572 19573 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19574 ArrayRef<Expr *> SubExprs, QualType T) { 19575 if (!Context.getLangOpts().RecoveryAST) 19576 return ExprError(); 19577 19578 if (isSFINAEContext()) 19579 return ExprError(); 19580 19581 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19582 // We don't know the concrete type, fallback to dependent type. 19583 T = Context.DependentTy; 19584 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19585 } 19586