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/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 298 return true; 299 } 300 301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 302 // Lambdas are only default-constructible or assignable in C++2a onwards. 303 if (MD->getParent()->isLambda() && 304 ((isa<CXXConstructorDecl>(MD) && 305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 308 << !isa<CXXConstructorDecl>(MD); 309 } 310 } 311 312 auto getReferencedObjCProp = [](const NamedDecl *D) -> 313 const ObjCPropertyDecl * { 314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 315 return MD->findPropertyDecl(); 316 return nullptr; 317 }; 318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 320 return true; 321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 322 return true; 323 } 324 325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 326 // Only the variables omp_in and omp_out are allowed in the combiner. 327 // Only the variables omp_priv and omp_orig are allowed in the 328 // initializer-clause. 329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 331 isa<VarDecl>(D)) { 332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 333 << getCurFunction()->HasOMPDeclareReductionCombiner; 334 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 335 return true; 336 } 337 338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 339 // List-items in map clauses on this construct may only refer to the declared 340 // variable var and entities that could be referenced by a procedure defined 341 // at the same location 342 if (LangOpts.OpenMP && isa<VarDecl>(D) && 343 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 344 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 345 << getOpenMPDeclareMapperVarName(); 346 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 347 return true; 348 } 349 350 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 351 AvoidPartialAvailabilityChecks, ClassReceiver); 352 353 DiagnoseUnusedOfDecl(*this, D, Loc); 354 355 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 356 357 // CUDA/HIP: Diagnose invalid references of host global variables in device 358 // functions. Reference of device global variables in host functions is 359 // allowed through shadow variables therefore it is not diagnosed. 360 if (LangOpts.CUDAIsDevice) { 361 auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); 362 auto Target = IdentifyCUDATarget(FD); 363 if (FD && Target != CFT_Host) { 364 const auto *VD = dyn_cast<VarDecl>(D); 365 if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && 366 !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && 367 !VD->getType()->isCUDADeviceBuiltinSurfaceType() && 368 !VD->getType()->isCUDADeviceBuiltinTextureType() && 369 !VD->isConstexpr() && !VD->getType().isConstQualified()) 370 targetDiag(*Locs.begin(), diag::err_ref_bad_target) 371 << /*host*/ 2 << /*variable*/ 1 << VD << Target; 372 } 373 } 374 375 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 376 if (const auto *VD = dyn_cast<ValueDecl>(D)) 377 checkDeviceDecl(VD, Loc); 378 379 if (!Context.getTargetInfo().isTLSSupported()) 380 if (const auto *VD = dyn_cast<VarDecl>(D)) 381 if (VD->getTLSKind() != VarDecl::TLS_None) 382 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 383 } 384 385 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 386 !isUnevaluatedContext()) { 387 // C++ [expr.prim.req.nested] p3 388 // A local parameter shall only appear as an unevaluated operand 389 // (Clause 8) within the constraint-expression. 390 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 391 << D; 392 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 393 return true; 394 } 395 396 return false; 397 } 398 399 /// DiagnoseSentinelCalls - This routine checks whether a call or 400 /// message-send is to a declaration with the sentinel attribute, and 401 /// if so, it checks that the requirements of the sentinel are 402 /// satisfied. 403 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 404 ArrayRef<Expr *> Args) { 405 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 406 if (!attr) 407 return; 408 409 // The number of formal parameters of the declaration. 410 unsigned numFormalParams; 411 412 // The kind of declaration. This is also an index into a %select in 413 // the diagnostic. 414 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 415 416 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 417 numFormalParams = MD->param_size(); 418 calleeType = CT_Method; 419 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 420 numFormalParams = FD->param_size(); 421 calleeType = CT_Function; 422 } else if (isa<VarDecl>(D)) { 423 QualType type = cast<ValueDecl>(D)->getType(); 424 const FunctionType *fn = nullptr; 425 if (const PointerType *ptr = type->getAs<PointerType>()) { 426 fn = ptr->getPointeeType()->getAs<FunctionType>(); 427 if (!fn) return; 428 calleeType = CT_Function; 429 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 430 fn = ptr->getPointeeType()->castAs<FunctionType>(); 431 calleeType = CT_Block; 432 } else { 433 return; 434 } 435 436 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 437 numFormalParams = proto->getNumParams(); 438 } else { 439 numFormalParams = 0; 440 } 441 } else { 442 return; 443 } 444 445 // "nullPos" is the number of formal parameters at the end which 446 // effectively count as part of the variadic arguments. This is 447 // useful if you would prefer to not have *any* formal parameters, 448 // but the language forces you to have at least one. 449 unsigned nullPos = attr->getNullPos(); 450 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 451 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 452 453 // The number of arguments which should follow the sentinel. 454 unsigned numArgsAfterSentinel = attr->getSentinel(); 455 456 // If there aren't enough arguments for all the formal parameters, 457 // the sentinel, and the args after the sentinel, complain. 458 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 459 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 460 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 461 return; 462 } 463 464 // Otherwise, find the sentinel expression. 465 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 466 if (!sentinelExpr) return; 467 if (sentinelExpr->isValueDependent()) return; 468 if (Context.isSentinelNullExpr(sentinelExpr)) return; 469 470 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 471 // or 'NULL' if those are actually defined in the context. Only use 472 // 'nil' for ObjC methods, where it's much more likely that the 473 // variadic arguments form a list of object pointers. 474 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 475 std::string NullValue; 476 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 477 NullValue = "nil"; 478 else if (getLangOpts().CPlusPlus11) 479 NullValue = "nullptr"; 480 else if (PP.isMacroDefined("NULL")) 481 NullValue = "NULL"; 482 else 483 NullValue = "(void*) 0"; 484 485 if (MissingNilLoc.isInvalid()) 486 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 487 else 488 Diag(MissingNilLoc, diag::warn_missing_sentinel) 489 << int(calleeType) 490 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 491 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 492 } 493 494 SourceRange Sema::getExprRange(Expr *E) const { 495 return E ? E->getSourceRange() : SourceRange(); 496 } 497 498 //===----------------------------------------------------------------------===// 499 // Standard Promotions and Conversions 500 //===----------------------------------------------------------------------===// 501 502 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 503 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 504 // Handle any placeholder expressions which made it here. 505 if (E->getType()->isPlaceholderType()) { 506 ExprResult result = CheckPlaceholderExpr(E); 507 if (result.isInvalid()) return ExprError(); 508 E = result.get(); 509 } 510 511 QualType Ty = E->getType(); 512 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 513 514 if (Ty->isFunctionType()) { 515 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 516 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 517 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 518 return ExprError(); 519 520 E = ImpCastExprToType(E, Context.getPointerType(Ty), 521 CK_FunctionToPointerDecay).get(); 522 } else if (Ty->isArrayType()) { 523 // In C90 mode, arrays only promote to pointers if the array expression is 524 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 525 // type 'array of type' is converted to an expression that has type 'pointer 526 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 527 // that has type 'array of type' ...". The relevant change is "an lvalue" 528 // (C90) to "an expression" (C99). 529 // 530 // C++ 4.2p1: 531 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 532 // T" can be converted to an rvalue of type "pointer to T". 533 // 534 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 535 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 536 CK_ArrayToPointerDecay).get(); 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 675 << FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 ExprResult Res = CheckLValueToRValueConversionOperand(E); 702 if (Res.isInvalid()) 703 return Res; 704 E = Res.get(); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 712 Cleanup.setExprNeedsCleanups(true); 713 714 // C++ [conv.lval]p3: 715 // If T is cv std::nullptr_t, the result is a null pointer constant. 716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 718 CurFPFeatureOverrides()); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_RValue, FPOptionsOverride()); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 // Half FP have to be promoted to float unless it is natively supported 777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 779 780 // Try to perform integral promotions if the object has a theoretically 781 // promotable type. 782 if (Ty->isIntegralOrUnscopedEnumerationType()) { 783 // C99 6.3.1.1p2: 784 // 785 // The following may be used in an expression wherever an int or 786 // unsigned int may be used: 787 // - an object or expression with an integer type whose integer 788 // conversion rank is less than or equal to the rank of int 789 // and unsigned int. 790 // - A bit-field of type _Bool, int, signed int, or unsigned int. 791 // 792 // If an int can represent all values of the original type, the 793 // value is converted to an int; otherwise, it is converted to an 794 // unsigned int. These are called the integer promotions. All 795 // other types are unchanged by the integer promotions. 796 797 QualType PTy = Context.isPromotableBitField(E); 798 if (!PTy.isNull()) { 799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 800 return E; 801 } 802 if (Ty->isPromotableIntegerType()) { 803 QualType PT = Context.getPromotedIntegerType(Ty); 804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 805 return E; 806 } 807 } 808 return E; 809 } 810 811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 812 /// do not have a prototype. Arguments that have type float or __fp16 813 /// are promoted to double. All other argument types are converted by 814 /// UsualUnaryConversions(). 815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 816 QualType Ty = E->getType(); 817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 818 819 ExprResult Res = UsualUnaryConversions(E); 820 if (Res.isInvalid()) 821 return ExprError(); 822 E = Res.get(); 823 824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 825 // promote to double. 826 // Note that default argument promotion applies only to float (and 827 // half/fp16); it does not apply to _Float16. 828 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 829 if (BTy && (BTy->getKind() == BuiltinType::Half || 830 BTy->getKind() == BuiltinType::Float)) { 831 if (getLangOpts().OpenCL && 832 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 833 if (BTy->getKind() == BuiltinType::Half) { 834 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 835 } 836 } else { 837 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 838 } 839 } 840 841 // C++ performs lvalue-to-rvalue conversion as a default argument 842 // promotion, even on class types, but note: 843 // C++11 [conv.lval]p2: 844 // When an lvalue-to-rvalue conversion occurs in an unevaluated 845 // operand or a subexpression thereof the value contained in the 846 // referenced object is not accessed. Otherwise, if the glvalue 847 // has a class type, the conversion copy-initializes a temporary 848 // of type T from the glvalue and the result of the conversion 849 // is a prvalue for the temporary. 850 // FIXME: add some way to gate this entire thing for correctness in 851 // potentially potentially evaluated contexts. 852 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 853 ExprResult Temp = PerformCopyInitialization( 854 InitializedEntity::InitializeTemporary(E->getType()), 855 E->getExprLoc(), E); 856 if (Temp.isInvalid()) 857 return ExprError(); 858 E = Temp.get(); 859 } 860 861 return E; 862 } 863 864 /// Determine the degree of POD-ness for an expression. 865 /// Incomplete types are considered POD, since this check can be performed 866 /// when we're in an unevaluated context. 867 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 868 if (Ty->isIncompleteType()) { 869 // C++11 [expr.call]p7: 870 // After these conversions, if the argument does not have arithmetic, 871 // enumeration, pointer, pointer to member, or class type, the program 872 // is ill-formed. 873 // 874 // Since we've already performed array-to-pointer and function-to-pointer 875 // decay, the only such type in C++ is cv void. This also handles 876 // initializer lists as variadic arguments. 877 if (Ty->isVoidType()) 878 return VAK_Invalid; 879 880 if (Ty->isObjCObjectType()) 881 return VAK_Invalid; 882 return VAK_Valid; 883 } 884 885 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 886 return VAK_Invalid; 887 888 if (Ty.isCXX98PODType(Context)) 889 return VAK_Valid; 890 891 // C++11 [expr.call]p7: 892 // Passing a potentially-evaluated argument of class type (Clause 9) 893 // having a non-trivial copy constructor, a non-trivial move constructor, 894 // or a non-trivial destructor, with no corresponding parameter, 895 // is conditionally-supported with implementation-defined semantics. 896 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 897 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 898 if (!Record->hasNonTrivialCopyConstructor() && 899 !Record->hasNonTrivialMoveConstructor() && 900 !Record->hasNonTrivialDestructor()) 901 return VAK_ValidInCXX11; 902 903 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 904 return VAK_Valid; 905 906 if (Ty->isObjCObjectType()) 907 return VAK_Invalid; 908 909 if (getLangOpts().MSVCCompat) 910 return VAK_MSVCUndefined; 911 912 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 913 // permitted to reject them. We should consider doing so. 914 return VAK_Undefined; 915 } 916 917 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 918 // Don't allow one to pass an Objective-C interface to a vararg. 919 const QualType &Ty = E->getType(); 920 VarArgKind VAK = isValidVarArgType(Ty); 921 922 // Complain about passing non-POD types through varargs. 923 switch (VAK) { 924 case VAK_ValidInCXX11: 925 DiagRuntimeBehavior( 926 E->getBeginLoc(), nullptr, 927 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 928 LLVM_FALLTHROUGH; 929 case VAK_Valid: 930 if (Ty->isRecordType()) { 931 // This is unlikely to be what the user intended. If the class has a 932 // 'c_str' member function, the user probably meant to call that. 933 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 934 PDiag(diag::warn_pass_class_arg_to_vararg) 935 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 936 } 937 break; 938 939 case VAK_Undefined: 940 case VAK_MSVCUndefined: 941 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 942 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 943 << getLangOpts().CPlusPlus11 << Ty << CT); 944 break; 945 946 case VAK_Invalid: 947 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 948 Diag(E->getBeginLoc(), 949 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 950 << Ty << CT; 951 else if (Ty->isObjCObjectType()) 952 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 953 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 954 << Ty << CT); 955 else 956 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 957 << isa<InitListExpr>(E) << Ty << CT; 958 break; 959 } 960 } 961 962 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 963 /// will create a trap if the resulting type is not a POD type. 964 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 965 FunctionDecl *FDecl) { 966 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 967 // Strip the unbridged-cast placeholder expression off, if applicable. 968 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 969 (CT == VariadicMethod || 970 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 971 E = stripARCUnbridgedCast(E); 972 973 // Otherwise, do normal placeholder checking. 974 } else { 975 ExprResult ExprRes = CheckPlaceholderExpr(E); 976 if (ExprRes.isInvalid()) 977 return ExprError(); 978 E = ExprRes.get(); 979 } 980 } 981 982 ExprResult ExprRes = DefaultArgumentPromotion(E); 983 if (ExprRes.isInvalid()) 984 return ExprError(); 985 986 // Copy blocks to the heap. 987 if (ExprRes.get()->getType()->isBlockPointerType()) 988 maybeExtendBlockObject(ExprRes); 989 990 E = ExprRes.get(); 991 992 // Diagnostics regarding non-POD argument types are 993 // emitted along with format string checking in Sema::CheckFunctionCall(). 994 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 995 // Turn this into a trap. 996 CXXScopeSpec SS; 997 SourceLocation TemplateKWLoc; 998 UnqualifiedId Name; 999 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1000 E->getBeginLoc()); 1001 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1002 /*HasTrailingLParen=*/true, 1003 /*IsAddressOfOperand=*/false); 1004 if (TrapFn.isInvalid()) 1005 return ExprError(); 1006 1007 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1008 None, E->getEndLoc()); 1009 if (Call.isInvalid()) 1010 return ExprError(); 1011 1012 ExprResult Comma = 1013 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1014 if (Comma.isInvalid()) 1015 return ExprError(); 1016 return Comma.get(); 1017 } 1018 1019 if (!getLangOpts().CPlusPlus && 1020 RequireCompleteType(E->getExprLoc(), E->getType(), 1021 diag::err_call_incomplete_argument)) 1022 return ExprError(); 1023 1024 return E; 1025 } 1026 1027 /// Converts an integer to complex float type. Helper function of 1028 /// UsualArithmeticConversions() 1029 /// 1030 /// \return false if the integer expression is an integer type and is 1031 /// successfully converted to the complex type. 1032 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1033 ExprResult &ComplexExpr, 1034 QualType IntTy, 1035 QualType ComplexTy, 1036 bool SkipCast) { 1037 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1038 if (SkipCast) return false; 1039 if (IntTy->isIntegerType()) { 1040 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1041 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1042 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1043 CK_FloatingRealToComplex); 1044 } else { 1045 assert(IntTy->isComplexIntegerType()); 1046 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1047 CK_IntegralComplexToFloatingComplex); 1048 } 1049 return false; 1050 } 1051 1052 /// Handle arithmetic conversion with complex types. Helper function of 1053 /// UsualArithmeticConversions() 1054 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1055 ExprResult &RHS, QualType LHSType, 1056 QualType RHSType, 1057 bool IsCompAssign) { 1058 // if we have an integer operand, the result is the complex type. 1059 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1060 /*skipCast*/false)) 1061 return LHSType; 1062 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1063 /*skipCast*/IsCompAssign)) 1064 return RHSType; 1065 1066 // This handles complex/complex, complex/float, or float/complex. 1067 // When both operands are complex, the shorter operand is converted to the 1068 // type of the longer, and that is the type of the result. This corresponds 1069 // to what is done when combining two real floating-point operands. 1070 // The fun begins when size promotion occur across type domains. 1071 // From H&S 6.3.4: When one operand is complex and the other is a real 1072 // floating-point type, the less precise type is converted, within it's 1073 // real or complex domain, to the precision of the other type. For example, 1074 // when combining a "long double" with a "double _Complex", the 1075 // "double _Complex" is promoted to "long double _Complex". 1076 1077 // Compute the rank of the two types, regardless of whether they are complex. 1078 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1079 1080 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1081 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1082 QualType LHSElementType = 1083 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1084 QualType RHSElementType = 1085 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1086 1087 QualType ResultType = S.Context.getComplexType(LHSElementType); 1088 if (Order < 0) { 1089 // Promote the precision of the LHS if not an assignment. 1090 ResultType = S.Context.getComplexType(RHSElementType); 1091 if (!IsCompAssign) { 1092 if (LHSComplexType) 1093 LHS = 1094 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1095 else 1096 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1097 } 1098 } else if (Order > 0) { 1099 // Promote the precision of the RHS. 1100 if (RHSComplexType) 1101 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1102 else 1103 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1104 } 1105 return ResultType; 1106 } 1107 1108 /// Handle arithmetic conversion from integer to float. Helper function 1109 /// of UsualArithmeticConversions() 1110 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1111 ExprResult &IntExpr, 1112 QualType FloatTy, QualType IntTy, 1113 bool ConvertFloat, bool ConvertInt) { 1114 if (IntTy->isIntegerType()) { 1115 if (ConvertInt) 1116 // Convert intExpr to the lhs floating point type. 1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1118 CK_IntegralToFloating); 1119 return FloatTy; 1120 } 1121 1122 // Convert both sides to the appropriate complex float. 1123 assert(IntTy->isComplexIntegerType()); 1124 QualType result = S.Context.getComplexType(FloatTy); 1125 1126 // _Complex int -> _Complex float 1127 if (ConvertInt) 1128 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1129 CK_IntegralComplexToFloatingComplex); 1130 1131 // float -> _Complex float 1132 if (ConvertFloat) 1133 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1134 CK_FloatingRealToComplex); 1135 1136 return result; 1137 } 1138 1139 /// Handle arithmethic conversion with floating point types. Helper 1140 /// function of UsualArithmeticConversions() 1141 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1142 ExprResult &RHS, QualType LHSType, 1143 QualType RHSType, bool IsCompAssign) { 1144 bool LHSFloat = LHSType->isRealFloatingType(); 1145 bool RHSFloat = RHSType->isRealFloatingType(); 1146 1147 // N1169 4.1.4: If one of the operands has a floating type and the other 1148 // operand has a fixed-point type, the fixed-point operand 1149 // is converted to the floating type [...] 1150 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1151 if (LHSFloat) 1152 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1153 else if (!IsCompAssign) 1154 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1155 return LHSFloat ? LHSType : RHSType; 1156 } 1157 1158 // If we have two real floating types, convert the smaller operand 1159 // to the bigger result. 1160 if (LHSFloat && RHSFloat) { 1161 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1162 if (order > 0) { 1163 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1164 return LHSType; 1165 } 1166 1167 assert(order < 0 && "illegal float comparison"); 1168 if (!IsCompAssign) 1169 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1170 return RHSType; 1171 } 1172 1173 if (LHSFloat) { 1174 // Half FP has to be promoted to float unless it is natively supported 1175 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1176 LHSType = S.Context.FloatTy; 1177 1178 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1179 /*ConvertFloat=*/!IsCompAssign, 1180 /*ConvertInt=*/ true); 1181 } 1182 assert(RHSFloat); 1183 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1184 /*ConvertFloat=*/ true, 1185 /*ConvertInt=*/!IsCompAssign); 1186 } 1187 1188 /// Diagnose attempts to convert between __float128 and long double if 1189 /// there is no support for such conversion. Helper function of 1190 /// UsualArithmeticConversions(). 1191 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1192 QualType RHSType) { 1193 /* No issue converting if at least one of the types is not a floating point 1194 type or the two types have the same rank. 1195 */ 1196 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1197 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1198 return false; 1199 1200 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1201 "The remaining types must be floating point types."); 1202 1203 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1204 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1205 1206 QualType LHSElemType = LHSComplex ? 1207 LHSComplex->getElementType() : LHSType; 1208 QualType RHSElemType = RHSComplex ? 1209 RHSComplex->getElementType() : RHSType; 1210 1211 // No issue if the two types have the same representation 1212 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1213 &S.Context.getFloatTypeSemantics(RHSElemType)) 1214 return false; 1215 1216 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1217 RHSElemType == S.Context.LongDoubleTy); 1218 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1219 RHSElemType == S.Context.Float128Ty); 1220 1221 // We've handled the situation where __float128 and long double have the same 1222 // representation. We allow all conversions for all possible long double types 1223 // except PPC's double double. 1224 return Float128AndLongDouble && 1225 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1226 &llvm::APFloat::PPCDoubleDouble()); 1227 } 1228 1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1230 1231 namespace { 1232 /// These helper callbacks are placed in an anonymous namespace to 1233 /// permit their use as function template parameters. 1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1235 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1236 } 1237 1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1239 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1240 CK_IntegralComplexCast); 1241 } 1242 } 1243 1244 /// Handle integer arithmetic conversions. Helper function of 1245 /// UsualArithmeticConversions() 1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1248 ExprResult &RHS, QualType LHSType, 1249 QualType RHSType, bool IsCompAssign) { 1250 // The rules for this case are in C99 6.3.1.8 1251 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1252 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1253 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1254 if (LHSSigned == RHSSigned) { 1255 // Same signedness; use the higher-ranked type 1256 if (order >= 0) { 1257 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1258 return LHSType; 1259 } else if (!IsCompAssign) 1260 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1261 return RHSType; 1262 } else if (order != (LHSSigned ? 1 : -1)) { 1263 // The unsigned type has greater than or equal rank to the 1264 // signed type, so use the unsigned type 1265 if (RHSSigned) { 1266 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1267 return LHSType; 1268 } else if (!IsCompAssign) 1269 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1270 return RHSType; 1271 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1272 // The two types are different widths; if we are here, that 1273 // means the signed type is larger than the unsigned type, so 1274 // use the signed type. 1275 if (LHSSigned) { 1276 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1277 return LHSType; 1278 } else if (!IsCompAssign) 1279 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1280 return RHSType; 1281 } else { 1282 // The signed type is higher-ranked than the unsigned type, 1283 // but isn't actually any bigger (like unsigned int and long 1284 // on most 32-bit systems). Use the unsigned type corresponding 1285 // to the signed type. 1286 QualType result = 1287 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1288 RHS = (*doRHSCast)(S, RHS.get(), result); 1289 if (!IsCompAssign) 1290 LHS = (*doLHSCast)(S, LHS.get(), result); 1291 return result; 1292 } 1293 } 1294 1295 /// Handle conversions with GCC complex int extension. Helper function 1296 /// of UsualArithmeticConversions() 1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1298 ExprResult &RHS, QualType LHSType, 1299 QualType RHSType, 1300 bool IsCompAssign) { 1301 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1302 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1303 1304 if (LHSComplexInt && RHSComplexInt) { 1305 QualType LHSEltType = LHSComplexInt->getElementType(); 1306 QualType RHSEltType = RHSComplexInt->getElementType(); 1307 QualType ScalarType = 1308 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1309 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1310 1311 return S.Context.getComplexType(ScalarType); 1312 } 1313 1314 if (LHSComplexInt) { 1315 QualType LHSEltType = LHSComplexInt->getElementType(); 1316 QualType ScalarType = 1317 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1318 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1319 QualType ComplexType = S.Context.getComplexType(ScalarType); 1320 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1321 CK_IntegralRealToComplex); 1322 1323 return ComplexType; 1324 } 1325 1326 assert(RHSComplexInt); 1327 1328 QualType RHSEltType = RHSComplexInt->getElementType(); 1329 QualType ScalarType = 1330 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1331 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1332 QualType ComplexType = S.Context.getComplexType(ScalarType); 1333 1334 if (!IsCompAssign) 1335 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1336 CK_IntegralRealToComplex); 1337 return ComplexType; 1338 } 1339 1340 /// Return the rank of a given fixed point or integer type. The value itself 1341 /// doesn't matter, but the values must be increasing with proper increasing 1342 /// rank as described in N1169 4.1.1. 1343 static unsigned GetFixedPointRank(QualType Ty) { 1344 const auto *BTy = Ty->getAs<BuiltinType>(); 1345 assert(BTy && "Expected a builtin type."); 1346 1347 switch (BTy->getKind()) { 1348 case BuiltinType::ShortFract: 1349 case BuiltinType::UShortFract: 1350 case BuiltinType::SatShortFract: 1351 case BuiltinType::SatUShortFract: 1352 return 1; 1353 case BuiltinType::Fract: 1354 case BuiltinType::UFract: 1355 case BuiltinType::SatFract: 1356 case BuiltinType::SatUFract: 1357 return 2; 1358 case BuiltinType::LongFract: 1359 case BuiltinType::ULongFract: 1360 case BuiltinType::SatLongFract: 1361 case BuiltinType::SatULongFract: 1362 return 3; 1363 case BuiltinType::ShortAccum: 1364 case BuiltinType::UShortAccum: 1365 case BuiltinType::SatShortAccum: 1366 case BuiltinType::SatUShortAccum: 1367 return 4; 1368 case BuiltinType::Accum: 1369 case BuiltinType::UAccum: 1370 case BuiltinType::SatAccum: 1371 case BuiltinType::SatUAccum: 1372 return 5; 1373 case BuiltinType::LongAccum: 1374 case BuiltinType::ULongAccum: 1375 case BuiltinType::SatLongAccum: 1376 case BuiltinType::SatULongAccum: 1377 return 6; 1378 default: 1379 if (BTy->isInteger()) 1380 return 0; 1381 llvm_unreachable("Unexpected fixed point or integer type"); 1382 } 1383 } 1384 1385 /// handleFixedPointConversion - Fixed point operations between fixed 1386 /// point types and integers or other fixed point types do not fall under 1387 /// usual arithmetic conversion since these conversions could result in loss 1388 /// of precsision (N1169 4.1.4). These operations should be calculated with 1389 /// the full precision of their result type (N1169 4.1.6.2.1). 1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1391 QualType RHSTy) { 1392 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1393 "Expected at least one of the operands to be a fixed point type"); 1394 assert((LHSTy->isFixedPointOrIntegerType() || 1395 RHSTy->isFixedPointOrIntegerType()) && 1396 "Special fixed point arithmetic operation conversions are only " 1397 "applied to ints or other fixed point types"); 1398 1399 // If one operand has signed fixed-point type and the other operand has 1400 // unsigned fixed-point type, then the unsigned fixed-point operand is 1401 // converted to its corresponding signed fixed-point type and the resulting 1402 // type is the type of the converted operand. 1403 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1404 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1405 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1406 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1407 1408 // The result type is the type with the highest rank, whereby a fixed-point 1409 // conversion rank is always greater than an integer conversion rank; if the 1410 // type of either of the operands is a saturating fixedpoint type, the result 1411 // type shall be the saturating fixed-point type corresponding to the type 1412 // with the highest rank; the resulting value is converted (taking into 1413 // account rounding and overflow) to the precision of the resulting type. 1414 // Same ranks between signed and unsigned types are resolved earlier, so both 1415 // types are either signed or both unsigned at this point. 1416 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1417 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1418 1419 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1420 1421 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1422 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1423 1424 return ResultTy; 1425 } 1426 1427 /// Check that the usual arithmetic conversions can be performed on this pair of 1428 /// expressions that might be of enumeration type. 1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1430 SourceLocation Loc, 1431 Sema::ArithConvKind ACK) { 1432 // C++2a [expr.arith.conv]p1: 1433 // If one operand is of enumeration type and the other operand is of a 1434 // different enumeration type or a floating-point type, this behavior is 1435 // deprecated ([depr.arith.conv.enum]). 1436 // 1437 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1438 // Eventually we will presumably reject these cases (in C++23 onwards?). 1439 QualType L = LHS->getType(), R = RHS->getType(); 1440 bool LEnum = L->isUnscopedEnumerationType(), 1441 REnum = R->isUnscopedEnumerationType(); 1442 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1443 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1444 (REnum && L->isFloatingType())) { 1445 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1446 ? diag::warn_arith_conv_enum_float_cxx20 1447 : diag::warn_arith_conv_enum_float) 1448 << LHS->getSourceRange() << RHS->getSourceRange() 1449 << (int)ACK << LEnum << L << R; 1450 } else if (!IsCompAssign && LEnum && REnum && 1451 !S.Context.hasSameUnqualifiedType(L, R)) { 1452 unsigned DiagID; 1453 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1454 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1455 // If either enumeration type is unnamed, it's less likely that the 1456 // user cares about this, but this situation is still deprecated in 1457 // C++2a. Use a different warning group. 1458 DiagID = S.getLangOpts().CPlusPlus20 1459 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1460 : diag::warn_arith_conv_mixed_anon_enum_types; 1461 } else if (ACK == Sema::ACK_Conditional) { 1462 // Conditional expressions are separated out because they have 1463 // historically had a different warning flag. 1464 DiagID = S.getLangOpts().CPlusPlus20 1465 ? diag::warn_conditional_mixed_enum_types_cxx20 1466 : diag::warn_conditional_mixed_enum_types; 1467 } else if (ACK == Sema::ACK_Comparison) { 1468 // Comparison expressions are separated out because they have 1469 // historically had a different warning flag. 1470 DiagID = S.getLangOpts().CPlusPlus20 1471 ? diag::warn_comparison_mixed_enum_types_cxx20 1472 : diag::warn_comparison_mixed_enum_types; 1473 } else { 1474 DiagID = S.getLangOpts().CPlusPlus20 1475 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1476 : diag::warn_arith_conv_mixed_enum_types; 1477 } 1478 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1479 << (int)ACK << L << R; 1480 } 1481 } 1482 1483 /// UsualArithmeticConversions - Performs various conversions that are common to 1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1485 /// routine returns the first non-arithmetic type found. The client is 1486 /// responsible for emitting appropriate error diagnostics. 1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1488 SourceLocation Loc, 1489 ArithConvKind ACK) { 1490 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1491 1492 if (ACK != ACK_CompAssign) { 1493 LHS = UsualUnaryConversions(LHS.get()); 1494 if (LHS.isInvalid()) 1495 return QualType(); 1496 } 1497 1498 RHS = UsualUnaryConversions(RHS.get()); 1499 if (RHS.isInvalid()) 1500 return QualType(); 1501 1502 // For conversion purposes, we ignore any qualifiers. 1503 // For example, "const float" and "float" are equivalent. 1504 QualType LHSType = 1505 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1506 QualType RHSType = 1507 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1508 1509 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1510 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1511 LHSType = AtomicLHS->getValueType(); 1512 1513 // If both types are identical, no conversion is needed. 1514 if (LHSType == RHSType) 1515 return LHSType; 1516 1517 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1518 // The caller can deal with this (e.g. pointer + int). 1519 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1520 return QualType(); 1521 1522 // Apply unary and bitfield promotions to the LHS's type. 1523 QualType LHSUnpromotedType = LHSType; 1524 if (LHSType->isPromotableIntegerType()) 1525 LHSType = Context.getPromotedIntegerType(LHSType); 1526 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1527 if (!LHSBitfieldPromoteTy.isNull()) 1528 LHSType = LHSBitfieldPromoteTy; 1529 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1530 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1531 1532 // If both types are identical, no conversion is needed. 1533 if (LHSType == RHSType) 1534 return LHSType; 1535 1536 // ExtInt types aren't subject to conversions between them or normal integers, 1537 // so this fails. 1538 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1539 return QualType(); 1540 1541 // At this point, we have two different arithmetic types. 1542 1543 // Diagnose attempts to convert between __float128 and long double where 1544 // such conversions currently can't be handled. 1545 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1546 return QualType(); 1547 1548 // Handle complex types first (C99 6.3.1.8p1). 1549 if (LHSType->isComplexType() || RHSType->isComplexType()) 1550 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1551 ACK == ACK_CompAssign); 1552 1553 // Now handle "real" floating types (i.e. float, double, long double). 1554 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1555 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1556 ACK == ACK_CompAssign); 1557 1558 // Handle GCC complex int extension. 1559 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1560 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1561 ACK == ACK_CompAssign); 1562 1563 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1564 return handleFixedPointConversion(*this, LHSType, RHSType); 1565 1566 // Finally, we have two differing integer types. 1567 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1568 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1569 } 1570 1571 //===----------------------------------------------------------------------===// 1572 // Semantic Analysis for various Expression Types 1573 //===----------------------------------------------------------------------===// 1574 1575 1576 ExprResult 1577 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1578 SourceLocation DefaultLoc, 1579 SourceLocation RParenLoc, 1580 Expr *ControllingExpr, 1581 ArrayRef<ParsedType> ArgTypes, 1582 ArrayRef<Expr *> ArgExprs) { 1583 unsigned NumAssocs = ArgTypes.size(); 1584 assert(NumAssocs == ArgExprs.size()); 1585 1586 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1587 for (unsigned i = 0; i < NumAssocs; ++i) { 1588 if (ArgTypes[i]) 1589 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1590 else 1591 Types[i] = nullptr; 1592 } 1593 1594 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1595 ControllingExpr, 1596 llvm::makeArrayRef(Types, NumAssocs), 1597 ArgExprs); 1598 delete [] Types; 1599 return ER; 1600 } 1601 1602 ExprResult 1603 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1604 SourceLocation DefaultLoc, 1605 SourceLocation RParenLoc, 1606 Expr *ControllingExpr, 1607 ArrayRef<TypeSourceInfo *> Types, 1608 ArrayRef<Expr *> Exprs) { 1609 unsigned NumAssocs = Types.size(); 1610 assert(NumAssocs == Exprs.size()); 1611 1612 // Decay and strip qualifiers for the controlling expression type, and handle 1613 // placeholder type replacement. See committee discussion from WG14 DR423. 1614 { 1615 EnterExpressionEvaluationContext Unevaluated( 1616 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1617 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1618 if (R.isInvalid()) 1619 return ExprError(); 1620 ControllingExpr = R.get(); 1621 } 1622 1623 // The controlling expression is an unevaluated operand, so side effects are 1624 // likely unintended. 1625 if (!inTemplateInstantiation() && 1626 ControllingExpr->HasSideEffects(Context, false)) 1627 Diag(ControllingExpr->getExprLoc(), 1628 diag::warn_side_effects_unevaluated_context); 1629 1630 bool TypeErrorFound = false, 1631 IsResultDependent = ControllingExpr->isTypeDependent(), 1632 ContainsUnexpandedParameterPack 1633 = ControllingExpr->containsUnexpandedParameterPack(); 1634 1635 for (unsigned i = 0; i < NumAssocs; ++i) { 1636 if (Exprs[i]->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]) { 1640 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1641 ContainsUnexpandedParameterPack = true; 1642 1643 if (Types[i]->getType()->isDependentType()) { 1644 IsResultDependent = true; 1645 } else { 1646 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1647 // complete object type other than a variably modified type." 1648 unsigned D = 0; 1649 if (Types[i]->getType()->isIncompleteType()) 1650 D = diag::err_assoc_type_incomplete; 1651 else if (!Types[i]->getType()->isObjectType()) 1652 D = diag::err_assoc_type_nonobject; 1653 else if (Types[i]->getType()->isVariablyModifiedType()) 1654 D = diag::err_assoc_type_variably_modified; 1655 1656 if (D != 0) { 1657 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1658 << Types[i]->getTypeLoc().getSourceRange() 1659 << Types[i]->getType(); 1660 TypeErrorFound = true; 1661 } 1662 1663 // C11 6.5.1.1p2 "No two generic associations in the same generic 1664 // selection shall specify compatible types." 1665 for (unsigned j = i+1; j < NumAssocs; ++j) 1666 if (Types[j] && !Types[j]->getType()->isDependentType() && 1667 Context.typesAreCompatible(Types[i]->getType(), 1668 Types[j]->getType())) { 1669 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1670 diag::err_assoc_compatible_types) 1671 << Types[j]->getTypeLoc().getSourceRange() 1672 << Types[j]->getType() 1673 << Types[i]->getType(); 1674 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1675 diag::note_compat_assoc) 1676 << Types[i]->getTypeLoc().getSourceRange() 1677 << Types[i]->getType(); 1678 TypeErrorFound = true; 1679 } 1680 } 1681 } 1682 } 1683 if (TypeErrorFound) 1684 return ExprError(); 1685 1686 // If we determined that the generic selection is result-dependent, don't 1687 // try to compute the result expression. 1688 if (IsResultDependent) 1689 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1690 Exprs, DefaultLoc, RParenLoc, 1691 ContainsUnexpandedParameterPack); 1692 1693 SmallVector<unsigned, 1> CompatIndices; 1694 unsigned DefaultIndex = -1U; 1695 for (unsigned i = 0; i < NumAssocs; ++i) { 1696 if (!Types[i]) 1697 DefaultIndex = i; 1698 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1699 Types[i]->getType())) 1700 CompatIndices.push_back(i); 1701 } 1702 1703 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1704 // type compatible with at most one of the types named in its generic 1705 // association list." 1706 if (CompatIndices.size() > 1) { 1707 // We strip parens here because the controlling expression is typically 1708 // parenthesized in macro definitions. 1709 ControllingExpr = ControllingExpr->IgnoreParens(); 1710 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1711 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1712 << (unsigned)CompatIndices.size(); 1713 for (unsigned I : CompatIndices) { 1714 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1715 diag::note_compat_assoc) 1716 << Types[I]->getTypeLoc().getSourceRange() 1717 << Types[I]->getType(); 1718 } 1719 return ExprError(); 1720 } 1721 1722 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1723 // its controlling expression shall have type compatible with exactly one of 1724 // the types named in its generic association list." 1725 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1726 // We strip parens here because the controlling expression is typically 1727 // parenthesized in macro definitions. 1728 ControllingExpr = ControllingExpr->IgnoreParens(); 1729 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1730 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1731 return ExprError(); 1732 } 1733 1734 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1735 // type name that is compatible with the type of the controlling expression, 1736 // then the result expression of the generic selection is the expression 1737 // in that generic association. Otherwise, the result expression of the 1738 // generic selection is the expression in the default generic association." 1739 unsigned ResultIndex = 1740 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1741 1742 return GenericSelectionExpr::Create( 1743 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1744 ContainsUnexpandedParameterPack, ResultIndex); 1745 } 1746 1747 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1748 /// location of the token and the offset of the ud-suffix within it. 1749 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1750 unsigned Offset) { 1751 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1752 S.getLangOpts()); 1753 } 1754 1755 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1756 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1757 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1758 IdentifierInfo *UDSuffix, 1759 SourceLocation UDSuffixLoc, 1760 ArrayRef<Expr*> Args, 1761 SourceLocation LitEndLoc) { 1762 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1763 1764 QualType ArgTy[2]; 1765 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1766 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1767 if (ArgTy[ArgIdx]->isArrayType()) 1768 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1769 } 1770 1771 DeclarationName OpName = 1772 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1773 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1774 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1775 1776 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1777 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1778 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1779 /*AllowStringTemplatePack*/ false, 1780 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1781 return ExprError(); 1782 1783 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1784 } 1785 1786 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1787 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1788 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1789 /// multiple tokens. However, the common case is that StringToks points to one 1790 /// string. 1791 /// 1792 ExprResult 1793 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1794 assert(!StringToks.empty() && "Must have at least one string!"); 1795 1796 StringLiteralParser Literal(StringToks, PP); 1797 if (Literal.hadError) 1798 return ExprError(); 1799 1800 SmallVector<SourceLocation, 4> StringTokLocs; 1801 for (const Token &Tok : StringToks) 1802 StringTokLocs.push_back(Tok.getLocation()); 1803 1804 QualType CharTy = Context.CharTy; 1805 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1806 if (Literal.isWide()) { 1807 CharTy = Context.getWideCharType(); 1808 Kind = StringLiteral::Wide; 1809 } else if (Literal.isUTF8()) { 1810 if (getLangOpts().Char8) 1811 CharTy = Context.Char8Ty; 1812 Kind = StringLiteral::UTF8; 1813 } else if (Literal.isUTF16()) { 1814 CharTy = Context.Char16Ty; 1815 Kind = StringLiteral::UTF16; 1816 } else if (Literal.isUTF32()) { 1817 CharTy = Context.Char32Ty; 1818 Kind = StringLiteral::UTF32; 1819 } else if (Literal.isPascal()) { 1820 CharTy = Context.UnsignedCharTy; 1821 } 1822 1823 // Warn on initializing an array of char from a u8 string literal; this 1824 // becomes ill-formed in C++2a. 1825 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1826 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1827 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1828 1829 // Create removals for all 'u8' prefixes in the string literal(s). This 1830 // ensures C++2a compatibility (but may change the program behavior when 1831 // built by non-Clang compilers for which the execution character set is 1832 // not always UTF-8). 1833 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1834 SourceLocation RemovalDiagLoc; 1835 for (const Token &Tok : StringToks) { 1836 if (Tok.getKind() == tok::utf8_string_literal) { 1837 if (RemovalDiagLoc.isInvalid()) 1838 RemovalDiagLoc = Tok.getLocation(); 1839 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1840 Tok.getLocation(), 1841 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1842 getSourceManager(), getLangOpts()))); 1843 } 1844 } 1845 Diag(RemovalDiagLoc, RemovalDiag); 1846 } 1847 1848 QualType StrTy = 1849 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1850 1851 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1852 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1853 Kind, Literal.Pascal, StrTy, 1854 &StringTokLocs[0], 1855 StringTokLocs.size()); 1856 if (Literal.getUDSuffix().empty()) 1857 return Lit; 1858 1859 // We're building a user-defined literal. 1860 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1861 SourceLocation UDSuffixLoc = 1862 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1863 Literal.getUDSuffixOffset()); 1864 1865 // Make sure we're allowed user-defined literals here. 1866 if (!UDLScope) 1867 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1868 1869 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1870 // operator "" X (str, len) 1871 QualType SizeType = Context.getSizeType(); 1872 1873 DeclarationName OpName = 1874 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1875 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1876 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1877 1878 QualType ArgTy[] = { 1879 Context.getArrayDecayedType(StrTy), SizeType 1880 }; 1881 1882 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1883 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1884 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1885 /*AllowStringTemplatePack*/ true, 1886 /*DiagnoseMissing*/ true, Lit)) { 1887 1888 case LOLR_Cooked: { 1889 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1890 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1891 StringTokLocs[0]); 1892 Expr *Args[] = { Lit, LenArg }; 1893 1894 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1895 } 1896 1897 case LOLR_Template: { 1898 TemplateArgumentListInfo ExplicitArgs; 1899 TemplateArgument Arg(Lit); 1900 TemplateArgumentLocInfo ArgInfo(Lit); 1901 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1902 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1903 &ExplicitArgs); 1904 } 1905 1906 case LOLR_StringTemplatePack: { 1907 TemplateArgumentListInfo ExplicitArgs; 1908 1909 unsigned CharBits = Context.getIntWidth(CharTy); 1910 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1911 llvm::APSInt Value(CharBits, CharIsUnsigned); 1912 1913 TemplateArgument TypeArg(CharTy); 1914 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1915 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1916 1917 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1918 Value = Lit->getCodeUnit(I); 1919 TemplateArgument Arg(Context, Value, CharTy); 1920 TemplateArgumentLocInfo ArgInfo; 1921 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1922 } 1923 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1924 &ExplicitArgs); 1925 } 1926 case LOLR_Raw: 1927 case LOLR_ErrorNoDiagnostic: 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 case LOLR_Error: 1930 return ExprError(); 1931 } 1932 llvm_unreachable("unexpected literal operator lookup result"); 1933 } 1934 1935 DeclRefExpr * 1936 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1937 SourceLocation Loc, 1938 const CXXScopeSpec *SS) { 1939 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1940 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1941 } 1942 1943 DeclRefExpr * 1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1945 const DeclarationNameInfo &NameInfo, 1946 const CXXScopeSpec *SS, NamedDecl *FoundD, 1947 SourceLocation TemplateKWLoc, 1948 const TemplateArgumentListInfo *TemplateArgs) { 1949 NestedNameSpecifierLoc NNS = 1950 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1951 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1952 TemplateArgs); 1953 } 1954 1955 // CUDA/HIP: Check whether a captured reference variable is referencing a 1956 // host variable in a device or host device lambda. 1957 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1958 VarDecl *VD) { 1959 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1960 return false; 1961 assert(VD->getType()->isReferenceType()); 1962 1963 // Check whether the reference variable is referencing a host variable. 1964 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1965 if (!DRE) 1966 return false; 1967 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1968 if (!Referee || !Referee->hasGlobalStorage() || 1969 Referee->hasAttr<CUDADeviceAttr>()) 1970 return false; 1971 1972 // Check whether the current function is a device or host device lambda. 1973 // Check whether the reference variable is a capture by getDeclContext() 1974 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1975 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1976 if (MD && MD->getParent()->isLambda() && 1977 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1978 VD->getDeclContext() != MD) 1979 return true; 1980 1981 return false; 1982 } 1983 1984 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1985 // A declaration named in an unevaluated operand never constitutes an odr-use. 1986 if (isUnevaluatedContext()) 1987 return NOUR_Unevaluated; 1988 1989 // C++2a [basic.def.odr]p4: 1990 // A variable x whose name appears as a potentially-evaluated expression e 1991 // is odr-used by e unless [...] x is a reference that is usable in 1992 // constant expressions. 1993 // CUDA/HIP: 1994 // If a reference variable referencing a host variable is captured in a 1995 // device or host device lambda, the value of the referee must be copied 1996 // to the capture and the reference variable must be treated as odr-use 1997 // since the value of the referee is not known at compile time and must 1998 // be loaded from the captured. 1999 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2000 if (VD->getType()->isReferenceType() && 2001 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2002 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2003 VD->isUsableInConstantExpressions(Context)) 2004 return NOUR_Constant; 2005 } 2006 2007 // All remaining non-variable cases constitute an odr-use. For variables, we 2008 // need to wait and see how the expression is used. 2009 return NOUR_None; 2010 } 2011 2012 /// BuildDeclRefExpr - Build an expression that references a 2013 /// declaration that does not require a closure capture. 2014 DeclRefExpr * 2015 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2016 const DeclarationNameInfo &NameInfo, 2017 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2018 SourceLocation TemplateKWLoc, 2019 const TemplateArgumentListInfo *TemplateArgs) { 2020 bool RefersToCapturedVariable = 2021 isa<VarDecl>(D) && 2022 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2023 2024 DeclRefExpr *E = DeclRefExpr::Create( 2025 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2026 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2027 MarkDeclRefReferenced(E); 2028 2029 // C++ [except.spec]p17: 2030 // An exception-specification is considered to be needed when: 2031 // - in an expression, the function is the unique lookup result or 2032 // the selected member of a set of overloaded functions. 2033 // 2034 // We delay doing this until after we've built the function reference and 2035 // marked it as used so that: 2036 // a) if the function is defaulted, we get errors from defining it before / 2037 // instead of errors from computing its exception specification, and 2038 // b) if the function is a defaulted comparison, we can use the body we 2039 // build when defining it as input to the exception specification 2040 // computation rather than computing a new body. 2041 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2042 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2043 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2044 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2045 } 2046 } 2047 2048 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2049 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2050 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2051 getCurFunction()->recordUseOfWeak(E); 2052 2053 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2054 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2055 FD = IFD->getAnonField(); 2056 if (FD) { 2057 UnusedPrivateFields.remove(FD); 2058 // Just in case we're building an illegal pointer-to-member. 2059 if (FD->isBitField()) 2060 E->setObjectKind(OK_BitField); 2061 } 2062 2063 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2064 // designates a bit-field. 2065 if (auto *BD = dyn_cast<BindingDecl>(D)) 2066 if (auto *BE = BD->getBinding()) 2067 E->setObjectKind(BE->getObjectKind()); 2068 2069 return E; 2070 } 2071 2072 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2073 /// possibly a list of template arguments. 2074 /// 2075 /// If this produces template arguments, it is permitted to call 2076 /// DecomposeTemplateName. 2077 /// 2078 /// This actually loses a lot of source location information for 2079 /// non-standard name kinds; we should consider preserving that in 2080 /// some way. 2081 void 2082 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2083 TemplateArgumentListInfo &Buffer, 2084 DeclarationNameInfo &NameInfo, 2085 const TemplateArgumentListInfo *&TemplateArgs) { 2086 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2087 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2088 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2089 2090 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2091 Id.TemplateId->NumArgs); 2092 translateTemplateArguments(TemplateArgsPtr, Buffer); 2093 2094 TemplateName TName = Id.TemplateId->Template.get(); 2095 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2096 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2097 TemplateArgs = &Buffer; 2098 } else { 2099 NameInfo = GetNameFromUnqualifiedId(Id); 2100 TemplateArgs = nullptr; 2101 } 2102 } 2103 2104 static void emitEmptyLookupTypoDiagnostic( 2105 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2106 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2107 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2108 DeclContext *Ctx = 2109 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2110 if (!TC) { 2111 // Emit a special diagnostic for failed member lookups. 2112 // FIXME: computing the declaration context might fail here (?) 2113 if (Ctx) 2114 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2115 << SS.getRange(); 2116 else 2117 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2118 return; 2119 } 2120 2121 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2122 bool DroppedSpecifier = 2123 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2124 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2125 ? diag::note_implicit_param_decl 2126 : diag::note_previous_decl; 2127 if (!Ctx) 2128 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2129 SemaRef.PDiag(NoteID)); 2130 else 2131 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2132 << Typo << Ctx << DroppedSpecifier 2133 << SS.getRange(), 2134 SemaRef.PDiag(NoteID)); 2135 } 2136 2137 /// Diagnose a lookup that found results in an enclosing class during error 2138 /// recovery. This usually indicates that the results were found in a dependent 2139 /// base class that could not be searched as part of a template definition. 2140 /// Always issues a diagnostic (though this may be only a warning in MS 2141 /// compatibility mode). 2142 /// 2143 /// Return \c true if the error is unrecoverable, or \c false if the caller 2144 /// should attempt to recover using these lookup results. 2145 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2146 // During a default argument instantiation the CurContext points 2147 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2148 // function parameter list, hence add an explicit check. 2149 bool isDefaultArgument = 2150 !CodeSynthesisContexts.empty() && 2151 CodeSynthesisContexts.back().Kind == 2152 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2153 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2154 bool isInstance = CurMethod && CurMethod->isInstance() && 2155 R.getNamingClass() == CurMethod->getParent() && 2156 !isDefaultArgument; 2157 2158 // There are two ways we can find a class-scope declaration during template 2159 // instantiation that we did not find in the template definition: if it is a 2160 // member of a dependent base class, or if it is declared after the point of 2161 // use in the same class. Distinguish these by comparing the class in which 2162 // the member was found to the naming class of the lookup. 2163 unsigned DiagID = diag::err_found_in_dependent_base; 2164 unsigned NoteID = diag::note_member_declared_at; 2165 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2166 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2167 : diag::err_found_later_in_class; 2168 } else if (getLangOpts().MSVCCompat) { 2169 DiagID = diag::ext_found_in_dependent_base; 2170 NoteID = diag::note_dependent_member_use; 2171 } 2172 2173 if (isInstance) { 2174 // Give a code modification hint to insert 'this->'. 2175 Diag(R.getNameLoc(), DiagID) 2176 << R.getLookupName() 2177 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2178 CheckCXXThisCapture(R.getNameLoc()); 2179 } else { 2180 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2181 // they're not shadowed). 2182 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2183 } 2184 2185 for (NamedDecl *D : R) 2186 Diag(D->getLocation(), NoteID); 2187 2188 // Return true if we are inside a default argument instantiation 2189 // and the found name refers to an instance member function, otherwise 2190 // the caller will try to create an implicit member call and this is wrong 2191 // for default arguments. 2192 // 2193 // FIXME: Is this special case necessary? We could allow the caller to 2194 // diagnose this. 2195 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2196 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2197 return true; 2198 } 2199 2200 // Tell the callee to try to recover. 2201 return false; 2202 } 2203 2204 /// Diagnose an empty lookup. 2205 /// 2206 /// \return false if new lookup candidates were found 2207 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2208 CorrectionCandidateCallback &CCC, 2209 TemplateArgumentListInfo *ExplicitTemplateArgs, 2210 ArrayRef<Expr *> Args, TypoExpr **Out) { 2211 DeclarationName Name = R.getLookupName(); 2212 2213 unsigned diagnostic = diag::err_undeclared_var_use; 2214 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2215 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2216 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2217 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2218 diagnostic = diag::err_undeclared_use; 2219 diagnostic_suggest = diag::err_undeclared_use_suggest; 2220 } 2221 2222 // If the original lookup was an unqualified lookup, fake an 2223 // unqualified lookup. This is useful when (for example) the 2224 // original lookup would not have found something because it was a 2225 // dependent name. 2226 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2227 while (DC) { 2228 if (isa<CXXRecordDecl>(DC)) { 2229 LookupQualifiedName(R, DC); 2230 2231 if (!R.empty()) { 2232 // Don't give errors about ambiguities in this lookup. 2233 R.suppressDiagnostics(); 2234 2235 // If there's a best viable function among the results, only mention 2236 // that one in the notes. 2237 OverloadCandidateSet Candidates(R.getNameLoc(), 2238 OverloadCandidateSet::CSK_Normal); 2239 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2240 OverloadCandidateSet::iterator Best; 2241 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2242 OR_Success) { 2243 R.clear(); 2244 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2245 R.resolveKind(); 2246 } 2247 2248 return DiagnoseDependentMemberLookup(R); 2249 } 2250 2251 R.clear(); 2252 } 2253 2254 DC = DC->getLookupParent(); 2255 } 2256 2257 // We didn't find anything, so try to correct for a typo. 2258 TypoCorrection Corrected; 2259 if (S && Out) { 2260 SourceLocation TypoLoc = R.getNameLoc(); 2261 assert(!ExplicitTemplateArgs && 2262 "Diagnosing an empty lookup with explicit template args!"); 2263 *Out = CorrectTypoDelayed( 2264 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2265 [=](const TypoCorrection &TC) { 2266 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2267 diagnostic, diagnostic_suggest); 2268 }, 2269 nullptr, CTK_ErrorRecovery); 2270 if (*Out) 2271 return true; 2272 } else if (S && 2273 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2274 S, &SS, CCC, CTK_ErrorRecovery))) { 2275 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2276 bool DroppedSpecifier = 2277 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2278 R.setLookupName(Corrected.getCorrection()); 2279 2280 bool AcceptableWithRecovery = false; 2281 bool AcceptableWithoutRecovery = false; 2282 NamedDecl *ND = Corrected.getFoundDecl(); 2283 if (ND) { 2284 if (Corrected.isOverloaded()) { 2285 OverloadCandidateSet OCS(R.getNameLoc(), 2286 OverloadCandidateSet::CSK_Normal); 2287 OverloadCandidateSet::iterator Best; 2288 for (NamedDecl *CD : Corrected) { 2289 if (FunctionTemplateDecl *FTD = 2290 dyn_cast<FunctionTemplateDecl>(CD)) 2291 AddTemplateOverloadCandidate( 2292 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2293 Args, OCS); 2294 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2295 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2296 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2297 Args, OCS); 2298 } 2299 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2300 case OR_Success: 2301 ND = Best->FoundDecl; 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 default: 2305 // FIXME: Arbitrarily pick the first declaration for the note. 2306 Corrected.setCorrectionDecl(ND); 2307 break; 2308 } 2309 } 2310 R.addDecl(ND); 2311 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2312 CXXRecordDecl *Record = nullptr; 2313 if (Corrected.getCorrectionSpecifier()) { 2314 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2315 Record = Ty->getAsCXXRecordDecl(); 2316 } 2317 if (!Record) 2318 Record = cast<CXXRecordDecl>( 2319 ND->getDeclContext()->getRedeclContext()); 2320 R.setNamingClass(Record); 2321 } 2322 2323 auto *UnderlyingND = ND->getUnderlyingDecl(); 2324 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2325 isa<FunctionTemplateDecl>(UnderlyingND); 2326 // FIXME: If we ended up with a typo for a type name or 2327 // Objective-C class name, we're in trouble because the parser 2328 // is in the wrong place to recover. Suggest the typo 2329 // correction, but don't make it a fix-it since we're not going 2330 // to recover well anyway. 2331 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2332 getAsTypeTemplateDecl(UnderlyingND) || 2333 isa<ObjCInterfaceDecl>(UnderlyingND); 2334 } else { 2335 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2336 // because we aren't able to recover. 2337 AcceptableWithoutRecovery = true; 2338 } 2339 2340 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2341 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2342 ? diag::note_implicit_param_decl 2343 : diag::note_previous_decl; 2344 if (SS.isEmpty()) 2345 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2346 PDiag(NoteID), AcceptableWithRecovery); 2347 else 2348 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2349 << Name << computeDeclContext(SS, false) 2350 << DroppedSpecifier << SS.getRange(), 2351 PDiag(NoteID), AcceptableWithRecovery); 2352 2353 // Tell the callee whether to try to recover. 2354 return !AcceptableWithRecovery; 2355 } 2356 } 2357 R.clear(); 2358 2359 // Emit a special diagnostic for failed member lookups. 2360 // FIXME: computing the declaration context might fail here (?) 2361 if (!SS.isEmpty()) { 2362 Diag(R.getNameLoc(), diag::err_no_member) 2363 << Name << computeDeclContext(SS, false) 2364 << SS.getRange(); 2365 return true; 2366 } 2367 2368 // Give up, we can't recover. 2369 Diag(R.getNameLoc(), diagnostic) << Name; 2370 return true; 2371 } 2372 2373 /// In Microsoft mode, if we are inside a template class whose parent class has 2374 /// dependent base classes, and we can't resolve an unqualified identifier, then 2375 /// assume the identifier is a member of a dependent base class. We can only 2376 /// recover successfully in static methods, instance methods, and other contexts 2377 /// where 'this' is available. This doesn't precisely match MSVC's 2378 /// instantiation model, but it's close enough. 2379 static Expr * 2380 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2381 DeclarationNameInfo &NameInfo, 2382 SourceLocation TemplateKWLoc, 2383 const TemplateArgumentListInfo *TemplateArgs) { 2384 // Only try to recover from lookup into dependent bases in static methods or 2385 // contexts where 'this' is available. 2386 QualType ThisType = S.getCurrentThisType(); 2387 const CXXRecordDecl *RD = nullptr; 2388 if (!ThisType.isNull()) 2389 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2390 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2391 RD = MD->getParent(); 2392 if (!RD || !RD->hasAnyDependentBases()) 2393 return nullptr; 2394 2395 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2396 // is available, suggest inserting 'this->' as a fixit. 2397 SourceLocation Loc = NameInfo.getLoc(); 2398 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2399 DB << NameInfo.getName() << RD; 2400 2401 if (!ThisType.isNull()) { 2402 DB << FixItHint::CreateInsertion(Loc, "this->"); 2403 return CXXDependentScopeMemberExpr::Create( 2404 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2405 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2406 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2407 } 2408 2409 // Synthesize a fake NNS that points to the derived class. This will 2410 // perform name lookup during template instantiation. 2411 CXXScopeSpec SS; 2412 auto *NNS = 2413 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2414 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2415 return DependentScopeDeclRefExpr::Create( 2416 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2417 TemplateArgs); 2418 } 2419 2420 ExprResult 2421 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2422 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2423 bool HasTrailingLParen, bool IsAddressOfOperand, 2424 CorrectionCandidateCallback *CCC, 2425 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2426 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2427 "cannot be direct & operand and have a trailing lparen"); 2428 if (SS.isInvalid()) 2429 return ExprError(); 2430 2431 TemplateArgumentListInfo TemplateArgsBuffer; 2432 2433 // Decompose the UnqualifiedId into the following data. 2434 DeclarationNameInfo NameInfo; 2435 const TemplateArgumentListInfo *TemplateArgs; 2436 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2437 2438 DeclarationName Name = NameInfo.getName(); 2439 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2440 SourceLocation NameLoc = NameInfo.getLoc(); 2441 2442 if (II && II->isEditorPlaceholder()) { 2443 // FIXME: When typed placeholders are supported we can create a typed 2444 // placeholder expression node. 2445 return ExprError(); 2446 } 2447 2448 // C++ [temp.dep.expr]p3: 2449 // An id-expression is type-dependent if it contains: 2450 // -- an identifier that was declared with a dependent type, 2451 // (note: handled after lookup) 2452 // -- a template-id that is dependent, 2453 // (note: handled in BuildTemplateIdExpr) 2454 // -- a conversion-function-id that specifies a dependent type, 2455 // -- a nested-name-specifier that contains a class-name that 2456 // names a dependent type. 2457 // Determine whether this is a member of an unknown specialization; 2458 // we need to handle these differently. 2459 bool DependentID = false; 2460 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2461 Name.getCXXNameType()->isDependentType()) { 2462 DependentID = true; 2463 } else if (SS.isSet()) { 2464 if (DeclContext *DC = computeDeclContext(SS, false)) { 2465 if (RequireCompleteDeclContext(SS, DC)) 2466 return ExprError(); 2467 } else { 2468 DependentID = true; 2469 } 2470 } 2471 2472 if (DependentID) 2473 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2474 IsAddressOfOperand, TemplateArgs); 2475 2476 // Perform the required lookup. 2477 LookupResult R(*this, NameInfo, 2478 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2479 ? LookupObjCImplicitSelfParam 2480 : LookupOrdinaryName); 2481 if (TemplateKWLoc.isValid() || TemplateArgs) { 2482 // Lookup the template name again to correctly establish the context in 2483 // which it was found. This is really unfortunate as we already did the 2484 // lookup to determine that it was a template name in the first place. If 2485 // this becomes a performance hit, we can work harder to preserve those 2486 // results until we get here but it's likely not worth it. 2487 bool MemberOfUnknownSpecialization; 2488 AssumedTemplateKind AssumedTemplate; 2489 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2490 MemberOfUnknownSpecialization, TemplateKWLoc, 2491 &AssumedTemplate)) 2492 return ExprError(); 2493 2494 if (MemberOfUnknownSpecialization || 2495 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2496 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2497 IsAddressOfOperand, TemplateArgs); 2498 } else { 2499 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2500 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2501 2502 // If the result might be in a dependent base class, this is a dependent 2503 // id-expression. 2504 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2505 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2506 IsAddressOfOperand, TemplateArgs); 2507 2508 // If this reference is in an Objective-C method, then we need to do 2509 // some special Objective-C lookup, too. 2510 if (IvarLookupFollowUp) { 2511 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2512 if (E.isInvalid()) 2513 return ExprError(); 2514 2515 if (Expr *Ex = E.getAs<Expr>()) 2516 return Ex; 2517 } 2518 } 2519 2520 if (R.isAmbiguous()) 2521 return ExprError(); 2522 2523 // This could be an implicitly declared function reference (legal in C90, 2524 // extension in C99, forbidden in C++). 2525 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2526 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2527 if (D) R.addDecl(D); 2528 } 2529 2530 // Determine whether this name might be a candidate for 2531 // argument-dependent lookup. 2532 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2533 2534 if (R.empty() && !ADL) { 2535 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2536 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2537 TemplateKWLoc, TemplateArgs)) 2538 return E; 2539 } 2540 2541 // Don't diagnose an empty lookup for inline assembly. 2542 if (IsInlineAsmIdentifier) 2543 return ExprError(); 2544 2545 // If this name wasn't predeclared and if this is not a function 2546 // call, diagnose the problem. 2547 TypoExpr *TE = nullptr; 2548 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2549 : nullptr); 2550 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2551 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2552 "Typo correction callback misconfigured"); 2553 if (CCC) { 2554 // Make sure the callback knows what the typo being diagnosed is. 2555 CCC->setTypoName(II); 2556 if (SS.isValid()) 2557 CCC->setTypoNNS(SS.getScopeRep()); 2558 } 2559 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2560 // a template name, but we happen to have always already looked up the name 2561 // before we get here if it must be a template name. 2562 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2563 None, &TE)) { 2564 if (TE && KeywordReplacement) { 2565 auto &State = getTypoExprState(TE); 2566 auto BestTC = State.Consumer->getNextCorrection(); 2567 if (BestTC.isKeyword()) { 2568 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2569 if (State.DiagHandler) 2570 State.DiagHandler(BestTC); 2571 KeywordReplacement->startToken(); 2572 KeywordReplacement->setKind(II->getTokenID()); 2573 KeywordReplacement->setIdentifierInfo(II); 2574 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2575 // Clean up the state associated with the TypoExpr, since it has 2576 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2577 clearDelayedTypo(TE); 2578 // Signal that a correction to a keyword was performed by returning a 2579 // valid-but-null ExprResult. 2580 return (Expr*)nullptr; 2581 } 2582 State.Consumer->resetCorrectionStream(); 2583 } 2584 return TE ? TE : ExprError(); 2585 } 2586 2587 assert(!R.empty() && 2588 "DiagnoseEmptyLookup returned false but added no results"); 2589 2590 // If we found an Objective-C instance variable, let 2591 // LookupInObjCMethod build the appropriate expression to 2592 // reference the ivar. 2593 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2594 R.clear(); 2595 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2596 // In a hopelessly buggy code, Objective-C instance variable 2597 // lookup fails and no expression will be built to reference it. 2598 if (!E.isInvalid() && !E.get()) 2599 return ExprError(); 2600 return E; 2601 } 2602 } 2603 2604 // This is guaranteed from this point on. 2605 assert(!R.empty() || ADL); 2606 2607 // Check whether this might be a C++ implicit instance member access. 2608 // C++ [class.mfct.non-static]p3: 2609 // When an id-expression that is not part of a class member access 2610 // syntax and not used to form a pointer to member is used in the 2611 // body of a non-static member function of class X, if name lookup 2612 // resolves the name in the id-expression to a non-static non-type 2613 // member of some class C, the id-expression is transformed into a 2614 // class member access expression using (*this) as the 2615 // postfix-expression to the left of the . operator. 2616 // 2617 // But we don't actually need to do this for '&' operands if R 2618 // resolved to a function or overloaded function set, because the 2619 // expression is ill-formed if it actually works out to be a 2620 // non-static member function: 2621 // 2622 // C++ [expr.ref]p4: 2623 // Otherwise, if E1.E2 refers to a non-static member function. . . 2624 // [t]he expression can be used only as the left-hand operand of a 2625 // member function call. 2626 // 2627 // There are other safeguards against such uses, but it's important 2628 // to get this right here so that we don't end up making a 2629 // spuriously dependent expression if we're inside a dependent 2630 // instance method. 2631 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2632 bool MightBeImplicitMember; 2633 if (!IsAddressOfOperand) 2634 MightBeImplicitMember = true; 2635 else if (!SS.isEmpty()) 2636 MightBeImplicitMember = false; 2637 else if (R.isOverloadedResult()) 2638 MightBeImplicitMember = false; 2639 else if (R.isUnresolvableResult()) 2640 MightBeImplicitMember = true; 2641 else 2642 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2643 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2644 isa<MSPropertyDecl>(R.getFoundDecl()); 2645 2646 if (MightBeImplicitMember) 2647 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2648 R, TemplateArgs, S); 2649 } 2650 2651 if (TemplateArgs || TemplateKWLoc.isValid()) { 2652 2653 // In C++1y, if this is a variable template id, then check it 2654 // in BuildTemplateIdExpr(). 2655 // The single lookup result must be a variable template declaration. 2656 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2657 Id.TemplateId->Kind == TNK_Var_template) { 2658 assert(R.getAsSingle<VarTemplateDecl>() && 2659 "There should only be one declaration found."); 2660 } 2661 2662 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2663 } 2664 2665 return BuildDeclarationNameExpr(SS, R, ADL); 2666 } 2667 2668 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2669 /// declaration name, generally during template instantiation. 2670 /// There's a large number of things which don't need to be done along 2671 /// this path. 2672 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2673 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2674 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2675 DeclContext *DC = computeDeclContext(SS, false); 2676 if (!DC) 2677 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2678 NameInfo, /*TemplateArgs=*/nullptr); 2679 2680 if (RequireCompleteDeclContext(SS, DC)) 2681 return ExprError(); 2682 2683 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2684 LookupQualifiedName(R, DC); 2685 2686 if (R.isAmbiguous()) 2687 return ExprError(); 2688 2689 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2690 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2691 NameInfo, /*TemplateArgs=*/nullptr); 2692 2693 if (R.empty()) { 2694 // Don't diagnose problems with invalid record decl, the secondary no_member 2695 // diagnostic during template instantiation is likely bogus, e.g. if a class 2696 // is invalid because it's derived from an invalid base class, then missing 2697 // members were likely supposed to be inherited. 2698 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2699 if (CD->isInvalidDecl()) 2700 return ExprError(); 2701 Diag(NameInfo.getLoc(), diag::err_no_member) 2702 << NameInfo.getName() << DC << SS.getRange(); 2703 return ExprError(); 2704 } 2705 2706 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2707 // Diagnose a missing typename if this resolved unambiguously to a type in 2708 // a dependent context. If we can recover with a type, downgrade this to 2709 // a warning in Microsoft compatibility mode. 2710 unsigned DiagID = diag::err_typename_missing; 2711 if (RecoveryTSI && getLangOpts().MSVCCompat) 2712 DiagID = diag::ext_typename_missing; 2713 SourceLocation Loc = SS.getBeginLoc(); 2714 auto D = Diag(Loc, DiagID); 2715 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2716 << SourceRange(Loc, NameInfo.getEndLoc()); 2717 2718 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2719 // context. 2720 if (!RecoveryTSI) 2721 return ExprError(); 2722 2723 // Only issue the fixit if we're prepared to recover. 2724 D << FixItHint::CreateInsertion(Loc, "typename "); 2725 2726 // Recover by pretending this was an elaborated type. 2727 QualType Ty = Context.getTypeDeclType(TD); 2728 TypeLocBuilder TLB; 2729 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2730 2731 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2732 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2733 QTL.setElaboratedKeywordLoc(SourceLocation()); 2734 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2735 2736 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2737 2738 return ExprEmpty(); 2739 } 2740 2741 // Defend against this resolving to an implicit member access. We usually 2742 // won't get here if this might be a legitimate a class member (we end up in 2743 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2744 // a pointer-to-member or in an unevaluated context in C++11. 2745 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2746 return BuildPossibleImplicitMemberExpr(SS, 2747 /*TemplateKWLoc=*/SourceLocation(), 2748 R, /*TemplateArgs=*/nullptr, S); 2749 2750 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2751 } 2752 2753 /// The parser has read a name in, and Sema has detected that we're currently 2754 /// inside an ObjC method. Perform some additional checks and determine if we 2755 /// should form a reference to an ivar. 2756 /// 2757 /// Ideally, most of this would be done by lookup, but there's 2758 /// actually quite a lot of extra work involved. 2759 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2760 IdentifierInfo *II) { 2761 SourceLocation Loc = Lookup.getNameLoc(); 2762 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2763 2764 // Check for error condition which is already reported. 2765 if (!CurMethod) 2766 return DeclResult(true); 2767 2768 // There are two cases to handle here. 1) scoped lookup could have failed, 2769 // in which case we should look for an ivar. 2) scoped lookup could have 2770 // found a decl, but that decl is outside the current instance method (i.e. 2771 // a global variable). In these two cases, we do a lookup for an ivar with 2772 // this name, if the lookup sucedes, we replace it our current decl. 2773 2774 // If we're in a class method, we don't normally want to look for 2775 // ivars. But if we don't find anything else, and there's an 2776 // ivar, that's an error. 2777 bool IsClassMethod = CurMethod->isClassMethod(); 2778 2779 bool LookForIvars; 2780 if (Lookup.empty()) 2781 LookForIvars = true; 2782 else if (IsClassMethod) 2783 LookForIvars = false; 2784 else 2785 LookForIvars = (Lookup.isSingleResult() && 2786 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2787 ObjCInterfaceDecl *IFace = nullptr; 2788 if (LookForIvars) { 2789 IFace = CurMethod->getClassInterface(); 2790 ObjCInterfaceDecl *ClassDeclared; 2791 ObjCIvarDecl *IV = nullptr; 2792 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2793 // Diagnose using an ivar in a class method. 2794 if (IsClassMethod) { 2795 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2796 return DeclResult(true); 2797 } 2798 2799 // Diagnose the use of an ivar outside of the declaring class. 2800 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2801 !declaresSameEntity(ClassDeclared, IFace) && 2802 !getLangOpts().DebuggerSupport) 2803 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2804 2805 // Success. 2806 return IV; 2807 } 2808 } else if (CurMethod->isInstanceMethod()) { 2809 // We should warn if a local variable hides an ivar. 2810 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2811 ObjCInterfaceDecl *ClassDeclared; 2812 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2813 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2814 declaresSameEntity(IFace, ClassDeclared)) 2815 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2816 } 2817 } 2818 } else if (Lookup.isSingleResult() && 2819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2820 // If accessing a stand-alone ivar in a class method, this is an error. 2821 if (const ObjCIvarDecl *IV = 2822 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2823 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2824 return DeclResult(true); 2825 } 2826 } 2827 2828 // Didn't encounter an error, didn't find an ivar. 2829 return DeclResult(false); 2830 } 2831 2832 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2833 ObjCIvarDecl *IV) { 2834 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2835 assert(CurMethod && CurMethod->isInstanceMethod() && 2836 "should not reference ivar from this context"); 2837 2838 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2839 assert(IFace && "should not reference ivar from this context"); 2840 2841 // If we're referencing an invalid decl, just return this as a silent 2842 // error node. The error diagnostic was already emitted on the decl. 2843 if (IV->isInvalidDecl()) 2844 return ExprError(); 2845 2846 // Check if referencing a field with __attribute__((deprecated)). 2847 if (DiagnoseUseOfDecl(IV, Loc)) 2848 return ExprError(); 2849 2850 // FIXME: This should use a new expr for a direct reference, don't 2851 // turn this into Self->ivar, just return a BareIVarExpr or something. 2852 IdentifierInfo &II = Context.Idents.get("self"); 2853 UnqualifiedId SelfName; 2854 SelfName.setIdentifier(&II, SourceLocation()); 2855 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2856 CXXScopeSpec SelfScopeSpec; 2857 SourceLocation TemplateKWLoc; 2858 ExprResult SelfExpr = 2859 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2860 /*HasTrailingLParen=*/false, 2861 /*IsAddressOfOperand=*/false); 2862 if (SelfExpr.isInvalid()) 2863 return ExprError(); 2864 2865 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2866 if (SelfExpr.isInvalid()) 2867 return ExprError(); 2868 2869 MarkAnyDeclReferenced(Loc, IV, true); 2870 2871 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2872 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2873 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2874 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2875 2876 ObjCIvarRefExpr *Result = new (Context) 2877 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2878 IV->getLocation(), SelfExpr.get(), true, true); 2879 2880 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2881 if (!isUnevaluatedContext() && 2882 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2883 getCurFunction()->recordUseOfWeak(Result); 2884 } 2885 if (getLangOpts().ObjCAutoRefCount) 2886 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2887 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2888 2889 return Result; 2890 } 2891 2892 /// The parser has read a name in, and Sema has detected that we're currently 2893 /// inside an ObjC method. Perform some additional checks and determine if we 2894 /// should form a reference to an ivar. If so, build an expression referencing 2895 /// that ivar. 2896 ExprResult 2897 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2898 IdentifierInfo *II, bool AllowBuiltinCreation) { 2899 // FIXME: Integrate this lookup step into LookupParsedName. 2900 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2901 if (Ivar.isInvalid()) 2902 return ExprError(); 2903 if (Ivar.isUsable()) 2904 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2905 cast<ObjCIvarDecl>(Ivar.get())); 2906 2907 if (Lookup.empty() && II && AllowBuiltinCreation) 2908 LookupBuiltin(Lookup); 2909 2910 // Sentinel value saying that we didn't do anything special. 2911 return ExprResult(false); 2912 } 2913 2914 /// Cast a base object to a member's actual type. 2915 /// 2916 /// There are two relevant checks: 2917 /// 2918 /// C++ [class.access.base]p7: 2919 /// 2920 /// If a class member access operator [...] is used to access a non-static 2921 /// data member or non-static member function, the reference is ill-formed if 2922 /// the left operand [...] cannot be implicitly converted to a pointer to the 2923 /// naming class of the right operand. 2924 /// 2925 /// C++ [expr.ref]p7: 2926 /// 2927 /// If E2 is a non-static data member or a non-static member function, the 2928 /// program is ill-formed if the class of which E2 is directly a member is an 2929 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2930 /// 2931 /// Note that the latter check does not consider access; the access of the 2932 /// "real" base class is checked as appropriate when checking the access of the 2933 /// member name. 2934 ExprResult 2935 Sema::PerformObjectMemberConversion(Expr *From, 2936 NestedNameSpecifier *Qualifier, 2937 NamedDecl *FoundDecl, 2938 NamedDecl *Member) { 2939 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2940 if (!RD) 2941 return From; 2942 2943 QualType DestRecordType; 2944 QualType DestType; 2945 QualType FromRecordType; 2946 QualType FromType = From->getType(); 2947 bool PointerConversions = false; 2948 if (isa<FieldDecl>(Member)) { 2949 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2950 auto FromPtrType = FromType->getAs<PointerType>(); 2951 DestRecordType = Context.getAddrSpaceQualType( 2952 DestRecordType, FromPtrType 2953 ? FromType->getPointeeType().getAddressSpace() 2954 : FromType.getAddressSpace()); 2955 2956 if (FromPtrType) { 2957 DestType = Context.getPointerType(DestRecordType); 2958 FromRecordType = FromPtrType->getPointeeType(); 2959 PointerConversions = true; 2960 } else { 2961 DestType = DestRecordType; 2962 FromRecordType = FromType; 2963 } 2964 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2965 if (Method->isStatic()) 2966 return From; 2967 2968 DestType = Method->getThisType(); 2969 DestRecordType = DestType->getPointeeType(); 2970 2971 if (FromType->getAs<PointerType>()) { 2972 FromRecordType = FromType->getPointeeType(); 2973 PointerConversions = true; 2974 } else { 2975 FromRecordType = FromType; 2976 DestType = DestRecordType; 2977 } 2978 2979 LangAS FromAS = FromRecordType.getAddressSpace(); 2980 LangAS DestAS = DestRecordType.getAddressSpace(); 2981 if (FromAS != DestAS) { 2982 QualType FromRecordTypeWithoutAS = 2983 Context.removeAddrSpaceQualType(FromRecordType); 2984 QualType FromTypeWithDestAS = 2985 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2986 if (PointerConversions) 2987 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2988 From = ImpCastExprToType(From, FromTypeWithDestAS, 2989 CK_AddressSpaceConversion, From->getValueKind()) 2990 .get(); 2991 } 2992 } else { 2993 // No conversion necessary. 2994 return From; 2995 } 2996 2997 if (DestType->isDependentType() || FromType->isDependentType()) 2998 return From; 2999 3000 // If the unqualified types are the same, no conversion is necessary. 3001 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3002 return From; 3003 3004 SourceRange FromRange = From->getSourceRange(); 3005 SourceLocation FromLoc = FromRange.getBegin(); 3006 3007 ExprValueKind VK = From->getValueKind(); 3008 3009 // C++ [class.member.lookup]p8: 3010 // [...] Ambiguities can often be resolved by qualifying a name with its 3011 // class name. 3012 // 3013 // If the member was a qualified name and the qualified referred to a 3014 // specific base subobject type, we'll cast to that intermediate type 3015 // first and then to the object in which the member is declared. That allows 3016 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3017 // 3018 // class Base { public: int x; }; 3019 // class Derived1 : public Base { }; 3020 // class Derived2 : public Base { }; 3021 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3022 // 3023 // void VeryDerived::f() { 3024 // x = 17; // error: ambiguous base subobjects 3025 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3026 // } 3027 if (Qualifier && Qualifier->getAsType()) { 3028 QualType QType = QualType(Qualifier->getAsType(), 0); 3029 assert(QType->isRecordType() && "lookup done with non-record type"); 3030 3031 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3032 3033 // In C++98, the qualifier type doesn't actually have to be a base 3034 // type of the object type, in which case we just ignore it. 3035 // Otherwise build the appropriate casts. 3036 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3037 CXXCastPath BasePath; 3038 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3039 FromLoc, FromRange, &BasePath)) 3040 return ExprError(); 3041 3042 if (PointerConversions) 3043 QType = Context.getPointerType(QType); 3044 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3045 VK, &BasePath).get(); 3046 3047 FromType = QType; 3048 FromRecordType = QRecordType; 3049 3050 // If the qualifier type was the same as the destination type, 3051 // we're done. 3052 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3053 return From; 3054 } 3055 } 3056 3057 CXXCastPath BasePath; 3058 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3059 FromLoc, FromRange, &BasePath, 3060 /*IgnoreAccess=*/true)) 3061 return ExprError(); 3062 3063 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3064 VK, &BasePath); 3065 } 3066 3067 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3068 const LookupResult &R, 3069 bool HasTrailingLParen) { 3070 // Only when used directly as the postfix-expression of a call. 3071 if (!HasTrailingLParen) 3072 return false; 3073 3074 // Never if a scope specifier was provided. 3075 if (SS.isSet()) 3076 return false; 3077 3078 // Only in C++ or ObjC++. 3079 if (!getLangOpts().CPlusPlus) 3080 return false; 3081 3082 // Turn off ADL when we find certain kinds of declarations during 3083 // normal lookup: 3084 for (NamedDecl *D : R) { 3085 // C++0x [basic.lookup.argdep]p3: 3086 // -- a declaration of a class member 3087 // Since using decls preserve this property, we check this on the 3088 // original decl. 3089 if (D->isCXXClassMember()) 3090 return false; 3091 3092 // C++0x [basic.lookup.argdep]p3: 3093 // -- a block-scope function declaration that is not a 3094 // using-declaration 3095 // NOTE: we also trigger this for function templates (in fact, we 3096 // don't check the decl type at all, since all other decl types 3097 // turn off ADL anyway). 3098 if (isa<UsingShadowDecl>(D)) 3099 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3100 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3101 return false; 3102 3103 // C++0x [basic.lookup.argdep]p3: 3104 // -- a declaration that is neither a function or a function 3105 // template 3106 // And also for builtin functions. 3107 if (isa<FunctionDecl>(D)) { 3108 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3109 3110 // But also builtin functions. 3111 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3112 return false; 3113 } else if (!isa<FunctionTemplateDecl>(D)) 3114 return false; 3115 } 3116 3117 return true; 3118 } 3119 3120 3121 /// Diagnoses obvious problems with the use of the given declaration 3122 /// as an expression. This is only actually called for lookups that 3123 /// were not overloaded, and it doesn't promise that the declaration 3124 /// will in fact be used. 3125 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3126 if (D->isInvalidDecl()) 3127 return true; 3128 3129 if (isa<TypedefNameDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<ObjCInterfaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 if (isa<NamespaceDecl>(D)) { 3140 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3141 return true; 3142 } 3143 3144 return false; 3145 } 3146 3147 // Certain multiversion types should be treated as overloaded even when there is 3148 // only one result. 3149 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3150 assert(R.isSingleResult() && "Expected only a single result"); 3151 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3152 return FD && 3153 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3154 } 3155 3156 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3157 LookupResult &R, bool NeedsADL, 3158 bool AcceptInvalidDecl) { 3159 // If this is a single, fully-resolved result and we don't need ADL, 3160 // just build an ordinary singleton decl ref. 3161 if (!NeedsADL && R.isSingleResult() && 3162 !R.getAsSingle<FunctionTemplateDecl>() && 3163 !ShouldLookupResultBeMultiVersionOverload(R)) 3164 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3165 R.getRepresentativeDecl(), nullptr, 3166 AcceptInvalidDecl); 3167 3168 // We only need to check the declaration if there's exactly one 3169 // result, because in the overloaded case the results can only be 3170 // functions and function templates. 3171 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3172 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3173 return ExprError(); 3174 3175 // Otherwise, just build an unresolved lookup expression. Suppress 3176 // any lookup-related diagnostics; we'll hash these out later, when 3177 // we've picked a target. 3178 R.suppressDiagnostics(); 3179 3180 UnresolvedLookupExpr *ULE 3181 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3182 SS.getWithLocInContext(Context), 3183 R.getLookupNameInfo(), 3184 NeedsADL, R.isOverloadedResult(), 3185 R.begin(), R.end()); 3186 3187 return ULE; 3188 } 3189 3190 static void 3191 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3192 ValueDecl *var, DeclContext *DC); 3193 3194 /// Complete semantic analysis for a reference to the given declaration. 3195 ExprResult Sema::BuildDeclarationNameExpr( 3196 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3197 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3198 bool AcceptInvalidDecl) { 3199 assert(D && "Cannot refer to a NULL declaration"); 3200 assert(!isa<FunctionTemplateDecl>(D) && 3201 "Cannot refer unambiguously to a function template"); 3202 3203 SourceLocation Loc = NameInfo.getLoc(); 3204 if (CheckDeclInExpr(*this, Loc, D)) 3205 return ExprError(); 3206 3207 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3208 // Specifically diagnose references to class templates that are missing 3209 // a template argument list. 3210 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3211 return ExprError(); 3212 } 3213 3214 // Make sure that we're referring to a value. 3215 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3216 if (!VD) { 3217 Diag(Loc, diag::err_ref_non_value) 3218 << D << SS.getRange(); 3219 Diag(D->getLocation(), diag::note_declared_at); 3220 return ExprError(); 3221 } 3222 3223 // Check whether this declaration can be used. Note that we suppress 3224 // this check when we're going to perform argument-dependent lookup 3225 // on this function name, because this might not be the function 3226 // that overload resolution actually selects. 3227 if (DiagnoseUseOfDecl(VD, Loc)) 3228 return ExprError(); 3229 3230 // Only create DeclRefExpr's for valid Decl's. 3231 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3232 return ExprError(); 3233 3234 // Handle members of anonymous structs and unions. If we got here, 3235 // and the reference is to a class member indirect field, then this 3236 // must be the subject of a pointer-to-member expression. 3237 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3238 if (!indirectField->isCXXClassMember()) 3239 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3240 indirectField); 3241 3242 { 3243 QualType type = VD->getType(); 3244 if (type.isNull()) 3245 return ExprError(); 3246 ExprValueKind valueKind = VK_RValue; 3247 3248 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3249 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3250 // is expanded by some outer '...' in the context of the use. 3251 type = type.getNonPackExpansionType(); 3252 3253 switch (D->getKind()) { 3254 // Ignore all the non-ValueDecl kinds. 3255 #define ABSTRACT_DECL(kind) 3256 #define VALUE(type, base) 3257 #define DECL(type, base) \ 3258 case Decl::type: 3259 #include "clang/AST/DeclNodes.inc" 3260 llvm_unreachable("invalid value decl kind"); 3261 3262 // These shouldn't make it here. 3263 case Decl::ObjCAtDefsField: 3264 llvm_unreachable("forming non-member reference to ivar?"); 3265 3266 // Enum constants are always r-values and never references. 3267 // Unresolved using declarations are dependent. 3268 case Decl::EnumConstant: 3269 case Decl::UnresolvedUsingValue: 3270 case Decl::OMPDeclareReduction: 3271 case Decl::OMPDeclareMapper: 3272 valueKind = VK_RValue; 3273 break; 3274 3275 // Fields and indirect fields that got here must be for 3276 // pointer-to-member expressions; we just call them l-values for 3277 // internal consistency, because this subexpression doesn't really 3278 // exist in the high-level semantics. 3279 case Decl::Field: 3280 case Decl::IndirectField: 3281 case Decl::ObjCIvar: 3282 assert(getLangOpts().CPlusPlus && 3283 "building reference to field in C?"); 3284 3285 // These can't have reference type in well-formed programs, but 3286 // for internal consistency we do this anyway. 3287 type = type.getNonReferenceType(); 3288 valueKind = VK_LValue; 3289 break; 3290 3291 // Non-type template parameters are either l-values or r-values 3292 // depending on the type. 3293 case Decl::NonTypeTemplateParm: { 3294 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3295 type = reftype->getPointeeType(); 3296 valueKind = VK_LValue; // even if the parameter is an r-value reference 3297 break; 3298 } 3299 3300 // [expr.prim.id.unqual]p2: 3301 // If the entity is a template parameter object for a template 3302 // parameter of type T, the type of the expression is const T. 3303 // [...] The expression is an lvalue if the entity is a [...] template 3304 // parameter object. 3305 if (type->isRecordType()) { 3306 type = type.getUnqualifiedType().withConst(); 3307 valueKind = VK_LValue; 3308 break; 3309 } 3310 3311 // For non-references, we need to strip qualifiers just in case 3312 // the template parameter was declared as 'const int' or whatever. 3313 valueKind = VK_RValue; 3314 type = type.getUnqualifiedType(); 3315 break; 3316 } 3317 3318 case Decl::Var: 3319 case Decl::VarTemplateSpecialization: 3320 case Decl::VarTemplatePartialSpecialization: 3321 case Decl::Decomposition: 3322 case Decl::OMPCapturedExpr: 3323 // In C, "extern void blah;" is valid and is an r-value. 3324 if (!getLangOpts().CPlusPlus && 3325 !type.hasQualifiers() && 3326 type->isVoidType()) { 3327 valueKind = VK_RValue; 3328 break; 3329 } 3330 LLVM_FALLTHROUGH; 3331 3332 case Decl::ImplicitParam: 3333 case Decl::ParmVar: { 3334 // These are always l-values. 3335 valueKind = VK_LValue; 3336 type = type.getNonReferenceType(); 3337 3338 // FIXME: Does the addition of const really only apply in 3339 // potentially-evaluated contexts? Since the variable isn't actually 3340 // captured in an unevaluated context, it seems that the answer is no. 3341 if (!isUnevaluatedContext()) { 3342 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3343 if (!CapturedType.isNull()) 3344 type = CapturedType; 3345 } 3346 3347 break; 3348 } 3349 3350 case Decl::Binding: { 3351 // These are always lvalues. 3352 valueKind = VK_LValue; 3353 type = type.getNonReferenceType(); 3354 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3355 // decides how that's supposed to work. 3356 auto *BD = cast<BindingDecl>(VD); 3357 if (BD->getDeclContext() != CurContext) { 3358 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3359 if (DD && DD->hasLocalStorage()) 3360 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3361 } 3362 break; 3363 } 3364 3365 case Decl::Function: { 3366 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3367 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3368 type = Context.BuiltinFnTy; 3369 valueKind = VK_RValue; 3370 break; 3371 } 3372 } 3373 3374 const FunctionType *fty = type->castAs<FunctionType>(); 3375 3376 // If we're referring to a function with an __unknown_anytype 3377 // result type, make the entire expression __unknown_anytype. 3378 if (fty->getReturnType() == Context.UnknownAnyTy) { 3379 type = Context.UnknownAnyTy; 3380 valueKind = VK_RValue; 3381 break; 3382 } 3383 3384 // Functions are l-values in C++. 3385 if (getLangOpts().CPlusPlus) { 3386 valueKind = VK_LValue; 3387 break; 3388 } 3389 3390 // C99 DR 316 says that, if a function type comes from a 3391 // function definition (without a prototype), that type is only 3392 // used for checking compatibility. Therefore, when referencing 3393 // the function, we pretend that we don't have the full function 3394 // type. 3395 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3396 isa<FunctionProtoType>(fty)) 3397 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3398 fty->getExtInfo()); 3399 3400 // Functions are r-values in C. 3401 valueKind = VK_RValue; 3402 break; 3403 } 3404 3405 case Decl::CXXDeductionGuide: 3406 llvm_unreachable("building reference to deduction guide"); 3407 3408 case Decl::MSProperty: 3409 case Decl::MSGuid: 3410 case Decl::TemplateParamObject: 3411 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3412 // capture in OpenMP, or duplicated between host and device? 3413 valueKind = VK_LValue; 3414 break; 3415 3416 case Decl::CXXMethod: 3417 // If we're referring to a method with an __unknown_anytype 3418 // result type, make the entire expression __unknown_anytype. 3419 // This should only be possible with a type written directly. 3420 if (const FunctionProtoType *proto 3421 = dyn_cast<FunctionProtoType>(VD->getType())) 3422 if (proto->getReturnType() == Context.UnknownAnyTy) { 3423 type = Context.UnknownAnyTy; 3424 valueKind = VK_RValue; 3425 break; 3426 } 3427 3428 // C++ methods are l-values if static, r-values if non-static. 3429 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3430 valueKind = VK_LValue; 3431 break; 3432 } 3433 LLVM_FALLTHROUGH; 3434 3435 case Decl::CXXConversion: 3436 case Decl::CXXDestructor: 3437 case Decl::CXXConstructor: 3438 valueKind = VK_RValue; 3439 break; 3440 } 3441 3442 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3443 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3444 TemplateArgs); 3445 } 3446 } 3447 3448 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3449 SmallString<32> &Target) { 3450 Target.resize(CharByteWidth * (Source.size() + 1)); 3451 char *ResultPtr = &Target[0]; 3452 const llvm::UTF8 *ErrorPtr; 3453 bool success = 3454 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3455 (void)success; 3456 assert(success); 3457 Target.resize(ResultPtr - &Target[0]); 3458 } 3459 3460 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3461 PredefinedExpr::IdentKind IK) { 3462 // Pick the current block, lambda, captured statement or function. 3463 Decl *currentDecl = nullptr; 3464 if (const BlockScopeInfo *BSI = getCurBlock()) 3465 currentDecl = BSI->TheDecl; 3466 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3467 currentDecl = LSI->CallOperator; 3468 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3469 currentDecl = CSI->TheCapturedDecl; 3470 else 3471 currentDecl = getCurFunctionOrMethodDecl(); 3472 3473 if (!currentDecl) { 3474 Diag(Loc, diag::ext_predef_outside_function); 3475 currentDecl = Context.getTranslationUnitDecl(); 3476 } 3477 3478 QualType ResTy; 3479 StringLiteral *SL = nullptr; 3480 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3481 ResTy = Context.DependentTy; 3482 else { 3483 // Pre-defined identifiers are of type char[x], where x is the length of 3484 // the string. 3485 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3486 unsigned Length = Str.length(); 3487 3488 llvm::APInt LengthI(32, Length + 1); 3489 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3490 ResTy = 3491 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3492 SmallString<32> RawChars; 3493 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3494 Str, RawChars); 3495 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3496 ArrayType::Normal, 3497 /*IndexTypeQuals*/ 0); 3498 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3499 /*Pascal*/ false, ResTy, Loc); 3500 } else { 3501 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3502 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3503 ArrayType::Normal, 3504 /*IndexTypeQuals*/ 0); 3505 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3506 /*Pascal*/ false, ResTy, Loc); 3507 } 3508 } 3509 3510 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3511 } 3512 3513 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3514 PredefinedExpr::IdentKind IK; 3515 3516 switch (Kind) { 3517 default: llvm_unreachable("Unknown simple primary expr!"); 3518 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3519 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3520 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3521 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3522 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3523 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3524 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3525 } 3526 3527 return BuildPredefinedExpr(Loc, IK); 3528 } 3529 3530 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3531 SmallString<16> CharBuffer; 3532 bool Invalid = false; 3533 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3534 if (Invalid) 3535 return ExprError(); 3536 3537 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3538 PP, Tok.getKind()); 3539 if (Literal.hadError()) 3540 return ExprError(); 3541 3542 QualType Ty; 3543 if (Literal.isWide()) 3544 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3545 else if (Literal.isUTF8() && getLangOpts().Char8) 3546 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3547 else if (Literal.isUTF16()) 3548 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3549 else if (Literal.isUTF32()) 3550 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3551 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3552 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3553 else 3554 Ty = Context.CharTy; // 'x' -> char in C++ 3555 3556 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3557 if (Literal.isWide()) 3558 Kind = CharacterLiteral::Wide; 3559 else if (Literal.isUTF16()) 3560 Kind = CharacterLiteral::UTF16; 3561 else if (Literal.isUTF32()) 3562 Kind = CharacterLiteral::UTF32; 3563 else if (Literal.isUTF8()) 3564 Kind = CharacterLiteral::UTF8; 3565 3566 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3567 Tok.getLocation()); 3568 3569 if (Literal.getUDSuffix().empty()) 3570 return Lit; 3571 3572 // We're building a user-defined literal. 3573 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3574 SourceLocation UDSuffixLoc = 3575 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3576 3577 // Make sure we're allowed user-defined literals here. 3578 if (!UDLScope) 3579 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3580 3581 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3582 // operator "" X (ch) 3583 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3584 Lit, Tok.getLocation()); 3585 } 3586 3587 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3588 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3589 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3590 Context.IntTy, Loc); 3591 } 3592 3593 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3594 QualType Ty, SourceLocation Loc) { 3595 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3596 3597 using llvm::APFloat; 3598 APFloat Val(Format); 3599 3600 APFloat::opStatus result = Literal.GetFloatValue(Val); 3601 3602 // Overflow is always an error, but underflow is only an error if 3603 // we underflowed to zero (APFloat reports denormals as underflow). 3604 if ((result & APFloat::opOverflow) || 3605 ((result & APFloat::opUnderflow) && Val.isZero())) { 3606 unsigned diagnostic; 3607 SmallString<20> buffer; 3608 if (result & APFloat::opOverflow) { 3609 diagnostic = diag::warn_float_overflow; 3610 APFloat::getLargest(Format).toString(buffer); 3611 } else { 3612 diagnostic = diag::warn_float_underflow; 3613 APFloat::getSmallest(Format).toString(buffer); 3614 } 3615 3616 S.Diag(Loc, diagnostic) 3617 << Ty 3618 << StringRef(buffer.data(), buffer.size()); 3619 } 3620 3621 bool isExact = (result == APFloat::opOK); 3622 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3623 } 3624 3625 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3626 assert(E && "Invalid expression"); 3627 3628 if (E->isValueDependent()) 3629 return false; 3630 3631 QualType QT = E->getType(); 3632 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3633 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3634 return true; 3635 } 3636 3637 llvm::APSInt ValueAPS; 3638 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3639 3640 if (R.isInvalid()) 3641 return true; 3642 3643 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3644 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3645 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3646 << ValueAPS.toString(10) << ValueIsPositive; 3647 return true; 3648 } 3649 3650 return false; 3651 } 3652 3653 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3654 // Fast path for a single digit (which is quite common). A single digit 3655 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3656 if (Tok.getLength() == 1) { 3657 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3658 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3659 } 3660 3661 SmallString<128> SpellingBuffer; 3662 // NumericLiteralParser wants to overread by one character. Add padding to 3663 // the buffer in case the token is copied to the buffer. If getSpelling() 3664 // returns a StringRef to the memory buffer, it should have a null char at 3665 // the EOF, so it is also safe. 3666 SpellingBuffer.resize(Tok.getLength() + 1); 3667 3668 // Get the spelling of the token, which eliminates trigraphs, etc. 3669 bool Invalid = false; 3670 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3671 if (Invalid) 3672 return ExprError(); 3673 3674 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3675 PP.getSourceManager(), PP.getLangOpts(), 3676 PP.getTargetInfo(), PP.getDiagnostics()); 3677 if (Literal.hadError) 3678 return ExprError(); 3679 3680 if (Literal.hasUDSuffix()) { 3681 // We're building a user-defined literal. 3682 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3683 SourceLocation UDSuffixLoc = 3684 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3685 3686 // Make sure we're allowed user-defined literals here. 3687 if (!UDLScope) 3688 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3689 3690 QualType CookedTy; 3691 if (Literal.isFloatingLiteral()) { 3692 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3693 // long double, the literal is treated as a call of the form 3694 // operator "" X (f L) 3695 CookedTy = Context.LongDoubleTy; 3696 } else { 3697 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3698 // unsigned long long, the literal is treated as a call of the form 3699 // operator "" X (n ULL) 3700 CookedTy = Context.UnsignedLongLongTy; 3701 } 3702 3703 DeclarationName OpName = 3704 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3705 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3706 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3707 3708 SourceLocation TokLoc = Tok.getLocation(); 3709 3710 // Perform literal operator lookup to determine if we're building a raw 3711 // literal or a cooked one. 3712 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3713 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3714 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3715 /*AllowStringTemplatePack*/ false, 3716 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3717 case LOLR_ErrorNoDiagnostic: 3718 // Lookup failure for imaginary constants isn't fatal, there's still the 3719 // GNU extension producing _Complex types. 3720 break; 3721 case LOLR_Error: 3722 return ExprError(); 3723 case LOLR_Cooked: { 3724 Expr *Lit; 3725 if (Literal.isFloatingLiteral()) { 3726 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3727 } else { 3728 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3729 if (Literal.GetIntegerValue(ResultVal)) 3730 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3731 << /* Unsigned */ 1; 3732 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3733 Tok.getLocation()); 3734 } 3735 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3736 } 3737 3738 case LOLR_Raw: { 3739 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3740 // literal is treated as a call of the form 3741 // operator "" X ("n") 3742 unsigned Length = Literal.getUDSuffixOffset(); 3743 QualType StrTy = Context.getConstantArrayType( 3744 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3745 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3746 Expr *Lit = StringLiteral::Create( 3747 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3748 /*Pascal*/false, StrTy, &TokLoc, 1); 3749 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3750 } 3751 3752 case LOLR_Template: { 3753 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3754 // template), L is treated as a call fo the form 3755 // operator "" X <'c1', 'c2', ... 'ck'>() 3756 // where n is the source character sequence c1 c2 ... ck. 3757 TemplateArgumentListInfo ExplicitArgs; 3758 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3759 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3760 llvm::APSInt Value(CharBits, CharIsUnsigned); 3761 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3762 Value = TokSpelling[I]; 3763 TemplateArgument Arg(Context, Value, Context.CharTy); 3764 TemplateArgumentLocInfo ArgInfo; 3765 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3766 } 3767 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3768 &ExplicitArgs); 3769 } 3770 case LOLR_StringTemplatePack: 3771 llvm_unreachable("unexpected literal operator lookup result"); 3772 } 3773 } 3774 3775 Expr *Res; 3776 3777 if (Literal.isFixedPointLiteral()) { 3778 QualType Ty; 3779 3780 if (Literal.isAccum) { 3781 if (Literal.isHalf) { 3782 Ty = Context.ShortAccumTy; 3783 } else if (Literal.isLong) { 3784 Ty = Context.LongAccumTy; 3785 } else { 3786 Ty = Context.AccumTy; 3787 } 3788 } else if (Literal.isFract) { 3789 if (Literal.isHalf) { 3790 Ty = Context.ShortFractTy; 3791 } else if (Literal.isLong) { 3792 Ty = Context.LongFractTy; 3793 } else { 3794 Ty = Context.FractTy; 3795 } 3796 } 3797 3798 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3799 3800 bool isSigned = !Literal.isUnsigned; 3801 unsigned scale = Context.getFixedPointScale(Ty); 3802 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3803 3804 llvm::APInt Val(bit_width, 0, isSigned); 3805 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3806 bool ValIsZero = Val.isNullValue() && !Overflowed; 3807 3808 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3809 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3810 // Clause 6.4.4 - The value of a constant shall be in the range of 3811 // representable values for its type, with exception for constants of a 3812 // fract type with a value of exactly 1; such a constant shall denote 3813 // the maximal value for the type. 3814 --Val; 3815 else if (Val.ugt(MaxVal) || Overflowed) 3816 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3817 3818 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3819 Tok.getLocation(), scale); 3820 } else if (Literal.isFloatingLiteral()) { 3821 QualType Ty; 3822 if (Literal.isHalf){ 3823 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3824 Ty = Context.HalfTy; 3825 else { 3826 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3827 return ExprError(); 3828 } 3829 } else if (Literal.isFloat) 3830 Ty = Context.FloatTy; 3831 else if (Literal.isLong) 3832 Ty = Context.LongDoubleTy; 3833 else if (Literal.isFloat16) 3834 Ty = Context.Float16Ty; 3835 else if (Literal.isFloat128) 3836 Ty = Context.Float128Ty; 3837 else 3838 Ty = Context.DoubleTy; 3839 3840 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3841 3842 if (Ty == Context.DoubleTy) { 3843 if (getLangOpts().SinglePrecisionConstants) { 3844 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3845 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3846 } 3847 } else if (getLangOpts().OpenCL && 3848 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3849 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3850 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3851 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3852 } 3853 } 3854 } else if (!Literal.isIntegerLiteral()) { 3855 return ExprError(); 3856 } else { 3857 QualType Ty; 3858 3859 // 'long long' is a C99 or C++11 feature. 3860 if (!getLangOpts().C99 && Literal.isLongLong) { 3861 if (getLangOpts().CPlusPlus) 3862 Diag(Tok.getLocation(), 3863 getLangOpts().CPlusPlus11 ? 3864 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3865 else 3866 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3867 } 3868 3869 // Get the value in the widest-possible width. 3870 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3871 llvm::APInt ResultVal(MaxWidth, 0); 3872 3873 if (Literal.GetIntegerValue(ResultVal)) { 3874 // If this value didn't fit into uintmax_t, error and force to ull. 3875 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3876 << /* Unsigned */ 1; 3877 Ty = Context.UnsignedLongLongTy; 3878 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3879 "long long is not intmax_t?"); 3880 } else { 3881 // If this value fits into a ULL, try to figure out what else it fits into 3882 // according to the rules of C99 6.4.4.1p5. 3883 3884 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3885 // be an unsigned int. 3886 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3887 3888 // Check from smallest to largest, picking the smallest type we can. 3889 unsigned Width = 0; 3890 3891 // Microsoft specific integer suffixes are explicitly sized. 3892 if (Literal.MicrosoftInteger) { 3893 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3894 Width = 8; 3895 Ty = Context.CharTy; 3896 } else { 3897 Width = Literal.MicrosoftInteger; 3898 Ty = Context.getIntTypeForBitwidth(Width, 3899 /*Signed=*/!Literal.isUnsigned); 3900 } 3901 } 3902 3903 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3904 // Are int/unsigned possibilities? 3905 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3906 3907 // Does it fit in a unsigned int? 3908 if (ResultVal.isIntN(IntSize)) { 3909 // Does it fit in a signed int? 3910 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3911 Ty = Context.IntTy; 3912 else if (AllowUnsigned) 3913 Ty = Context.UnsignedIntTy; 3914 Width = IntSize; 3915 } 3916 } 3917 3918 // Are long/unsigned long possibilities? 3919 if (Ty.isNull() && !Literal.isLongLong) { 3920 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3921 3922 // Does it fit in a unsigned long? 3923 if (ResultVal.isIntN(LongSize)) { 3924 // Does it fit in a signed long? 3925 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3926 Ty = Context.LongTy; 3927 else if (AllowUnsigned) 3928 Ty = Context.UnsignedLongTy; 3929 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3930 // is compatible. 3931 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3932 const unsigned LongLongSize = 3933 Context.getTargetInfo().getLongLongWidth(); 3934 Diag(Tok.getLocation(), 3935 getLangOpts().CPlusPlus 3936 ? Literal.isLong 3937 ? diag::warn_old_implicitly_unsigned_long_cxx 3938 : /*C++98 UB*/ diag:: 3939 ext_old_implicitly_unsigned_long_cxx 3940 : diag::warn_old_implicitly_unsigned_long) 3941 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3942 : /*will be ill-formed*/ 1); 3943 Ty = Context.UnsignedLongTy; 3944 } 3945 Width = LongSize; 3946 } 3947 } 3948 3949 // Check long long if needed. 3950 if (Ty.isNull()) { 3951 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3952 3953 // Does it fit in a unsigned long long? 3954 if (ResultVal.isIntN(LongLongSize)) { 3955 // Does it fit in a signed long long? 3956 // To be compatible with MSVC, hex integer literals ending with the 3957 // LL or i64 suffix are always signed in Microsoft mode. 3958 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3959 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3960 Ty = Context.LongLongTy; 3961 else if (AllowUnsigned) 3962 Ty = Context.UnsignedLongLongTy; 3963 Width = LongLongSize; 3964 } 3965 } 3966 3967 // If we still couldn't decide a type, we probably have something that 3968 // does not fit in a signed long long, but has no U suffix. 3969 if (Ty.isNull()) { 3970 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3971 Ty = Context.UnsignedLongLongTy; 3972 Width = Context.getTargetInfo().getLongLongWidth(); 3973 } 3974 3975 if (ResultVal.getBitWidth() != Width) 3976 ResultVal = ResultVal.trunc(Width); 3977 } 3978 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3979 } 3980 3981 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3982 if (Literal.isImaginary) { 3983 Res = new (Context) ImaginaryLiteral(Res, 3984 Context.getComplexType(Res->getType())); 3985 3986 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3987 } 3988 return Res; 3989 } 3990 3991 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3992 assert(E && "ActOnParenExpr() missing expr"); 3993 return new (Context) ParenExpr(L, R, E); 3994 } 3995 3996 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3997 SourceLocation Loc, 3998 SourceRange ArgRange) { 3999 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4000 // scalar or vector data type argument..." 4001 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4002 // type (C99 6.2.5p18) or void. 4003 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4004 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4005 << T << ArgRange; 4006 return true; 4007 } 4008 4009 assert((T->isVoidType() || !T->isIncompleteType()) && 4010 "Scalar types should always be complete"); 4011 return false; 4012 } 4013 4014 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4015 SourceLocation Loc, 4016 SourceRange ArgRange, 4017 UnaryExprOrTypeTrait TraitKind) { 4018 // Invalid types must be hard errors for SFINAE in C++. 4019 if (S.LangOpts.CPlusPlus) 4020 return true; 4021 4022 // C99 6.5.3.4p1: 4023 if (T->isFunctionType() && 4024 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4025 TraitKind == UETT_PreferredAlignOf)) { 4026 // sizeof(function)/alignof(function) is allowed as an extension. 4027 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4028 << getTraitSpelling(TraitKind) << ArgRange; 4029 return false; 4030 } 4031 4032 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4033 // this is an error (OpenCL v1.1 s6.3.k) 4034 if (T->isVoidType()) { 4035 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4036 : diag::ext_sizeof_alignof_void_type; 4037 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4038 return false; 4039 } 4040 4041 return true; 4042 } 4043 4044 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4045 SourceLocation Loc, 4046 SourceRange ArgRange, 4047 UnaryExprOrTypeTrait TraitKind) { 4048 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4049 // runtime doesn't allow it. 4050 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4051 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4052 << T << (TraitKind == UETT_SizeOf) 4053 << ArgRange; 4054 return true; 4055 } 4056 4057 return false; 4058 } 4059 4060 /// Check whether E is a pointer from a decayed array type (the decayed 4061 /// pointer type is equal to T) and emit a warning if it is. 4062 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4063 Expr *E) { 4064 // Don't warn if the operation changed the type. 4065 if (T != E->getType()) 4066 return; 4067 4068 // Now look for array decays. 4069 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4070 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4071 return; 4072 4073 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4074 << ICE->getType() 4075 << ICE->getSubExpr()->getType(); 4076 } 4077 4078 /// Check the constraints on expression operands to unary type expression 4079 /// and type traits. 4080 /// 4081 /// Completes any types necessary and validates the constraints on the operand 4082 /// expression. The logic mostly mirrors the type-based overload, but may modify 4083 /// the expression as it completes the type for that expression through template 4084 /// instantiation, etc. 4085 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4086 UnaryExprOrTypeTrait ExprKind) { 4087 QualType ExprTy = E->getType(); 4088 assert(!ExprTy->isReferenceType()); 4089 4090 bool IsUnevaluatedOperand = 4091 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4092 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4093 if (IsUnevaluatedOperand) { 4094 ExprResult Result = CheckUnevaluatedOperand(E); 4095 if (Result.isInvalid()) 4096 return true; 4097 E = Result.get(); 4098 } 4099 4100 // The operand for sizeof and alignof is in an unevaluated expression context, 4101 // so side effects could result in unintended consequences. 4102 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4103 // used to build SFINAE gadgets. 4104 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4105 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4106 !E->isInstantiationDependent() && 4107 E->HasSideEffects(Context, false)) 4108 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4109 4110 if (ExprKind == UETT_VecStep) 4111 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4112 E->getSourceRange()); 4113 4114 // Explicitly list some types as extensions. 4115 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4116 E->getSourceRange(), ExprKind)) 4117 return false; 4118 4119 // 'alignof' applied to an expression only requires the base element type of 4120 // the expression to be complete. 'sizeof' requires the expression's type to 4121 // be complete (and will attempt to complete it if it's an array of unknown 4122 // bound). 4123 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4124 if (RequireCompleteSizedType( 4125 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4126 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4127 getTraitSpelling(ExprKind), E->getSourceRange())) 4128 return true; 4129 } else { 4130 if (RequireCompleteSizedExprType( 4131 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4132 getTraitSpelling(ExprKind), E->getSourceRange())) 4133 return true; 4134 } 4135 4136 // Completing the expression's type may have changed it. 4137 ExprTy = E->getType(); 4138 assert(!ExprTy->isReferenceType()); 4139 4140 if (ExprTy->isFunctionType()) { 4141 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4142 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4143 return true; 4144 } 4145 4146 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4147 E->getSourceRange(), ExprKind)) 4148 return true; 4149 4150 if (ExprKind == UETT_SizeOf) { 4151 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4152 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4153 QualType OType = PVD->getOriginalType(); 4154 QualType Type = PVD->getType(); 4155 if (Type->isPointerType() && OType->isArrayType()) { 4156 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4157 << Type << OType; 4158 Diag(PVD->getLocation(), diag::note_declared_at); 4159 } 4160 } 4161 } 4162 4163 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4164 // decays into a pointer and returns an unintended result. This is most 4165 // likely a typo for "sizeof(array) op x". 4166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4167 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4168 BO->getLHS()); 4169 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4170 BO->getRHS()); 4171 } 4172 } 4173 4174 return false; 4175 } 4176 4177 /// Check the constraints on operands to unary expression and type 4178 /// traits. 4179 /// 4180 /// This will complete any types necessary, and validate the various constraints 4181 /// on those operands. 4182 /// 4183 /// The UsualUnaryConversions() function is *not* called by this routine. 4184 /// C99 6.3.2.1p[2-4] all state: 4185 /// Except when it is the operand of the sizeof operator ... 4186 /// 4187 /// C++ [expr.sizeof]p4 4188 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4189 /// standard conversions are not applied to the operand of sizeof. 4190 /// 4191 /// This policy is followed for all of the unary trait expressions. 4192 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4193 SourceLocation OpLoc, 4194 SourceRange ExprRange, 4195 UnaryExprOrTypeTrait ExprKind) { 4196 if (ExprType->isDependentType()) 4197 return false; 4198 4199 // C++ [expr.sizeof]p2: 4200 // When applied to a reference or a reference type, the result 4201 // is the size of the referenced type. 4202 // C++11 [expr.alignof]p3: 4203 // When alignof is applied to a reference type, the result 4204 // shall be the alignment of the referenced type. 4205 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4206 ExprType = Ref->getPointeeType(); 4207 4208 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4209 // When alignof or _Alignof is applied to an array type, the result 4210 // is the alignment of the element type. 4211 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4212 ExprKind == UETT_OpenMPRequiredSimdAlign) 4213 ExprType = Context.getBaseElementType(ExprType); 4214 4215 if (ExprKind == UETT_VecStep) 4216 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4217 4218 // Explicitly list some types as extensions. 4219 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4220 ExprKind)) 4221 return false; 4222 4223 if (RequireCompleteSizedType( 4224 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4225 getTraitSpelling(ExprKind), ExprRange)) 4226 return true; 4227 4228 if (ExprType->isFunctionType()) { 4229 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4230 << getTraitSpelling(ExprKind) << ExprRange; 4231 return true; 4232 } 4233 4234 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4235 ExprKind)) 4236 return true; 4237 4238 return false; 4239 } 4240 4241 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4242 // Cannot know anything else if the expression is dependent. 4243 if (E->isTypeDependent()) 4244 return false; 4245 4246 if (E->getObjectKind() == OK_BitField) { 4247 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4248 << 1 << E->getSourceRange(); 4249 return true; 4250 } 4251 4252 ValueDecl *D = nullptr; 4253 Expr *Inner = E->IgnoreParens(); 4254 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4255 D = DRE->getDecl(); 4256 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4257 D = ME->getMemberDecl(); 4258 } 4259 4260 // If it's a field, require the containing struct to have a 4261 // complete definition so that we can compute the layout. 4262 // 4263 // This can happen in C++11 onwards, either by naming the member 4264 // in a way that is not transformed into a member access expression 4265 // (in an unevaluated operand, for instance), or by naming the member 4266 // in a trailing-return-type. 4267 // 4268 // For the record, since __alignof__ on expressions is a GCC 4269 // extension, GCC seems to permit this but always gives the 4270 // nonsensical answer 0. 4271 // 4272 // We don't really need the layout here --- we could instead just 4273 // directly check for all the appropriate alignment-lowing 4274 // attributes --- but that would require duplicating a lot of 4275 // logic that just isn't worth duplicating for such a marginal 4276 // use-case. 4277 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4278 // Fast path this check, since we at least know the record has a 4279 // definition if we can find a member of it. 4280 if (!FD->getParent()->isCompleteDefinition()) { 4281 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4282 << E->getSourceRange(); 4283 return true; 4284 } 4285 4286 // Otherwise, if it's a field, and the field doesn't have 4287 // reference type, then it must have a complete type (or be a 4288 // flexible array member, which we explicitly want to 4289 // white-list anyway), which makes the following checks trivial. 4290 if (!FD->getType()->isReferenceType()) 4291 return false; 4292 } 4293 4294 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4295 } 4296 4297 bool Sema::CheckVecStepExpr(Expr *E) { 4298 E = E->IgnoreParens(); 4299 4300 // Cannot know anything else if the expression is dependent. 4301 if (E->isTypeDependent()) 4302 return false; 4303 4304 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4305 } 4306 4307 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4308 CapturingScopeInfo *CSI) { 4309 assert(T->isVariablyModifiedType()); 4310 assert(CSI != nullptr); 4311 4312 // We're going to walk down into the type and look for VLA expressions. 4313 do { 4314 const Type *Ty = T.getTypePtr(); 4315 switch (Ty->getTypeClass()) { 4316 #define TYPE(Class, Base) 4317 #define ABSTRACT_TYPE(Class, Base) 4318 #define NON_CANONICAL_TYPE(Class, Base) 4319 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4320 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4321 #include "clang/AST/TypeNodes.inc" 4322 T = QualType(); 4323 break; 4324 // These types are never variably-modified. 4325 case Type::Builtin: 4326 case Type::Complex: 4327 case Type::Vector: 4328 case Type::ExtVector: 4329 case Type::ConstantMatrix: 4330 case Type::Record: 4331 case Type::Enum: 4332 case Type::Elaborated: 4333 case Type::TemplateSpecialization: 4334 case Type::ObjCObject: 4335 case Type::ObjCInterface: 4336 case Type::ObjCObjectPointer: 4337 case Type::ObjCTypeParam: 4338 case Type::Pipe: 4339 case Type::ExtInt: 4340 llvm_unreachable("type class is never variably-modified!"); 4341 case Type::Adjusted: 4342 T = cast<AdjustedType>(Ty)->getOriginalType(); 4343 break; 4344 case Type::Decayed: 4345 T = cast<DecayedType>(Ty)->getPointeeType(); 4346 break; 4347 case Type::Pointer: 4348 T = cast<PointerType>(Ty)->getPointeeType(); 4349 break; 4350 case Type::BlockPointer: 4351 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4352 break; 4353 case Type::LValueReference: 4354 case Type::RValueReference: 4355 T = cast<ReferenceType>(Ty)->getPointeeType(); 4356 break; 4357 case Type::MemberPointer: 4358 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4359 break; 4360 case Type::ConstantArray: 4361 case Type::IncompleteArray: 4362 // Losing element qualification here is fine. 4363 T = cast<ArrayType>(Ty)->getElementType(); 4364 break; 4365 case Type::VariableArray: { 4366 // Losing element qualification here is fine. 4367 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4368 4369 // Unknown size indication requires no size computation. 4370 // Otherwise, evaluate and record it. 4371 auto Size = VAT->getSizeExpr(); 4372 if (Size && !CSI->isVLATypeCaptured(VAT) && 4373 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4374 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4375 4376 T = VAT->getElementType(); 4377 break; 4378 } 4379 case Type::FunctionProto: 4380 case Type::FunctionNoProto: 4381 T = cast<FunctionType>(Ty)->getReturnType(); 4382 break; 4383 case Type::Paren: 4384 case Type::TypeOf: 4385 case Type::UnaryTransform: 4386 case Type::Attributed: 4387 case Type::SubstTemplateTypeParm: 4388 case Type::MacroQualified: 4389 // Keep walking after single level desugaring. 4390 T = T.getSingleStepDesugaredType(Context); 4391 break; 4392 case Type::Typedef: 4393 T = cast<TypedefType>(Ty)->desugar(); 4394 break; 4395 case Type::Decltype: 4396 T = cast<DecltypeType>(Ty)->desugar(); 4397 break; 4398 case Type::Auto: 4399 case Type::DeducedTemplateSpecialization: 4400 T = cast<DeducedType>(Ty)->getDeducedType(); 4401 break; 4402 case Type::TypeOfExpr: 4403 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4404 break; 4405 case Type::Atomic: 4406 T = cast<AtomicType>(Ty)->getValueType(); 4407 break; 4408 } 4409 } while (!T.isNull() && T->isVariablyModifiedType()); 4410 } 4411 4412 /// Build a sizeof or alignof expression given a type operand. 4413 ExprResult 4414 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4415 SourceLocation OpLoc, 4416 UnaryExprOrTypeTrait ExprKind, 4417 SourceRange R) { 4418 if (!TInfo) 4419 return ExprError(); 4420 4421 QualType T = TInfo->getType(); 4422 4423 if (!T->isDependentType() && 4424 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4425 return ExprError(); 4426 4427 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4428 if (auto *TT = T->getAs<TypedefType>()) { 4429 for (auto I = FunctionScopes.rbegin(), 4430 E = std::prev(FunctionScopes.rend()); 4431 I != E; ++I) { 4432 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4433 if (CSI == nullptr) 4434 break; 4435 DeclContext *DC = nullptr; 4436 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4437 DC = LSI->CallOperator; 4438 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4439 DC = CRSI->TheCapturedDecl; 4440 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4441 DC = BSI->TheDecl; 4442 if (DC) { 4443 if (DC->containsDecl(TT->getDecl())) 4444 break; 4445 captureVariablyModifiedType(Context, T, CSI); 4446 } 4447 } 4448 } 4449 } 4450 4451 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4452 return new (Context) UnaryExprOrTypeTraitExpr( 4453 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4454 } 4455 4456 /// Build a sizeof or alignof expression given an expression 4457 /// operand. 4458 ExprResult 4459 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4460 UnaryExprOrTypeTrait ExprKind) { 4461 ExprResult PE = CheckPlaceholderExpr(E); 4462 if (PE.isInvalid()) 4463 return ExprError(); 4464 4465 E = PE.get(); 4466 4467 // Verify that the operand is valid. 4468 bool isInvalid = false; 4469 if (E->isTypeDependent()) { 4470 // Delay type-checking for type-dependent expressions. 4471 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4472 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4473 } else if (ExprKind == UETT_VecStep) { 4474 isInvalid = CheckVecStepExpr(E); 4475 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4476 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4477 isInvalid = true; 4478 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4479 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4480 isInvalid = true; 4481 } else { 4482 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4483 } 4484 4485 if (isInvalid) 4486 return ExprError(); 4487 4488 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4489 PE = TransformToPotentiallyEvaluated(E); 4490 if (PE.isInvalid()) return ExprError(); 4491 E = PE.get(); 4492 } 4493 4494 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4495 return new (Context) UnaryExprOrTypeTraitExpr( 4496 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4497 } 4498 4499 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4500 /// expr and the same for @c alignof and @c __alignof 4501 /// Note that the ArgRange is invalid if isType is false. 4502 ExprResult 4503 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4504 UnaryExprOrTypeTrait ExprKind, bool IsType, 4505 void *TyOrEx, SourceRange ArgRange) { 4506 // If error parsing type, ignore. 4507 if (!TyOrEx) return ExprError(); 4508 4509 if (IsType) { 4510 TypeSourceInfo *TInfo; 4511 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4512 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4513 } 4514 4515 Expr *ArgEx = (Expr *)TyOrEx; 4516 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4517 return Result; 4518 } 4519 4520 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4521 bool IsReal) { 4522 if (V.get()->isTypeDependent()) 4523 return S.Context.DependentTy; 4524 4525 // _Real and _Imag are only l-values for normal l-values. 4526 if (V.get()->getObjectKind() != OK_Ordinary) { 4527 V = S.DefaultLvalueConversion(V.get()); 4528 if (V.isInvalid()) 4529 return QualType(); 4530 } 4531 4532 // These operators return the element type of a complex type. 4533 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4534 return CT->getElementType(); 4535 4536 // Otherwise they pass through real integer and floating point types here. 4537 if (V.get()->getType()->isArithmeticType()) 4538 return V.get()->getType(); 4539 4540 // Test for placeholders. 4541 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4542 if (PR.isInvalid()) return QualType(); 4543 if (PR.get() != V.get()) { 4544 V = PR; 4545 return CheckRealImagOperand(S, V, Loc, IsReal); 4546 } 4547 4548 // Reject anything else. 4549 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4550 << (IsReal ? "__real" : "__imag"); 4551 return QualType(); 4552 } 4553 4554 4555 4556 ExprResult 4557 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4558 tok::TokenKind Kind, Expr *Input) { 4559 UnaryOperatorKind Opc; 4560 switch (Kind) { 4561 default: llvm_unreachable("Unknown unary op!"); 4562 case tok::plusplus: Opc = UO_PostInc; break; 4563 case tok::minusminus: Opc = UO_PostDec; break; 4564 } 4565 4566 // Since this might is a postfix expression, get rid of ParenListExprs. 4567 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4568 if (Result.isInvalid()) return ExprError(); 4569 Input = Result.get(); 4570 4571 return BuildUnaryOp(S, OpLoc, Opc, Input); 4572 } 4573 4574 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4575 /// 4576 /// \return true on error 4577 static bool checkArithmeticOnObjCPointer(Sema &S, 4578 SourceLocation opLoc, 4579 Expr *op) { 4580 assert(op->getType()->isObjCObjectPointerType()); 4581 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4582 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4583 return false; 4584 4585 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4586 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4587 << op->getSourceRange(); 4588 return true; 4589 } 4590 4591 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4592 auto *BaseNoParens = Base->IgnoreParens(); 4593 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4594 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4595 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4596 } 4597 4598 ExprResult 4599 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4600 Expr *idx, SourceLocation rbLoc) { 4601 if (base && !base->getType().isNull() && 4602 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4603 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4604 SourceLocation(), /*Length*/ nullptr, 4605 /*Stride=*/nullptr, rbLoc); 4606 4607 // Since this might be a postfix expression, get rid of ParenListExprs. 4608 if (isa<ParenListExpr>(base)) { 4609 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4610 if (result.isInvalid()) return ExprError(); 4611 base = result.get(); 4612 } 4613 4614 // Check if base and idx form a MatrixSubscriptExpr. 4615 // 4616 // Helper to check for comma expressions, which are not allowed as indices for 4617 // matrix subscript expressions. 4618 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4619 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4620 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4621 << SourceRange(base->getBeginLoc(), rbLoc); 4622 return true; 4623 } 4624 return false; 4625 }; 4626 // The matrix subscript operator ([][])is considered a single operator. 4627 // Separating the index expressions by parenthesis is not allowed. 4628 if (base->getType()->isSpecificPlaceholderType( 4629 BuiltinType::IncompleteMatrixIdx) && 4630 !isa<MatrixSubscriptExpr>(base)) { 4631 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4632 << SourceRange(base->getBeginLoc(), rbLoc); 4633 return ExprError(); 4634 } 4635 // If the base is a MatrixSubscriptExpr, try to create a new 4636 // MatrixSubscriptExpr. 4637 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4638 if (matSubscriptE) { 4639 if (CheckAndReportCommaError(idx)) 4640 return ExprError(); 4641 4642 assert(matSubscriptE->isIncomplete() && 4643 "base has to be an incomplete matrix subscript"); 4644 return CreateBuiltinMatrixSubscriptExpr( 4645 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4646 } 4647 4648 // Handle any non-overload placeholder types in the base and index 4649 // expressions. We can't handle overloads here because the other 4650 // operand might be an overloadable type, in which case the overload 4651 // resolution for the operator overload should get the first crack 4652 // at the overload. 4653 bool IsMSPropertySubscript = false; 4654 if (base->getType()->isNonOverloadPlaceholderType()) { 4655 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4656 if (!IsMSPropertySubscript) { 4657 ExprResult result = CheckPlaceholderExpr(base); 4658 if (result.isInvalid()) 4659 return ExprError(); 4660 base = result.get(); 4661 } 4662 } 4663 4664 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4665 if (base->getType()->isMatrixType()) { 4666 if (CheckAndReportCommaError(idx)) 4667 return ExprError(); 4668 4669 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4670 } 4671 4672 // A comma-expression as the index is deprecated in C++2a onwards. 4673 if (getLangOpts().CPlusPlus20 && 4674 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4675 (isa<CXXOperatorCallExpr>(idx) && 4676 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4677 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4678 << SourceRange(base->getBeginLoc(), rbLoc); 4679 } 4680 4681 if (idx->getType()->isNonOverloadPlaceholderType()) { 4682 ExprResult result = CheckPlaceholderExpr(idx); 4683 if (result.isInvalid()) return ExprError(); 4684 idx = result.get(); 4685 } 4686 4687 // Build an unanalyzed expression if either operand is type-dependent. 4688 if (getLangOpts().CPlusPlus && 4689 (base->isTypeDependent() || idx->isTypeDependent())) { 4690 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4691 VK_LValue, OK_Ordinary, rbLoc); 4692 } 4693 4694 // MSDN, property (C++) 4695 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4696 // This attribute can also be used in the declaration of an empty array in a 4697 // class or structure definition. For example: 4698 // __declspec(property(get=GetX, put=PutX)) int x[]; 4699 // The above statement indicates that x[] can be used with one or more array 4700 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4701 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4702 if (IsMSPropertySubscript) { 4703 // Build MS property subscript expression if base is MS property reference 4704 // or MS property subscript. 4705 return new (Context) MSPropertySubscriptExpr( 4706 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4707 } 4708 4709 // Use C++ overloaded-operator rules if either operand has record 4710 // type. The spec says to do this if either type is *overloadable*, 4711 // but enum types can't declare subscript operators or conversion 4712 // operators, so there's nothing interesting for overload resolution 4713 // to do if there aren't any record types involved. 4714 // 4715 // ObjC pointers have their own subscripting logic that is not tied 4716 // to overload resolution and so should not take this path. 4717 if (getLangOpts().CPlusPlus && 4718 (base->getType()->isRecordType() || 4719 (!base->getType()->isObjCObjectPointerType() && 4720 idx->getType()->isRecordType()))) { 4721 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4722 } 4723 4724 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4725 4726 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4727 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4728 4729 return Res; 4730 } 4731 4732 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4733 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4734 InitializationKind Kind = 4735 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4736 InitializationSequence InitSeq(*this, Entity, Kind, E); 4737 return InitSeq.Perform(*this, Entity, Kind, E); 4738 } 4739 4740 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4741 Expr *ColumnIdx, 4742 SourceLocation RBLoc) { 4743 ExprResult BaseR = CheckPlaceholderExpr(Base); 4744 if (BaseR.isInvalid()) 4745 return BaseR; 4746 Base = BaseR.get(); 4747 4748 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4749 if (RowR.isInvalid()) 4750 return RowR; 4751 RowIdx = RowR.get(); 4752 4753 if (!ColumnIdx) 4754 return new (Context) MatrixSubscriptExpr( 4755 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4756 4757 // Build an unanalyzed expression if any of the operands is type-dependent. 4758 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4759 ColumnIdx->isTypeDependent()) 4760 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4761 Context.DependentTy, RBLoc); 4762 4763 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4764 if (ColumnR.isInvalid()) 4765 return ColumnR; 4766 ColumnIdx = ColumnR.get(); 4767 4768 // Check that IndexExpr is an integer expression. If it is a constant 4769 // expression, check that it is less than Dim (= the number of elements in the 4770 // corresponding dimension). 4771 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4772 bool IsColumnIdx) -> Expr * { 4773 if (!IndexExpr->getType()->isIntegerType() && 4774 !IndexExpr->isTypeDependent()) { 4775 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4776 << IsColumnIdx; 4777 return nullptr; 4778 } 4779 4780 if (Optional<llvm::APSInt> Idx = 4781 IndexExpr->getIntegerConstantExpr(Context)) { 4782 if ((*Idx < 0 || *Idx >= Dim)) { 4783 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4784 << IsColumnIdx << Dim; 4785 return nullptr; 4786 } 4787 } 4788 4789 ExprResult ConvExpr = 4790 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4791 assert(!ConvExpr.isInvalid() && 4792 "should be able to convert any integer type to size type"); 4793 return ConvExpr.get(); 4794 }; 4795 4796 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4797 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4798 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4799 if (!RowIdx || !ColumnIdx) 4800 return ExprError(); 4801 4802 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4803 MTy->getElementType(), RBLoc); 4804 } 4805 4806 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4807 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4808 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4809 4810 // For expressions like `&(*s).b`, the base is recorded and what should be 4811 // checked. 4812 const MemberExpr *Member = nullptr; 4813 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4814 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4815 4816 LastRecord.PossibleDerefs.erase(StrippedExpr); 4817 } 4818 4819 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4820 if (isUnevaluatedContext()) 4821 return; 4822 4823 QualType ResultTy = E->getType(); 4824 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4825 4826 // Bail if the element is an array since it is not memory access. 4827 if (isa<ArrayType>(ResultTy)) 4828 return; 4829 4830 if (ResultTy->hasAttr(attr::NoDeref)) { 4831 LastRecord.PossibleDerefs.insert(E); 4832 return; 4833 } 4834 4835 // Check if the base type is a pointer to a member access of a struct 4836 // marked with noderef. 4837 const Expr *Base = E->getBase(); 4838 QualType BaseTy = Base->getType(); 4839 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4840 // Not a pointer access 4841 return; 4842 4843 const MemberExpr *Member = nullptr; 4844 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4845 Member->isArrow()) 4846 Base = Member->getBase(); 4847 4848 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4849 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4850 LastRecord.PossibleDerefs.insert(E); 4851 } 4852 } 4853 4854 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4855 Expr *LowerBound, 4856 SourceLocation ColonLocFirst, 4857 SourceLocation ColonLocSecond, 4858 Expr *Length, Expr *Stride, 4859 SourceLocation RBLoc) { 4860 if (Base->getType()->isPlaceholderType() && 4861 !Base->getType()->isSpecificPlaceholderType( 4862 BuiltinType::OMPArraySection)) { 4863 ExprResult Result = CheckPlaceholderExpr(Base); 4864 if (Result.isInvalid()) 4865 return ExprError(); 4866 Base = Result.get(); 4867 } 4868 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4869 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4870 if (Result.isInvalid()) 4871 return ExprError(); 4872 Result = DefaultLvalueConversion(Result.get()); 4873 if (Result.isInvalid()) 4874 return ExprError(); 4875 LowerBound = Result.get(); 4876 } 4877 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4878 ExprResult Result = CheckPlaceholderExpr(Length); 4879 if (Result.isInvalid()) 4880 return ExprError(); 4881 Result = DefaultLvalueConversion(Result.get()); 4882 if (Result.isInvalid()) 4883 return ExprError(); 4884 Length = Result.get(); 4885 } 4886 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4887 ExprResult Result = CheckPlaceholderExpr(Stride); 4888 if (Result.isInvalid()) 4889 return ExprError(); 4890 Result = DefaultLvalueConversion(Result.get()); 4891 if (Result.isInvalid()) 4892 return ExprError(); 4893 Stride = Result.get(); 4894 } 4895 4896 // Build an unanalyzed expression if either operand is type-dependent. 4897 if (Base->isTypeDependent() || 4898 (LowerBound && 4899 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4900 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4901 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4902 return new (Context) OMPArraySectionExpr( 4903 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4904 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4905 } 4906 4907 // Perform default conversions. 4908 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4909 QualType ResultTy; 4910 if (OriginalTy->isAnyPointerType()) { 4911 ResultTy = OriginalTy->getPointeeType(); 4912 } else if (OriginalTy->isArrayType()) { 4913 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4914 } else { 4915 return ExprError( 4916 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4917 << Base->getSourceRange()); 4918 } 4919 // C99 6.5.2.1p1 4920 if (LowerBound) { 4921 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4922 LowerBound); 4923 if (Res.isInvalid()) 4924 return ExprError(Diag(LowerBound->getExprLoc(), 4925 diag::err_omp_typecheck_section_not_integer) 4926 << 0 << LowerBound->getSourceRange()); 4927 LowerBound = Res.get(); 4928 4929 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4930 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4931 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4932 << 0 << LowerBound->getSourceRange(); 4933 } 4934 if (Length) { 4935 auto Res = 4936 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4937 if (Res.isInvalid()) 4938 return ExprError(Diag(Length->getExprLoc(), 4939 diag::err_omp_typecheck_section_not_integer) 4940 << 1 << Length->getSourceRange()); 4941 Length = Res.get(); 4942 4943 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4944 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4945 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4946 << 1 << Length->getSourceRange(); 4947 } 4948 if (Stride) { 4949 ExprResult Res = 4950 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4951 if (Res.isInvalid()) 4952 return ExprError(Diag(Stride->getExprLoc(), 4953 diag::err_omp_typecheck_section_not_integer) 4954 << 1 << Stride->getSourceRange()); 4955 Stride = Res.get(); 4956 4957 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4958 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4959 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4960 << 1 << Stride->getSourceRange(); 4961 } 4962 4963 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4964 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4965 // type. Note that functions are not objects, and that (in C99 parlance) 4966 // incomplete types are not object types. 4967 if (ResultTy->isFunctionType()) { 4968 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4969 << ResultTy << Base->getSourceRange(); 4970 return ExprError(); 4971 } 4972 4973 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4974 diag::err_omp_section_incomplete_type, Base)) 4975 return ExprError(); 4976 4977 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4978 Expr::EvalResult Result; 4979 if (LowerBound->EvaluateAsInt(Result, Context)) { 4980 // OpenMP 5.0, [2.1.5 Array Sections] 4981 // The array section must be a subset of the original array. 4982 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4983 if (LowerBoundValue.isNegative()) { 4984 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4985 << LowerBound->getSourceRange(); 4986 return ExprError(); 4987 } 4988 } 4989 } 4990 4991 if (Length) { 4992 Expr::EvalResult Result; 4993 if (Length->EvaluateAsInt(Result, Context)) { 4994 // OpenMP 5.0, [2.1.5 Array Sections] 4995 // The length must evaluate to non-negative integers. 4996 llvm::APSInt LengthValue = Result.Val.getInt(); 4997 if (LengthValue.isNegative()) { 4998 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4999 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 5000 << Length->getSourceRange(); 5001 return ExprError(); 5002 } 5003 } 5004 } else if (ColonLocFirst.isValid() && 5005 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5006 !OriginalTy->isVariableArrayType()))) { 5007 // OpenMP 5.0, [2.1.5 Array Sections] 5008 // When the size of the array dimension is not known, the length must be 5009 // specified explicitly. 5010 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5011 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5012 return ExprError(); 5013 } 5014 5015 if (Stride) { 5016 Expr::EvalResult Result; 5017 if (Stride->EvaluateAsInt(Result, Context)) { 5018 // OpenMP 5.0, [2.1.5 Array Sections] 5019 // The stride must evaluate to a positive integer. 5020 llvm::APSInt StrideValue = Result.Val.getInt(); 5021 if (!StrideValue.isStrictlyPositive()) { 5022 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5023 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5024 << Stride->getSourceRange(); 5025 return ExprError(); 5026 } 5027 } 5028 } 5029 5030 if (!Base->getType()->isSpecificPlaceholderType( 5031 BuiltinType::OMPArraySection)) { 5032 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5033 if (Result.isInvalid()) 5034 return ExprError(); 5035 Base = Result.get(); 5036 } 5037 return new (Context) OMPArraySectionExpr( 5038 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5039 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5040 } 5041 5042 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5043 SourceLocation RParenLoc, 5044 ArrayRef<Expr *> Dims, 5045 ArrayRef<SourceRange> Brackets) { 5046 if (Base->getType()->isPlaceholderType()) { 5047 ExprResult Result = CheckPlaceholderExpr(Base); 5048 if (Result.isInvalid()) 5049 return ExprError(); 5050 Result = DefaultLvalueConversion(Result.get()); 5051 if (Result.isInvalid()) 5052 return ExprError(); 5053 Base = Result.get(); 5054 } 5055 QualType BaseTy = Base->getType(); 5056 // Delay analysis of the types/expressions if instantiation/specialization is 5057 // required. 5058 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5059 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5060 LParenLoc, RParenLoc, Dims, Brackets); 5061 if (!BaseTy->isPointerType() || 5062 (!Base->isTypeDependent() && 5063 BaseTy->getPointeeType()->isIncompleteType())) 5064 return ExprError(Diag(Base->getExprLoc(), 5065 diag::err_omp_non_pointer_type_array_shaping_base) 5066 << Base->getSourceRange()); 5067 5068 SmallVector<Expr *, 4> NewDims; 5069 bool ErrorFound = false; 5070 for (Expr *Dim : Dims) { 5071 if (Dim->getType()->isPlaceholderType()) { 5072 ExprResult Result = CheckPlaceholderExpr(Dim); 5073 if (Result.isInvalid()) { 5074 ErrorFound = true; 5075 continue; 5076 } 5077 Result = DefaultLvalueConversion(Result.get()); 5078 if (Result.isInvalid()) { 5079 ErrorFound = true; 5080 continue; 5081 } 5082 Dim = Result.get(); 5083 } 5084 if (!Dim->isTypeDependent()) { 5085 ExprResult Result = 5086 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5087 if (Result.isInvalid()) { 5088 ErrorFound = true; 5089 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5090 << Dim->getSourceRange(); 5091 continue; 5092 } 5093 Dim = Result.get(); 5094 Expr::EvalResult EvResult; 5095 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5096 // OpenMP 5.0, [2.1.4 Array Shaping] 5097 // Each si is an integral type expression that must evaluate to a 5098 // positive integer. 5099 llvm::APSInt Value = EvResult.Val.getInt(); 5100 if (!Value.isStrictlyPositive()) { 5101 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5102 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5103 << Dim->getSourceRange(); 5104 ErrorFound = true; 5105 continue; 5106 } 5107 } 5108 } 5109 NewDims.push_back(Dim); 5110 } 5111 if (ErrorFound) 5112 return ExprError(); 5113 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5114 LParenLoc, RParenLoc, NewDims, Brackets); 5115 } 5116 5117 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5118 SourceLocation LLoc, SourceLocation RLoc, 5119 ArrayRef<OMPIteratorData> Data) { 5120 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5121 bool IsCorrect = true; 5122 for (const OMPIteratorData &D : Data) { 5123 TypeSourceInfo *TInfo = nullptr; 5124 SourceLocation StartLoc; 5125 QualType DeclTy; 5126 if (!D.Type.getAsOpaquePtr()) { 5127 // OpenMP 5.0, 2.1.6 Iterators 5128 // In an iterator-specifier, if the iterator-type is not specified then 5129 // the type of that iterator is of int type. 5130 DeclTy = Context.IntTy; 5131 StartLoc = D.DeclIdentLoc; 5132 } else { 5133 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5134 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5135 } 5136 5137 bool IsDeclTyDependent = DeclTy->isDependentType() || 5138 DeclTy->containsUnexpandedParameterPack() || 5139 DeclTy->isInstantiationDependentType(); 5140 if (!IsDeclTyDependent) { 5141 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5142 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5143 // The iterator-type must be an integral or pointer type. 5144 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5145 << DeclTy; 5146 IsCorrect = false; 5147 continue; 5148 } 5149 if (DeclTy.isConstant(Context)) { 5150 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5151 // The iterator-type must not be const qualified. 5152 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5153 << DeclTy; 5154 IsCorrect = false; 5155 continue; 5156 } 5157 } 5158 5159 // Iterator declaration. 5160 assert(D.DeclIdent && "Identifier expected."); 5161 // Always try to create iterator declarator to avoid extra error messages 5162 // about unknown declarations use. 5163 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5164 D.DeclIdent, DeclTy, TInfo, SC_None); 5165 VD->setImplicit(); 5166 if (S) { 5167 // Check for conflicting previous declaration. 5168 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5169 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5170 ForVisibleRedeclaration); 5171 Previous.suppressDiagnostics(); 5172 LookupName(Previous, S); 5173 5174 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5175 /*AllowInlineNamespace=*/false); 5176 if (!Previous.empty()) { 5177 NamedDecl *Old = Previous.getRepresentativeDecl(); 5178 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5179 Diag(Old->getLocation(), diag::note_previous_definition); 5180 } else { 5181 PushOnScopeChains(VD, S); 5182 } 5183 } else { 5184 CurContext->addDecl(VD); 5185 } 5186 Expr *Begin = D.Range.Begin; 5187 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5188 ExprResult BeginRes = 5189 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5190 Begin = BeginRes.get(); 5191 } 5192 Expr *End = D.Range.End; 5193 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5194 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5195 End = EndRes.get(); 5196 } 5197 Expr *Step = D.Range.Step; 5198 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5199 if (!Step->getType()->isIntegralType(Context)) { 5200 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5201 << Step << Step->getSourceRange(); 5202 IsCorrect = false; 5203 continue; 5204 } 5205 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5206 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5207 // If the step expression of a range-specification equals zero, the 5208 // behavior is unspecified. 5209 if (Result && Result->isNullValue()) { 5210 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5211 << Step << Step->getSourceRange(); 5212 IsCorrect = false; 5213 continue; 5214 } 5215 } 5216 if (!Begin || !End || !IsCorrect) { 5217 IsCorrect = false; 5218 continue; 5219 } 5220 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5221 IDElem.IteratorDecl = VD; 5222 IDElem.AssignmentLoc = D.AssignLoc; 5223 IDElem.Range.Begin = Begin; 5224 IDElem.Range.End = End; 5225 IDElem.Range.Step = Step; 5226 IDElem.ColonLoc = D.ColonLoc; 5227 IDElem.SecondColonLoc = D.SecColonLoc; 5228 } 5229 if (!IsCorrect) { 5230 // Invalidate all created iterator declarations if error is found. 5231 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5232 if (Decl *ID = D.IteratorDecl) 5233 ID->setInvalidDecl(); 5234 } 5235 return ExprError(); 5236 } 5237 SmallVector<OMPIteratorHelperData, 4> Helpers; 5238 if (!CurContext->isDependentContext()) { 5239 // Build number of ityeration for each iteration range. 5240 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5241 // ((Begini-Stepi-1-Endi) / -Stepi); 5242 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5243 // (Endi - Begini) 5244 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5245 D.Range.Begin); 5246 if(!Res.isUsable()) { 5247 IsCorrect = false; 5248 continue; 5249 } 5250 ExprResult St, St1; 5251 if (D.Range.Step) { 5252 St = D.Range.Step; 5253 // (Endi - Begini) + Stepi 5254 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5255 if (!Res.isUsable()) { 5256 IsCorrect = false; 5257 continue; 5258 } 5259 // (Endi - Begini) + Stepi - 1 5260 Res = 5261 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5262 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5263 if (!Res.isUsable()) { 5264 IsCorrect = false; 5265 continue; 5266 } 5267 // ((Endi - Begini) + Stepi - 1) / Stepi 5268 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5269 if (!Res.isUsable()) { 5270 IsCorrect = false; 5271 continue; 5272 } 5273 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5274 // (Begini - Endi) 5275 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5276 D.Range.Begin, D.Range.End); 5277 if (!Res1.isUsable()) { 5278 IsCorrect = false; 5279 continue; 5280 } 5281 // (Begini - Endi) - Stepi 5282 Res1 = 5283 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5284 if (!Res1.isUsable()) { 5285 IsCorrect = false; 5286 continue; 5287 } 5288 // (Begini - Endi) - Stepi - 1 5289 Res1 = 5290 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5291 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5292 if (!Res1.isUsable()) { 5293 IsCorrect = false; 5294 continue; 5295 } 5296 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5297 Res1 = 5298 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5299 if (!Res1.isUsable()) { 5300 IsCorrect = false; 5301 continue; 5302 } 5303 // Stepi > 0. 5304 ExprResult CmpRes = 5305 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5306 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5307 if (!CmpRes.isUsable()) { 5308 IsCorrect = false; 5309 continue; 5310 } 5311 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5312 Res.get(), Res1.get()); 5313 if (!Res.isUsable()) { 5314 IsCorrect = false; 5315 continue; 5316 } 5317 } 5318 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5319 if (!Res.isUsable()) { 5320 IsCorrect = false; 5321 continue; 5322 } 5323 5324 // Build counter update. 5325 // Build counter. 5326 auto *CounterVD = 5327 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5328 D.IteratorDecl->getBeginLoc(), nullptr, 5329 Res.get()->getType(), nullptr, SC_None); 5330 CounterVD->setImplicit(); 5331 ExprResult RefRes = 5332 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5333 D.IteratorDecl->getBeginLoc()); 5334 // Build counter update. 5335 // I = Begini + counter * Stepi; 5336 ExprResult UpdateRes; 5337 if (D.Range.Step) { 5338 UpdateRes = CreateBuiltinBinOp( 5339 D.AssignmentLoc, BO_Mul, 5340 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5341 } else { 5342 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5343 } 5344 if (!UpdateRes.isUsable()) { 5345 IsCorrect = false; 5346 continue; 5347 } 5348 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5349 UpdateRes.get()); 5350 if (!UpdateRes.isUsable()) { 5351 IsCorrect = false; 5352 continue; 5353 } 5354 ExprResult VDRes = 5355 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5356 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5357 D.IteratorDecl->getBeginLoc()); 5358 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5359 UpdateRes.get()); 5360 if (!UpdateRes.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 UpdateRes = 5365 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5366 if (!UpdateRes.isUsable()) { 5367 IsCorrect = false; 5368 continue; 5369 } 5370 ExprResult CounterUpdateRes = 5371 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5372 if (!CounterUpdateRes.isUsable()) { 5373 IsCorrect = false; 5374 continue; 5375 } 5376 CounterUpdateRes = 5377 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5378 if (!CounterUpdateRes.isUsable()) { 5379 IsCorrect = false; 5380 continue; 5381 } 5382 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5383 HD.CounterVD = CounterVD; 5384 HD.Upper = Res.get(); 5385 HD.Update = UpdateRes.get(); 5386 HD.CounterUpdate = CounterUpdateRes.get(); 5387 } 5388 } else { 5389 Helpers.assign(ID.size(), {}); 5390 } 5391 if (!IsCorrect) { 5392 // Invalidate all created iterator declarations if error is found. 5393 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5394 if (Decl *ID = D.IteratorDecl) 5395 ID->setInvalidDecl(); 5396 } 5397 return ExprError(); 5398 } 5399 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5400 LLoc, RLoc, ID, Helpers); 5401 } 5402 5403 ExprResult 5404 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5405 Expr *Idx, SourceLocation RLoc) { 5406 Expr *LHSExp = Base; 5407 Expr *RHSExp = Idx; 5408 5409 ExprValueKind VK = VK_LValue; 5410 ExprObjectKind OK = OK_Ordinary; 5411 5412 // Per C++ core issue 1213, the result is an xvalue if either operand is 5413 // a non-lvalue array, and an lvalue otherwise. 5414 if (getLangOpts().CPlusPlus11) { 5415 for (auto *Op : {LHSExp, RHSExp}) { 5416 Op = Op->IgnoreImplicit(); 5417 if (Op->getType()->isArrayType() && !Op->isLValue()) 5418 VK = VK_XValue; 5419 } 5420 } 5421 5422 // Perform default conversions. 5423 if (!LHSExp->getType()->getAs<VectorType>()) { 5424 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5425 if (Result.isInvalid()) 5426 return ExprError(); 5427 LHSExp = Result.get(); 5428 } 5429 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5430 if (Result.isInvalid()) 5431 return ExprError(); 5432 RHSExp = Result.get(); 5433 5434 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5435 5436 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5437 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5438 // in the subscript position. As a result, we need to derive the array base 5439 // and index from the expression types. 5440 Expr *BaseExpr, *IndexExpr; 5441 QualType ResultType; 5442 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5443 BaseExpr = LHSExp; 5444 IndexExpr = RHSExp; 5445 ResultType = Context.DependentTy; 5446 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5447 BaseExpr = LHSExp; 5448 IndexExpr = RHSExp; 5449 ResultType = PTy->getPointeeType(); 5450 } else if (const ObjCObjectPointerType *PTy = 5451 LHSTy->getAs<ObjCObjectPointerType>()) { 5452 BaseExpr = LHSExp; 5453 IndexExpr = RHSExp; 5454 5455 // Use custom logic if this should be the pseudo-object subscript 5456 // expression. 5457 if (!LangOpts.isSubscriptPointerArithmetic()) 5458 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5459 nullptr); 5460 5461 ResultType = PTy->getPointeeType(); 5462 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5463 // Handle the uncommon case of "123[Ptr]". 5464 BaseExpr = RHSExp; 5465 IndexExpr = LHSExp; 5466 ResultType = PTy->getPointeeType(); 5467 } else if (const ObjCObjectPointerType *PTy = 5468 RHSTy->getAs<ObjCObjectPointerType>()) { 5469 // Handle the uncommon case of "123[Ptr]". 5470 BaseExpr = RHSExp; 5471 IndexExpr = LHSExp; 5472 ResultType = PTy->getPointeeType(); 5473 if (!LangOpts.isSubscriptPointerArithmetic()) { 5474 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5475 << ResultType << BaseExpr->getSourceRange(); 5476 return ExprError(); 5477 } 5478 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5479 BaseExpr = LHSExp; // vectors: V[123] 5480 IndexExpr = RHSExp; 5481 // We apply C++ DR1213 to vector subscripting too. 5482 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5483 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5484 if (Materialized.isInvalid()) 5485 return ExprError(); 5486 LHSExp = Materialized.get(); 5487 } 5488 VK = LHSExp->getValueKind(); 5489 if (VK != VK_RValue) 5490 OK = OK_VectorComponent; 5491 5492 ResultType = VTy->getElementType(); 5493 QualType BaseType = BaseExpr->getType(); 5494 Qualifiers BaseQuals = BaseType.getQualifiers(); 5495 Qualifiers MemberQuals = ResultType.getQualifiers(); 5496 Qualifiers Combined = BaseQuals + MemberQuals; 5497 if (Combined != MemberQuals) 5498 ResultType = Context.getQualifiedType(ResultType, Combined); 5499 } else if (LHSTy->isArrayType()) { 5500 // If we see an array that wasn't promoted by 5501 // DefaultFunctionArrayLvalueConversion, it must be an array that 5502 // wasn't promoted because of the C90 rule that doesn't 5503 // allow promoting non-lvalue arrays. Warn, then 5504 // force the promotion here. 5505 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5506 << LHSExp->getSourceRange(); 5507 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5508 CK_ArrayToPointerDecay).get(); 5509 LHSTy = LHSExp->getType(); 5510 5511 BaseExpr = LHSExp; 5512 IndexExpr = RHSExp; 5513 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5514 } else if (RHSTy->isArrayType()) { 5515 // Same as previous, except for 123[f().a] case 5516 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5517 << RHSExp->getSourceRange(); 5518 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5519 CK_ArrayToPointerDecay).get(); 5520 RHSTy = RHSExp->getType(); 5521 5522 BaseExpr = RHSExp; 5523 IndexExpr = LHSExp; 5524 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5525 } else { 5526 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5527 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5528 } 5529 // C99 6.5.2.1p1 5530 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5531 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5532 << IndexExpr->getSourceRange()); 5533 5534 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5535 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5536 && !IndexExpr->isTypeDependent()) 5537 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5538 5539 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5540 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5541 // type. Note that Functions are not objects, and that (in C99 parlance) 5542 // incomplete types are not object types. 5543 if (ResultType->isFunctionType()) { 5544 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5545 << ResultType << BaseExpr->getSourceRange(); 5546 return ExprError(); 5547 } 5548 5549 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5550 // GNU extension: subscripting on pointer to void 5551 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5552 << BaseExpr->getSourceRange(); 5553 5554 // C forbids expressions of unqualified void type from being l-values. 5555 // See IsCForbiddenLValueType. 5556 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5557 } else if (!ResultType->isDependentType() && 5558 RequireCompleteSizedType( 5559 LLoc, ResultType, 5560 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5561 return ExprError(); 5562 5563 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5564 !ResultType.isCForbiddenLValueType()); 5565 5566 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5567 FunctionScopes.size() > 1) { 5568 if (auto *TT = 5569 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5570 for (auto I = FunctionScopes.rbegin(), 5571 E = std::prev(FunctionScopes.rend()); 5572 I != E; ++I) { 5573 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5574 if (CSI == nullptr) 5575 break; 5576 DeclContext *DC = nullptr; 5577 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5578 DC = LSI->CallOperator; 5579 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5580 DC = CRSI->TheCapturedDecl; 5581 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5582 DC = BSI->TheDecl; 5583 if (DC) { 5584 if (DC->containsDecl(TT->getDecl())) 5585 break; 5586 captureVariablyModifiedType( 5587 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5588 } 5589 } 5590 } 5591 } 5592 5593 return new (Context) 5594 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5595 } 5596 5597 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5598 ParmVarDecl *Param) { 5599 if (Param->hasUnparsedDefaultArg()) { 5600 // If we've already cleared out the location for the default argument, 5601 // that means we're parsing it right now. 5602 if (!UnparsedDefaultArgLocs.count(Param)) { 5603 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5604 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5605 Param->setInvalidDecl(); 5606 return true; 5607 } 5608 5609 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5610 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5611 Diag(UnparsedDefaultArgLocs[Param], 5612 diag::note_default_argument_declared_here); 5613 return true; 5614 } 5615 5616 if (Param->hasUninstantiatedDefaultArg() && 5617 InstantiateDefaultArgument(CallLoc, FD, Param)) 5618 return true; 5619 5620 assert(Param->hasInit() && "default argument but no initializer?"); 5621 5622 // If the default expression creates temporaries, we need to 5623 // push them to the current stack of expression temporaries so they'll 5624 // be properly destroyed. 5625 // FIXME: We should really be rebuilding the default argument with new 5626 // bound temporaries; see the comment in PR5810. 5627 // We don't need to do that with block decls, though, because 5628 // blocks in default argument expression can never capture anything. 5629 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5630 // Set the "needs cleanups" bit regardless of whether there are 5631 // any explicit objects. 5632 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5633 5634 // Append all the objects to the cleanup list. Right now, this 5635 // should always be a no-op, because blocks in default argument 5636 // expressions should never be able to capture anything. 5637 assert(!Init->getNumObjects() && 5638 "default argument expression has capturing blocks?"); 5639 } 5640 5641 // We already type-checked the argument, so we know it works. 5642 // Just mark all of the declarations in this potentially-evaluated expression 5643 // as being "referenced". 5644 EnterExpressionEvaluationContext EvalContext( 5645 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5646 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5647 /*SkipLocalVariables=*/true); 5648 return false; 5649 } 5650 5651 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5652 FunctionDecl *FD, ParmVarDecl *Param) { 5653 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5654 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5655 return ExprError(); 5656 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5657 } 5658 5659 Sema::VariadicCallType 5660 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5661 Expr *Fn) { 5662 if (Proto && Proto->isVariadic()) { 5663 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5664 return VariadicConstructor; 5665 else if (Fn && Fn->getType()->isBlockPointerType()) 5666 return VariadicBlock; 5667 else if (FDecl) { 5668 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5669 if (Method->isInstance()) 5670 return VariadicMethod; 5671 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5672 return VariadicMethod; 5673 return VariadicFunction; 5674 } 5675 return VariadicDoesNotApply; 5676 } 5677 5678 namespace { 5679 class FunctionCallCCC final : public FunctionCallFilterCCC { 5680 public: 5681 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5682 unsigned NumArgs, MemberExpr *ME) 5683 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5684 FunctionName(FuncName) {} 5685 5686 bool ValidateCandidate(const TypoCorrection &candidate) override { 5687 if (!candidate.getCorrectionSpecifier() || 5688 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5689 return false; 5690 } 5691 5692 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5693 } 5694 5695 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5696 return std::make_unique<FunctionCallCCC>(*this); 5697 } 5698 5699 private: 5700 const IdentifierInfo *const FunctionName; 5701 }; 5702 } 5703 5704 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5705 FunctionDecl *FDecl, 5706 ArrayRef<Expr *> Args) { 5707 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5708 DeclarationName FuncName = FDecl->getDeclName(); 5709 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5710 5711 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5712 if (TypoCorrection Corrected = S.CorrectTypo( 5713 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5714 S.getScopeForContext(S.CurContext), nullptr, CCC, 5715 Sema::CTK_ErrorRecovery)) { 5716 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5717 if (Corrected.isOverloaded()) { 5718 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5719 OverloadCandidateSet::iterator Best; 5720 for (NamedDecl *CD : Corrected) { 5721 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5722 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5723 OCS); 5724 } 5725 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5726 case OR_Success: 5727 ND = Best->FoundDecl; 5728 Corrected.setCorrectionDecl(ND); 5729 break; 5730 default: 5731 break; 5732 } 5733 } 5734 ND = ND->getUnderlyingDecl(); 5735 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5736 return Corrected; 5737 } 5738 } 5739 return TypoCorrection(); 5740 } 5741 5742 /// ConvertArgumentsForCall - Converts the arguments specified in 5743 /// Args/NumArgs to the parameter types of the function FDecl with 5744 /// function prototype Proto. Call is the call expression itself, and 5745 /// Fn is the function expression. For a C++ member function, this 5746 /// routine does not attempt to convert the object argument. Returns 5747 /// true if the call is ill-formed. 5748 bool 5749 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5750 FunctionDecl *FDecl, 5751 const FunctionProtoType *Proto, 5752 ArrayRef<Expr *> Args, 5753 SourceLocation RParenLoc, 5754 bool IsExecConfig) { 5755 // Bail out early if calling a builtin with custom typechecking. 5756 if (FDecl) 5757 if (unsigned ID = FDecl->getBuiltinID()) 5758 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5759 return false; 5760 5761 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5762 // assignment, to the types of the corresponding parameter, ... 5763 unsigned NumParams = Proto->getNumParams(); 5764 bool Invalid = false; 5765 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5766 unsigned FnKind = Fn->getType()->isBlockPointerType() 5767 ? 1 /* block */ 5768 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5769 : 0 /* function */); 5770 5771 // If too few arguments are available (and we don't have default 5772 // arguments for the remaining parameters), don't make the call. 5773 if (Args.size() < NumParams) { 5774 if (Args.size() < MinArgs) { 5775 TypoCorrection TC; 5776 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5777 unsigned diag_id = 5778 MinArgs == NumParams && !Proto->isVariadic() 5779 ? diag::err_typecheck_call_too_few_args_suggest 5780 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5781 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5782 << static_cast<unsigned>(Args.size()) 5783 << TC.getCorrectionRange()); 5784 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5785 Diag(RParenLoc, 5786 MinArgs == NumParams && !Proto->isVariadic() 5787 ? diag::err_typecheck_call_too_few_args_one 5788 : diag::err_typecheck_call_too_few_args_at_least_one) 5789 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5790 else 5791 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5792 ? diag::err_typecheck_call_too_few_args 5793 : diag::err_typecheck_call_too_few_args_at_least) 5794 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5795 << Fn->getSourceRange(); 5796 5797 // Emit the location of the prototype. 5798 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5799 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5800 5801 return true; 5802 } 5803 // We reserve space for the default arguments when we create 5804 // the call expression, before calling ConvertArgumentsForCall. 5805 assert((Call->getNumArgs() == NumParams) && 5806 "We should have reserved space for the default arguments before!"); 5807 } 5808 5809 // If too many are passed and not variadic, error on the extras and drop 5810 // them. 5811 if (Args.size() > NumParams) { 5812 if (!Proto->isVariadic()) { 5813 TypoCorrection TC; 5814 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5815 unsigned diag_id = 5816 MinArgs == NumParams && !Proto->isVariadic() 5817 ? diag::err_typecheck_call_too_many_args_suggest 5818 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5819 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5820 << static_cast<unsigned>(Args.size()) 5821 << TC.getCorrectionRange()); 5822 } else if (NumParams == 1 && FDecl && 5823 FDecl->getParamDecl(0)->getDeclName()) 5824 Diag(Args[NumParams]->getBeginLoc(), 5825 MinArgs == NumParams 5826 ? diag::err_typecheck_call_too_many_args_one 5827 : diag::err_typecheck_call_too_many_args_at_most_one) 5828 << FnKind << FDecl->getParamDecl(0) 5829 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5830 << SourceRange(Args[NumParams]->getBeginLoc(), 5831 Args.back()->getEndLoc()); 5832 else 5833 Diag(Args[NumParams]->getBeginLoc(), 5834 MinArgs == NumParams 5835 ? diag::err_typecheck_call_too_many_args 5836 : diag::err_typecheck_call_too_many_args_at_most) 5837 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5838 << Fn->getSourceRange() 5839 << SourceRange(Args[NumParams]->getBeginLoc(), 5840 Args.back()->getEndLoc()); 5841 5842 // Emit the location of the prototype. 5843 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5844 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5845 5846 // This deletes the extra arguments. 5847 Call->shrinkNumArgs(NumParams); 5848 return true; 5849 } 5850 } 5851 SmallVector<Expr *, 8> AllArgs; 5852 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5853 5854 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5855 AllArgs, CallType); 5856 if (Invalid) 5857 return true; 5858 unsigned TotalNumArgs = AllArgs.size(); 5859 for (unsigned i = 0; i < TotalNumArgs; ++i) 5860 Call->setArg(i, AllArgs[i]); 5861 5862 return false; 5863 } 5864 5865 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5866 const FunctionProtoType *Proto, 5867 unsigned FirstParam, ArrayRef<Expr *> Args, 5868 SmallVectorImpl<Expr *> &AllArgs, 5869 VariadicCallType CallType, bool AllowExplicit, 5870 bool IsListInitialization) { 5871 unsigned NumParams = Proto->getNumParams(); 5872 bool Invalid = false; 5873 size_t ArgIx = 0; 5874 // Continue to check argument types (even if we have too few/many args). 5875 for (unsigned i = FirstParam; i < NumParams; i++) { 5876 QualType ProtoArgType = Proto->getParamType(i); 5877 5878 Expr *Arg; 5879 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5880 if (ArgIx < Args.size()) { 5881 Arg = Args[ArgIx++]; 5882 5883 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5884 diag::err_call_incomplete_argument, Arg)) 5885 return true; 5886 5887 // Strip the unbridged-cast placeholder expression off, if applicable. 5888 bool CFAudited = false; 5889 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5890 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5891 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5892 Arg = stripARCUnbridgedCast(Arg); 5893 else if (getLangOpts().ObjCAutoRefCount && 5894 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5895 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5896 CFAudited = true; 5897 5898 if (Proto->getExtParameterInfo(i).isNoEscape()) 5899 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5900 BE->getBlockDecl()->setDoesNotEscape(); 5901 5902 InitializedEntity Entity = 5903 Param ? InitializedEntity::InitializeParameter(Context, Param, 5904 ProtoArgType) 5905 : InitializedEntity::InitializeParameter( 5906 Context, ProtoArgType, Proto->isParamConsumed(i)); 5907 5908 // Remember that parameter belongs to a CF audited API. 5909 if (CFAudited) 5910 Entity.setParameterCFAudited(); 5911 5912 ExprResult ArgE = PerformCopyInitialization( 5913 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5914 if (ArgE.isInvalid()) 5915 return true; 5916 5917 Arg = ArgE.getAs<Expr>(); 5918 } else { 5919 assert(Param && "can't use default arguments without a known callee"); 5920 5921 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5922 if (ArgExpr.isInvalid()) 5923 return true; 5924 5925 Arg = ArgExpr.getAs<Expr>(); 5926 } 5927 5928 // Check for array bounds violations for each argument to the call. This 5929 // check only triggers warnings when the argument isn't a more complex Expr 5930 // with its own checking, such as a BinaryOperator. 5931 CheckArrayAccess(Arg); 5932 5933 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5934 CheckStaticArrayArgument(CallLoc, Param, Arg); 5935 5936 AllArgs.push_back(Arg); 5937 } 5938 5939 // If this is a variadic call, handle args passed through "...". 5940 if (CallType != VariadicDoesNotApply) { 5941 // Assume that extern "C" functions with variadic arguments that 5942 // return __unknown_anytype aren't *really* variadic. 5943 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5944 FDecl->isExternC()) { 5945 for (Expr *A : Args.slice(ArgIx)) { 5946 QualType paramType; // ignored 5947 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5948 Invalid |= arg.isInvalid(); 5949 AllArgs.push_back(arg.get()); 5950 } 5951 5952 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5953 } else { 5954 for (Expr *A : Args.slice(ArgIx)) { 5955 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5956 Invalid |= Arg.isInvalid(); 5957 AllArgs.push_back(Arg.get()); 5958 } 5959 } 5960 5961 // Check for array bounds violations. 5962 for (Expr *A : Args.slice(ArgIx)) 5963 CheckArrayAccess(A); 5964 } 5965 return Invalid; 5966 } 5967 5968 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5969 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5970 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5971 TL = DTL.getOriginalLoc(); 5972 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5973 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5974 << ATL.getLocalSourceRange(); 5975 } 5976 5977 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5978 /// array parameter, check that it is non-null, and that if it is formed by 5979 /// array-to-pointer decay, the underlying array is sufficiently large. 5980 /// 5981 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5982 /// array type derivation, then for each call to the function, the value of the 5983 /// corresponding actual argument shall provide access to the first element of 5984 /// an array with at least as many elements as specified by the size expression. 5985 void 5986 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5987 ParmVarDecl *Param, 5988 const Expr *ArgExpr) { 5989 // Static array parameters are not supported in C++. 5990 if (!Param || getLangOpts().CPlusPlus) 5991 return; 5992 5993 QualType OrigTy = Param->getOriginalType(); 5994 5995 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5996 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5997 return; 5998 5999 if (ArgExpr->isNullPointerConstant(Context, 6000 Expr::NPC_NeverValueDependent)) { 6001 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6002 DiagnoseCalleeStaticArrayParam(*this, Param); 6003 return; 6004 } 6005 6006 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6007 if (!CAT) 6008 return; 6009 6010 const ConstantArrayType *ArgCAT = 6011 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6012 if (!ArgCAT) 6013 return; 6014 6015 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6016 ArgCAT->getElementType())) { 6017 if (ArgCAT->getSize().ult(CAT->getSize())) { 6018 Diag(CallLoc, diag::warn_static_array_too_small) 6019 << ArgExpr->getSourceRange() 6020 << (unsigned)ArgCAT->getSize().getZExtValue() 6021 << (unsigned)CAT->getSize().getZExtValue() << 0; 6022 DiagnoseCalleeStaticArrayParam(*this, Param); 6023 } 6024 return; 6025 } 6026 6027 Optional<CharUnits> ArgSize = 6028 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6029 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6030 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6031 Diag(CallLoc, diag::warn_static_array_too_small) 6032 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6033 << (unsigned)ParmSize->getQuantity() << 1; 6034 DiagnoseCalleeStaticArrayParam(*this, Param); 6035 } 6036 } 6037 6038 /// Given a function expression of unknown-any type, try to rebuild it 6039 /// to have a function type. 6040 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6041 6042 /// Is the given type a placeholder that we need to lower out 6043 /// immediately during argument processing? 6044 static bool isPlaceholderToRemoveAsArg(QualType type) { 6045 // Placeholders are never sugared. 6046 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6047 if (!placeholder) return false; 6048 6049 switch (placeholder->getKind()) { 6050 // Ignore all the non-placeholder types. 6051 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6052 case BuiltinType::Id: 6053 #include "clang/Basic/OpenCLImageTypes.def" 6054 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6055 case BuiltinType::Id: 6056 #include "clang/Basic/OpenCLExtensionTypes.def" 6057 // In practice we'll never use this, since all SVE types are sugared 6058 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6059 #define SVE_TYPE(Name, Id, SingletonId) \ 6060 case BuiltinType::Id: 6061 #include "clang/Basic/AArch64SVEACLETypes.def" 6062 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6063 case BuiltinType::Id: 6064 #include "clang/Basic/PPCTypes.def" 6065 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6066 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6067 #include "clang/AST/BuiltinTypes.def" 6068 return false; 6069 6070 // We cannot lower out overload sets; they might validly be resolved 6071 // by the call machinery. 6072 case BuiltinType::Overload: 6073 return false; 6074 6075 // Unbridged casts in ARC can be handled in some call positions and 6076 // should be left in place. 6077 case BuiltinType::ARCUnbridgedCast: 6078 return false; 6079 6080 // Pseudo-objects should be converted as soon as possible. 6081 case BuiltinType::PseudoObject: 6082 return true; 6083 6084 // The debugger mode could theoretically but currently does not try 6085 // to resolve unknown-typed arguments based on known parameter types. 6086 case BuiltinType::UnknownAny: 6087 return true; 6088 6089 // These are always invalid as call arguments and should be reported. 6090 case BuiltinType::BoundMember: 6091 case BuiltinType::BuiltinFn: 6092 case BuiltinType::IncompleteMatrixIdx: 6093 case BuiltinType::OMPArraySection: 6094 case BuiltinType::OMPArrayShaping: 6095 case BuiltinType::OMPIterator: 6096 return true; 6097 6098 } 6099 llvm_unreachable("bad builtin type kind"); 6100 } 6101 6102 /// Check an argument list for placeholders that we won't try to 6103 /// handle later. 6104 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6105 // Apply this processing to all the arguments at once instead of 6106 // dying at the first failure. 6107 bool hasInvalid = false; 6108 for (size_t i = 0, e = args.size(); i != e; i++) { 6109 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6110 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6111 if (result.isInvalid()) hasInvalid = true; 6112 else args[i] = result.get(); 6113 } 6114 } 6115 return hasInvalid; 6116 } 6117 6118 /// If a builtin function has a pointer argument with no explicit address 6119 /// space, then it should be able to accept a pointer to any address 6120 /// space as input. In order to do this, we need to replace the 6121 /// standard builtin declaration with one that uses the same address space 6122 /// as the call. 6123 /// 6124 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6125 /// it does not contain any pointer arguments without 6126 /// an address space qualifer. Otherwise the rewritten 6127 /// FunctionDecl is returned. 6128 /// TODO: Handle pointer return types. 6129 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6130 FunctionDecl *FDecl, 6131 MultiExprArg ArgExprs) { 6132 6133 QualType DeclType = FDecl->getType(); 6134 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6135 6136 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6137 ArgExprs.size() < FT->getNumParams()) 6138 return nullptr; 6139 6140 bool NeedsNewDecl = false; 6141 unsigned i = 0; 6142 SmallVector<QualType, 8> OverloadParams; 6143 6144 for (QualType ParamType : FT->param_types()) { 6145 6146 // Convert array arguments to pointer to simplify type lookup. 6147 ExprResult ArgRes = 6148 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6149 if (ArgRes.isInvalid()) 6150 return nullptr; 6151 Expr *Arg = ArgRes.get(); 6152 QualType ArgType = Arg->getType(); 6153 if (!ParamType->isPointerType() || 6154 ParamType.hasAddressSpace() || 6155 !ArgType->isPointerType() || 6156 !ArgType->getPointeeType().hasAddressSpace()) { 6157 OverloadParams.push_back(ParamType); 6158 continue; 6159 } 6160 6161 QualType PointeeType = ParamType->getPointeeType(); 6162 if (PointeeType.hasAddressSpace()) 6163 continue; 6164 6165 NeedsNewDecl = true; 6166 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6167 6168 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6169 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6170 } 6171 6172 if (!NeedsNewDecl) 6173 return nullptr; 6174 6175 FunctionProtoType::ExtProtoInfo EPI; 6176 EPI.Variadic = FT->isVariadic(); 6177 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6178 OverloadParams, EPI); 6179 DeclContext *Parent = FDecl->getParent(); 6180 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6181 FDecl->getLocation(), 6182 FDecl->getLocation(), 6183 FDecl->getIdentifier(), 6184 OverloadTy, 6185 /*TInfo=*/nullptr, 6186 SC_Extern, false, 6187 /*hasPrototype=*/true); 6188 SmallVector<ParmVarDecl*, 16> Params; 6189 FT = cast<FunctionProtoType>(OverloadTy); 6190 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6191 QualType ParamType = FT->getParamType(i); 6192 ParmVarDecl *Parm = 6193 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6194 SourceLocation(), nullptr, ParamType, 6195 /*TInfo=*/nullptr, SC_None, nullptr); 6196 Parm->setScopeInfo(0, i); 6197 Params.push_back(Parm); 6198 } 6199 OverloadDecl->setParams(Params); 6200 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6201 return OverloadDecl; 6202 } 6203 6204 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6205 FunctionDecl *Callee, 6206 MultiExprArg ArgExprs) { 6207 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6208 // similar attributes) really don't like it when functions are called with an 6209 // invalid number of args. 6210 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6211 /*PartialOverloading=*/false) && 6212 !Callee->isVariadic()) 6213 return; 6214 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6215 return; 6216 6217 if (const EnableIfAttr *Attr = 6218 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6219 S.Diag(Fn->getBeginLoc(), 6220 isa<CXXMethodDecl>(Callee) 6221 ? diag::err_ovl_no_viable_member_function_in_call 6222 : diag::err_ovl_no_viable_function_in_call) 6223 << Callee << Callee->getSourceRange(); 6224 S.Diag(Callee->getLocation(), 6225 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6226 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6227 return; 6228 } 6229 } 6230 6231 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6232 const UnresolvedMemberExpr *const UME, Sema &S) { 6233 6234 const auto GetFunctionLevelDCIfCXXClass = 6235 [](Sema &S) -> const CXXRecordDecl * { 6236 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6237 if (!DC || !DC->getParent()) 6238 return nullptr; 6239 6240 // If the call to some member function was made from within a member 6241 // function body 'M' return return 'M's parent. 6242 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6243 return MD->getParent()->getCanonicalDecl(); 6244 // else the call was made from within a default member initializer of a 6245 // class, so return the class. 6246 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6247 return RD->getCanonicalDecl(); 6248 return nullptr; 6249 }; 6250 // If our DeclContext is neither a member function nor a class (in the 6251 // case of a lambda in a default member initializer), we can't have an 6252 // enclosing 'this'. 6253 6254 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6255 if (!CurParentClass) 6256 return false; 6257 6258 // The naming class for implicit member functions call is the class in which 6259 // name lookup starts. 6260 const CXXRecordDecl *const NamingClass = 6261 UME->getNamingClass()->getCanonicalDecl(); 6262 assert(NamingClass && "Must have naming class even for implicit access"); 6263 6264 // If the unresolved member functions were found in a 'naming class' that is 6265 // related (either the same or derived from) to the class that contains the 6266 // member function that itself contained the implicit member access. 6267 6268 return CurParentClass == NamingClass || 6269 CurParentClass->isDerivedFrom(NamingClass); 6270 } 6271 6272 static void 6273 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6274 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6275 6276 if (!UME) 6277 return; 6278 6279 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6280 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6281 // already been captured, or if this is an implicit member function call (if 6282 // it isn't, an attempt to capture 'this' should already have been made). 6283 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6284 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6285 return; 6286 6287 // Check if the naming class in which the unresolved members were found is 6288 // related (same as or is a base of) to the enclosing class. 6289 6290 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6291 return; 6292 6293 6294 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6295 // If the enclosing function is not dependent, then this lambda is 6296 // capture ready, so if we can capture this, do so. 6297 if (!EnclosingFunctionCtx->isDependentContext()) { 6298 // If the current lambda and all enclosing lambdas can capture 'this' - 6299 // then go ahead and capture 'this' (since our unresolved overload set 6300 // contains at least one non-static member function). 6301 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6302 S.CheckCXXThisCapture(CallLoc); 6303 } else if (S.CurContext->isDependentContext()) { 6304 // ... since this is an implicit member reference, that might potentially 6305 // involve a 'this' capture, mark 'this' for potential capture in 6306 // enclosing lambdas. 6307 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6308 CurLSI->addPotentialThisCapture(CallLoc); 6309 } 6310 } 6311 6312 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6313 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6314 Expr *ExecConfig) { 6315 ExprResult Call = 6316 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6317 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6318 if (Call.isInvalid()) 6319 return Call; 6320 6321 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6322 // language modes. 6323 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6324 if (ULE->hasExplicitTemplateArgs() && 6325 ULE->decls_begin() == ULE->decls_end()) { 6326 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6327 ? diag::warn_cxx17_compat_adl_only_template_id 6328 : diag::ext_adl_only_template_id) 6329 << ULE->getName(); 6330 } 6331 } 6332 6333 if (LangOpts.OpenMP) 6334 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6335 ExecConfig); 6336 6337 return Call; 6338 } 6339 6340 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6341 /// This provides the location of the left/right parens and a list of comma 6342 /// locations. 6343 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6344 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6345 Expr *ExecConfig, bool IsExecConfig, 6346 bool AllowRecovery) { 6347 // Since this might be a postfix expression, get rid of ParenListExprs. 6348 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6349 if (Result.isInvalid()) return ExprError(); 6350 Fn = Result.get(); 6351 6352 if (checkArgsForPlaceholders(*this, ArgExprs)) 6353 return ExprError(); 6354 6355 if (getLangOpts().CPlusPlus) { 6356 // If this is a pseudo-destructor expression, build the call immediately. 6357 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6358 if (!ArgExprs.empty()) { 6359 // Pseudo-destructor calls should not have any arguments. 6360 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6361 << FixItHint::CreateRemoval( 6362 SourceRange(ArgExprs.front()->getBeginLoc(), 6363 ArgExprs.back()->getEndLoc())); 6364 } 6365 6366 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6367 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6368 } 6369 if (Fn->getType() == Context.PseudoObjectTy) { 6370 ExprResult result = CheckPlaceholderExpr(Fn); 6371 if (result.isInvalid()) return ExprError(); 6372 Fn = result.get(); 6373 } 6374 6375 // Determine whether this is a dependent call inside a C++ template, 6376 // in which case we won't do any semantic analysis now. 6377 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6378 if (ExecConfig) { 6379 return CUDAKernelCallExpr::Create( 6380 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6381 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6382 } else { 6383 6384 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6385 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6386 Fn->getBeginLoc()); 6387 6388 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6389 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6390 } 6391 } 6392 6393 // Determine whether this is a call to an object (C++ [over.call.object]). 6394 if (Fn->getType()->isRecordType()) 6395 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6396 RParenLoc); 6397 6398 if (Fn->getType() == Context.UnknownAnyTy) { 6399 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6400 if (result.isInvalid()) return ExprError(); 6401 Fn = result.get(); 6402 } 6403 6404 if (Fn->getType() == Context.BoundMemberTy) { 6405 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6406 RParenLoc, AllowRecovery); 6407 } 6408 } 6409 6410 // Check for overloaded calls. This can happen even in C due to extensions. 6411 if (Fn->getType() == Context.OverloadTy) { 6412 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6413 6414 // We aren't supposed to apply this logic if there's an '&' involved. 6415 if (!find.HasFormOfMemberPointer) { 6416 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6417 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6418 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6419 OverloadExpr *ovl = find.Expression; 6420 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6421 return BuildOverloadedCallExpr( 6422 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6423 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6424 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6425 RParenLoc, AllowRecovery); 6426 } 6427 } 6428 6429 // If we're directly calling a function, get the appropriate declaration. 6430 if (Fn->getType() == Context.UnknownAnyTy) { 6431 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6432 if (result.isInvalid()) return ExprError(); 6433 Fn = result.get(); 6434 } 6435 6436 Expr *NakedFn = Fn->IgnoreParens(); 6437 6438 bool CallingNDeclIndirectly = false; 6439 NamedDecl *NDecl = nullptr; 6440 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6441 if (UnOp->getOpcode() == UO_AddrOf) { 6442 CallingNDeclIndirectly = true; 6443 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6444 } 6445 } 6446 6447 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6448 NDecl = DRE->getDecl(); 6449 6450 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6451 if (FDecl && FDecl->getBuiltinID()) { 6452 // Rewrite the function decl for this builtin by replacing parameters 6453 // with no explicit address space with the address space of the arguments 6454 // in ArgExprs. 6455 if ((FDecl = 6456 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6457 NDecl = FDecl; 6458 Fn = DeclRefExpr::Create( 6459 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6460 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6461 nullptr, DRE->isNonOdrUse()); 6462 } 6463 } 6464 } else if (isa<MemberExpr>(NakedFn)) 6465 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6466 6467 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6468 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6469 FD, /*Complain=*/true, Fn->getBeginLoc())) 6470 return ExprError(); 6471 6472 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6473 return ExprError(); 6474 6475 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6476 } 6477 6478 if (Context.isDependenceAllowed() && 6479 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6480 assert(!getLangOpts().CPlusPlus); 6481 assert((Fn->containsErrors() || 6482 llvm::any_of(ArgExprs, 6483 [](clang::Expr *E) { return E->containsErrors(); })) && 6484 "should only occur in error-recovery path."); 6485 QualType ReturnType = 6486 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6487 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6488 : Context.DependentTy; 6489 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6490 Expr::getValueKindForType(ReturnType), RParenLoc, 6491 CurFPFeatureOverrides()); 6492 } 6493 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6494 ExecConfig, IsExecConfig); 6495 } 6496 6497 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6498 /// 6499 /// __builtin_astype( value, dst type ) 6500 /// 6501 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6502 SourceLocation BuiltinLoc, 6503 SourceLocation RParenLoc) { 6504 ExprValueKind VK = VK_RValue; 6505 ExprObjectKind OK = OK_Ordinary; 6506 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6507 QualType SrcTy = E->getType(); 6508 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6509 return ExprError(Diag(BuiltinLoc, 6510 diag::err_invalid_astype_of_different_size) 6511 << DstTy 6512 << SrcTy 6513 << E->getSourceRange()); 6514 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6515 } 6516 6517 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6518 /// provided arguments. 6519 /// 6520 /// __builtin_convertvector( value, dst type ) 6521 /// 6522 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6523 SourceLocation BuiltinLoc, 6524 SourceLocation RParenLoc) { 6525 TypeSourceInfo *TInfo; 6526 GetTypeFromParser(ParsedDestTy, &TInfo); 6527 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6528 } 6529 6530 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6531 /// i.e. an expression not of \p OverloadTy. The expression should 6532 /// unary-convert to an expression of function-pointer or 6533 /// block-pointer type. 6534 /// 6535 /// \param NDecl the declaration being called, if available 6536 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6537 SourceLocation LParenLoc, 6538 ArrayRef<Expr *> Args, 6539 SourceLocation RParenLoc, Expr *Config, 6540 bool IsExecConfig, ADLCallKind UsesADL) { 6541 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6542 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6543 6544 // Functions with 'interrupt' attribute cannot be called directly. 6545 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6546 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6547 return ExprError(); 6548 } 6549 6550 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6551 // so there's some risk when calling out to non-interrupt handler functions 6552 // that the callee might not preserve them. This is easy to diagnose here, 6553 // but can be very challenging to debug. 6554 if (auto *Caller = getCurFunctionDecl()) 6555 if (Caller->hasAttr<ARMInterruptAttr>()) { 6556 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6557 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6558 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6559 } 6560 6561 // Promote the function operand. 6562 // We special-case function promotion here because we only allow promoting 6563 // builtin functions to function pointers in the callee of a call. 6564 ExprResult Result; 6565 QualType ResultTy; 6566 if (BuiltinID && 6567 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6568 // Extract the return type from the (builtin) function pointer type. 6569 // FIXME Several builtins still have setType in 6570 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6571 // Builtins.def to ensure they are correct before removing setType calls. 6572 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6573 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6574 ResultTy = FDecl->getCallResultType(); 6575 } else { 6576 Result = CallExprUnaryConversions(Fn); 6577 ResultTy = Context.BoolTy; 6578 } 6579 if (Result.isInvalid()) 6580 return ExprError(); 6581 Fn = Result.get(); 6582 6583 // Check for a valid function type, but only if it is not a builtin which 6584 // requires custom type checking. These will be handled by 6585 // CheckBuiltinFunctionCall below just after creation of the call expression. 6586 const FunctionType *FuncT = nullptr; 6587 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6588 retry: 6589 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6590 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6591 // have type pointer to function". 6592 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6593 if (!FuncT) 6594 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6595 << Fn->getType() << Fn->getSourceRange()); 6596 } else if (const BlockPointerType *BPT = 6597 Fn->getType()->getAs<BlockPointerType>()) { 6598 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6599 } else { 6600 // Handle calls to expressions of unknown-any type. 6601 if (Fn->getType() == Context.UnknownAnyTy) { 6602 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6603 if (rewrite.isInvalid()) 6604 return ExprError(); 6605 Fn = rewrite.get(); 6606 goto retry; 6607 } 6608 6609 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6610 << Fn->getType() << Fn->getSourceRange()); 6611 } 6612 } 6613 6614 // Get the number of parameters in the function prototype, if any. 6615 // We will allocate space for max(Args.size(), NumParams) arguments 6616 // in the call expression. 6617 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6618 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6619 6620 CallExpr *TheCall; 6621 if (Config) { 6622 assert(UsesADL == ADLCallKind::NotADL && 6623 "CUDAKernelCallExpr should not use ADL"); 6624 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6625 Args, ResultTy, VK_RValue, RParenLoc, 6626 CurFPFeatureOverrides(), NumParams); 6627 } else { 6628 TheCall = 6629 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6630 CurFPFeatureOverrides(), NumParams, UsesADL); 6631 } 6632 6633 if (!Context.isDependenceAllowed()) { 6634 // Forget about the nulled arguments since typo correction 6635 // do not handle them well. 6636 TheCall->shrinkNumArgs(Args.size()); 6637 // C cannot always handle TypoExpr nodes in builtin calls and direct 6638 // function calls as their argument checking don't necessarily handle 6639 // dependent types properly, so make sure any TypoExprs have been 6640 // dealt with. 6641 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6642 if (!Result.isUsable()) return ExprError(); 6643 CallExpr *TheOldCall = TheCall; 6644 TheCall = dyn_cast<CallExpr>(Result.get()); 6645 bool CorrectedTypos = TheCall != TheOldCall; 6646 if (!TheCall) return Result; 6647 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6648 6649 // A new call expression node was created if some typos were corrected. 6650 // However it may not have been constructed with enough storage. In this 6651 // case, rebuild the node with enough storage. The waste of space is 6652 // immaterial since this only happens when some typos were corrected. 6653 if (CorrectedTypos && Args.size() < NumParams) { 6654 if (Config) 6655 TheCall = CUDAKernelCallExpr::Create( 6656 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6657 RParenLoc, CurFPFeatureOverrides(), NumParams); 6658 else 6659 TheCall = 6660 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6661 CurFPFeatureOverrides(), NumParams, UsesADL); 6662 } 6663 // We can now handle the nulled arguments for the default arguments. 6664 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6665 } 6666 6667 // Bail out early if calling a builtin with custom type checking. 6668 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6669 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6670 6671 if (getLangOpts().CUDA) { 6672 if (Config) { 6673 // CUDA: Kernel calls must be to global functions 6674 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6675 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6676 << FDecl << Fn->getSourceRange()); 6677 6678 // CUDA: Kernel function must have 'void' return type 6679 if (!FuncT->getReturnType()->isVoidType() && 6680 !FuncT->getReturnType()->getAs<AutoType>() && 6681 !FuncT->getReturnType()->isInstantiationDependentType()) 6682 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6683 << Fn->getType() << Fn->getSourceRange()); 6684 } else { 6685 // CUDA: Calls to global functions must be configured 6686 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6687 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6688 << FDecl << Fn->getSourceRange()); 6689 } 6690 } 6691 6692 // Check for a valid return type 6693 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6694 FDecl)) 6695 return ExprError(); 6696 6697 // We know the result type of the call, set it. 6698 TheCall->setType(FuncT->getCallResultType(Context)); 6699 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6700 6701 if (Proto) { 6702 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6703 IsExecConfig)) 6704 return ExprError(); 6705 } else { 6706 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6707 6708 if (FDecl) { 6709 // Check if we have too few/too many template arguments, based 6710 // on our knowledge of the function definition. 6711 const FunctionDecl *Def = nullptr; 6712 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6713 Proto = Def->getType()->getAs<FunctionProtoType>(); 6714 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6715 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6716 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6717 } 6718 6719 // If the function we're calling isn't a function prototype, but we have 6720 // a function prototype from a prior declaratiom, use that prototype. 6721 if (!FDecl->hasPrototype()) 6722 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6723 } 6724 6725 // Promote the arguments (C99 6.5.2.2p6). 6726 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6727 Expr *Arg = Args[i]; 6728 6729 if (Proto && i < Proto->getNumParams()) { 6730 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6731 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6732 ExprResult ArgE = 6733 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6734 if (ArgE.isInvalid()) 6735 return true; 6736 6737 Arg = ArgE.getAs<Expr>(); 6738 6739 } else { 6740 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6741 6742 if (ArgE.isInvalid()) 6743 return true; 6744 6745 Arg = ArgE.getAs<Expr>(); 6746 } 6747 6748 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6749 diag::err_call_incomplete_argument, Arg)) 6750 return ExprError(); 6751 6752 TheCall->setArg(i, Arg); 6753 } 6754 } 6755 6756 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6757 if (!Method->isStatic()) 6758 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6759 << Fn->getSourceRange()); 6760 6761 // Check for sentinels 6762 if (NDecl) 6763 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6764 6765 // Warn for unions passing across security boundary (CMSE). 6766 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6767 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6768 if (const auto *RT = 6769 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6770 if (RT->getDecl()->isOrContainsUnion()) 6771 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6772 << 0 << i; 6773 } 6774 } 6775 } 6776 6777 // Do special checking on direct calls to functions. 6778 if (FDecl) { 6779 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6780 return ExprError(); 6781 6782 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6783 6784 if (BuiltinID) 6785 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6786 } else if (NDecl) { 6787 if (CheckPointerCall(NDecl, TheCall, Proto)) 6788 return ExprError(); 6789 } else { 6790 if (CheckOtherCall(TheCall, Proto)) 6791 return ExprError(); 6792 } 6793 6794 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6795 } 6796 6797 ExprResult 6798 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6799 SourceLocation RParenLoc, Expr *InitExpr) { 6800 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6801 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6802 6803 TypeSourceInfo *TInfo; 6804 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6805 if (!TInfo) 6806 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6807 6808 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6809 } 6810 6811 ExprResult 6812 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6813 SourceLocation RParenLoc, Expr *LiteralExpr) { 6814 QualType literalType = TInfo->getType(); 6815 6816 if (literalType->isArrayType()) { 6817 if (RequireCompleteSizedType( 6818 LParenLoc, Context.getBaseElementType(literalType), 6819 diag::err_array_incomplete_or_sizeless_type, 6820 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6821 return ExprError(); 6822 if (literalType->isVariableArrayType()) 6823 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6824 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6825 } else if (!literalType->isDependentType() && 6826 RequireCompleteType(LParenLoc, literalType, 6827 diag::err_typecheck_decl_incomplete_type, 6828 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6829 return ExprError(); 6830 6831 InitializedEntity Entity 6832 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6833 InitializationKind Kind 6834 = InitializationKind::CreateCStyleCast(LParenLoc, 6835 SourceRange(LParenLoc, RParenLoc), 6836 /*InitList=*/true); 6837 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6838 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6839 &literalType); 6840 if (Result.isInvalid()) 6841 return ExprError(); 6842 LiteralExpr = Result.get(); 6843 6844 bool isFileScope = !CurContext->isFunctionOrMethod(); 6845 6846 // In C, compound literals are l-values for some reason. 6847 // For GCC compatibility, in C++, file-scope array compound literals with 6848 // constant initializers are also l-values, and compound literals are 6849 // otherwise prvalues. 6850 // 6851 // (GCC also treats C++ list-initialized file-scope array prvalues with 6852 // constant initializers as l-values, but that's non-conforming, so we don't 6853 // follow it there.) 6854 // 6855 // FIXME: It would be better to handle the lvalue cases as materializing and 6856 // lifetime-extending a temporary object, but our materialized temporaries 6857 // representation only supports lifetime extension from a variable, not "out 6858 // of thin air". 6859 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6860 // is bound to the result of applying array-to-pointer decay to the compound 6861 // literal. 6862 // FIXME: GCC supports compound literals of reference type, which should 6863 // obviously have a value kind derived from the kind of reference involved. 6864 ExprValueKind VK = 6865 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6866 ? VK_RValue 6867 : VK_LValue; 6868 6869 if (isFileScope) 6870 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6871 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6872 Expr *Init = ILE->getInit(i); 6873 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6874 } 6875 6876 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6877 VK, LiteralExpr, isFileScope); 6878 if (isFileScope) { 6879 if (!LiteralExpr->isTypeDependent() && 6880 !LiteralExpr->isValueDependent() && 6881 !literalType->isDependentType()) // C99 6.5.2.5p3 6882 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6883 return ExprError(); 6884 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6885 literalType.getAddressSpace() != LangAS::Default) { 6886 // Embedded-C extensions to C99 6.5.2.5: 6887 // "If the compound literal occurs inside the body of a function, the 6888 // type name shall not be qualified by an address-space qualifier." 6889 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6890 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6891 return ExprError(); 6892 } 6893 6894 if (!isFileScope && !getLangOpts().CPlusPlus) { 6895 // Compound literals that have automatic storage duration are destroyed at 6896 // the end of the scope in C; in C++, they're just temporaries. 6897 6898 // Emit diagnostics if it is or contains a C union type that is non-trivial 6899 // to destruct. 6900 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6901 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6902 NTCUC_CompoundLiteral, NTCUK_Destruct); 6903 6904 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6905 if (literalType.isDestructedType()) { 6906 Cleanup.setExprNeedsCleanups(true); 6907 ExprCleanupObjects.push_back(E); 6908 getCurFunction()->setHasBranchProtectedScope(); 6909 } 6910 } 6911 6912 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6913 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6914 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6915 E->getInitializer()->getExprLoc()); 6916 6917 return MaybeBindToTemporary(E); 6918 } 6919 6920 ExprResult 6921 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6922 SourceLocation RBraceLoc) { 6923 // Only produce each kind of designated initialization diagnostic once. 6924 SourceLocation FirstDesignator; 6925 bool DiagnosedArrayDesignator = false; 6926 bool DiagnosedNestedDesignator = false; 6927 bool DiagnosedMixedDesignator = false; 6928 6929 // Check that any designated initializers are syntactically valid in the 6930 // current language mode. 6931 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6932 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6933 if (FirstDesignator.isInvalid()) 6934 FirstDesignator = DIE->getBeginLoc(); 6935 6936 if (!getLangOpts().CPlusPlus) 6937 break; 6938 6939 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6940 DiagnosedNestedDesignator = true; 6941 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6942 << DIE->getDesignatorsSourceRange(); 6943 } 6944 6945 for (auto &Desig : DIE->designators()) { 6946 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6947 DiagnosedArrayDesignator = true; 6948 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6949 << Desig.getSourceRange(); 6950 } 6951 } 6952 6953 if (!DiagnosedMixedDesignator && 6954 !isa<DesignatedInitExpr>(InitArgList[0])) { 6955 DiagnosedMixedDesignator = true; 6956 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6957 << DIE->getSourceRange(); 6958 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6959 << InitArgList[0]->getSourceRange(); 6960 } 6961 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6962 isa<DesignatedInitExpr>(InitArgList[0])) { 6963 DiagnosedMixedDesignator = true; 6964 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6965 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6966 << DIE->getSourceRange(); 6967 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6968 << InitArgList[I]->getSourceRange(); 6969 } 6970 } 6971 6972 if (FirstDesignator.isValid()) { 6973 // Only diagnose designated initiaization as a C++20 extension if we didn't 6974 // already diagnose use of (non-C++20) C99 designator syntax. 6975 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6976 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6977 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6978 ? diag::warn_cxx17_compat_designated_init 6979 : diag::ext_cxx_designated_init); 6980 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6981 Diag(FirstDesignator, diag::ext_designated_init); 6982 } 6983 } 6984 6985 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6986 } 6987 6988 ExprResult 6989 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6990 SourceLocation RBraceLoc) { 6991 // Semantic analysis for initializers is done by ActOnDeclarator() and 6992 // CheckInitializer() - it requires knowledge of the object being initialized. 6993 6994 // Immediately handle non-overload placeholders. Overloads can be 6995 // resolved contextually, but everything else here can't. 6996 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6997 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6998 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6999 7000 // Ignore failures; dropping the entire initializer list because 7001 // of one failure would be terrible for indexing/etc. 7002 if (result.isInvalid()) continue; 7003 7004 InitArgList[I] = result.get(); 7005 } 7006 } 7007 7008 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7009 RBraceLoc); 7010 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7011 return E; 7012 } 7013 7014 /// Do an explicit extend of the given block pointer if we're in ARC. 7015 void Sema::maybeExtendBlockObject(ExprResult &E) { 7016 assert(E.get()->getType()->isBlockPointerType()); 7017 assert(E.get()->isRValue()); 7018 7019 // Only do this in an r-value context. 7020 if (!getLangOpts().ObjCAutoRefCount) return; 7021 7022 E = ImplicitCastExpr::Create( 7023 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7024 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7025 Cleanup.setExprNeedsCleanups(true); 7026 } 7027 7028 /// Prepare a conversion of the given expression to an ObjC object 7029 /// pointer type. 7030 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7031 QualType type = E.get()->getType(); 7032 if (type->isObjCObjectPointerType()) { 7033 return CK_BitCast; 7034 } else if (type->isBlockPointerType()) { 7035 maybeExtendBlockObject(E); 7036 return CK_BlockPointerToObjCPointerCast; 7037 } else { 7038 assert(type->isPointerType()); 7039 return CK_CPointerToObjCPointerCast; 7040 } 7041 } 7042 7043 /// Prepares for a scalar cast, performing all the necessary stages 7044 /// except the final cast and returning the kind required. 7045 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7046 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7047 // Also, callers should have filtered out the invalid cases with 7048 // pointers. Everything else should be possible. 7049 7050 QualType SrcTy = Src.get()->getType(); 7051 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7052 return CK_NoOp; 7053 7054 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7055 case Type::STK_MemberPointer: 7056 llvm_unreachable("member pointer type in C"); 7057 7058 case Type::STK_CPointer: 7059 case Type::STK_BlockPointer: 7060 case Type::STK_ObjCObjectPointer: 7061 switch (DestTy->getScalarTypeKind()) { 7062 case Type::STK_CPointer: { 7063 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7064 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7065 if (SrcAS != DestAS) 7066 return CK_AddressSpaceConversion; 7067 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7068 return CK_NoOp; 7069 return CK_BitCast; 7070 } 7071 case Type::STK_BlockPointer: 7072 return (SrcKind == Type::STK_BlockPointer 7073 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7074 case Type::STK_ObjCObjectPointer: 7075 if (SrcKind == Type::STK_ObjCObjectPointer) 7076 return CK_BitCast; 7077 if (SrcKind == Type::STK_CPointer) 7078 return CK_CPointerToObjCPointerCast; 7079 maybeExtendBlockObject(Src); 7080 return CK_BlockPointerToObjCPointerCast; 7081 case Type::STK_Bool: 7082 return CK_PointerToBoolean; 7083 case Type::STK_Integral: 7084 return CK_PointerToIntegral; 7085 case Type::STK_Floating: 7086 case Type::STK_FloatingComplex: 7087 case Type::STK_IntegralComplex: 7088 case Type::STK_MemberPointer: 7089 case Type::STK_FixedPoint: 7090 llvm_unreachable("illegal cast from pointer"); 7091 } 7092 llvm_unreachable("Should have returned before this"); 7093 7094 case Type::STK_FixedPoint: 7095 switch (DestTy->getScalarTypeKind()) { 7096 case Type::STK_FixedPoint: 7097 return CK_FixedPointCast; 7098 case Type::STK_Bool: 7099 return CK_FixedPointToBoolean; 7100 case Type::STK_Integral: 7101 return CK_FixedPointToIntegral; 7102 case Type::STK_Floating: 7103 return CK_FixedPointToFloating; 7104 case Type::STK_IntegralComplex: 7105 case Type::STK_FloatingComplex: 7106 Diag(Src.get()->getExprLoc(), 7107 diag::err_unimplemented_conversion_with_fixed_point_type) 7108 << DestTy; 7109 return CK_IntegralCast; 7110 case Type::STK_CPointer: 7111 case Type::STK_ObjCObjectPointer: 7112 case Type::STK_BlockPointer: 7113 case Type::STK_MemberPointer: 7114 llvm_unreachable("illegal cast to pointer type"); 7115 } 7116 llvm_unreachable("Should have returned before this"); 7117 7118 case Type::STK_Bool: // casting from bool is like casting from an integer 7119 case Type::STK_Integral: 7120 switch (DestTy->getScalarTypeKind()) { 7121 case Type::STK_CPointer: 7122 case Type::STK_ObjCObjectPointer: 7123 case Type::STK_BlockPointer: 7124 if (Src.get()->isNullPointerConstant(Context, 7125 Expr::NPC_ValueDependentIsNull)) 7126 return CK_NullToPointer; 7127 return CK_IntegralToPointer; 7128 case Type::STK_Bool: 7129 return CK_IntegralToBoolean; 7130 case Type::STK_Integral: 7131 return CK_IntegralCast; 7132 case Type::STK_Floating: 7133 return CK_IntegralToFloating; 7134 case Type::STK_IntegralComplex: 7135 Src = ImpCastExprToType(Src.get(), 7136 DestTy->castAs<ComplexType>()->getElementType(), 7137 CK_IntegralCast); 7138 return CK_IntegralRealToComplex; 7139 case Type::STK_FloatingComplex: 7140 Src = ImpCastExprToType(Src.get(), 7141 DestTy->castAs<ComplexType>()->getElementType(), 7142 CK_IntegralToFloating); 7143 return CK_FloatingRealToComplex; 7144 case Type::STK_MemberPointer: 7145 llvm_unreachable("member pointer type in C"); 7146 case Type::STK_FixedPoint: 7147 return CK_IntegralToFixedPoint; 7148 } 7149 llvm_unreachable("Should have returned before this"); 7150 7151 case Type::STK_Floating: 7152 switch (DestTy->getScalarTypeKind()) { 7153 case Type::STK_Floating: 7154 return CK_FloatingCast; 7155 case Type::STK_Bool: 7156 return CK_FloatingToBoolean; 7157 case Type::STK_Integral: 7158 return CK_FloatingToIntegral; 7159 case Type::STK_FloatingComplex: 7160 Src = ImpCastExprToType(Src.get(), 7161 DestTy->castAs<ComplexType>()->getElementType(), 7162 CK_FloatingCast); 7163 return CK_FloatingRealToComplex; 7164 case Type::STK_IntegralComplex: 7165 Src = ImpCastExprToType(Src.get(), 7166 DestTy->castAs<ComplexType>()->getElementType(), 7167 CK_FloatingToIntegral); 7168 return CK_IntegralRealToComplex; 7169 case Type::STK_CPointer: 7170 case Type::STK_ObjCObjectPointer: 7171 case Type::STK_BlockPointer: 7172 llvm_unreachable("valid float->pointer cast?"); 7173 case Type::STK_MemberPointer: 7174 llvm_unreachable("member pointer type in C"); 7175 case Type::STK_FixedPoint: 7176 return CK_FloatingToFixedPoint; 7177 } 7178 llvm_unreachable("Should have returned before this"); 7179 7180 case Type::STK_FloatingComplex: 7181 switch (DestTy->getScalarTypeKind()) { 7182 case Type::STK_FloatingComplex: 7183 return CK_FloatingComplexCast; 7184 case Type::STK_IntegralComplex: 7185 return CK_FloatingComplexToIntegralComplex; 7186 case Type::STK_Floating: { 7187 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7188 if (Context.hasSameType(ET, DestTy)) 7189 return CK_FloatingComplexToReal; 7190 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7191 return CK_FloatingCast; 7192 } 7193 case Type::STK_Bool: 7194 return CK_FloatingComplexToBoolean; 7195 case Type::STK_Integral: 7196 Src = ImpCastExprToType(Src.get(), 7197 SrcTy->castAs<ComplexType>()->getElementType(), 7198 CK_FloatingComplexToReal); 7199 return CK_FloatingToIntegral; 7200 case Type::STK_CPointer: 7201 case Type::STK_ObjCObjectPointer: 7202 case Type::STK_BlockPointer: 7203 llvm_unreachable("valid complex float->pointer cast?"); 7204 case Type::STK_MemberPointer: 7205 llvm_unreachable("member pointer type in C"); 7206 case Type::STK_FixedPoint: 7207 Diag(Src.get()->getExprLoc(), 7208 diag::err_unimplemented_conversion_with_fixed_point_type) 7209 << SrcTy; 7210 return CK_IntegralCast; 7211 } 7212 llvm_unreachable("Should have returned before this"); 7213 7214 case Type::STK_IntegralComplex: 7215 switch (DestTy->getScalarTypeKind()) { 7216 case Type::STK_FloatingComplex: 7217 return CK_IntegralComplexToFloatingComplex; 7218 case Type::STK_IntegralComplex: 7219 return CK_IntegralComplexCast; 7220 case Type::STK_Integral: { 7221 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7222 if (Context.hasSameType(ET, DestTy)) 7223 return CK_IntegralComplexToReal; 7224 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7225 return CK_IntegralCast; 7226 } 7227 case Type::STK_Bool: 7228 return CK_IntegralComplexToBoolean; 7229 case Type::STK_Floating: 7230 Src = ImpCastExprToType(Src.get(), 7231 SrcTy->castAs<ComplexType>()->getElementType(), 7232 CK_IntegralComplexToReal); 7233 return CK_IntegralToFloating; 7234 case Type::STK_CPointer: 7235 case Type::STK_ObjCObjectPointer: 7236 case Type::STK_BlockPointer: 7237 llvm_unreachable("valid complex int->pointer cast?"); 7238 case Type::STK_MemberPointer: 7239 llvm_unreachable("member pointer type in C"); 7240 case Type::STK_FixedPoint: 7241 Diag(Src.get()->getExprLoc(), 7242 diag::err_unimplemented_conversion_with_fixed_point_type) 7243 << SrcTy; 7244 return CK_IntegralCast; 7245 } 7246 llvm_unreachable("Should have returned before this"); 7247 } 7248 7249 llvm_unreachable("Unhandled scalar cast"); 7250 } 7251 7252 static bool breakDownVectorType(QualType type, uint64_t &len, 7253 QualType &eltType) { 7254 // Vectors are simple. 7255 if (const VectorType *vecType = type->getAs<VectorType>()) { 7256 len = vecType->getNumElements(); 7257 eltType = vecType->getElementType(); 7258 assert(eltType->isScalarType()); 7259 return true; 7260 } 7261 7262 // We allow lax conversion to and from non-vector types, but only if 7263 // they're real types (i.e. non-complex, non-pointer scalar types). 7264 if (!type->isRealType()) return false; 7265 7266 len = 1; 7267 eltType = type; 7268 return true; 7269 } 7270 7271 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7272 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7273 /// allowed? 7274 /// 7275 /// This will also return false if the two given types do not make sense from 7276 /// the perspective of SVE bitcasts. 7277 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7278 assert(srcTy->isVectorType() || destTy->isVectorType()); 7279 7280 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7281 if (!FirstType->isSizelessBuiltinType()) 7282 return false; 7283 7284 const auto *VecTy = SecondType->getAs<VectorType>(); 7285 return VecTy && 7286 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7287 }; 7288 7289 return ValidScalableConversion(srcTy, destTy) || 7290 ValidScalableConversion(destTy, srcTy); 7291 } 7292 7293 /// Are the two types lax-compatible vector types? That is, given 7294 /// that one of them is a vector, do they have equal storage sizes, 7295 /// where the storage size is the number of elements times the element 7296 /// size? 7297 /// 7298 /// This will also return false if either of the types is neither a 7299 /// vector nor a real type. 7300 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7301 assert(destTy->isVectorType() || srcTy->isVectorType()); 7302 7303 // Disallow lax conversions between scalars and ExtVectors (these 7304 // conversions are allowed for other vector types because common headers 7305 // depend on them). Most scalar OP ExtVector cases are handled by the 7306 // splat path anyway, which does what we want (convert, not bitcast). 7307 // What this rules out for ExtVectors is crazy things like char4*float. 7308 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7309 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7310 7311 uint64_t srcLen, destLen; 7312 QualType srcEltTy, destEltTy; 7313 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7314 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7315 7316 // ASTContext::getTypeSize will return the size rounded up to a 7317 // power of 2, so instead of using that, we need to use the raw 7318 // element size multiplied by the element count. 7319 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7320 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7321 7322 return (srcLen * srcEltSize == destLen * destEltSize); 7323 } 7324 7325 /// Is this a legal conversion between two types, one of which is 7326 /// known to be a vector type? 7327 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7328 assert(destTy->isVectorType() || srcTy->isVectorType()); 7329 7330 switch (Context.getLangOpts().getLaxVectorConversions()) { 7331 case LangOptions::LaxVectorConversionKind::None: 7332 return false; 7333 7334 case LangOptions::LaxVectorConversionKind::Integer: 7335 if (!srcTy->isIntegralOrEnumerationType()) { 7336 auto *Vec = srcTy->getAs<VectorType>(); 7337 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7338 return false; 7339 } 7340 if (!destTy->isIntegralOrEnumerationType()) { 7341 auto *Vec = destTy->getAs<VectorType>(); 7342 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7343 return false; 7344 } 7345 // OK, integer (vector) -> integer (vector) bitcast. 7346 break; 7347 7348 case LangOptions::LaxVectorConversionKind::All: 7349 break; 7350 } 7351 7352 return areLaxCompatibleVectorTypes(srcTy, destTy); 7353 } 7354 7355 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7356 CastKind &Kind) { 7357 assert(VectorTy->isVectorType() && "Not a vector type!"); 7358 7359 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7360 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7361 return Diag(R.getBegin(), 7362 Ty->isVectorType() ? 7363 diag::err_invalid_conversion_between_vectors : 7364 diag::err_invalid_conversion_between_vector_and_integer) 7365 << VectorTy << Ty << R; 7366 } else 7367 return Diag(R.getBegin(), 7368 diag::err_invalid_conversion_between_vector_and_scalar) 7369 << VectorTy << Ty << R; 7370 7371 Kind = CK_BitCast; 7372 return false; 7373 } 7374 7375 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7376 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7377 7378 if (DestElemTy == SplattedExpr->getType()) 7379 return SplattedExpr; 7380 7381 assert(DestElemTy->isFloatingType() || 7382 DestElemTy->isIntegralOrEnumerationType()); 7383 7384 CastKind CK; 7385 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7386 // OpenCL requires that we convert `true` boolean expressions to -1, but 7387 // only when splatting vectors. 7388 if (DestElemTy->isFloatingType()) { 7389 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7390 // in two steps: boolean to signed integral, then to floating. 7391 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7392 CK_BooleanToSignedIntegral); 7393 SplattedExpr = CastExprRes.get(); 7394 CK = CK_IntegralToFloating; 7395 } else { 7396 CK = CK_BooleanToSignedIntegral; 7397 } 7398 } else { 7399 ExprResult CastExprRes = SplattedExpr; 7400 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7401 if (CastExprRes.isInvalid()) 7402 return ExprError(); 7403 SplattedExpr = CastExprRes.get(); 7404 } 7405 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7406 } 7407 7408 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7409 Expr *CastExpr, CastKind &Kind) { 7410 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7411 7412 QualType SrcTy = CastExpr->getType(); 7413 7414 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7415 // an ExtVectorType. 7416 // In OpenCL, casts between vectors of different types are not allowed. 7417 // (See OpenCL 6.2). 7418 if (SrcTy->isVectorType()) { 7419 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7420 (getLangOpts().OpenCL && 7421 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7422 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7423 << DestTy << SrcTy << R; 7424 return ExprError(); 7425 } 7426 Kind = CK_BitCast; 7427 return CastExpr; 7428 } 7429 7430 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7431 // conversion will take place first from scalar to elt type, and then 7432 // splat from elt type to vector. 7433 if (SrcTy->isPointerType()) 7434 return Diag(R.getBegin(), 7435 diag::err_invalid_conversion_between_vector_and_scalar) 7436 << DestTy << SrcTy << R; 7437 7438 Kind = CK_VectorSplat; 7439 return prepareVectorSplat(DestTy, CastExpr); 7440 } 7441 7442 ExprResult 7443 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7444 Declarator &D, ParsedType &Ty, 7445 SourceLocation RParenLoc, Expr *CastExpr) { 7446 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7447 "ActOnCastExpr(): missing type or expr"); 7448 7449 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7450 if (D.isInvalidType()) 7451 return ExprError(); 7452 7453 if (getLangOpts().CPlusPlus) { 7454 // Check that there are no default arguments (C++ only). 7455 CheckExtraCXXDefaultArguments(D); 7456 } else { 7457 // Make sure any TypoExprs have been dealt with. 7458 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7459 if (!Res.isUsable()) 7460 return ExprError(); 7461 CastExpr = Res.get(); 7462 } 7463 7464 checkUnusedDeclAttributes(D); 7465 7466 QualType castType = castTInfo->getType(); 7467 Ty = CreateParsedType(castType, castTInfo); 7468 7469 bool isVectorLiteral = false; 7470 7471 // Check for an altivec or OpenCL literal, 7472 // i.e. all the elements are integer constants. 7473 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7474 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7475 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7476 && castType->isVectorType() && (PE || PLE)) { 7477 if (PLE && PLE->getNumExprs() == 0) { 7478 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7479 return ExprError(); 7480 } 7481 if (PE || PLE->getNumExprs() == 1) { 7482 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7483 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7484 isVectorLiteral = true; 7485 } 7486 else 7487 isVectorLiteral = true; 7488 } 7489 7490 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7491 // then handle it as such. 7492 if (isVectorLiteral) 7493 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7494 7495 // If the Expr being casted is a ParenListExpr, handle it specially. 7496 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7497 // sequence of BinOp comma operators. 7498 if (isa<ParenListExpr>(CastExpr)) { 7499 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7500 if (Result.isInvalid()) return ExprError(); 7501 CastExpr = Result.get(); 7502 } 7503 7504 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7505 !getSourceManager().isInSystemMacro(LParenLoc)) 7506 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7507 7508 CheckTollFreeBridgeCast(castType, CastExpr); 7509 7510 CheckObjCBridgeRelatedCast(castType, CastExpr); 7511 7512 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7513 7514 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7515 } 7516 7517 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7518 SourceLocation RParenLoc, Expr *E, 7519 TypeSourceInfo *TInfo) { 7520 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7521 "Expected paren or paren list expression"); 7522 7523 Expr **exprs; 7524 unsigned numExprs; 7525 Expr *subExpr; 7526 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7527 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7528 LiteralLParenLoc = PE->getLParenLoc(); 7529 LiteralRParenLoc = PE->getRParenLoc(); 7530 exprs = PE->getExprs(); 7531 numExprs = PE->getNumExprs(); 7532 } else { // isa<ParenExpr> by assertion at function entrance 7533 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7534 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7535 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7536 exprs = &subExpr; 7537 numExprs = 1; 7538 } 7539 7540 QualType Ty = TInfo->getType(); 7541 assert(Ty->isVectorType() && "Expected vector type"); 7542 7543 SmallVector<Expr *, 8> initExprs; 7544 const VectorType *VTy = Ty->castAs<VectorType>(); 7545 unsigned numElems = VTy->getNumElements(); 7546 7547 // '(...)' form of vector initialization in AltiVec: the number of 7548 // initializers must be one or must match the size of the vector. 7549 // If a single value is specified in the initializer then it will be 7550 // replicated to all the components of the vector 7551 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7552 // The number of initializers must be one or must match the size of the 7553 // vector. If a single value is specified in the initializer then it will 7554 // be replicated to all the components of the vector 7555 if (numExprs == 1) { 7556 QualType ElemTy = VTy->getElementType(); 7557 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7558 if (Literal.isInvalid()) 7559 return ExprError(); 7560 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7561 PrepareScalarCast(Literal, ElemTy)); 7562 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7563 } 7564 else if (numExprs < numElems) { 7565 Diag(E->getExprLoc(), 7566 diag::err_incorrect_number_of_vector_initializers); 7567 return ExprError(); 7568 } 7569 else 7570 initExprs.append(exprs, exprs + numExprs); 7571 } 7572 else { 7573 // For OpenCL, when the number of initializers is a single value, 7574 // it will be replicated to all components of the vector. 7575 if (getLangOpts().OpenCL && 7576 VTy->getVectorKind() == VectorType::GenericVector && 7577 numExprs == 1) { 7578 QualType ElemTy = VTy->getElementType(); 7579 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7580 if (Literal.isInvalid()) 7581 return ExprError(); 7582 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7583 PrepareScalarCast(Literal, ElemTy)); 7584 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7585 } 7586 7587 initExprs.append(exprs, exprs + numExprs); 7588 } 7589 // FIXME: This means that pretty-printing the final AST will produce curly 7590 // braces instead of the original commas. 7591 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7592 initExprs, LiteralRParenLoc); 7593 initE->setType(Ty); 7594 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7595 } 7596 7597 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7598 /// the ParenListExpr into a sequence of comma binary operators. 7599 ExprResult 7600 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7601 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7602 if (!E) 7603 return OrigExpr; 7604 7605 ExprResult Result(E->getExpr(0)); 7606 7607 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7608 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7609 E->getExpr(i)); 7610 7611 if (Result.isInvalid()) return ExprError(); 7612 7613 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7614 } 7615 7616 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7617 SourceLocation R, 7618 MultiExprArg Val) { 7619 return ParenListExpr::Create(Context, L, Val, R); 7620 } 7621 7622 /// Emit a specialized diagnostic when one expression is a null pointer 7623 /// constant and the other is not a pointer. Returns true if a diagnostic is 7624 /// emitted. 7625 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7626 SourceLocation QuestionLoc) { 7627 Expr *NullExpr = LHSExpr; 7628 Expr *NonPointerExpr = RHSExpr; 7629 Expr::NullPointerConstantKind NullKind = 7630 NullExpr->isNullPointerConstant(Context, 7631 Expr::NPC_ValueDependentIsNotNull); 7632 7633 if (NullKind == Expr::NPCK_NotNull) { 7634 NullExpr = RHSExpr; 7635 NonPointerExpr = LHSExpr; 7636 NullKind = 7637 NullExpr->isNullPointerConstant(Context, 7638 Expr::NPC_ValueDependentIsNotNull); 7639 } 7640 7641 if (NullKind == Expr::NPCK_NotNull) 7642 return false; 7643 7644 if (NullKind == Expr::NPCK_ZeroExpression) 7645 return false; 7646 7647 if (NullKind == Expr::NPCK_ZeroLiteral) { 7648 // In this case, check to make sure that we got here from a "NULL" 7649 // string in the source code. 7650 NullExpr = NullExpr->IgnoreParenImpCasts(); 7651 SourceLocation loc = NullExpr->getExprLoc(); 7652 if (!findMacroSpelling(loc, "NULL")) 7653 return false; 7654 } 7655 7656 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7657 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7658 << NonPointerExpr->getType() << DiagType 7659 << NonPointerExpr->getSourceRange(); 7660 return true; 7661 } 7662 7663 /// Return false if the condition expression is valid, true otherwise. 7664 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7665 QualType CondTy = Cond->getType(); 7666 7667 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7668 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7669 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7670 << CondTy << Cond->getSourceRange(); 7671 return true; 7672 } 7673 7674 // C99 6.5.15p2 7675 if (CondTy->isScalarType()) return false; 7676 7677 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7678 << CondTy << Cond->getSourceRange(); 7679 return true; 7680 } 7681 7682 /// Handle when one or both operands are void type. 7683 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7684 ExprResult &RHS) { 7685 Expr *LHSExpr = LHS.get(); 7686 Expr *RHSExpr = RHS.get(); 7687 7688 if (!LHSExpr->getType()->isVoidType()) 7689 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7690 << RHSExpr->getSourceRange(); 7691 if (!RHSExpr->getType()->isVoidType()) 7692 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7693 << LHSExpr->getSourceRange(); 7694 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7695 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7696 return S.Context.VoidTy; 7697 } 7698 7699 /// Return false if the NullExpr can be promoted to PointerTy, 7700 /// true otherwise. 7701 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7702 QualType PointerTy) { 7703 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7704 !NullExpr.get()->isNullPointerConstant(S.Context, 7705 Expr::NPC_ValueDependentIsNull)) 7706 return true; 7707 7708 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7709 return false; 7710 } 7711 7712 /// Checks compatibility between two pointers and return the resulting 7713 /// type. 7714 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7715 ExprResult &RHS, 7716 SourceLocation Loc) { 7717 QualType LHSTy = LHS.get()->getType(); 7718 QualType RHSTy = RHS.get()->getType(); 7719 7720 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7721 // Two identical pointers types are always compatible. 7722 return LHSTy; 7723 } 7724 7725 QualType lhptee, rhptee; 7726 7727 // Get the pointee types. 7728 bool IsBlockPointer = false; 7729 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7730 lhptee = LHSBTy->getPointeeType(); 7731 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7732 IsBlockPointer = true; 7733 } else { 7734 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7735 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7736 } 7737 7738 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7739 // differently qualified versions of compatible types, the result type is 7740 // a pointer to an appropriately qualified version of the composite 7741 // type. 7742 7743 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7744 // clause doesn't make sense for our extensions. E.g. address space 2 should 7745 // be incompatible with address space 3: they may live on different devices or 7746 // anything. 7747 Qualifiers lhQual = lhptee.getQualifiers(); 7748 Qualifiers rhQual = rhptee.getQualifiers(); 7749 7750 LangAS ResultAddrSpace = LangAS::Default; 7751 LangAS LAddrSpace = lhQual.getAddressSpace(); 7752 LangAS RAddrSpace = rhQual.getAddressSpace(); 7753 7754 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7755 // spaces is disallowed. 7756 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7757 ResultAddrSpace = LAddrSpace; 7758 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7759 ResultAddrSpace = RAddrSpace; 7760 else { 7761 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7762 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7763 << RHS.get()->getSourceRange(); 7764 return QualType(); 7765 } 7766 7767 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7768 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7769 lhQual.removeCVRQualifiers(); 7770 rhQual.removeCVRQualifiers(); 7771 7772 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7773 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7774 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7775 // qual types are compatible iff 7776 // * corresponded types are compatible 7777 // * CVR qualifiers are equal 7778 // * address spaces are equal 7779 // Thus for conditional operator we merge CVR and address space unqualified 7780 // pointees and if there is a composite type we return a pointer to it with 7781 // merged qualifiers. 7782 LHSCastKind = 7783 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7784 RHSCastKind = 7785 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7786 lhQual.removeAddressSpace(); 7787 rhQual.removeAddressSpace(); 7788 7789 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7790 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7791 7792 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7793 7794 if (CompositeTy.isNull()) { 7795 // In this situation, we assume void* type. No especially good 7796 // reason, but this is what gcc does, and we do have to pick 7797 // to get a consistent AST. 7798 QualType incompatTy; 7799 incompatTy = S.Context.getPointerType( 7800 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7801 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7802 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7803 7804 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7805 // for casts between types with incompatible address space qualifiers. 7806 // For the following code the compiler produces casts between global and 7807 // local address spaces of the corresponded innermost pointees: 7808 // local int *global *a; 7809 // global int *global *b; 7810 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7811 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7812 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7813 << RHS.get()->getSourceRange(); 7814 7815 return incompatTy; 7816 } 7817 7818 // The pointer types are compatible. 7819 // In case of OpenCL ResultTy should have the address space qualifier 7820 // which is a superset of address spaces of both the 2nd and the 3rd 7821 // operands of the conditional operator. 7822 QualType ResultTy = [&, ResultAddrSpace]() { 7823 if (S.getLangOpts().OpenCL) { 7824 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7825 CompositeQuals.setAddressSpace(ResultAddrSpace); 7826 return S.Context 7827 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7828 .withCVRQualifiers(MergedCVRQual); 7829 } 7830 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7831 }(); 7832 if (IsBlockPointer) 7833 ResultTy = S.Context.getBlockPointerType(ResultTy); 7834 else 7835 ResultTy = S.Context.getPointerType(ResultTy); 7836 7837 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7838 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7839 return ResultTy; 7840 } 7841 7842 /// Return the resulting type when the operands are both block pointers. 7843 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7844 ExprResult &LHS, 7845 ExprResult &RHS, 7846 SourceLocation Loc) { 7847 QualType LHSTy = LHS.get()->getType(); 7848 QualType RHSTy = RHS.get()->getType(); 7849 7850 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7851 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7852 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7853 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7854 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7855 return destType; 7856 } 7857 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7858 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7859 << RHS.get()->getSourceRange(); 7860 return QualType(); 7861 } 7862 7863 // We have 2 block pointer types. 7864 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7865 } 7866 7867 /// Return the resulting type when the operands are both pointers. 7868 static QualType 7869 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7870 ExprResult &RHS, 7871 SourceLocation Loc) { 7872 // get the pointer types 7873 QualType LHSTy = LHS.get()->getType(); 7874 QualType RHSTy = RHS.get()->getType(); 7875 7876 // get the "pointed to" types 7877 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7878 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7879 7880 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7881 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7882 // Figure out necessary qualifiers (C99 6.5.15p6) 7883 QualType destPointee 7884 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7885 QualType destType = S.Context.getPointerType(destPointee); 7886 // Add qualifiers if necessary. 7887 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7888 // Promote to void*. 7889 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7890 return destType; 7891 } 7892 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7893 QualType destPointee 7894 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7895 QualType destType = S.Context.getPointerType(destPointee); 7896 // Add qualifiers if necessary. 7897 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7898 // Promote to void*. 7899 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7900 return destType; 7901 } 7902 7903 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7904 } 7905 7906 /// Return false if the first expression is not an integer and the second 7907 /// expression is not a pointer, true otherwise. 7908 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7909 Expr* PointerExpr, SourceLocation Loc, 7910 bool IsIntFirstExpr) { 7911 if (!PointerExpr->getType()->isPointerType() || 7912 !Int.get()->getType()->isIntegerType()) 7913 return false; 7914 7915 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7916 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7917 7918 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7919 << Expr1->getType() << Expr2->getType() 7920 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7921 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7922 CK_IntegralToPointer); 7923 return true; 7924 } 7925 7926 /// Simple conversion between integer and floating point types. 7927 /// 7928 /// Used when handling the OpenCL conditional operator where the 7929 /// condition is a vector while the other operands are scalar. 7930 /// 7931 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7932 /// types are either integer or floating type. Between the two 7933 /// operands, the type with the higher rank is defined as the "result 7934 /// type". The other operand needs to be promoted to the same type. No 7935 /// other type promotion is allowed. We cannot use 7936 /// UsualArithmeticConversions() for this purpose, since it always 7937 /// promotes promotable types. 7938 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7939 ExprResult &RHS, 7940 SourceLocation QuestionLoc) { 7941 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7942 if (LHS.isInvalid()) 7943 return QualType(); 7944 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7945 if (RHS.isInvalid()) 7946 return QualType(); 7947 7948 // For conversion purposes, we ignore any qualifiers. 7949 // For example, "const float" and "float" are equivalent. 7950 QualType LHSType = 7951 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7952 QualType RHSType = 7953 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7954 7955 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7956 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7957 << LHSType << LHS.get()->getSourceRange(); 7958 return QualType(); 7959 } 7960 7961 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7962 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7963 << RHSType << RHS.get()->getSourceRange(); 7964 return QualType(); 7965 } 7966 7967 // If both types are identical, no conversion is needed. 7968 if (LHSType == RHSType) 7969 return LHSType; 7970 7971 // Now handle "real" floating types (i.e. float, double, long double). 7972 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7973 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7974 /*IsCompAssign = */ false); 7975 7976 // Finally, we have two differing integer types. 7977 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7978 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7979 } 7980 7981 /// Convert scalar operands to a vector that matches the 7982 /// condition in length. 7983 /// 7984 /// Used when handling the OpenCL conditional operator where the 7985 /// condition is a vector while the other operands are scalar. 7986 /// 7987 /// We first compute the "result type" for the scalar operands 7988 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7989 /// into a vector of that type where the length matches the condition 7990 /// vector type. s6.11.6 requires that the element types of the result 7991 /// and the condition must have the same number of bits. 7992 static QualType 7993 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7994 QualType CondTy, SourceLocation QuestionLoc) { 7995 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7996 if (ResTy.isNull()) return QualType(); 7997 7998 const VectorType *CV = CondTy->getAs<VectorType>(); 7999 assert(CV); 8000 8001 // Determine the vector result type 8002 unsigned NumElements = CV->getNumElements(); 8003 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8004 8005 // Ensure that all types have the same number of bits 8006 if (S.Context.getTypeSize(CV->getElementType()) 8007 != S.Context.getTypeSize(ResTy)) { 8008 // Since VectorTy is created internally, it does not pretty print 8009 // with an OpenCL name. Instead, we just print a description. 8010 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8011 SmallString<64> Str; 8012 llvm::raw_svector_ostream OS(Str); 8013 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8014 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8015 << CondTy << OS.str(); 8016 return QualType(); 8017 } 8018 8019 // Convert operands to the vector result type 8020 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8021 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8022 8023 return VectorTy; 8024 } 8025 8026 /// Return false if this is a valid OpenCL condition vector 8027 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8028 SourceLocation QuestionLoc) { 8029 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8030 // integral type. 8031 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8032 assert(CondTy); 8033 QualType EleTy = CondTy->getElementType(); 8034 if (EleTy->isIntegerType()) return false; 8035 8036 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8037 << Cond->getType() << Cond->getSourceRange(); 8038 return true; 8039 } 8040 8041 /// Return false if the vector condition type and the vector 8042 /// result type are compatible. 8043 /// 8044 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8045 /// number of elements, and their element types have the same number 8046 /// of bits. 8047 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8048 SourceLocation QuestionLoc) { 8049 const VectorType *CV = CondTy->getAs<VectorType>(); 8050 const VectorType *RV = VecResTy->getAs<VectorType>(); 8051 assert(CV && RV); 8052 8053 if (CV->getNumElements() != RV->getNumElements()) { 8054 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8055 << CondTy << VecResTy; 8056 return true; 8057 } 8058 8059 QualType CVE = CV->getElementType(); 8060 QualType RVE = RV->getElementType(); 8061 8062 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8063 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8064 << CondTy << VecResTy; 8065 return true; 8066 } 8067 8068 return false; 8069 } 8070 8071 /// Return the resulting type for the conditional operator in 8072 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8073 /// s6.3.i) when the condition is a vector type. 8074 static QualType 8075 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8076 ExprResult &LHS, ExprResult &RHS, 8077 SourceLocation QuestionLoc) { 8078 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8079 if (Cond.isInvalid()) 8080 return QualType(); 8081 QualType CondTy = Cond.get()->getType(); 8082 8083 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8084 return QualType(); 8085 8086 // If either operand is a vector then find the vector type of the 8087 // result as specified in OpenCL v1.1 s6.3.i. 8088 if (LHS.get()->getType()->isVectorType() || 8089 RHS.get()->getType()->isVectorType()) { 8090 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8091 /*isCompAssign*/false, 8092 /*AllowBothBool*/true, 8093 /*AllowBoolConversions*/false); 8094 if (VecResTy.isNull()) return QualType(); 8095 // The result type must match the condition type as specified in 8096 // OpenCL v1.1 s6.11.6. 8097 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8098 return QualType(); 8099 return VecResTy; 8100 } 8101 8102 // Both operands are scalar. 8103 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8104 } 8105 8106 /// Return true if the Expr is block type 8107 static bool checkBlockType(Sema &S, const Expr *E) { 8108 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8109 QualType Ty = CE->getCallee()->getType(); 8110 if (Ty->isBlockPointerType()) { 8111 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8112 return true; 8113 } 8114 } 8115 return false; 8116 } 8117 8118 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8119 /// In that case, LHS = cond. 8120 /// C99 6.5.15 8121 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8122 ExprResult &RHS, ExprValueKind &VK, 8123 ExprObjectKind &OK, 8124 SourceLocation QuestionLoc) { 8125 8126 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8127 if (!LHSResult.isUsable()) return QualType(); 8128 LHS = LHSResult; 8129 8130 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8131 if (!RHSResult.isUsable()) return QualType(); 8132 RHS = RHSResult; 8133 8134 // C++ is sufficiently different to merit its own checker. 8135 if (getLangOpts().CPlusPlus) 8136 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8137 8138 VK = VK_RValue; 8139 OK = OK_Ordinary; 8140 8141 if (Context.isDependenceAllowed() && 8142 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8143 RHS.get()->isTypeDependent())) { 8144 assert(!getLangOpts().CPlusPlus); 8145 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8146 RHS.get()->containsErrors()) && 8147 "should only occur in error-recovery path."); 8148 return Context.DependentTy; 8149 } 8150 8151 // The OpenCL operator with a vector condition is sufficiently 8152 // different to merit its own checker. 8153 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8154 Cond.get()->getType()->isExtVectorType()) 8155 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8156 8157 // First, check the condition. 8158 Cond = UsualUnaryConversions(Cond.get()); 8159 if (Cond.isInvalid()) 8160 return QualType(); 8161 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8162 return QualType(); 8163 8164 // Now check the two expressions. 8165 if (LHS.get()->getType()->isVectorType() || 8166 RHS.get()->getType()->isVectorType()) 8167 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8168 /*AllowBothBool*/true, 8169 /*AllowBoolConversions*/false); 8170 8171 QualType ResTy = 8172 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8173 if (LHS.isInvalid() || RHS.isInvalid()) 8174 return QualType(); 8175 8176 QualType LHSTy = LHS.get()->getType(); 8177 QualType RHSTy = RHS.get()->getType(); 8178 8179 // Diagnose attempts to convert between __float128 and long double where 8180 // such conversions currently can't be handled. 8181 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8182 Diag(QuestionLoc, 8183 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8184 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8185 return QualType(); 8186 } 8187 8188 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8189 // selection operator (?:). 8190 if (getLangOpts().OpenCL && 8191 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8192 return QualType(); 8193 } 8194 8195 // If both operands have arithmetic type, do the usual arithmetic conversions 8196 // to find a common type: C99 6.5.15p3,5. 8197 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8198 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8199 // different sizes, or between ExtInts and other types. 8200 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8201 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8202 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8203 << RHS.get()->getSourceRange(); 8204 return QualType(); 8205 } 8206 8207 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8208 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8209 8210 return ResTy; 8211 } 8212 8213 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8214 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8215 return LHSTy; 8216 } 8217 8218 // If both operands are the same structure or union type, the result is that 8219 // type. 8220 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8221 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8222 if (LHSRT->getDecl() == RHSRT->getDecl()) 8223 // "If both the operands have structure or union type, the result has 8224 // that type." This implies that CV qualifiers are dropped. 8225 return LHSTy.getUnqualifiedType(); 8226 // FIXME: Type of conditional expression must be complete in C mode. 8227 } 8228 8229 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8230 // The following || allows only one side to be void (a GCC-ism). 8231 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8232 return checkConditionalVoidType(*this, LHS, RHS); 8233 } 8234 8235 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8236 // the type of the other operand." 8237 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8238 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8239 8240 // All objective-c pointer type analysis is done here. 8241 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8242 QuestionLoc); 8243 if (LHS.isInvalid() || RHS.isInvalid()) 8244 return QualType(); 8245 if (!compositeType.isNull()) 8246 return compositeType; 8247 8248 8249 // Handle block pointer types. 8250 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8251 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8252 QuestionLoc); 8253 8254 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8255 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8256 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8257 QuestionLoc); 8258 8259 // GCC compatibility: soften pointer/integer mismatch. Note that 8260 // null pointers have been filtered out by this point. 8261 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8262 /*IsIntFirstExpr=*/true)) 8263 return RHSTy; 8264 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8265 /*IsIntFirstExpr=*/false)) 8266 return LHSTy; 8267 8268 // Allow ?: operations in which both operands have the same 8269 // built-in sizeless type. 8270 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8271 return LHSTy; 8272 8273 // Emit a better diagnostic if one of the expressions is a null pointer 8274 // constant and the other is not a pointer type. In this case, the user most 8275 // likely forgot to take the address of the other expression. 8276 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8277 return QualType(); 8278 8279 // Otherwise, the operands are not compatible. 8280 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8281 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8282 << RHS.get()->getSourceRange(); 8283 return QualType(); 8284 } 8285 8286 /// FindCompositeObjCPointerType - Helper method to find composite type of 8287 /// two objective-c pointer types of the two input expressions. 8288 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8289 SourceLocation QuestionLoc) { 8290 QualType LHSTy = LHS.get()->getType(); 8291 QualType RHSTy = RHS.get()->getType(); 8292 8293 // Handle things like Class and struct objc_class*. Here we case the result 8294 // to the pseudo-builtin, because that will be implicitly cast back to the 8295 // redefinition type if an attempt is made to access its fields. 8296 if (LHSTy->isObjCClassType() && 8297 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8298 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8299 return LHSTy; 8300 } 8301 if (RHSTy->isObjCClassType() && 8302 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8303 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8304 return RHSTy; 8305 } 8306 // And the same for struct objc_object* / id 8307 if (LHSTy->isObjCIdType() && 8308 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8309 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8310 return LHSTy; 8311 } 8312 if (RHSTy->isObjCIdType() && 8313 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8314 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8315 return RHSTy; 8316 } 8317 // And the same for struct objc_selector* / SEL 8318 if (Context.isObjCSelType(LHSTy) && 8319 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8320 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8321 return LHSTy; 8322 } 8323 if (Context.isObjCSelType(RHSTy) && 8324 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8325 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8326 return RHSTy; 8327 } 8328 // Check constraints for Objective-C object pointers types. 8329 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8330 8331 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8332 // Two identical object pointer types are always compatible. 8333 return LHSTy; 8334 } 8335 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8336 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8337 QualType compositeType = LHSTy; 8338 8339 // If both operands are interfaces and either operand can be 8340 // assigned to the other, use that type as the composite 8341 // type. This allows 8342 // xxx ? (A*) a : (B*) b 8343 // where B is a subclass of A. 8344 // 8345 // Additionally, as for assignment, if either type is 'id' 8346 // allow silent coercion. Finally, if the types are 8347 // incompatible then make sure to use 'id' as the composite 8348 // type so the result is acceptable for sending messages to. 8349 8350 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8351 // It could return the composite type. 8352 if (!(compositeType = 8353 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8354 // Nothing more to do. 8355 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8356 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8357 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8358 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8359 } else if ((LHSOPT->isObjCQualifiedIdType() || 8360 RHSOPT->isObjCQualifiedIdType()) && 8361 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8362 true)) { 8363 // Need to handle "id<xx>" explicitly. 8364 // GCC allows qualified id and any Objective-C type to devolve to 8365 // id. Currently localizing to here until clear this should be 8366 // part of ObjCQualifiedIdTypesAreCompatible. 8367 compositeType = Context.getObjCIdType(); 8368 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8369 compositeType = Context.getObjCIdType(); 8370 } else { 8371 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8372 << LHSTy << RHSTy 8373 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8374 QualType incompatTy = Context.getObjCIdType(); 8375 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8376 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8377 return incompatTy; 8378 } 8379 // The object pointer types are compatible. 8380 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8381 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8382 return compositeType; 8383 } 8384 // Check Objective-C object pointer types and 'void *' 8385 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8386 if (getLangOpts().ObjCAutoRefCount) { 8387 // ARC forbids the implicit conversion of object pointers to 'void *', 8388 // so these types are not compatible. 8389 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8390 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8391 LHS = RHS = true; 8392 return QualType(); 8393 } 8394 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8395 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8396 QualType destPointee 8397 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8398 QualType destType = Context.getPointerType(destPointee); 8399 // Add qualifiers if necessary. 8400 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8401 // Promote to void*. 8402 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8403 return destType; 8404 } 8405 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8406 if (getLangOpts().ObjCAutoRefCount) { 8407 // ARC forbids the implicit conversion of object pointers to 'void *', 8408 // so these types are not compatible. 8409 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8410 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8411 LHS = RHS = true; 8412 return QualType(); 8413 } 8414 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8415 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8416 QualType destPointee 8417 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8418 QualType destType = Context.getPointerType(destPointee); 8419 // Add qualifiers if necessary. 8420 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8421 // Promote to void*. 8422 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8423 return destType; 8424 } 8425 return QualType(); 8426 } 8427 8428 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8429 /// ParenRange in parentheses. 8430 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8431 const PartialDiagnostic &Note, 8432 SourceRange ParenRange) { 8433 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8434 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8435 EndLoc.isValid()) { 8436 Self.Diag(Loc, Note) 8437 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8438 << FixItHint::CreateInsertion(EndLoc, ")"); 8439 } else { 8440 // We can't display the parentheses, so just show the bare note. 8441 Self.Diag(Loc, Note) << ParenRange; 8442 } 8443 } 8444 8445 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8446 return BinaryOperator::isAdditiveOp(Opc) || 8447 BinaryOperator::isMultiplicativeOp(Opc) || 8448 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8449 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8450 // not any of the logical operators. Bitwise-xor is commonly used as a 8451 // logical-xor because there is no logical-xor operator. The logical 8452 // operators, including uses of xor, have a high false positive rate for 8453 // precedence warnings. 8454 } 8455 8456 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8457 /// expression, either using a built-in or overloaded operator, 8458 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8459 /// expression. 8460 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8461 Expr **RHSExprs) { 8462 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8463 E = E->IgnoreImpCasts(); 8464 E = E->IgnoreConversionOperatorSingleStep(); 8465 E = E->IgnoreImpCasts(); 8466 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8467 E = MTE->getSubExpr(); 8468 E = E->IgnoreImpCasts(); 8469 } 8470 8471 // Built-in binary operator. 8472 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8473 if (IsArithmeticOp(OP->getOpcode())) { 8474 *Opcode = OP->getOpcode(); 8475 *RHSExprs = OP->getRHS(); 8476 return true; 8477 } 8478 } 8479 8480 // Overloaded operator. 8481 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8482 if (Call->getNumArgs() != 2) 8483 return false; 8484 8485 // Make sure this is really a binary operator that is safe to pass into 8486 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8487 OverloadedOperatorKind OO = Call->getOperator(); 8488 if (OO < OO_Plus || OO > OO_Arrow || 8489 OO == OO_PlusPlus || OO == OO_MinusMinus) 8490 return false; 8491 8492 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8493 if (IsArithmeticOp(OpKind)) { 8494 *Opcode = OpKind; 8495 *RHSExprs = Call->getArg(1); 8496 return true; 8497 } 8498 } 8499 8500 return false; 8501 } 8502 8503 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8504 /// or is a logical expression such as (x==y) which has int type, but is 8505 /// commonly interpreted as boolean. 8506 static bool ExprLooksBoolean(Expr *E) { 8507 E = E->IgnoreParenImpCasts(); 8508 8509 if (E->getType()->isBooleanType()) 8510 return true; 8511 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8512 return OP->isComparisonOp() || OP->isLogicalOp(); 8513 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8514 return OP->getOpcode() == UO_LNot; 8515 if (E->getType()->isPointerType()) 8516 return true; 8517 // FIXME: What about overloaded operator calls returning "unspecified boolean 8518 // type"s (commonly pointer-to-members)? 8519 8520 return false; 8521 } 8522 8523 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8524 /// and binary operator are mixed in a way that suggests the programmer assumed 8525 /// the conditional operator has higher precedence, for example: 8526 /// "int x = a + someBinaryCondition ? 1 : 2". 8527 static void DiagnoseConditionalPrecedence(Sema &Self, 8528 SourceLocation OpLoc, 8529 Expr *Condition, 8530 Expr *LHSExpr, 8531 Expr *RHSExpr) { 8532 BinaryOperatorKind CondOpcode; 8533 Expr *CondRHS; 8534 8535 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8536 return; 8537 if (!ExprLooksBoolean(CondRHS)) 8538 return; 8539 8540 // The condition is an arithmetic binary expression, with a right- 8541 // hand side that looks boolean, so warn. 8542 8543 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8544 ? diag::warn_precedence_bitwise_conditional 8545 : diag::warn_precedence_conditional; 8546 8547 Self.Diag(OpLoc, DiagID) 8548 << Condition->getSourceRange() 8549 << BinaryOperator::getOpcodeStr(CondOpcode); 8550 8551 SuggestParentheses( 8552 Self, OpLoc, 8553 Self.PDiag(diag::note_precedence_silence) 8554 << BinaryOperator::getOpcodeStr(CondOpcode), 8555 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8556 8557 SuggestParentheses(Self, OpLoc, 8558 Self.PDiag(diag::note_precedence_conditional_first), 8559 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8560 } 8561 8562 /// Compute the nullability of a conditional expression. 8563 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8564 QualType LHSTy, QualType RHSTy, 8565 ASTContext &Ctx) { 8566 if (!ResTy->isAnyPointerType()) 8567 return ResTy; 8568 8569 auto GetNullability = [&Ctx](QualType Ty) { 8570 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8571 if (Kind) { 8572 // For our purposes, treat _Nullable_result as _Nullable. 8573 if (*Kind == NullabilityKind::NullableResult) 8574 return NullabilityKind::Nullable; 8575 return *Kind; 8576 } 8577 return NullabilityKind::Unspecified; 8578 }; 8579 8580 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8581 NullabilityKind MergedKind; 8582 8583 // Compute nullability of a binary conditional expression. 8584 if (IsBin) { 8585 if (LHSKind == NullabilityKind::NonNull) 8586 MergedKind = NullabilityKind::NonNull; 8587 else 8588 MergedKind = RHSKind; 8589 // Compute nullability of a normal conditional expression. 8590 } else { 8591 if (LHSKind == NullabilityKind::Nullable || 8592 RHSKind == NullabilityKind::Nullable) 8593 MergedKind = NullabilityKind::Nullable; 8594 else if (LHSKind == NullabilityKind::NonNull) 8595 MergedKind = RHSKind; 8596 else if (RHSKind == NullabilityKind::NonNull) 8597 MergedKind = LHSKind; 8598 else 8599 MergedKind = NullabilityKind::Unspecified; 8600 } 8601 8602 // Return if ResTy already has the correct nullability. 8603 if (GetNullability(ResTy) == MergedKind) 8604 return ResTy; 8605 8606 // Strip all nullability from ResTy. 8607 while (ResTy->getNullability(Ctx)) 8608 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8609 8610 // Create a new AttributedType with the new nullability kind. 8611 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8612 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8613 } 8614 8615 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8616 /// in the case of a the GNU conditional expr extension. 8617 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8618 SourceLocation ColonLoc, 8619 Expr *CondExpr, Expr *LHSExpr, 8620 Expr *RHSExpr) { 8621 if (!Context.isDependenceAllowed()) { 8622 // C cannot handle TypoExpr nodes in the condition because it 8623 // doesn't handle dependent types properly, so make sure any TypoExprs have 8624 // been dealt with before checking the operands. 8625 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8626 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8627 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8628 8629 if (!CondResult.isUsable()) 8630 return ExprError(); 8631 8632 if (LHSExpr) { 8633 if (!LHSResult.isUsable()) 8634 return ExprError(); 8635 } 8636 8637 if (!RHSResult.isUsable()) 8638 return ExprError(); 8639 8640 CondExpr = CondResult.get(); 8641 LHSExpr = LHSResult.get(); 8642 RHSExpr = RHSResult.get(); 8643 } 8644 8645 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8646 // was the condition. 8647 OpaqueValueExpr *opaqueValue = nullptr; 8648 Expr *commonExpr = nullptr; 8649 if (!LHSExpr) { 8650 commonExpr = CondExpr; 8651 // Lower out placeholder types first. This is important so that we don't 8652 // try to capture a placeholder. This happens in few cases in C++; such 8653 // as Objective-C++'s dictionary subscripting syntax. 8654 if (commonExpr->hasPlaceholderType()) { 8655 ExprResult result = CheckPlaceholderExpr(commonExpr); 8656 if (!result.isUsable()) return ExprError(); 8657 commonExpr = result.get(); 8658 } 8659 // We usually want to apply unary conversions *before* saving, except 8660 // in the special case of a C++ l-value conditional. 8661 if (!(getLangOpts().CPlusPlus 8662 && !commonExpr->isTypeDependent() 8663 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8664 && commonExpr->isGLValue() 8665 && commonExpr->isOrdinaryOrBitFieldObject() 8666 && RHSExpr->isOrdinaryOrBitFieldObject() 8667 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8668 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8669 if (commonRes.isInvalid()) 8670 return ExprError(); 8671 commonExpr = commonRes.get(); 8672 } 8673 8674 // If the common expression is a class or array prvalue, materialize it 8675 // so that we can safely refer to it multiple times. 8676 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8677 commonExpr->getType()->isArrayType())) { 8678 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8679 if (MatExpr.isInvalid()) 8680 return ExprError(); 8681 commonExpr = MatExpr.get(); 8682 } 8683 8684 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8685 commonExpr->getType(), 8686 commonExpr->getValueKind(), 8687 commonExpr->getObjectKind(), 8688 commonExpr); 8689 LHSExpr = CondExpr = opaqueValue; 8690 } 8691 8692 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8693 ExprValueKind VK = VK_RValue; 8694 ExprObjectKind OK = OK_Ordinary; 8695 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8696 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8697 VK, OK, QuestionLoc); 8698 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8699 RHS.isInvalid()) 8700 return ExprError(); 8701 8702 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8703 RHS.get()); 8704 8705 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8706 8707 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8708 Context); 8709 8710 if (!commonExpr) 8711 return new (Context) 8712 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8713 RHS.get(), result, VK, OK); 8714 8715 return new (Context) BinaryConditionalOperator( 8716 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8717 ColonLoc, result, VK, OK); 8718 } 8719 8720 // Check if we have a conversion between incompatible cmse function pointer 8721 // types, that is, a conversion between a function pointer with the 8722 // cmse_nonsecure_call attribute and one without. 8723 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8724 QualType ToType) { 8725 if (const auto *ToFn = 8726 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8727 if (const auto *FromFn = 8728 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8729 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8730 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8731 8732 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8733 } 8734 } 8735 return false; 8736 } 8737 8738 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8739 // being closely modeled after the C99 spec:-). The odd characteristic of this 8740 // routine is it effectively iqnores the qualifiers on the top level pointee. 8741 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8742 // FIXME: add a couple examples in this comment. 8743 static Sema::AssignConvertType 8744 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8745 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8746 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8747 8748 // get the "pointed to" type (ignoring qualifiers at the top level) 8749 const Type *lhptee, *rhptee; 8750 Qualifiers lhq, rhq; 8751 std::tie(lhptee, lhq) = 8752 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8753 std::tie(rhptee, rhq) = 8754 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8755 8756 Sema::AssignConvertType ConvTy = Sema::Compatible; 8757 8758 // C99 6.5.16.1p1: This following citation is common to constraints 8759 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8760 // qualifiers of the type *pointed to* by the right; 8761 8762 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8763 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8764 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8765 // Ignore lifetime for further calculation. 8766 lhq.removeObjCLifetime(); 8767 rhq.removeObjCLifetime(); 8768 } 8769 8770 if (!lhq.compatiblyIncludes(rhq)) { 8771 // Treat address-space mismatches as fatal. 8772 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8773 return Sema::IncompatiblePointerDiscardsQualifiers; 8774 8775 // It's okay to add or remove GC or lifetime qualifiers when converting to 8776 // and from void*. 8777 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8778 .compatiblyIncludes( 8779 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8780 && (lhptee->isVoidType() || rhptee->isVoidType())) 8781 ; // keep old 8782 8783 // Treat lifetime mismatches as fatal. 8784 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8785 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8786 8787 // For GCC/MS compatibility, other qualifier mismatches are treated 8788 // as still compatible in C. 8789 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8790 } 8791 8792 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8793 // incomplete type and the other is a pointer to a qualified or unqualified 8794 // version of void... 8795 if (lhptee->isVoidType()) { 8796 if (rhptee->isIncompleteOrObjectType()) 8797 return ConvTy; 8798 8799 // As an extension, we allow cast to/from void* to function pointer. 8800 assert(rhptee->isFunctionType()); 8801 return Sema::FunctionVoidPointer; 8802 } 8803 8804 if (rhptee->isVoidType()) { 8805 if (lhptee->isIncompleteOrObjectType()) 8806 return ConvTy; 8807 8808 // As an extension, we allow cast to/from void* to function pointer. 8809 assert(lhptee->isFunctionType()); 8810 return Sema::FunctionVoidPointer; 8811 } 8812 8813 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8814 // unqualified versions of compatible types, ... 8815 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8816 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8817 // Check if the pointee types are compatible ignoring the sign. 8818 // We explicitly check for char so that we catch "char" vs 8819 // "unsigned char" on systems where "char" is unsigned. 8820 if (lhptee->isCharType()) 8821 ltrans = S.Context.UnsignedCharTy; 8822 else if (lhptee->hasSignedIntegerRepresentation()) 8823 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8824 8825 if (rhptee->isCharType()) 8826 rtrans = S.Context.UnsignedCharTy; 8827 else if (rhptee->hasSignedIntegerRepresentation()) 8828 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8829 8830 if (ltrans == rtrans) { 8831 // Types are compatible ignoring the sign. Qualifier incompatibility 8832 // takes priority over sign incompatibility because the sign 8833 // warning can be disabled. 8834 if (ConvTy != Sema::Compatible) 8835 return ConvTy; 8836 8837 return Sema::IncompatiblePointerSign; 8838 } 8839 8840 // If we are a multi-level pointer, it's possible that our issue is simply 8841 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8842 // the eventual target type is the same and the pointers have the same 8843 // level of indirection, this must be the issue. 8844 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8845 do { 8846 std::tie(lhptee, lhq) = 8847 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8848 std::tie(rhptee, rhq) = 8849 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8850 8851 // Inconsistent address spaces at this point is invalid, even if the 8852 // address spaces would be compatible. 8853 // FIXME: This doesn't catch address space mismatches for pointers of 8854 // different nesting levels, like: 8855 // __local int *** a; 8856 // int ** b = a; 8857 // It's not clear how to actually determine when such pointers are 8858 // invalidly incompatible. 8859 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8860 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8861 8862 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8863 8864 if (lhptee == rhptee) 8865 return Sema::IncompatibleNestedPointerQualifiers; 8866 } 8867 8868 // General pointer incompatibility takes priority over qualifiers. 8869 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8870 return Sema::IncompatibleFunctionPointer; 8871 return Sema::IncompatiblePointer; 8872 } 8873 if (!S.getLangOpts().CPlusPlus && 8874 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8875 return Sema::IncompatibleFunctionPointer; 8876 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8877 return Sema::IncompatibleFunctionPointer; 8878 return ConvTy; 8879 } 8880 8881 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8882 /// block pointer types are compatible or whether a block and normal pointer 8883 /// are compatible. It is more restrict than comparing two function pointer 8884 // types. 8885 static Sema::AssignConvertType 8886 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8887 QualType RHSType) { 8888 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8889 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8890 8891 QualType lhptee, rhptee; 8892 8893 // get the "pointed to" type (ignoring qualifiers at the top level) 8894 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8895 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8896 8897 // In C++, the types have to match exactly. 8898 if (S.getLangOpts().CPlusPlus) 8899 return Sema::IncompatibleBlockPointer; 8900 8901 Sema::AssignConvertType ConvTy = Sema::Compatible; 8902 8903 // For blocks we enforce that qualifiers are identical. 8904 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8905 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8906 if (S.getLangOpts().OpenCL) { 8907 LQuals.removeAddressSpace(); 8908 RQuals.removeAddressSpace(); 8909 } 8910 if (LQuals != RQuals) 8911 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8912 8913 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8914 // assignment. 8915 // The current behavior is similar to C++ lambdas. A block might be 8916 // assigned to a variable iff its return type and parameters are compatible 8917 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8918 // an assignment. Presumably it should behave in way that a function pointer 8919 // assignment does in C, so for each parameter and return type: 8920 // * CVR and address space of LHS should be a superset of CVR and address 8921 // space of RHS. 8922 // * unqualified types should be compatible. 8923 if (S.getLangOpts().OpenCL) { 8924 if (!S.Context.typesAreBlockPointerCompatible( 8925 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8926 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8927 return Sema::IncompatibleBlockPointer; 8928 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8929 return Sema::IncompatibleBlockPointer; 8930 8931 return ConvTy; 8932 } 8933 8934 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8935 /// for assignment compatibility. 8936 static Sema::AssignConvertType 8937 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8938 QualType RHSType) { 8939 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8940 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8941 8942 if (LHSType->isObjCBuiltinType()) { 8943 // Class is not compatible with ObjC object pointers. 8944 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8945 !RHSType->isObjCQualifiedClassType()) 8946 return Sema::IncompatiblePointer; 8947 return Sema::Compatible; 8948 } 8949 if (RHSType->isObjCBuiltinType()) { 8950 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8951 !LHSType->isObjCQualifiedClassType()) 8952 return Sema::IncompatiblePointer; 8953 return Sema::Compatible; 8954 } 8955 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8956 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8957 8958 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8959 // make an exception for id<P> 8960 !LHSType->isObjCQualifiedIdType()) 8961 return Sema::CompatiblePointerDiscardsQualifiers; 8962 8963 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8964 return Sema::Compatible; 8965 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8966 return Sema::IncompatibleObjCQualifiedId; 8967 return Sema::IncompatiblePointer; 8968 } 8969 8970 Sema::AssignConvertType 8971 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8972 QualType LHSType, QualType RHSType) { 8973 // Fake up an opaque expression. We don't actually care about what 8974 // cast operations are required, so if CheckAssignmentConstraints 8975 // adds casts to this they'll be wasted, but fortunately that doesn't 8976 // usually happen on valid code. 8977 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8978 ExprResult RHSPtr = &RHSExpr; 8979 CastKind K; 8980 8981 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8982 } 8983 8984 /// This helper function returns true if QT is a vector type that has element 8985 /// type ElementType. 8986 static bool isVector(QualType QT, QualType ElementType) { 8987 if (const VectorType *VT = QT->getAs<VectorType>()) 8988 return VT->getElementType().getCanonicalType() == ElementType; 8989 return false; 8990 } 8991 8992 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8993 /// has code to accommodate several GCC extensions when type checking 8994 /// pointers. Here are some objectionable examples that GCC considers warnings: 8995 /// 8996 /// int a, *pint; 8997 /// short *pshort; 8998 /// struct foo *pfoo; 8999 /// 9000 /// pint = pshort; // warning: assignment from incompatible pointer type 9001 /// a = pint; // warning: assignment makes integer from pointer without a cast 9002 /// pint = a; // warning: assignment makes pointer from integer without a cast 9003 /// pint = pfoo; // warning: assignment from incompatible pointer type 9004 /// 9005 /// As a result, the code for dealing with pointers is more complex than the 9006 /// C99 spec dictates. 9007 /// 9008 /// Sets 'Kind' for any result kind except Incompatible. 9009 Sema::AssignConvertType 9010 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9011 CastKind &Kind, bool ConvertRHS) { 9012 QualType RHSType = RHS.get()->getType(); 9013 QualType OrigLHSType = LHSType; 9014 9015 // Get canonical types. We're not formatting these types, just comparing 9016 // them. 9017 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9018 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9019 9020 // Common case: no conversion required. 9021 if (LHSType == RHSType) { 9022 Kind = CK_NoOp; 9023 return Compatible; 9024 } 9025 9026 // If we have an atomic type, try a non-atomic assignment, then just add an 9027 // atomic qualification step. 9028 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9029 Sema::AssignConvertType result = 9030 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9031 if (result != Compatible) 9032 return result; 9033 if (Kind != CK_NoOp && ConvertRHS) 9034 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9035 Kind = CK_NonAtomicToAtomic; 9036 return Compatible; 9037 } 9038 9039 // If the left-hand side is a reference type, then we are in a 9040 // (rare!) case where we've allowed the use of references in C, 9041 // e.g., as a parameter type in a built-in function. In this case, 9042 // just make sure that the type referenced is compatible with the 9043 // right-hand side type. The caller is responsible for adjusting 9044 // LHSType so that the resulting expression does not have reference 9045 // type. 9046 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9047 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9048 Kind = CK_LValueBitCast; 9049 return Compatible; 9050 } 9051 return Incompatible; 9052 } 9053 9054 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9055 // to the same ExtVector type. 9056 if (LHSType->isExtVectorType()) { 9057 if (RHSType->isExtVectorType()) 9058 return Incompatible; 9059 if (RHSType->isArithmeticType()) { 9060 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9061 if (ConvertRHS) 9062 RHS = prepareVectorSplat(LHSType, RHS.get()); 9063 Kind = CK_VectorSplat; 9064 return Compatible; 9065 } 9066 } 9067 9068 // Conversions to or from vector type. 9069 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9070 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9071 // Allow assignments of an AltiVec vector type to an equivalent GCC 9072 // vector type and vice versa 9073 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9074 Kind = CK_BitCast; 9075 return Compatible; 9076 } 9077 9078 // If we are allowing lax vector conversions, and LHS and RHS are both 9079 // vectors, the total size only needs to be the same. This is a bitcast; 9080 // no bits are changed but the result type is different. 9081 if (isLaxVectorConversion(RHSType, LHSType)) { 9082 Kind = CK_BitCast; 9083 return IncompatibleVectors; 9084 } 9085 } 9086 9087 // When the RHS comes from another lax conversion (e.g. binops between 9088 // scalars and vectors) the result is canonicalized as a vector. When the 9089 // LHS is also a vector, the lax is allowed by the condition above. Handle 9090 // the case where LHS is a scalar. 9091 if (LHSType->isScalarType()) { 9092 const VectorType *VecType = RHSType->getAs<VectorType>(); 9093 if (VecType && VecType->getNumElements() == 1 && 9094 isLaxVectorConversion(RHSType, LHSType)) { 9095 ExprResult *VecExpr = &RHS; 9096 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9097 Kind = CK_BitCast; 9098 return Compatible; 9099 } 9100 } 9101 9102 // Allow assignments between fixed-length and sizeless SVE vectors. 9103 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9104 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9105 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9106 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9107 Kind = CK_BitCast; 9108 return Compatible; 9109 } 9110 9111 return Incompatible; 9112 } 9113 9114 // Diagnose attempts to convert between __float128 and long double where 9115 // such conversions currently can't be handled. 9116 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9117 return Incompatible; 9118 9119 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9120 // discards the imaginary part. 9121 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9122 !LHSType->getAs<ComplexType>()) 9123 return Incompatible; 9124 9125 // Arithmetic conversions. 9126 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9127 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9128 if (ConvertRHS) 9129 Kind = PrepareScalarCast(RHS, LHSType); 9130 return Compatible; 9131 } 9132 9133 // Conversions to normal pointers. 9134 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9135 // U* -> T* 9136 if (isa<PointerType>(RHSType)) { 9137 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9138 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9139 if (AddrSpaceL != AddrSpaceR) 9140 Kind = CK_AddressSpaceConversion; 9141 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9142 Kind = CK_NoOp; 9143 else 9144 Kind = CK_BitCast; 9145 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9146 } 9147 9148 // int -> T* 9149 if (RHSType->isIntegerType()) { 9150 Kind = CK_IntegralToPointer; // FIXME: null? 9151 return IntToPointer; 9152 } 9153 9154 // C pointers are not compatible with ObjC object pointers, 9155 // with two exceptions: 9156 if (isa<ObjCObjectPointerType>(RHSType)) { 9157 // - conversions to void* 9158 if (LHSPointer->getPointeeType()->isVoidType()) { 9159 Kind = CK_BitCast; 9160 return Compatible; 9161 } 9162 9163 // - conversions from 'Class' to the redefinition type 9164 if (RHSType->isObjCClassType() && 9165 Context.hasSameType(LHSType, 9166 Context.getObjCClassRedefinitionType())) { 9167 Kind = CK_BitCast; 9168 return Compatible; 9169 } 9170 9171 Kind = CK_BitCast; 9172 return IncompatiblePointer; 9173 } 9174 9175 // U^ -> void* 9176 if (RHSType->getAs<BlockPointerType>()) { 9177 if (LHSPointer->getPointeeType()->isVoidType()) { 9178 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9179 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9180 ->getPointeeType() 9181 .getAddressSpace(); 9182 Kind = 9183 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9184 return Compatible; 9185 } 9186 } 9187 9188 return Incompatible; 9189 } 9190 9191 // Conversions to block pointers. 9192 if (isa<BlockPointerType>(LHSType)) { 9193 // U^ -> T^ 9194 if (RHSType->isBlockPointerType()) { 9195 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9196 ->getPointeeType() 9197 .getAddressSpace(); 9198 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9199 ->getPointeeType() 9200 .getAddressSpace(); 9201 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9202 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9203 } 9204 9205 // int or null -> T^ 9206 if (RHSType->isIntegerType()) { 9207 Kind = CK_IntegralToPointer; // FIXME: null 9208 return IntToBlockPointer; 9209 } 9210 9211 // id -> T^ 9212 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9213 Kind = CK_AnyPointerToBlockPointerCast; 9214 return Compatible; 9215 } 9216 9217 // void* -> T^ 9218 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9219 if (RHSPT->getPointeeType()->isVoidType()) { 9220 Kind = CK_AnyPointerToBlockPointerCast; 9221 return Compatible; 9222 } 9223 9224 return Incompatible; 9225 } 9226 9227 // Conversions to Objective-C pointers. 9228 if (isa<ObjCObjectPointerType>(LHSType)) { 9229 // A* -> B* 9230 if (RHSType->isObjCObjectPointerType()) { 9231 Kind = CK_BitCast; 9232 Sema::AssignConvertType result = 9233 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9234 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9235 result == Compatible && 9236 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9237 result = IncompatibleObjCWeakRef; 9238 return result; 9239 } 9240 9241 // int or null -> A* 9242 if (RHSType->isIntegerType()) { 9243 Kind = CK_IntegralToPointer; // FIXME: null 9244 return IntToPointer; 9245 } 9246 9247 // In general, C pointers are not compatible with ObjC object pointers, 9248 // with two exceptions: 9249 if (isa<PointerType>(RHSType)) { 9250 Kind = CK_CPointerToObjCPointerCast; 9251 9252 // - conversions from 'void*' 9253 if (RHSType->isVoidPointerType()) { 9254 return Compatible; 9255 } 9256 9257 // - conversions to 'Class' from its redefinition type 9258 if (LHSType->isObjCClassType() && 9259 Context.hasSameType(RHSType, 9260 Context.getObjCClassRedefinitionType())) { 9261 return Compatible; 9262 } 9263 9264 return IncompatiblePointer; 9265 } 9266 9267 // Only under strict condition T^ is compatible with an Objective-C pointer. 9268 if (RHSType->isBlockPointerType() && 9269 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9270 if (ConvertRHS) 9271 maybeExtendBlockObject(RHS); 9272 Kind = CK_BlockPointerToObjCPointerCast; 9273 return Compatible; 9274 } 9275 9276 return Incompatible; 9277 } 9278 9279 // Conversions from pointers that are not covered by the above. 9280 if (isa<PointerType>(RHSType)) { 9281 // T* -> _Bool 9282 if (LHSType == Context.BoolTy) { 9283 Kind = CK_PointerToBoolean; 9284 return Compatible; 9285 } 9286 9287 // T* -> int 9288 if (LHSType->isIntegerType()) { 9289 Kind = CK_PointerToIntegral; 9290 return PointerToInt; 9291 } 9292 9293 return Incompatible; 9294 } 9295 9296 // Conversions from Objective-C pointers that are not covered by the above. 9297 if (isa<ObjCObjectPointerType>(RHSType)) { 9298 // T* -> _Bool 9299 if (LHSType == Context.BoolTy) { 9300 Kind = CK_PointerToBoolean; 9301 return Compatible; 9302 } 9303 9304 // T* -> int 9305 if (LHSType->isIntegerType()) { 9306 Kind = CK_PointerToIntegral; 9307 return PointerToInt; 9308 } 9309 9310 return Incompatible; 9311 } 9312 9313 // struct A -> struct B 9314 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9315 if (Context.typesAreCompatible(LHSType, RHSType)) { 9316 Kind = CK_NoOp; 9317 return Compatible; 9318 } 9319 } 9320 9321 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9322 Kind = CK_IntToOCLSampler; 9323 return Compatible; 9324 } 9325 9326 return Incompatible; 9327 } 9328 9329 /// Constructs a transparent union from an expression that is 9330 /// used to initialize the transparent union. 9331 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9332 ExprResult &EResult, QualType UnionType, 9333 FieldDecl *Field) { 9334 // Build an initializer list that designates the appropriate member 9335 // of the transparent union. 9336 Expr *E = EResult.get(); 9337 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9338 E, SourceLocation()); 9339 Initializer->setType(UnionType); 9340 Initializer->setInitializedFieldInUnion(Field); 9341 9342 // Build a compound literal constructing a value of the transparent 9343 // union type from this initializer list. 9344 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9345 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9346 VK_RValue, Initializer, false); 9347 } 9348 9349 Sema::AssignConvertType 9350 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9351 ExprResult &RHS) { 9352 QualType RHSType = RHS.get()->getType(); 9353 9354 // If the ArgType is a Union type, we want to handle a potential 9355 // transparent_union GCC extension. 9356 const RecordType *UT = ArgType->getAsUnionType(); 9357 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9358 return Incompatible; 9359 9360 // The field to initialize within the transparent union. 9361 RecordDecl *UD = UT->getDecl(); 9362 FieldDecl *InitField = nullptr; 9363 // It's compatible if the expression matches any of the fields. 9364 for (auto *it : UD->fields()) { 9365 if (it->getType()->isPointerType()) { 9366 // If the transparent union contains a pointer type, we allow: 9367 // 1) void pointer 9368 // 2) null pointer constant 9369 if (RHSType->isPointerType()) 9370 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9371 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9372 InitField = it; 9373 break; 9374 } 9375 9376 if (RHS.get()->isNullPointerConstant(Context, 9377 Expr::NPC_ValueDependentIsNull)) { 9378 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9379 CK_NullToPointer); 9380 InitField = it; 9381 break; 9382 } 9383 } 9384 9385 CastKind Kind; 9386 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9387 == Compatible) { 9388 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9389 InitField = it; 9390 break; 9391 } 9392 } 9393 9394 if (!InitField) 9395 return Incompatible; 9396 9397 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9398 return Compatible; 9399 } 9400 9401 Sema::AssignConvertType 9402 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9403 bool Diagnose, 9404 bool DiagnoseCFAudited, 9405 bool ConvertRHS) { 9406 // We need to be able to tell the caller whether we diagnosed a problem, if 9407 // they ask us to issue diagnostics. 9408 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9409 9410 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9411 // we can't avoid *all* modifications at the moment, so we need some somewhere 9412 // to put the updated value. 9413 ExprResult LocalRHS = CallerRHS; 9414 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9415 9416 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9417 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9418 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9419 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9420 Diag(RHS.get()->getExprLoc(), 9421 diag::warn_noderef_to_dereferenceable_pointer) 9422 << RHS.get()->getSourceRange(); 9423 } 9424 } 9425 } 9426 9427 if (getLangOpts().CPlusPlus) { 9428 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9429 // C++ 5.17p3: If the left operand is not of class type, the 9430 // expression is implicitly converted (C++ 4) to the 9431 // cv-unqualified type of the left operand. 9432 QualType RHSType = RHS.get()->getType(); 9433 if (Diagnose) { 9434 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9435 AA_Assigning); 9436 } else { 9437 ImplicitConversionSequence ICS = 9438 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9439 /*SuppressUserConversions=*/false, 9440 AllowedExplicit::None, 9441 /*InOverloadResolution=*/false, 9442 /*CStyle=*/false, 9443 /*AllowObjCWritebackConversion=*/false); 9444 if (ICS.isFailure()) 9445 return Incompatible; 9446 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9447 ICS, AA_Assigning); 9448 } 9449 if (RHS.isInvalid()) 9450 return Incompatible; 9451 Sema::AssignConvertType result = Compatible; 9452 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9453 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9454 result = IncompatibleObjCWeakRef; 9455 return result; 9456 } 9457 9458 // FIXME: Currently, we fall through and treat C++ classes like C 9459 // structures. 9460 // FIXME: We also fall through for atomics; not sure what should 9461 // happen there, though. 9462 } else if (RHS.get()->getType() == Context.OverloadTy) { 9463 // As a set of extensions to C, we support overloading on functions. These 9464 // functions need to be resolved here. 9465 DeclAccessPair DAP; 9466 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9467 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9468 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9469 else 9470 return Incompatible; 9471 } 9472 9473 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9474 // a null pointer constant. 9475 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9476 LHSType->isBlockPointerType()) && 9477 RHS.get()->isNullPointerConstant(Context, 9478 Expr::NPC_ValueDependentIsNull)) { 9479 if (Diagnose || ConvertRHS) { 9480 CastKind Kind; 9481 CXXCastPath Path; 9482 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9483 /*IgnoreBaseAccess=*/false, Diagnose); 9484 if (ConvertRHS) 9485 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9486 } 9487 return Compatible; 9488 } 9489 9490 // OpenCL queue_t type assignment. 9491 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9492 Context, Expr::NPC_ValueDependentIsNull)) { 9493 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9494 return Compatible; 9495 } 9496 9497 // This check seems unnatural, however it is necessary to ensure the proper 9498 // conversion of functions/arrays. If the conversion were done for all 9499 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9500 // expressions that suppress this implicit conversion (&, sizeof). 9501 // 9502 // Suppress this for references: C++ 8.5.3p5. 9503 if (!LHSType->isReferenceType()) { 9504 // FIXME: We potentially allocate here even if ConvertRHS is false. 9505 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9506 if (RHS.isInvalid()) 9507 return Incompatible; 9508 } 9509 CastKind Kind; 9510 Sema::AssignConvertType result = 9511 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9512 9513 // C99 6.5.16.1p2: The value of the right operand is converted to the 9514 // type of the assignment expression. 9515 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9516 // so that we can use references in built-in functions even in C. 9517 // The getNonReferenceType() call makes sure that the resulting expression 9518 // does not have reference type. 9519 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9520 QualType Ty = LHSType.getNonLValueExprType(Context); 9521 Expr *E = RHS.get(); 9522 9523 // Check for various Objective-C errors. If we are not reporting 9524 // diagnostics and just checking for errors, e.g., during overload 9525 // resolution, return Incompatible to indicate the failure. 9526 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9527 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9528 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9529 if (!Diagnose) 9530 return Incompatible; 9531 } 9532 if (getLangOpts().ObjC && 9533 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9534 E->getType(), E, Diagnose) || 9535 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9536 if (!Diagnose) 9537 return Incompatible; 9538 // Replace the expression with a corrected version and continue so we 9539 // can find further errors. 9540 RHS = E; 9541 return Compatible; 9542 } 9543 9544 if (ConvertRHS) 9545 RHS = ImpCastExprToType(E, Ty, Kind); 9546 } 9547 9548 return result; 9549 } 9550 9551 namespace { 9552 /// The original operand to an operator, prior to the application of the usual 9553 /// arithmetic conversions and converting the arguments of a builtin operator 9554 /// candidate. 9555 struct OriginalOperand { 9556 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9557 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9558 Op = MTE->getSubExpr(); 9559 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9560 Op = BTE->getSubExpr(); 9561 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9562 Orig = ICE->getSubExprAsWritten(); 9563 Conversion = ICE->getConversionFunction(); 9564 } 9565 } 9566 9567 QualType getType() const { return Orig->getType(); } 9568 9569 Expr *Orig; 9570 NamedDecl *Conversion; 9571 }; 9572 } 9573 9574 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9575 ExprResult &RHS) { 9576 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9577 9578 Diag(Loc, diag::err_typecheck_invalid_operands) 9579 << OrigLHS.getType() << OrigRHS.getType() 9580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9581 9582 // If a user-defined conversion was applied to either of the operands prior 9583 // to applying the built-in operator rules, tell the user about it. 9584 if (OrigLHS.Conversion) { 9585 Diag(OrigLHS.Conversion->getLocation(), 9586 diag::note_typecheck_invalid_operands_converted) 9587 << 0 << LHS.get()->getType(); 9588 } 9589 if (OrigRHS.Conversion) { 9590 Diag(OrigRHS.Conversion->getLocation(), 9591 diag::note_typecheck_invalid_operands_converted) 9592 << 1 << RHS.get()->getType(); 9593 } 9594 9595 return QualType(); 9596 } 9597 9598 // Diagnose cases where a scalar was implicitly converted to a vector and 9599 // diagnose the underlying types. Otherwise, diagnose the error 9600 // as invalid vector logical operands for non-C++ cases. 9601 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9602 ExprResult &RHS) { 9603 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9604 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9605 9606 bool LHSNatVec = LHSType->isVectorType(); 9607 bool RHSNatVec = RHSType->isVectorType(); 9608 9609 if (!(LHSNatVec && RHSNatVec)) { 9610 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9611 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9612 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9613 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9614 << Vector->getSourceRange(); 9615 return QualType(); 9616 } 9617 9618 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9619 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9620 << RHS.get()->getSourceRange(); 9621 9622 return QualType(); 9623 } 9624 9625 /// Try to convert a value of non-vector type to a vector type by converting 9626 /// the type to the element type of the vector and then performing a splat. 9627 /// If the language is OpenCL, we only use conversions that promote scalar 9628 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9629 /// for float->int. 9630 /// 9631 /// OpenCL V2.0 6.2.6.p2: 9632 /// An error shall occur if any scalar operand type has greater rank 9633 /// than the type of the vector element. 9634 /// 9635 /// \param scalar - if non-null, actually perform the conversions 9636 /// \return true if the operation fails (but without diagnosing the failure) 9637 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9638 QualType scalarTy, 9639 QualType vectorEltTy, 9640 QualType vectorTy, 9641 unsigned &DiagID) { 9642 // The conversion to apply to the scalar before splatting it, 9643 // if necessary. 9644 CastKind scalarCast = CK_NoOp; 9645 9646 if (vectorEltTy->isIntegralType(S.Context)) { 9647 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9648 (scalarTy->isIntegerType() && 9649 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9650 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9651 return true; 9652 } 9653 if (!scalarTy->isIntegralType(S.Context)) 9654 return true; 9655 scalarCast = CK_IntegralCast; 9656 } else if (vectorEltTy->isRealFloatingType()) { 9657 if (scalarTy->isRealFloatingType()) { 9658 if (S.getLangOpts().OpenCL && 9659 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9660 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9661 return true; 9662 } 9663 scalarCast = CK_FloatingCast; 9664 } 9665 else if (scalarTy->isIntegralType(S.Context)) 9666 scalarCast = CK_IntegralToFloating; 9667 else 9668 return true; 9669 } else { 9670 return true; 9671 } 9672 9673 // Adjust scalar if desired. 9674 if (scalar) { 9675 if (scalarCast != CK_NoOp) 9676 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9677 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9678 } 9679 return false; 9680 } 9681 9682 /// Convert vector E to a vector with the same number of elements but different 9683 /// element type. 9684 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9685 const auto *VecTy = E->getType()->getAs<VectorType>(); 9686 assert(VecTy && "Expression E must be a vector"); 9687 QualType NewVecTy = S.Context.getVectorType(ElementType, 9688 VecTy->getNumElements(), 9689 VecTy->getVectorKind()); 9690 9691 // Look through the implicit cast. Return the subexpression if its type is 9692 // NewVecTy. 9693 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9694 if (ICE->getSubExpr()->getType() == NewVecTy) 9695 return ICE->getSubExpr(); 9696 9697 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9698 return S.ImpCastExprToType(E, NewVecTy, Cast); 9699 } 9700 9701 /// Test if a (constant) integer Int can be casted to another integer type 9702 /// IntTy without losing precision. 9703 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9704 QualType OtherIntTy) { 9705 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9706 9707 // Reject cases where the value of the Int is unknown as that would 9708 // possibly cause truncation, but accept cases where the scalar can be 9709 // demoted without loss of precision. 9710 Expr::EvalResult EVResult; 9711 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9712 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9713 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9714 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9715 9716 if (CstInt) { 9717 // If the scalar is constant and is of a higher order and has more active 9718 // bits that the vector element type, reject it. 9719 llvm::APSInt Result = EVResult.Val.getInt(); 9720 unsigned NumBits = IntSigned 9721 ? (Result.isNegative() ? Result.getMinSignedBits() 9722 : Result.getActiveBits()) 9723 : Result.getActiveBits(); 9724 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9725 return true; 9726 9727 // If the signedness of the scalar type and the vector element type 9728 // differs and the number of bits is greater than that of the vector 9729 // element reject it. 9730 return (IntSigned != OtherIntSigned && 9731 NumBits > S.Context.getIntWidth(OtherIntTy)); 9732 } 9733 9734 // Reject cases where the value of the scalar is not constant and it's 9735 // order is greater than that of the vector element type. 9736 return (Order < 0); 9737 } 9738 9739 /// Test if a (constant) integer Int can be casted to floating point type 9740 /// FloatTy without losing precision. 9741 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9742 QualType FloatTy) { 9743 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9744 9745 // Determine if the integer constant can be expressed as a floating point 9746 // number of the appropriate type. 9747 Expr::EvalResult EVResult; 9748 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9749 9750 uint64_t Bits = 0; 9751 if (CstInt) { 9752 // Reject constants that would be truncated if they were converted to 9753 // the floating point type. Test by simple to/from conversion. 9754 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9755 // could be avoided if there was a convertFromAPInt method 9756 // which could signal back if implicit truncation occurred. 9757 llvm::APSInt Result = EVResult.Val.getInt(); 9758 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9759 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9760 llvm::APFloat::rmTowardZero); 9761 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9762 !IntTy->hasSignedIntegerRepresentation()); 9763 bool Ignored = false; 9764 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9765 &Ignored); 9766 if (Result != ConvertBack) 9767 return true; 9768 } else { 9769 // Reject types that cannot be fully encoded into the mantissa of 9770 // the float. 9771 Bits = S.Context.getTypeSize(IntTy); 9772 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9773 S.Context.getFloatTypeSemantics(FloatTy)); 9774 if (Bits > FloatPrec) 9775 return true; 9776 } 9777 9778 return false; 9779 } 9780 9781 /// Attempt to convert and splat Scalar into a vector whose types matches 9782 /// Vector following GCC conversion rules. The rule is that implicit 9783 /// conversion can occur when Scalar can be casted to match Vector's element 9784 /// type without causing truncation of Scalar. 9785 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9786 ExprResult *Vector) { 9787 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9788 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9789 const VectorType *VT = VectorTy->getAs<VectorType>(); 9790 9791 assert(!isa<ExtVectorType>(VT) && 9792 "ExtVectorTypes should not be handled here!"); 9793 9794 QualType VectorEltTy = VT->getElementType(); 9795 9796 // Reject cases where the vector element type or the scalar element type are 9797 // not integral or floating point types. 9798 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9799 return true; 9800 9801 // The conversion to apply to the scalar before splatting it, 9802 // if necessary. 9803 CastKind ScalarCast = CK_NoOp; 9804 9805 // Accept cases where the vector elements are integers and the scalar is 9806 // an integer. 9807 // FIXME: Notionally if the scalar was a floating point value with a precise 9808 // integral representation, we could cast it to an appropriate integer 9809 // type and then perform the rest of the checks here. GCC will perform 9810 // this conversion in some cases as determined by the input language. 9811 // We should accept it on a language independent basis. 9812 if (VectorEltTy->isIntegralType(S.Context) && 9813 ScalarTy->isIntegralType(S.Context) && 9814 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9815 9816 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9817 return true; 9818 9819 ScalarCast = CK_IntegralCast; 9820 } else if (VectorEltTy->isIntegralType(S.Context) && 9821 ScalarTy->isRealFloatingType()) { 9822 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9823 ScalarCast = CK_FloatingToIntegral; 9824 else 9825 return true; 9826 } else if (VectorEltTy->isRealFloatingType()) { 9827 if (ScalarTy->isRealFloatingType()) { 9828 9829 // Reject cases where the scalar type is not a constant and has a higher 9830 // Order than the vector element type. 9831 llvm::APFloat Result(0.0); 9832 9833 // Determine whether this is a constant scalar. In the event that the 9834 // value is dependent (and thus cannot be evaluated by the constant 9835 // evaluator), skip the evaluation. This will then diagnose once the 9836 // expression is instantiated. 9837 bool CstScalar = Scalar->get()->isValueDependent() || 9838 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9839 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9840 if (!CstScalar && Order < 0) 9841 return true; 9842 9843 // If the scalar cannot be safely casted to the vector element type, 9844 // reject it. 9845 if (CstScalar) { 9846 bool Truncated = false; 9847 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9848 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9849 if (Truncated) 9850 return true; 9851 } 9852 9853 ScalarCast = CK_FloatingCast; 9854 } else if (ScalarTy->isIntegralType(S.Context)) { 9855 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9856 return true; 9857 9858 ScalarCast = CK_IntegralToFloating; 9859 } else 9860 return true; 9861 } else if (ScalarTy->isEnumeralType()) 9862 return true; 9863 9864 // Adjust scalar if desired. 9865 if (Scalar) { 9866 if (ScalarCast != CK_NoOp) 9867 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9868 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9869 } 9870 return false; 9871 } 9872 9873 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9874 SourceLocation Loc, bool IsCompAssign, 9875 bool AllowBothBool, 9876 bool AllowBoolConversions) { 9877 if (!IsCompAssign) { 9878 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9879 if (LHS.isInvalid()) 9880 return QualType(); 9881 } 9882 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9883 if (RHS.isInvalid()) 9884 return QualType(); 9885 9886 // For conversion purposes, we ignore any qualifiers. 9887 // For example, "const float" and "float" are equivalent. 9888 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9889 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9890 9891 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9892 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9893 assert(LHSVecType || RHSVecType); 9894 9895 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9896 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9897 return InvalidOperands(Loc, LHS, RHS); 9898 9899 // AltiVec-style "vector bool op vector bool" combinations are allowed 9900 // for some operators but not others. 9901 if (!AllowBothBool && 9902 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9903 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9904 return InvalidOperands(Loc, LHS, RHS); 9905 9906 // If the vector types are identical, return. 9907 if (Context.hasSameType(LHSType, RHSType)) 9908 return LHSType; 9909 9910 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9911 if (LHSVecType && RHSVecType && 9912 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9913 if (isa<ExtVectorType>(LHSVecType)) { 9914 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9915 return LHSType; 9916 } 9917 9918 if (!IsCompAssign) 9919 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9920 return RHSType; 9921 } 9922 9923 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9924 // can be mixed, with the result being the non-bool type. The non-bool 9925 // operand must have integer element type. 9926 if (AllowBoolConversions && LHSVecType && RHSVecType && 9927 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9928 (Context.getTypeSize(LHSVecType->getElementType()) == 9929 Context.getTypeSize(RHSVecType->getElementType()))) { 9930 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9931 LHSVecType->getElementType()->isIntegerType() && 9932 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9933 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9934 return LHSType; 9935 } 9936 if (!IsCompAssign && 9937 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9938 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9939 RHSVecType->getElementType()->isIntegerType()) { 9940 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9941 return RHSType; 9942 } 9943 } 9944 9945 // Expressions containing fixed-length and sizeless SVE vectors are invalid 9946 // since the ambiguity can affect the ABI. 9947 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9948 const VectorType *VecType = SecondType->getAs<VectorType>(); 9949 return FirstType->isSizelessBuiltinType() && VecType && 9950 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9951 VecType->getVectorKind() == 9952 VectorType::SveFixedLengthPredicateVector); 9953 }; 9954 9955 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9956 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 9957 return QualType(); 9958 } 9959 9960 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 9961 // since the ambiguity can affect the ABI. 9962 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 9963 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 9964 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 9965 9966 if (FirstVecType && SecondVecType) 9967 return FirstVecType->getVectorKind() == VectorType::GenericVector && 9968 (SecondVecType->getVectorKind() == 9969 VectorType::SveFixedLengthDataVector || 9970 SecondVecType->getVectorKind() == 9971 VectorType::SveFixedLengthPredicateVector); 9972 9973 return FirstType->isSizelessBuiltinType() && SecondVecType && 9974 SecondVecType->getVectorKind() == VectorType::GenericVector; 9975 }; 9976 9977 if (IsSveGnuConversion(LHSType, RHSType) || 9978 IsSveGnuConversion(RHSType, LHSType)) { 9979 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 9980 return QualType(); 9981 } 9982 9983 // If there's a vector type and a scalar, try to convert the scalar to 9984 // the vector element type and splat. 9985 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9986 if (!RHSVecType) { 9987 if (isa<ExtVectorType>(LHSVecType)) { 9988 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9989 LHSVecType->getElementType(), LHSType, 9990 DiagID)) 9991 return LHSType; 9992 } else { 9993 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9994 return LHSType; 9995 } 9996 } 9997 if (!LHSVecType) { 9998 if (isa<ExtVectorType>(RHSVecType)) { 9999 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10000 LHSType, RHSVecType->getElementType(), 10001 RHSType, DiagID)) 10002 return RHSType; 10003 } else { 10004 if (LHS.get()->getValueKind() == VK_LValue || 10005 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10006 return RHSType; 10007 } 10008 } 10009 10010 // FIXME: The code below also handles conversion between vectors and 10011 // non-scalars, we should break this down into fine grained specific checks 10012 // and emit proper diagnostics. 10013 QualType VecType = LHSVecType ? LHSType : RHSType; 10014 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10015 QualType OtherType = LHSVecType ? RHSType : LHSType; 10016 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10017 if (isLaxVectorConversion(OtherType, VecType)) { 10018 // If we're allowing lax vector conversions, only the total (data) size 10019 // needs to be the same. For non compound assignment, if one of the types is 10020 // scalar, the result is always the vector type. 10021 if (!IsCompAssign) { 10022 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10023 return VecType; 10024 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10025 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10026 // type. Note that this is already done by non-compound assignments in 10027 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10028 // <1 x T> -> T. The result is also a vector type. 10029 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10030 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10031 ExprResult *RHSExpr = &RHS; 10032 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10033 return VecType; 10034 } 10035 } 10036 10037 // Okay, the expression is invalid. 10038 10039 // If there's a non-vector, non-real operand, diagnose that. 10040 if ((!RHSVecType && !RHSType->isRealType()) || 10041 (!LHSVecType && !LHSType->isRealType())) { 10042 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10043 << LHSType << RHSType 10044 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10045 return QualType(); 10046 } 10047 10048 // OpenCL V1.1 6.2.6.p1: 10049 // If the operands are of more than one vector type, then an error shall 10050 // occur. Implicit conversions between vector types are not permitted, per 10051 // section 6.2.1. 10052 if (getLangOpts().OpenCL && 10053 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10054 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10055 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10056 << RHSType; 10057 return QualType(); 10058 } 10059 10060 10061 // If there is a vector type that is not a ExtVector and a scalar, we reach 10062 // this point if scalar could not be converted to the vector's element type 10063 // without truncation. 10064 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10065 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10066 QualType Scalar = LHSVecType ? RHSType : LHSType; 10067 QualType Vector = LHSVecType ? LHSType : RHSType; 10068 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10069 Diag(Loc, 10070 diag::err_typecheck_vector_not_convertable_implict_truncation) 10071 << ScalarOrVector << Scalar << Vector; 10072 10073 return QualType(); 10074 } 10075 10076 // Otherwise, use the generic diagnostic. 10077 Diag(Loc, DiagID) 10078 << LHSType << RHSType 10079 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10080 return QualType(); 10081 } 10082 10083 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10084 // expression. These are mainly cases where the null pointer is used as an 10085 // integer instead of a pointer. 10086 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10087 SourceLocation Loc, bool IsCompare) { 10088 // The canonical way to check for a GNU null is with isNullPointerConstant, 10089 // but we use a bit of a hack here for speed; this is a relatively 10090 // hot path, and isNullPointerConstant is slow. 10091 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10092 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10093 10094 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10095 10096 // Avoid analyzing cases where the result will either be invalid (and 10097 // diagnosed as such) or entirely valid and not something to warn about. 10098 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10099 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10100 return; 10101 10102 // Comparison operations would not make sense with a null pointer no matter 10103 // what the other expression is. 10104 if (!IsCompare) { 10105 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10106 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10107 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10108 return; 10109 } 10110 10111 // The rest of the operations only make sense with a null pointer 10112 // if the other expression is a pointer. 10113 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10114 NonNullType->canDecayToPointerType()) 10115 return; 10116 10117 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10118 << LHSNull /* LHS is NULL */ << NonNullType 10119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10120 } 10121 10122 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10123 SourceLocation Loc) { 10124 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10125 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10126 if (!LUE || !RUE) 10127 return; 10128 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10129 RUE->getKind() != UETT_SizeOf) 10130 return; 10131 10132 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10133 QualType LHSTy = LHSArg->getType(); 10134 QualType RHSTy; 10135 10136 if (RUE->isArgumentType()) 10137 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10138 else 10139 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10140 10141 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10142 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10143 return; 10144 10145 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10146 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10147 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10148 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10149 << LHSArgDecl; 10150 } 10151 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10152 QualType ArrayElemTy = ArrayTy->getElementType(); 10153 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10154 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10155 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10156 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10157 return; 10158 S.Diag(Loc, diag::warn_division_sizeof_array) 10159 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10160 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10161 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10162 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10163 << LHSArgDecl; 10164 } 10165 10166 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10167 } 10168 } 10169 10170 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10171 ExprResult &RHS, 10172 SourceLocation Loc, bool IsDiv) { 10173 // Check for division/remainder by zero. 10174 Expr::EvalResult RHSValue; 10175 if (!RHS.get()->isValueDependent() && 10176 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10177 RHSValue.Val.getInt() == 0) 10178 S.DiagRuntimeBehavior(Loc, RHS.get(), 10179 S.PDiag(diag::warn_remainder_division_by_zero) 10180 << IsDiv << RHS.get()->getSourceRange()); 10181 } 10182 10183 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10184 SourceLocation Loc, 10185 bool IsCompAssign, bool IsDiv) { 10186 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10187 10188 if (LHS.get()->getType()->isVectorType() || 10189 RHS.get()->getType()->isVectorType()) 10190 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10191 /*AllowBothBool*/getLangOpts().AltiVec, 10192 /*AllowBoolConversions*/false); 10193 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10194 RHS.get()->getType()->isConstantMatrixType())) 10195 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10196 10197 QualType compType = UsualArithmeticConversions( 10198 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10199 if (LHS.isInvalid() || RHS.isInvalid()) 10200 return QualType(); 10201 10202 10203 if (compType.isNull() || !compType->isArithmeticType()) 10204 return InvalidOperands(Loc, LHS, RHS); 10205 if (IsDiv) { 10206 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10207 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10208 } 10209 return compType; 10210 } 10211 10212 QualType Sema::CheckRemainderOperands( 10213 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10214 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10215 10216 if (LHS.get()->getType()->isVectorType() || 10217 RHS.get()->getType()->isVectorType()) { 10218 if (LHS.get()->getType()->hasIntegerRepresentation() && 10219 RHS.get()->getType()->hasIntegerRepresentation()) 10220 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10221 /*AllowBothBool*/getLangOpts().AltiVec, 10222 /*AllowBoolConversions*/false); 10223 return InvalidOperands(Loc, LHS, RHS); 10224 } 10225 10226 QualType compType = UsualArithmeticConversions( 10227 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10228 if (LHS.isInvalid() || RHS.isInvalid()) 10229 return QualType(); 10230 10231 if (compType.isNull() || !compType->isIntegerType()) 10232 return InvalidOperands(Loc, LHS, RHS); 10233 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10234 return compType; 10235 } 10236 10237 /// Diagnose invalid arithmetic on two void pointers. 10238 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10239 Expr *LHSExpr, Expr *RHSExpr) { 10240 S.Diag(Loc, S.getLangOpts().CPlusPlus 10241 ? diag::err_typecheck_pointer_arith_void_type 10242 : diag::ext_gnu_void_ptr) 10243 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10244 << RHSExpr->getSourceRange(); 10245 } 10246 10247 /// Diagnose invalid arithmetic on a void pointer. 10248 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10249 Expr *Pointer) { 10250 S.Diag(Loc, S.getLangOpts().CPlusPlus 10251 ? diag::err_typecheck_pointer_arith_void_type 10252 : diag::ext_gnu_void_ptr) 10253 << 0 /* one pointer */ << Pointer->getSourceRange(); 10254 } 10255 10256 /// Diagnose invalid arithmetic on a null pointer. 10257 /// 10258 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10259 /// idiom, which we recognize as a GNU extension. 10260 /// 10261 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10262 Expr *Pointer, bool IsGNUIdiom) { 10263 if (IsGNUIdiom) 10264 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10265 << Pointer->getSourceRange(); 10266 else 10267 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10268 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10269 } 10270 10271 /// Diagnose invalid arithmetic on two function pointers. 10272 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10273 Expr *LHS, Expr *RHS) { 10274 assert(LHS->getType()->isAnyPointerType()); 10275 assert(RHS->getType()->isAnyPointerType()); 10276 S.Diag(Loc, S.getLangOpts().CPlusPlus 10277 ? diag::err_typecheck_pointer_arith_function_type 10278 : diag::ext_gnu_ptr_func_arith) 10279 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10280 // We only show the second type if it differs from the first. 10281 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10282 RHS->getType()) 10283 << RHS->getType()->getPointeeType() 10284 << LHS->getSourceRange() << RHS->getSourceRange(); 10285 } 10286 10287 /// Diagnose invalid arithmetic on a function pointer. 10288 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10289 Expr *Pointer) { 10290 assert(Pointer->getType()->isAnyPointerType()); 10291 S.Diag(Loc, S.getLangOpts().CPlusPlus 10292 ? diag::err_typecheck_pointer_arith_function_type 10293 : diag::ext_gnu_ptr_func_arith) 10294 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10295 << 0 /* one pointer, so only one type */ 10296 << Pointer->getSourceRange(); 10297 } 10298 10299 /// Emit error if Operand is incomplete pointer type 10300 /// 10301 /// \returns True if pointer has incomplete type 10302 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10303 Expr *Operand) { 10304 QualType ResType = Operand->getType(); 10305 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10306 ResType = ResAtomicType->getValueType(); 10307 10308 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10309 QualType PointeeTy = ResType->getPointeeType(); 10310 return S.RequireCompleteSizedType( 10311 Loc, PointeeTy, 10312 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10313 Operand->getSourceRange()); 10314 } 10315 10316 /// Check the validity of an arithmetic pointer operand. 10317 /// 10318 /// If the operand has pointer type, this code will check for pointer types 10319 /// which are invalid in arithmetic operations. These will be diagnosed 10320 /// appropriately, including whether or not the use is supported as an 10321 /// extension. 10322 /// 10323 /// \returns True when the operand is valid to use (even if as an extension). 10324 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10325 Expr *Operand) { 10326 QualType ResType = Operand->getType(); 10327 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10328 ResType = ResAtomicType->getValueType(); 10329 10330 if (!ResType->isAnyPointerType()) return true; 10331 10332 QualType PointeeTy = ResType->getPointeeType(); 10333 if (PointeeTy->isVoidType()) { 10334 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10335 return !S.getLangOpts().CPlusPlus; 10336 } 10337 if (PointeeTy->isFunctionType()) { 10338 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10339 return !S.getLangOpts().CPlusPlus; 10340 } 10341 10342 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10343 10344 return true; 10345 } 10346 10347 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10348 /// operands. 10349 /// 10350 /// This routine will diagnose any invalid arithmetic on pointer operands much 10351 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10352 /// for emitting a single diagnostic even for operations where both LHS and RHS 10353 /// are (potentially problematic) pointers. 10354 /// 10355 /// \returns True when the operand is valid to use (even if as an extension). 10356 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10357 Expr *LHSExpr, Expr *RHSExpr) { 10358 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10359 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10360 if (!isLHSPointer && !isRHSPointer) return true; 10361 10362 QualType LHSPointeeTy, RHSPointeeTy; 10363 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10364 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10365 10366 // if both are pointers check if operation is valid wrt address spaces 10367 if (isLHSPointer && isRHSPointer) { 10368 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10369 S.Diag(Loc, 10370 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10371 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10372 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10373 return false; 10374 } 10375 } 10376 10377 // Check for arithmetic on pointers to incomplete types. 10378 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10379 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10380 if (isLHSVoidPtr || isRHSVoidPtr) { 10381 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10382 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10383 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10384 10385 return !S.getLangOpts().CPlusPlus; 10386 } 10387 10388 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10389 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10390 if (isLHSFuncPtr || isRHSFuncPtr) { 10391 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10392 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10393 RHSExpr); 10394 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10395 10396 return !S.getLangOpts().CPlusPlus; 10397 } 10398 10399 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10400 return false; 10401 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10402 return false; 10403 10404 return true; 10405 } 10406 10407 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10408 /// literal. 10409 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10410 Expr *LHSExpr, Expr *RHSExpr) { 10411 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10412 Expr* IndexExpr = RHSExpr; 10413 if (!StrExpr) { 10414 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10415 IndexExpr = LHSExpr; 10416 } 10417 10418 bool IsStringPlusInt = StrExpr && 10419 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10420 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10421 return; 10422 10423 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10424 Self.Diag(OpLoc, diag::warn_string_plus_int) 10425 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10426 10427 // Only print a fixit for "str" + int, not for int + "str". 10428 if (IndexExpr == RHSExpr) { 10429 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10430 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10431 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10432 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10433 << FixItHint::CreateInsertion(EndLoc, "]"); 10434 } else 10435 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10436 } 10437 10438 /// Emit a warning when adding a char literal to a string. 10439 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10440 Expr *LHSExpr, Expr *RHSExpr) { 10441 const Expr *StringRefExpr = LHSExpr; 10442 const CharacterLiteral *CharExpr = 10443 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10444 10445 if (!CharExpr) { 10446 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10447 StringRefExpr = RHSExpr; 10448 } 10449 10450 if (!CharExpr || !StringRefExpr) 10451 return; 10452 10453 const QualType StringType = StringRefExpr->getType(); 10454 10455 // Return if not a PointerType. 10456 if (!StringType->isAnyPointerType()) 10457 return; 10458 10459 // Return if not a CharacterType. 10460 if (!StringType->getPointeeType()->isAnyCharacterType()) 10461 return; 10462 10463 ASTContext &Ctx = Self.getASTContext(); 10464 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10465 10466 const QualType CharType = CharExpr->getType(); 10467 if (!CharType->isAnyCharacterType() && 10468 CharType->isIntegerType() && 10469 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10470 Self.Diag(OpLoc, diag::warn_string_plus_char) 10471 << DiagRange << Ctx.CharTy; 10472 } else { 10473 Self.Diag(OpLoc, diag::warn_string_plus_char) 10474 << DiagRange << CharExpr->getType(); 10475 } 10476 10477 // Only print a fixit for str + char, not for char + str. 10478 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10479 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10480 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10481 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10482 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10483 << FixItHint::CreateInsertion(EndLoc, "]"); 10484 } else { 10485 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10486 } 10487 } 10488 10489 /// Emit error when two pointers are incompatible. 10490 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10491 Expr *LHSExpr, Expr *RHSExpr) { 10492 assert(LHSExpr->getType()->isAnyPointerType()); 10493 assert(RHSExpr->getType()->isAnyPointerType()); 10494 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10495 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10496 << RHSExpr->getSourceRange(); 10497 } 10498 10499 // C99 6.5.6 10500 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10501 SourceLocation Loc, BinaryOperatorKind Opc, 10502 QualType* CompLHSTy) { 10503 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10504 10505 if (LHS.get()->getType()->isVectorType() || 10506 RHS.get()->getType()->isVectorType()) { 10507 QualType compType = CheckVectorOperands( 10508 LHS, RHS, Loc, CompLHSTy, 10509 /*AllowBothBool*/getLangOpts().AltiVec, 10510 /*AllowBoolConversions*/getLangOpts().ZVector); 10511 if (CompLHSTy) *CompLHSTy = compType; 10512 return compType; 10513 } 10514 10515 if (LHS.get()->getType()->isConstantMatrixType() || 10516 RHS.get()->getType()->isConstantMatrixType()) { 10517 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10518 } 10519 10520 QualType compType = UsualArithmeticConversions( 10521 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10522 if (LHS.isInvalid() || RHS.isInvalid()) 10523 return QualType(); 10524 10525 // Diagnose "string literal" '+' int and string '+' "char literal". 10526 if (Opc == BO_Add) { 10527 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10528 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10529 } 10530 10531 // handle the common case first (both operands are arithmetic). 10532 if (!compType.isNull() && compType->isArithmeticType()) { 10533 if (CompLHSTy) *CompLHSTy = compType; 10534 return compType; 10535 } 10536 10537 // Type-checking. Ultimately the pointer's going to be in PExp; 10538 // note that we bias towards the LHS being the pointer. 10539 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10540 10541 bool isObjCPointer; 10542 if (PExp->getType()->isPointerType()) { 10543 isObjCPointer = false; 10544 } else if (PExp->getType()->isObjCObjectPointerType()) { 10545 isObjCPointer = true; 10546 } else { 10547 std::swap(PExp, IExp); 10548 if (PExp->getType()->isPointerType()) { 10549 isObjCPointer = false; 10550 } else if (PExp->getType()->isObjCObjectPointerType()) { 10551 isObjCPointer = true; 10552 } else { 10553 return InvalidOperands(Loc, LHS, RHS); 10554 } 10555 } 10556 assert(PExp->getType()->isAnyPointerType()); 10557 10558 if (!IExp->getType()->isIntegerType()) 10559 return InvalidOperands(Loc, LHS, RHS); 10560 10561 // Adding to a null pointer results in undefined behavior. 10562 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10563 Context, Expr::NPC_ValueDependentIsNotNull)) { 10564 // In C++ adding zero to a null pointer is defined. 10565 Expr::EvalResult KnownVal; 10566 if (!getLangOpts().CPlusPlus || 10567 (!IExp->isValueDependent() && 10568 (!IExp->EvaluateAsInt(KnownVal, Context) || 10569 KnownVal.Val.getInt() != 0))) { 10570 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10571 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10572 Context, BO_Add, PExp, IExp); 10573 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10574 } 10575 } 10576 10577 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10578 return QualType(); 10579 10580 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10581 return QualType(); 10582 10583 // Check array bounds for pointer arithemtic 10584 CheckArrayAccess(PExp, IExp); 10585 10586 if (CompLHSTy) { 10587 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10588 if (LHSTy.isNull()) { 10589 LHSTy = LHS.get()->getType(); 10590 if (LHSTy->isPromotableIntegerType()) 10591 LHSTy = Context.getPromotedIntegerType(LHSTy); 10592 } 10593 *CompLHSTy = LHSTy; 10594 } 10595 10596 return PExp->getType(); 10597 } 10598 10599 // C99 6.5.6 10600 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10601 SourceLocation Loc, 10602 QualType* CompLHSTy) { 10603 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10604 10605 if (LHS.get()->getType()->isVectorType() || 10606 RHS.get()->getType()->isVectorType()) { 10607 QualType compType = CheckVectorOperands( 10608 LHS, RHS, Loc, CompLHSTy, 10609 /*AllowBothBool*/getLangOpts().AltiVec, 10610 /*AllowBoolConversions*/getLangOpts().ZVector); 10611 if (CompLHSTy) *CompLHSTy = compType; 10612 return compType; 10613 } 10614 10615 if (LHS.get()->getType()->isConstantMatrixType() || 10616 RHS.get()->getType()->isConstantMatrixType()) { 10617 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10618 } 10619 10620 QualType compType = UsualArithmeticConversions( 10621 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10622 if (LHS.isInvalid() || RHS.isInvalid()) 10623 return QualType(); 10624 10625 // Enforce type constraints: C99 6.5.6p3. 10626 10627 // Handle the common case first (both operands are arithmetic). 10628 if (!compType.isNull() && compType->isArithmeticType()) { 10629 if (CompLHSTy) *CompLHSTy = compType; 10630 return compType; 10631 } 10632 10633 // Either ptr - int or ptr - ptr. 10634 if (LHS.get()->getType()->isAnyPointerType()) { 10635 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10636 10637 // Diagnose bad cases where we step over interface counts. 10638 if (LHS.get()->getType()->isObjCObjectPointerType() && 10639 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10640 return QualType(); 10641 10642 // The result type of a pointer-int computation is the pointer type. 10643 if (RHS.get()->getType()->isIntegerType()) { 10644 // Subtracting from a null pointer should produce a warning. 10645 // The last argument to the diagnose call says this doesn't match the 10646 // GNU int-to-pointer idiom. 10647 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10648 Expr::NPC_ValueDependentIsNotNull)) { 10649 // In C++ adding zero to a null pointer is defined. 10650 Expr::EvalResult KnownVal; 10651 if (!getLangOpts().CPlusPlus || 10652 (!RHS.get()->isValueDependent() && 10653 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10654 KnownVal.Val.getInt() != 0))) { 10655 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10656 } 10657 } 10658 10659 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10660 return QualType(); 10661 10662 // Check array bounds for pointer arithemtic 10663 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10664 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10665 10666 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10667 return LHS.get()->getType(); 10668 } 10669 10670 // Handle pointer-pointer subtractions. 10671 if (const PointerType *RHSPTy 10672 = RHS.get()->getType()->getAs<PointerType>()) { 10673 QualType rpointee = RHSPTy->getPointeeType(); 10674 10675 if (getLangOpts().CPlusPlus) { 10676 // Pointee types must be the same: C++ [expr.add] 10677 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10678 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10679 } 10680 } else { 10681 // Pointee types must be compatible C99 6.5.6p3 10682 if (!Context.typesAreCompatible( 10683 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10684 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10685 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10686 return QualType(); 10687 } 10688 } 10689 10690 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10691 LHS.get(), RHS.get())) 10692 return QualType(); 10693 10694 // FIXME: Add warnings for nullptr - ptr. 10695 10696 // The pointee type may have zero size. As an extension, a structure or 10697 // union may have zero size or an array may have zero length. In this 10698 // case subtraction does not make sense. 10699 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10700 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10701 if (ElementSize.isZero()) { 10702 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10703 << rpointee.getUnqualifiedType() 10704 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10705 } 10706 } 10707 10708 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10709 return Context.getPointerDiffType(); 10710 } 10711 } 10712 10713 return InvalidOperands(Loc, LHS, RHS); 10714 } 10715 10716 static bool isScopedEnumerationType(QualType T) { 10717 if (const EnumType *ET = T->getAs<EnumType>()) 10718 return ET->getDecl()->isScoped(); 10719 return false; 10720 } 10721 10722 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10723 SourceLocation Loc, BinaryOperatorKind Opc, 10724 QualType LHSType) { 10725 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10726 // so skip remaining warnings as we don't want to modify values within Sema. 10727 if (S.getLangOpts().OpenCL) 10728 return; 10729 10730 // Check right/shifter operand 10731 Expr::EvalResult RHSResult; 10732 if (RHS.get()->isValueDependent() || 10733 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10734 return; 10735 llvm::APSInt Right = RHSResult.Val.getInt(); 10736 10737 if (Right.isNegative()) { 10738 S.DiagRuntimeBehavior(Loc, RHS.get(), 10739 S.PDiag(diag::warn_shift_negative) 10740 << RHS.get()->getSourceRange()); 10741 return; 10742 } 10743 10744 QualType LHSExprType = LHS.get()->getType(); 10745 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10746 if (LHSExprType->isExtIntType()) 10747 LeftSize = S.Context.getIntWidth(LHSExprType); 10748 else if (LHSExprType->isFixedPointType()) { 10749 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10750 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10751 } 10752 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10753 if (Right.uge(LeftBits)) { 10754 S.DiagRuntimeBehavior(Loc, RHS.get(), 10755 S.PDiag(diag::warn_shift_gt_typewidth) 10756 << RHS.get()->getSourceRange()); 10757 return; 10758 } 10759 10760 // FIXME: We probably need to handle fixed point types specially here. 10761 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10762 return; 10763 10764 // When left shifting an ICE which is signed, we can check for overflow which 10765 // according to C++ standards prior to C++2a has undefined behavior 10766 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10767 // more than the maximum value representable in the result type, so never 10768 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10769 // expression is still probably a bug.) 10770 Expr::EvalResult LHSResult; 10771 if (LHS.get()->isValueDependent() || 10772 LHSType->hasUnsignedIntegerRepresentation() || 10773 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10774 return; 10775 llvm::APSInt Left = LHSResult.Val.getInt(); 10776 10777 // If LHS does not have a signed type and non-negative value 10778 // then, the behavior is undefined before C++2a. Warn about it. 10779 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10780 !S.getLangOpts().CPlusPlus20) { 10781 S.DiagRuntimeBehavior(Loc, LHS.get(), 10782 S.PDiag(diag::warn_shift_lhs_negative) 10783 << LHS.get()->getSourceRange()); 10784 return; 10785 } 10786 10787 llvm::APInt ResultBits = 10788 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10789 if (LeftBits.uge(ResultBits)) 10790 return; 10791 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10792 Result = Result.shl(Right); 10793 10794 // Print the bit representation of the signed integer as an unsigned 10795 // hexadecimal number. 10796 SmallString<40> HexResult; 10797 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10798 10799 // If we are only missing a sign bit, this is less likely to result in actual 10800 // bugs -- if the result is cast back to an unsigned type, it will have the 10801 // expected value. Thus we place this behind a different warning that can be 10802 // turned off separately if needed. 10803 if (LeftBits == ResultBits - 1) { 10804 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10805 << HexResult << LHSType 10806 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10807 return; 10808 } 10809 10810 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10811 << HexResult.str() << Result.getMinSignedBits() << LHSType 10812 << Left.getBitWidth() << LHS.get()->getSourceRange() 10813 << RHS.get()->getSourceRange(); 10814 } 10815 10816 /// Return the resulting type when a vector is shifted 10817 /// by a scalar or vector shift amount. 10818 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10819 SourceLocation Loc, bool IsCompAssign) { 10820 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10821 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10822 !LHS.get()->getType()->isVectorType()) { 10823 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10824 << RHS.get()->getType() << LHS.get()->getType() 10825 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10826 return QualType(); 10827 } 10828 10829 if (!IsCompAssign) { 10830 LHS = S.UsualUnaryConversions(LHS.get()); 10831 if (LHS.isInvalid()) return QualType(); 10832 } 10833 10834 RHS = S.UsualUnaryConversions(RHS.get()); 10835 if (RHS.isInvalid()) return QualType(); 10836 10837 QualType LHSType = LHS.get()->getType(); 10838 // Note that LHS might be a scalar because the routine calls not only in 10839 // OpenCL case. 10840 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10841 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10842 10843 // Note that RHS might not be a vector. 10844 QualType RHSType = RHS.get()->getType(); 10845 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10846 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10847 10848 // The operands need to be integers. 10849 if (!LHSEleType->isIntegerType()) { 10850 S.Diag(Loc, diag::err_typecheck_expect_int) 10851 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10852 return QualType(); 10853 } 10854 10855 if (!RHSEleType->isIntegerType()) { 10856 S.Diag(Loc, diag::err_typecheck_expect_int) 10857 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10858 return QualType(); 10859 } 10860 10861 if (!LHSVecTy) { 10862 assert(RHSVecTy); 10863 if (IsCompAssign) 10864 return RHSType; 10865 if (LHSEleType != RHSEleType) { 10866 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10867 LHSEleType = RHSEleType; 10868 } 10869 QualType VecTy = 10870 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10871 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10872 LHSType = VecTy; 10873 } else if (RHSVecTy) { 10874 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10875 // are applied component-wise. So if RHS is a vector, then ensure 10876 // that the number of elements is the same as LHS... 10877 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10878 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10879 << LHS.get()->getType() << RHS.get()->getType() 10880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10881 return QualType(); 10882 } 10883 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10884 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10885 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10886 if (LHSBT != RHSBT && 10887 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10888 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10889 << LHS.get()->getType() << RHS.get()->getType() 10890 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10891 } 10892 } 10893 } else { 10894 // ...else expand RHS to match the number of elements in LHS. 10895 QualType VecTy = 10896 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10897 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10898 } 10899 10900 return LHSType; 10901 } 10902 10903 // C99 6.5.7 10904 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10905 SourceLocation Loc, BinaryOperatorKind Opc, 10906 bool IsCompAssign) { 10907 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10908 10909 // Vector shifts promote their scalar inputs to vector type. 10910 if (LHS.get()->getType()->isVectorType() || 10911 RHS.get()->getType()->isVectorType()) { 10912 if (LangOpts.ZVector) { 10913 // The shift operators for the z vector extensions work basically 10914 // like general shifts, except that neither the LHS nor the RHS is 10915 // allowed to be a "vector bool". 10916 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10917 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10918 return InvalidOperands(Loc, LHS, RHS); 10919 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10920 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10921 return InvalidOperands(Loc, LHS, RHS); 10922 } 10923 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10924 } 10925 10926 // Shifts don't perform usual arithmetic conversions, they just do integer 10927 // promotions on each operand. C99 6.5.7p3 10928 10929 // For the LHS, do usual unary conversions, but then reset them away 10930 // if this is a compound assignment. 10931 ExprResult OldLHS = LHS; 10932 LHS = UsualUnaryConversions(LHS.get()); 10933 if (LHS.isInvalid()) 10934 return QualType(); 10935 QualType LHSType = LHS.get()->getType(); 10936 if (IsCompAssign) LHS = OldLHS; 10937 10938 // The RHS is simpler. 10939 RHS = UsualUnaryConversions(RHS.get()); 10940 if (RHS.isInvalid()) 10941 return QualType(); 10942 QualType RHSType = RHS.get()->getType(); 10943 10944 // C99 6.5.7p2: Each of the operands shall have integer type. 10945 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10946 if ((!LHSType->isFixedPointOrIntegerType() && 10947 !LHSType->hasIntegerRepresentation()) || 10948 !RHSType->hasIntegerRepresentation()) 10949 return InvalidOperands(Loc, LHS, RHS); 10950 10951 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10952 // hasIntegerRepresentation() above instead of this. 10953 if (isScopedEnumerationType(LHSType) || 10954 isScopedEnumerationType(RHSType)) { 10955 return InvalidOperands(Loc, LHS, RHS); 10956 } 10957 // Sanity-check shift operands 10958 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10959 10960 // "The type of the result is that of the promoted left operand." 10961 return LHSType; 10962 } 10963 10964 /// Diagnose bad pointer comparisons. 10965 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10966 ExprResult &LHS, ExprResult &RHS, 10967 bool IsError) { 10968 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10969 : diag::ext_typecheck_comparison_of_distinct_pointers) 10970 << LHS.get()->getType() << RHS.get()->getType() 10971 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10972 } 10973 10974 /// Returns false if the pointers are converted to a composite type, 10975 /// true otherwise. 10976 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10977 ExprResult &LHS, ExprResult &RHS) { 10978 // C++ [expr.rel]p2: 10979 // [...] Pointer conversions (4.10) and qualification 10980 // conversions (4.4) are performed on pointer operands (or on 10981 // a pointer operand and a null pointer constant) to bring 10982 // them to their composite pointer type. [...] 10983 // 10984 // C++ [expr.eq]p1 uses the same notion for (in)equality 10985 // comparisons of pointers. 10986 10987 QualType LHSType = LHS.get()->getType(); 10988 QualType RHSType = RHS.get()->getType(); 10989 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10990 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10991 10992 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10993 if (T.isNull()) { 10994 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10995 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10996 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10997 else 10998 S.InvalidOperands(Loc, LHS, RHS); 10999 return true; 11000 } 11001 11002 return false; 11003 } 11004 11005 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11006 ExprResult &LHS, 11007 ExprResult &RHS, 11008 bool IsError) { 11009 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11010 : diag::ext_typecheck_comparison_of_fptr_to_void) 11011 << LHS.get()->getType() << RHS.get()->getType() 11012 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11013 } 11014 11015 static bool isObjCObjectLiteral(ExprResult &E) { 11016 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11017 case Stmt::ObjCArrayLiteralClass: 11018 case Stmt::ObjCDictionaryLiteralClass: 11019 case Stmt::ObjCStringLiteralClass: 11020 case Stmt::ObjCBoxedExprClass: 11021 return true; 11022 default: 11023 // Note that ObjCBoolLiteral is NOT an object literal! 11024 return false; 11025 } 11026 } 11027 11028 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11029 const ObjCObjectPointerType *Type = 11030 LHS->getType()->getAs<ObjCObjectPointerType>(); 11031 11032 // If this is not actually an Objective-C object, bail out. 11033 if (!Type) 11034 return false; 11035 11036 // Get the LHS object's interface type. 11037 QualType InterfaceType = Type->getPointeeType(); 11038 11039 // If the RHS isn't an Objective-C object, bail out. 11040 if (!RHS->getType()->isObjCObjectPointerType()) 11041 return false; 11042 11043 // Try to find the -isEqual: method. 11044 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11045 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11046 InterfaceType, 11047 /*IsInstance=*/true); 11048 if (!Method) { 11049 if (Type->isObjCIdType()) { 11050 // For 'id', just check the global pool. 11051 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11052 /*receiverId=*/true); 11053 } else { 11054 // Check protocols. 11055 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11056 /*IsInstance=*/true); 11057 } 11058 } 11059 11060 if (!Method) 11061 return false; 11062 11063 QualType T = Method->parameters()[0]->getType(); 11064 if (!T->isObjCObjectPointerType()) 11065 return false; 11066 11067 QualType R = Method->getReturnType(); 11068 if (!R->isScalarType()) 11069 return false; 11070 11071 return true; 11072 } 11073 11074 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11075 FromE = FromE->IgnoreParenImpCasts(); 11076 switch (FromE->getStmtClass()) { 11077 default: 11078 break; 11079 case Stmt::ObjCStringLiteralClass: 11080 // "string literal" 11081 return LK_String; 11082 case Stmt::ObjCArrayLiteralClass: 11083 // "array literal" 11084 return LK_Array; 11085 case Stmt::ObjCDictionaryLiteralClass: 11086 // "dictionary literal" 11087 return LK_Dictionary; 11088 case Stmt::BlockExprClass: 11089 return LK_Block; 11090 case Stmt::ObjCBoxedExprClass: { 11091 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11092 switch (Inner->getStmtClass()) { 11093 case Stmt::IntegerLiteralClass: 11094 case Stmt::FloatingLiteralClass: 11095 case Stmt::CharacterLiteralClass: 11096 case Stmt::ObjCBoolLiteralExprClass: 11097 case Stmt::CXXBoolLiteralExprClass: 11098 // "numeric literal" 11099 return LK_Numeric; 11100 case Stmt::ImplicitCastExprClass: { 11101 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11102 // Boolean literals can be represented by implicit casts. 11103 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11104 return LK_Numeric; 11105 break; 11106 } 11107 default: 11108 break; 11109 } 11110 return LK_Boxed; 11111 } 11112 } 11113 return LK_None; 11114 } 11115 11116 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11117 ExprResult &LHS, ExprResult &RHS, 11118 BinaryOperator::Opcode Opc){ 11119 Expr *Literal; 11120 Expr *Other; 11121 if (isObjCObjectLiteral(LHS)) { 11122 Literal = LHS.get(); 11123 Other = RHS.get(); 11124 } else { 11125 Literal = RHS.get(); 11126 Other = LHS.get(); 11127 } 11128 11129 // Don't warn on comparisons against nil. 11130 Other = Other->IgnoreParenCasts(); 11131 if (Other->isNullPointerConstant(S.getASTContext(), 11132 Expr::NPC_ValueDependentIsNotNull)) 11133 return; 11134 11135 // This should be kept in sync with warn_objc_literal_comparison. 11136 // LK_String should always be after the other literals, since it has its own 11137 // warning flag. 11138 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11139 assert(LiteralKind != Sema::LK_Block); 11140 if (LiteralKind == Sema::LK_None) { 11141 llvm_unreachable("Unknown Objective-C object literal kind"); 11142 } 11143 11144 if (LiteralKind == Sema::LK_String) 11145 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11146 << Literal->getSourceRange(); 11147 else 11148 S.Diag(Loc, diag::warn_objc_literal_comparison) 11149 << LiteralKind << Literal->getSourceRange(); 11150 11151 if (BinaryOperator::isEqualityOp(Opc) && 11152 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11153 SourceLocation Start = LHS.get()->getBeginLoc(); 11154 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11155 CharSourceRange OpRange = 11156 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11157 11158 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11159 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11160 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11161 << FixItHint::CreateInsertion(End, "]"); 11162 } 11163 } 11164 11165 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11166 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11167 ExprResult &RHS, SourceLocation Loc, 11168 BinaryOperatorKind Opc) { 11169 // Check that left hand side is !something. 11170 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11171 if (!UO || UO->getOpcode() != UO_LNot) return; 11172 11173 // Only check if the right hand side is non-bool arithmetic type. 11174 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11175 11176 // Make sure that the something in !something is not bool. 11177 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11178 if (SubExpr->isKnownToHaveBooleanValue()) return; 11179 11180 // Emit warning. 11181 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11182 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11183 << Loc << IsBitwiseOp; 11184 11185 // First note suggest !(x < y) 11186 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11187 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11188 FirstClose = S.getLocForEndOfToken(FirstClose); 11189 if (FirstClose.isInvalid()) 11190 FirstOpen = SourceLocation(); 11191 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11192 << IsBitwiseOp 11193 << FixItHint::CreateInsertion(FirstOpen, "(") 11194 << FixItHint::CreateInsertion(FirstClose, ")"); 11195 11196 // Second note suggests (!x) < y 11197 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11198 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11199 SecondClose = S.getLocForEndOfToken(SecondClose); 11200 if (SecondClose.isInvalid()) 11201 SecondOpen = SourceLocation(); 11202 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11203 << FixItHint::CreateInsertion(SecondOpen, "(") 11204 << FixItHint::CreateInsertion(SecondClose, ")"); 11205 } 11206 11207 // Returns true if E refers to a non-weak array. 11208 static bool checkForArray(const Expr *E) { 11209 const ValueDecl *D = nullptr; 11210 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11211 D = DR->getDecl(); 11212 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11213 if (Mem->isImplicitAccess()) 11214 D = Mem->getMemberDecl(); 11215 } 11216 if (!D) 11217 return false; 11218 return D->getType()->isArrayType() && !D->isWeak(); 11219 } 11220 11221 /// Diagnose some forms of syntactically-obvious tautological comparison. 11222 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11223 Expr *LHS, Expr *RHS, 11224 BinaryOperatorKind Opc) { 11225 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11226 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11227 11228 QualType LHSType = LHS->getType(); 11229 QualType RHSType = RHS->getType(); 11230 if (LHSType->hasFloatingRepresentation() || 11231 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11232 S.inTemplateInstantiation()) 11233 return; 11234 11235 // Comparisons between two array types are ill-formed for operator<=>, so 11236 // we shouldn't emit any additional warnings about it. 11237 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11238 return; 11239 11240 // For non-floating point types, check for self-comparisons of the form 11241 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11242 // often indicate logic errors in the program. 11243 // 11244 // NOTE: Don't warn about comparison expressions resulting from macro 11245 // expansion. Also don't warn about comparisons which are only self 11246 // comparisons within a template instantiation. The warnings should catch 11247 // obvious cases in the definition of the template anyways. The idea is to 11248 // warn when the typed comparison operator will always evaluate to the same 11249 // result. 11250 11251 // Used for indexing into %select in warn_comparison_always 11252 enum { 11253 AlwaysConstant, 11254 AlwaysTrue, 11255 AlwaysFalse, 11256 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11257 }; 11258 11259 // C++2a [depr.array.comp]: 11260 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11261 // operands of array type are deprecated. 11262 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11263 RHSStripped->getType()->isArrayType()) { 11264 S.Diag(Loc, diag::warn_depr_array_comparison) 11265 << LHS->getSourceRange() << RHS->getSourceRange() 11266 << LHSStripped->getType() << RHSStripped->getType(); 11267 // Carry on to produce the tautological comparison warning, if this 11268 // expression is potentially-evaluated, we can resolve the array to a 11269 // non-weak declaration, and so on. 11270 } 11271 11272 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11273 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11274 unsigned Result; 11275 switch (Opc) { 11276 case BO_EQ: 11277 case BO_LE: 11278 case BO_GE: 11279 Result = AlwaysTrue; 11280 break; 11281 case BO_NE: 11282 case BO_LT: 11283 case BO_GT: 11284 Result = AlwaysFalse; 11285 break; 11286 case BO_Cmp: 11287 Result = AlwaysEqual; 11288 break; 11289 default: 11290 Result = AlwaysConstant; 11291 break; 11292 } 11293 S.DiagRuntimeBehavior(Loc, nullptr, 11294 S.PDiag(diag::warn_comparison_always) 11295 << 0 /*self-comparison*/ 11296 << Result); 11297 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11298 // What is it always going to evaluate to? 11299 unsigned Result; 11300 switch (Opc) { 11301 case BO_EQ: // e.g. array1 == array2 11302 Result = AlwaysFalse; 11303 break; 11304 case BO_NE: // e.g. array1 != array2 11305 Result = AlwaysTrue; 11306 break; 11307 default: // e.g. array1 <= array2 11308 // The best we can say is 'a constant' 11309 Result = AlwaysConstant; 11310 break; 11311 } 11312 S.DiagRuntimeBehavior(Loc, nullptr, 11313 S.PDiag(diag::warn_comparison_always) 11314 << 1 /*array comparison*/ 11315 << Result); 11316 } 11317 } 11318 11319 if (isa<CastExpr>(LHSStripped)) 11320 LHSStripped = LHSStripped->IgnoreParenCasts(); 11321 if (isa<CastExpr>(RHSStripped)) 11322 RHSStripped = RHSStripped->IgnoreParenCasts(); 11323 11324 // Warn about comparisons against a string constant (unless the other 11325 // operand is null); the user probably wants string comparison function. 11326 Expr *LiteralString = nullptr; 11327 Expr *LiteralStringStripped = nullptr; 11328 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11329 !RHSStripped->isNullPointerConstant(S.Context, 11330 Expr::NPC_ValueDependentIsNull)) { 11331 LiteralString = LHS; 11332 LiteralStringStripped = LHSStripped; 11333 } else if ((isa<StringLiteral>(RHSStripped) || 11334 isa<ObjCEncodeExpr>(RHSStripped)) && 11335 !LHSStripped->isNullPointerConstant(S.Context, 11336 Expr::NPC_ValueDependentIsNull)) { 11337 LiteralString = RHS; 11338 LiteralStringStripped = RHSStripped; 11339 } 11340 11341 if (LiteralString) { 11342 S.DiagRuntimeBehavior(Loc, nullptr, 11343 S.PDiag(diag::warn_stringcompare) 11344 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11345 << LiteralString->getSourceRange()); 11346 } 11347 } 11348 11349 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11350 switch (CK) { 11351 default: { 11352 #ifndef NDEBUG 11353 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11354 << "\n"; 11355 #endif 11356 llvm_unreachable("unhandled cast kind"); 11357 } 11358 case CK_UserDefinedConversion: 11359 return ICK_Identity; 11360 case CK_LValueToRValue: 11361 return ICK_Lvalue_To_Rvalue; 11362 case CK_ArrayToPointerDecay: 11363 return ICK_Array_To_Pointer; 11364 case CK_FunctionToPointerDecay: 11365 return ICK_Function_To_Pointer; 11366 case CK_IntegralCast: 11367 return ICK_Integral_Conversion; 11368 case CK_FloatingCast: 11369 return ICK_Floating_Conversion; 11370 case CK_IntegralToFloating: 11371 case CK_FloatingToIntegral: 11372 return ICK_Floating_Integral; 11373 case CK_IntegralComplexCast: 11374 case CK_FloatingComplexCast: 11375 case CK_FloatingComplexToIntegralComplex: 11376 case CK_IntegralComplexToFloatingComplex: 11377 return ICK_Complex_Conversion; 11378 case CK_FloatingComplexToReal: 11379 case CK_FloatingRealToComplex: 11380 case CK_IntegralComplexToReal: 11381 case CK_IntegralRealToComplex: 11382 return ICK_Complex_Real; 11383 } 11384 } 11385 11386 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11387 QualType FromType, 11388 SourceLocation Loc) { 11389 // Check for a narrowing implicit conversion. 11390 StandardConversionSequence SCS; 11391 SCS.setAsIdentityConversion(); 11392 SCS.setToType(0, FromType); 11393 SCS.setToType(1, ToType); 11394 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11395 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11396 11397 APValue PreNarrowingValue; 11398 QualType PreNarrowingType; 11399 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11400 PreNarrowingType, 11401 /*IgnoreFloatToIntegralConversion*/ true)) { 11402 case NK_Dependent_Narrowing: 11403 // Implicit conversion to a narrower type, but the expression is 11404 // value-dependent so we can't tell whether it's actually narrowing. 11405 case NK_Not_Narrowing: 11406 return false; 11407 11408 case NK_Constant_Narrowing: 11409 // Implicit conversion to a narrower type, and the value is not a constant 11410 // expression. 11411 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11412 << /*Constant*/ 1 11413 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11414 return true; 11415 11416 case NK_Variable_Narrowing: 11417 // Implicit conversion to a narrower type, and the value is not a constant 11418 // expression. 11419 case NK_Type_Narrowing: 11420 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11421 << /*Constant*/ 0 << FromType << ToType; 11422 // TODO: It's not a constant expression, but what if the user intended it 11423 // to be? Can we produce notes to help them figure out why it isn't? 11424 return true; 11425 } 11426 llvm_unreachable("unhandled case in switch"); 11427 } 11428 11429 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11430 ExprResult &LHS, 11431 ExprResult &RHS, 11432 SourceLocation Loc) { 11433 QualType LHSType = LHS.get()->getType(); 11434 QualType RHSType = RHS.get()->getType(); 11435 // Dig out the original argument type and expression before implicit casts 11436 // were applied. These are the types/expressions we need to check the 11437 // [expr.spaceship] requirements against. 11438 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11439 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11440 QualType LHSStrippedType = LHSStripped.get()->getType(); 11441 QualType RHSStrippedType = RHSStripped.get()->getType(); 11442 11443 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11444 // other is not, the program is ill-formed. 11445 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11446 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11447 return QualType(); 11448 } 11449 11450 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11451 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11452 RHSStrippedType->isEnumeralType(); 11453 if (NumEnumArgs == 1) { 11454 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11455 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11456 if (OtherTy->hasFloatingRepresentation()) { 11457 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11458 return QualType(); 11459 } 11460 } 11461 if (NumEnumArgs == 2) { 11462 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11463 // type E, the operator yields the result of converting the operands 11464 // to the underlying type of E and applying <=> to the converted operands. 11465 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11466 S.InvalidOperands(Loc, LHS, RHS); 11467 return QualType(); 11468 } 11469 QualType IntType = 11470 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11471 assert(IntType->isArithmeticType()); 11472 11473 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11474 // promote the boolean type, and all other promotable integer types, to 11475 // avoid this. 11476 if (IntType->isPromotableIntegerType()) 11477 IntType = S.Context.getPromotedIntegerType(IntType); 11478 11479 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11480 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11481 LHSType = RHSType = IntType; 11482 } 11483 11484 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11485 // usual arithmetic conversions are applied to the operands. 11486 QualType Type = 11487 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11488 if (LHS.isInvalid() || RHS.isInvalid()) 11489 return QualType(); 11490 if (Type.isNull()) 11491 return S.InvalidOperands(Loc, LHS, RHS); 11492 11493 Optional<ComparisonCategoryType> CCT = 11494 getComparisonCategoryForBuiltinCmp(Type); 11495 if (!CCT) 11496 return S.InvalidOperands(Loc, LHS, RHS); 11497 11498 bool HasNarrowing = checkThreeWayNarrowingConversion( 11499 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11500 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11501 RHS.get()->getBeginLoc()); 11502 if (HasNarrowing) 11503 return QualType(); 11504 11505 assert(!Type.isNull() && "composite type for <=> has not been set"); 11506 11507 return S.CheckComparisonCategoryType( 11508 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11509 } 11510 11511 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11512 ExprResult &RHS, 11513 SourceLocation Loc, 11514 BinaryOperatorKind Opc) { 11515 if (Opc == BO_Cmp) 11516 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11517 11518 // C99 6.5.8p3 / C99 6.5.9p4 11519 QualType Type = 11520 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11521 if (LHS.isInvalid() || RHS.isInvalid()) 11522 return QualType(); 11523 if (Type.isNull()) 11524 return S.InvalidOperands(Loc, LHS, RHS); 11525 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11526 11527 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11528 return S.InvalidOperands(Loc, LHS, RHS); 11529 11530 // Check for comparisons of floating point operands using != and ==. 11531 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11532 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11533 11534 // The result of comparisons is 'bool' in C++, 'int' in C. 11535 return S.Context.getLogicalOperationType(); 11536 } 11537 11538 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11539 if (!NullE.get()->getType()->isAnyPointerType()) 11540 return; 11541 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11542 if (!E.get()->getType()->isAnyPointerType() && 11543 E.get()->isNullPointerConstant(Context, 11544 Expr::NPC_ValueDependentIsNotNull) == 11545 Expr::NPCK_ZeroExpression) { 11546 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11547 if (CL->getValue() == 0) 11548 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11549 << NullValue 11550 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11551 NullValue ? "NULL" : "(void *)0"); 11552 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11553 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11554 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11555 if (T == Context.CharTy) 11556 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11557 << NullValue 11558 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11559 NullValue ? "NULL" : "(void *)0"); 11560 } 11561 } 11562 } 11563 11564 // C99 6.5.8, C++ [expr.rel] 11565 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11566 SourceLocation Loc, 11567 BinaryOperatorKind Opc) { 11568 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11569 bool IsThreeWay = Opc == BO_Cmp; 11570 bool IsOrdered = IsRelational || IsThreeWay; 11571 auto IsAnyPointerType = [](ExprResult E) { 11572 QualType Ty = E.get()->getType(); 11573 return Ty->isPointerType() || Ty->isMemberPointerType(); 11574 }; 11575 11576 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11577 // type, array-to-pointer, ..., conversions are performed on both operands to 11578 // bring them to their composite type. 11579 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11580 // any type-related checks. 11581 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11582 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11583 if (LHS.isInvalid()) 11584 return QualType(); 11585 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11586 if (RHS.isInvalid()) 11587 return QualType(); 11588 } else { 11589 LHS = DefaultLvalueConversion(LHS.get()); 11590 if (LHS.isInvalid()) 11591 return QualType(); 11592 RHS = DefaultLvalueConversion(RHS.get()); 11593 if (RHS.isInvalid()) 11594 return QualType(); 11595 } 11596 11597 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11598 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11599 CheckPtrComparisonWithNullChar(LHS, RHS); 11600 CheckPtrComparisonWithNullChar(RHS, LHS); 11601 } 11602 11603 // Handle vector comparisons separately. 11604 if (LHS.get()->getType()->isVectorType() || 11605 RHS.get()->getType()->isVectorType()) 11606 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11607 11608 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11609 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11610 11611 QualType LHSType = LHS.get()->getType(); 11612 QualType RHSType = RHS.get()->getType(); 11613 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11614 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11615 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11616 11617 const Expr::NullPointerConstantKind LHSNullKind = 11618 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11619 const Expr::NullPointerConstantKind RHSNullKind = 11620 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11621 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11622 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11623 11624 auto computeResultTy = [&]() { 11625 if (Opc != BO_Cmp) 11626 return Context.getLogicalOperationType(); 11627 assert(getLangOpts().CPlusPlus); 11628 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11629 11630 QualType CompositeTy = LHS.get()->getType(); 11631 assert(!CompositeTy->isReferenceType()); 11632 11633 Optional<ComparisonCategoryType> CCT = 11634 getComparisonCategoryForBuiltinCmp(CompositeTy); 11635 if (!CCT) 11636 return InvalidOperands(Loc, LHS, RHS); 11637 11638 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11639 // P0946R0: Comparisons between a null pointer constant and an object 11640 // pointer result in std::strong_equality, which is ill-formed under 11641 // P1959R0. 11642 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11643 << (LHSIsNull ? LHS.get()->getSourceRange() 11644 : RHS.get()->getSourceRange()); 11645 return QualType(); 11646 } 11647 11648 return CheckComparisonCategoryType( 11649 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11650 }; 11651 11652 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11653 bool IsEquality = Opc == BO_EQ; 11654 if (RHSIsNull) 11655 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11656 RHS.get()->getSourceRange()); 11657 else 11658 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11659 LHS.get()->getSourceRange()); 11660 } 11661 11662 if ((LHSType->isIntegerType() && !LHSIsNull) || 11663 (RHSType->isIntegerType() && !RHSIsNull)) { 11664 // Skip normal pointer conversion checks in this case; we have better 11665 // diagnostics for this below. 11666 } else if (getLangOpts().CPlusPlus) { 11667 // Equality comparison of a function pointer to a void pointer is invalid, 11668 // but we allow it as an extension. 11669 // FIXME: If we really want to allow this, should it be part of composite 11670 // pointer type computation so it works in conditionals too? 11671 if (!IsOrdered && 11672 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11673 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11674 // This is a gcc extension compatibility comparison. 11675 // In a SFINAE context, we treat this as a hard error to maintain 11676 // conformance with the C++ standard. 11677 diagnoseFunctionPointerToVoidComparison( 11678 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11679 11680 if (isSFINAEContext()) 11681 return QualType(); 11682 11683 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11684 return computeResultTy(); 11685 } 11686 11687 // C++ [expr.eq]p2: 11688 // If at least one operand is a pointer [...] bring them to their 11689 // composite pointer type. 11690 // C++ [expr.spaceship]p6 11691 // If at least one of the operands is of pointer type, [...] bring them 11692 // to their composite pointer type. 11693 // C++ [expr.rel]p2: 11694 // If both operands are pointers, [...] bring them to their composite 11695 // pointer type. 11696 // For <=>, the only valid non-pointer types are arrays and functions, and 11697 // we already decayed those, so this is really the same as the relational 11698 // comparison rule. 11699 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11700 (IsOrdered ? 2 : 1) && 11701 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11702 RHSType->isObjCObjectPointerType()))) { 11703 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11704 return QualType(); 11705 return computeResultTy(); 11706 } 11707 } else if (LHSType->isPointerType() && 11708 RHSType->isPointerType()) { // C99 6.5.8p2 11709 // All of the following pointer-related warnings are GCC extensions, except 11710 // when handling null pointer constants. 11711 QualType LCanPointeeTy = 11712 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11713 QualType RCanPointeeTy = 11714 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11715 11716 // C99 6.5.9p2 and C99 6.5.8p2 11717 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11718 RCanPointeeTy.getUnqualifiedType())) { 11719 if (IsRelational) { 11720 // Pointers both need to point to complete or incomplete types 11721 if ((LCanPointeeTy->isIncompleteType() != 11722 RCanPointeeTy->isIncompleteType()) && 11723 !getLangOpts().C11) { 11724 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11726 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11727 << RCanPointeeTy->isIncompleteType(); 11728 } 11729 if (LCanPointeeTy->isFunctionType()) { 11730 // Valid unless a relational comparison of function pointers 11731 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11732 << LHSType << RHSType << LHS.get()->getSourceRange() 11733 << RHS.get()->getSourceRange(); 11734 } 11735 } 11736 } else if (!IsRelational && 11737 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11738 // Valid unless comparison between non-null pointer and function pointer 11739 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11740 && !LHSIsNull && !RHSIsNull) 11741 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11742 /*isError*/false); 11743 } else { 11744 // Invalid 11745 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11746 } 11747 if (LCanPointeeTy != RCanPointeeTy) { 11748 // Treat NULL constant as a special case in OpenCL. 11749 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11750 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11751 Diag(Loc, 11752 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11753 << LHSType << RHSType << 0 /* comparison */ 11754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11755 } 11756 } 11757 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11758 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11759 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11760 : CK_BitCast; 11761 if (LHSIsNull && !RHSIsNull) 11762 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11763 else 11764 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11765 } 11766 return computeResultTy(); 11767 } 11768 11769 if (getLangOpts().CPlusPlus) { 11770 // C++ [expr.eq]p4: 11771 // Two operands of type std::nullptr_t or one operand of type 11772 // std::nullptr_t and the other a null pointer constant compare equal. 11773 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11774 if (LHSType->isNullPtrType()) { 11775 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11776 return computeResultTy(); 11777 } 11778 if (RHSType->isNullPtrType()) { 11779 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11780 return computeResultTy(); 11781 } 11782 } 11783 11784 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11785 // These aren't covered by the composite pointer type rules. 11786 if (!IsOrdered && RHSType->isNullPtrType() && 11787 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11788 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11789 return computeResultTy(); 11790 } 11791 if (!IsOrdered && LHSType->isNullPtrType() && 11792 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11793 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11794 return computeResultTy(); 11795 } 11796 11797 if (IsRelational && 11798 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11799 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11800 // HACK: Relational comparison of nullptr_t against a pointer type is 11801 // invalid per DR583, but we allow it within std::less<> and friends, 11802 // since otherwise common uses of it break. 11803 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11804 // friends to have std::nullptr_t overload candidates. 11805 DeclContext *DC = CurContext; 11806 if (isa<FunctionDecl>(DC)) 11807 DC = DC->getParent(); 11808 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11809 if (CTSD->isInStdNamespace() && 11810 llvm::StringSwitch<bool>(CTSD->getName()) 11811 .Cases("less", "less_equal", "greater", "greater_equal", true) 11812 .Default(false)) { 11813 if (RHSType->isNullPtrType()) 11814 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11815 else 11816 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11817 return computeResultTy(); 11818 } 11819 } 11820 } 11821 11822 // C++ [expr.eq]p2: 11823 // If at least one operand is a pointer to member, [...] bring them to 11824 // their composite pointer type. 11825 if (!IsOrdered && 11826 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11827 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11828 return QualType(); 11829 else 11830 return computeResultTy(); 11831 } 11832 } 11833 11834 // Handle block pointer types. 11835 if (!IsOrdered && LHSType->isBlockPointerType() && 11836 RHSType->isBlockPointerType()) { 11837 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11838 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11839 11840 if (!LHSIsNull && !RHSIsNull && 11841 !Context.typesAreCompatible(lpointee, rpointee)) { 11842 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11843 << LHSType << RHSType << LHS.get()->getSourceRange() 11844 << RHS.get()->getSourceRange(); 11845 } 11846 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11847 return computeResultTy(); 11848 } 11849 11850 // Allow block pointers to be compared with null pointer constants. 11851 if (!IsOrdered 11852 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11853 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11854 if (!LHSIsNull && !RHSIsNull) { 11855 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11856 ->getPointeeType()->isVoidType()) 11857 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11858 ->getPointeeType()->isVoidType()))) 11859 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11860 << LHSType << RHSType << LHS.get()->getSourceRange() 11861 << RHS.get()->getSourceRange(); 11862 } 11863 if (LHSIsNull && !RHSIsNull) 11864 LHS = ImpCastExprToType(LHS.get(), RHSType, 11865 RHSType->isPointerType() ? CK_BitCast 11866 : CK_AnyPointerToBlockPointerCast); 11867 else 11868 RHS = ImpCastExprToType(RHS.get(), LHSType, 11869 LHSType->isPointerType() ? CK_BitCast 11870 : CK_AnyPointerToBlockPointerCast); 11871 return computeResultTy(); 11872 } 11873 11874 if (LHSType->isObjCObjectPointerType() || 11875 RHSType->isObjCObjectPointerType()) { 11876 const PointerType *LPT = LHSType->getAs<PointerType>(); 11877 const PointerType *RPT = RHSType->getAs<PointerType>(); 11878 if (LPT || RPT) { 11879 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11880 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11881 11882 if (!LPtrToVoid && !RPtrToVoid && 11883 !Context.typesAreCompatible(LHSType, RHSType)) { 11884 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11885 /*isError*/false); 11886 } 11887 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11888 // the RHS, but we have test coverage for this behavior. 11889 // FIXME: Consider using convertPointersToCompositeType in C++. 11890 if (LHSIsNull && !RHSIsNull) { 11891 Expr *E = LHS.get(); 11892 if (getLangOpts().ObjCAutoRefCount) 11893 CheckObjCConversion(SourceRange(), RHSType, E, 11894 CCK_ImplicitConversion); 11895 LHS = ImpCastExprToType(E, RHSType, 11896 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11897 } 11898 else { 11899 Expr *E = RHS.get(); 11900 if (getLangOpts().ObjCAutoRefCount) 11901 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11902 /*Diagnose=*/true, 11903 /*DiagnoseCFAudited=*/false, Opc); 11904 RHS = ImpCastExprToType(E, LHSType, 11905 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11906 } 11907 return computeResultTy(); 11908 } 11909 if (LHSType->isObjCObjectPointerType() && 11910 RHSType->isObjCObjectPointerType()) { 11911 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11912 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11913 /*isError*/false); 11914 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11915 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11916 11917 if (LHSIsNull && !RHSIsNull) 11918 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11919 else 11920 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11921 return computeResultTy(); 11922 } 11923 11924 if (!IsOrdered && LHSType->isBlockPointerType() && 11925 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11926 LHS = ImpCastExprToType(LHS.get(), RHSType, 11927 CK_BlockPointerToObjCPointerCast); 11928 return computeResultTy(); 11929 } else if (!IsOrdered && 11930 LHSType->isBlockCompatibleObjCPointerType(Context) && 11931 RHSType->isBlockPointerType()) { 11932 RHS = ImpCastExprToType(RHS.get(), LHSType, 11933 CK_BlockPointerToObjCPointerCast); 11934 return computeResultTy(); 11935 } 11936 } 11937 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11938 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11939 unsigned DiagID = 0; 11940 bool isError = false; 11941 if (LangOpts.DebuggerSupport) { 11942 // Under a debugger, allow the comparison of pointers to integers, 11943 // since users tend to want to compare addresses. 11944 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11945 (RHSIsNull && RHSType->isIntegerType())) { 11946 if (IsOrdered) { 11947 isError = getLangOpts().CPlusPlus; 11948 DiagID = 11949 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11950 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11951 } 11952 } else if (getLangOpts().CPlusPlus) { 11953 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11954 isError = true; 11955 } else if (IsOrdered) 11956 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11957 else 11958 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11959 11960 if (DiagID) { 11961 Diag(Loc, DiagID) 11962 << LHSType << RHSType << LHS.get()->getSourceRange() 11963 << RHS.get()->getSourceRange(); 11964 if (isError) 11965 return QualType(); 11966 } 11967 11968 if (LHSType->isIntegerType()) 11969 LHS = ImpCastExprToType(LHS.get(), RHSType, 11970 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11971 else 11972 RHS = ImpCastExprToType(RHS.get(), LHSType, 11973 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11974 return computeResultTy(); 11975 } 11976 11977 // Handle block pointers. 11978 if (!IsOrdered && RHSIsNull 11979 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11980 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11981 return computeResultTy(); 11982 } 11983 if (!IsOrdered && LHSIsNull 11984 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11985 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11986 return computeResultTy(); 11987 } 11988 11989 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11990 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11991 return computeResultTy(); 11992 } 11993 11994 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11995 return computeResultTy(); 11996 } 11997 11998 if (LHSIsNull && RHSType->isQueueT()) { 11999 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12000 return computeResultTy(); 12001 } 12002 12003 if (LHSType->isQueueT() && RHSIsNull) { 12004 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12005 return computeResultTy(); 12006 } 12007 } 12008 12009 return InvalidOperands(Loc, LHS, RHS); 12010 } 12011 12012 // Return a signed ext_vector_type that is of identical size and number of 12013 // elements. For floating point vectors, return an integer type of identical 12014 // size and number of elements. In the non ext_vector_type case, search from 12015 // the largest type to the smallest type to avoid cases where long long == long, 12016 // where long gets picked over long long. 12017 QualType Sema::GetSignedVectorType(QualType V) { 12018 const VectorType *VTy = V->castAs<VectorType>(); 12019 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12020 12021 if (isa<ExtVectorType>(VTy)) { 12022 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12023 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12024 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12025 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12026 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12027 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12028 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12029 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12030 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12031 "Unhandled vector element size in vector compare"); 12032 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12033 } 12034 12035 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12036 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12037 VectorType::GenericVector); 12038 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12039 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12040 VectorType::GenericVector); 12041 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12042 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12043 VectorType::GenericVector); 12044 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12045 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12046 VectorType::GenericVector); 12047 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12048 "Unhandled vector element size in vector compare"); 12049 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12050 VectorType::GenericVector); 12051 } 12052 12053 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12054 /// operates on extended vector types. Instead of producing an IntTy result, 12055 /// like a scalar comparison, a vector comparison produces a vector of integer 12056 /// types. 12057 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12058 SourceLocation Loc, 12059 BinaryOperatorKind Opc) { 12060 if (Opc == BO_Cmp) { 12061 Diag(Loc, diag::err_three_way_vector_comparison); 12062 return QualType(); 12063 } 12064 12065 // Check to make sure we're operating on vectors of the same type and width, 12066 // Allowing one side to be a scalar of element type. 12067 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12068 /*AllowBothBool*/true, 12069 /*AllowBoolConversions*/getLangOpts().ZVector); 12070 if (vType.isNull()) 12071 return vType; 12072 12073 QualType LHSType = LHS.get()->getType(); 12074 12075 // If AltiVec, the comparison results in a numeric type, i.e. 12076 // bool for C++, int for C 12077 if (getLangOpts().AltiVec && 12078 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12079 return Context.getLogicalOperationType(); 12080 12081 // For non-floating point types, check for self-comparisons of the form 12082 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12083 // often indicate logic errors in the program. 12084 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12085 12086 // Check for comparisons of floating point operands using != and ==. 12087 if (BinaryOperator::isEqualityOp(Opc) && 12088 LHSType->hasFloatingRepresentation()) { 12089 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12090 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12091 } 12092 12093 // Return a signed type for the vector. 12094 return GetSignedVectorType(vType); 12095 } 12096 12097 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12098 const ExprResult &XorRHS, 12099 const SourceLocation Loc) { 12100 // Do not diagnose macros. 12101 if (Loc.isMacroID()) 12102 return; 12103 12104 bool Negative = false; 12105 bool ExplicitPlus = false; 12106 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12107 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12108 12109 if (!LHSInt) 12110 return; 12111 if (!RHSInt) { 12112 // Check negative literals. 12113 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12114 UnaryOperatorKind Opc = UO->getOpcode(); 12115 if (Opc != UO_Minus && Opc != UO_Plus) 12116 return; 12117 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12118 if (!RHSInt) 12119 return; 12120 Negative = (Opc == UO_Minus); 12121 ExplicitPlus = !Negative; 12122 } else { 12123 return; 12124 } 12125 } 12126 12127 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12128 llvm::APInt RightSideValue = RHSInt->getValue(); 12129 if (LeftSideValue != 2 && LeftSideValue != 10) 12130 return; 12131 12132 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12133 return; 12134 12135 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12136 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12137 llvm::StringRef ExprStr = 12138 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12139 12140 CharSourceRange XorRange = 12141 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12142 llvm::StringRef XorStr = 12143 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12144 // Do not diagnose if xor keyword/macro is used. 12145 if (XorStr == "xor") 12146 return; 12147 12148 std::string LHSStr = std::string(Lexer::getSourceText( 12149 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12150 S.getSourceManager(), S.getLangOpts())); 12151 std::string RHSStr = std::string(Lexer::getSourceText( 12152 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12153 S.getSourceManager(), S.getLangOpts())); 12154 12155 if (Negative) { 12156 RightSideValue = -RightSideValue; 12157 RHSStr = "-" + RHSStr; 12158 } else if (ExplicitPlus) { 12159 RHSStr = "+" + RHSStr; 12160 } 12161 12162 StringRef LHSStrRef = LHSStr; 12163 StringRef RHSStrRef = RHSStr; 12164 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12165 // literals. 12166 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12167 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12168 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12169 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12170 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12171 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12172 LHSStrRef.find('\'') != StringRef::npos || 12173 RHSStrRef.find('\'') != StringRef::npos) 12174 return; 12175 12176 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12177 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12178 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12179 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12180 std::string SuggestedExpr = "1 << " + RHSStr; 12181 bool Overflow = false; 12182 llvm::APInt One = (LeftSideValue - 1); 12183 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12184 if (Overflow) { 12185 if (RightSideIntValue < 64) 12186 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12187 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12188 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12189 else if (RightSideIntValue == 64) 12190 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12191 else 12192 return; 12193 } else { 12194 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12195 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12196 << PowValue.toString(10, true) 12197 << FixItHint::CreateReplacement( 12198 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12199 } 12200 12201 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12202 } else if (LeftSideValue == 10) { 12203 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12204 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12205 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12206 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12207 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12208 } 12209 } 12210 12211 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12212 SourceLocation Loc) { 12213 // Ensure that either both operands are of the same vector type, or 12214 // one operand is of a vector type and the other is of its element type. 12215 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12216 /*AllowBothBool*/true, 12217 /*AllowBoolConversions*/false); 12218 if (vType.isNull()) 12219 return InvalidOperands(Loc, LHS, RHS); 12220 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12221 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12222 return InvalidOperands(Loc, LHS, RHS); 12223 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12224 // usage of the logical operators && and || with vectors in C. This 12225 // check could be notionally dropped. 12226 if (!getLangOpts().CPlusPlus && 12227 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12228 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12229 12230 return GetSignedVectorType(LHS.get()->getType()); 12231 } 12232 12233 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12234 SourceLocation Loc, 12235 bool IsCompAssign) { 12236 if (!IsCompAssign) { 12237 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12238 if (LHS.isInvalid()) 12239 return QualType(); 12240 } 12241 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12242 if (RHS.isInvalid()) 12243 return QualType(); 12244 12245 // For conversion purposes, we ignore any qualifiers. 12246 // For example, "const float" and "float" are equivalent. 12247 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12248 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12249 12250 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12251 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12252 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12253 12254 if (Context.hasSameType(LHSType, RHSType)) 12255 return LHSType; 12256 12257 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12258 // case we have to return InvalidOperands. 12259 ExprResult OriginalLHS = LHS; 12260 ExprResult OriginalRHS = RHS; 12261 if (LHSMatType && !RHSMatType) { 12262 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12263 if (!RHS.isInvalid()) 12264 return LHSType; 12265 12266 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12267 } 12268 12269 if (!LHSMatType && RHSMatType) { 12270 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12271 if (!LHS.isInvalid()) 12272 return RHSType; 12273 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12274 } 12275 12276 return InvalidOperands(Loc, LHS, RHS); 12277 } 12278 12279 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12280 SourceLocation Loc, 12281 bool IsCompAssign) { 12282 if (!IsCompAssign) { 12283 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12284 if (LHS.isInvalid()) 12285 return QualType(); 12286 } 12287 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12288 if (RHS.isInvalid()) 12289 return QualType(); 12290 12291 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12292 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12293 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12294 12295 if (LHSMatType && RHSMatType) { 12296 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12297 return InvalidOperands(Loc, LHS, RHS); 12298 12299 if (!Context.hasSameType(LHSMatType->getElementType(), 12300 RHSMatType->getElementType())) 12301 return InvalidOperands(Loc, LHS, RHS); 12302 12303 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12304 LHSMatType->getNumRows(), 12305 RHSMatType->getNumColumns()); 12306 } 12307 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12308 } 12309 12310 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12311 SourceLocation Loc, 12312 BinaryOperatorKind Opc) { 12313 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12314 12315 bool IsCompAssign = 12316 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12317 12318 if (LHS.get()->getType()->isVectorType() || 12319 RHS.get()->getType()->isVectorType()) { 12320 if (LHS.get()->getType()->hasIntegerRepresentation() && 12321 RHS.get()->getType()->hasIntegerRepresentation()) 12322 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12323 /*AllowBothBool*/true, 12324 /*AllowBoolConversions*/getLangOpts().ZVector); 12325 return InvalidOperands(Loc, LHS, RHS); 12326 } 12327 12328 if (Opc == BO_And) 12329 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12330 12331 if (LHS.get()->getType()->hasFloatingRepresentation() || 12332 RHS.get()->getType()->hasFloatingRepresentation()) 12333 return InvalidOperands(Loc, LHS, RHS); 12334 12335 ExprResult LHSResult = LHS, RHSResult = RHS; 12336 QualType compType = UsualArithmeticConversions( 12337 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12338 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12339 return QualType(); 12340 LHS = LHSResult.get(); 12341 RHS = RHSResult.get(); 12342 12343 if (Opc == BO_Xor) 12344 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12345 12346 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12347 return compType; 12348 return InvalidOperands(Loc, LHS, RHS); 12349 } 12350 12351 // C99 6.5.[13,14] 12352 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12353 SourceLocation Loc, 12354 BinaryOperatorKind Opc) { 12355 // Check vector operands differently. 12356 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12357 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12358 12359 bool EnumConstantInBoolContext = false; 12360 for (const ExprResult &HS : {LHS, RHS}) { 12361 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12362 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12363 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12364 EnumConstantInBoolContext = true; 12365 } 12366 } 12367 12368 if (EnumConstantInBoolContext) 12369 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12370 12371 // Diagnose cases where the user write a logical and/or but probably meant a 12372 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12373 // is a constant. 12374 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12375 !LHS.get()->getType()->isBooleanType() && 12376 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12377 // Don't warn in macros or template instantiations. 12378 !Loc.isMacroID() && !inTemplateInstantiation()) { 12379 // If the RHS can be constant folded, and if it constant folds to something 12380 // that isn't 0 or 1 (which indicate a potential logical operation that 12381 // happened to fold to true/false) then warn. 12382 // Parens on the RHS are ignored. 12383 Expr::EvalResult EVResult; 12384 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12385 llvm::APSInt Result = EVResult.Val.getInt(); 12386 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12387 !RHS.get()->getExprLoc().isMacroID()) || 12388 (Result != 0 && Result != 1)) { 12389 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12390 << RHS.get()->getSourceRange() 12391 << (Opc == BO_LAnd ? "&&" : "||"); 12392 // Suggest replacing the logical operator with the bitwise version 12393 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12394 << (Opc == BO_LAnd ? "&" : "|") 12395 << FixItHint::CreateReplacement(SourceRange( 12396 Loc, getLocForEndOfToken(Loc)), 12397 Opc == BO_LAnd ? "&" : "|"); 12398 if (Opc == BO_LAnd) 12399 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12400 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12401 << FixItHint::CreateRemoval( 12402 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12403 RHS.get()->getEndLoc())); 12404 } 12405 } 12406 } 12407 12408 if (!Context.getLangOpts().CPlusPlus) { 12409 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12410 // not operate on the built-in scalar and vector float types. 12411 if (Context.getLangOpts().OpenCL && 12412 Context.getLangOpts().OpenCLVersion < 120) { 12413 if (LHS.get()->getType()->isFloatingType() || 12414 RHS.get()->getType()->isFloatingType()) 12415 return InvalidOperands(Loc, LHS, RHS); 12416 } 12417 12418 LHS = UsualUnaryConversions(LHS.get()); 12419 if (LHS.isInvalid()) 12420 return QualType(); 12421 12422 RHS = UsualUnaryConversions(RHS.get()); 12423 if (RHS.isInvalid()) 12424 return QualType(); 12425 12426 if (!LHS.get()->getType()->isScalarType() || 12427 !RHS.get()->getType()->isScalarType()) 12428 return InvalidOperands(Loc, LHS, RHS); 12429 12430 return Context.IntTy; 12431 } 12432 12433 // The following is safe because we only use this method for 12434 // non-overloadable operands. 12435 12436 // C++ [expr.log.and]p1 12437 // C++ [expr.log.or]p1 12438 // The operands are both contextually converted to type bool. 12439 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12440 if (LHSRes.isInvalid()) 12441 return InvalidOperands(Loc, LHS, RHS); 12442 LHS = LHSRes; 12443 12444 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12445 if (RHSRes.isInvalid()) 12446 return InvalidOperands(Loc, LHS, RHS); 12447 RHS = RHSRes; 12448 12449 // C++ [expr.log.and]p2 12450 // C++ [expr.log.or]p2 12451 // The result is a bool. 12452 return Context.BoolTy; 12453 } 12454 12455 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12456 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12457 if (!ME) return false; 12458 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12459 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12460 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12461 if (!Base) return false; 12462 return Base->getMethodDecl() != nullptr; 12463 } 12464 12465 /// Is the given expression (which must be 'const') a reference to a 12466 /// variable which was originally non-const, but which has become 12467 /// 'const' due to being captured within a block? 12468 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12469 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12470 assert(E->isLValue() && E->getType().isConstQualified()); 12471 E = E->IgnoreParens(); 12472 12473 // Must be a reference to a declaration from an enclosing scope. 12474 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12475 if (!DRE) return NCCK_None; 12476 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12477 12478 // The declaration must be a variable which is not declared 'const'. 12479 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12480 if (!var) return NCCK_None; 12481 if (var->getType().isConstQualified()) return NCCK_None; 12482 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12483 12484 // Decide whether the first capture was for a block or a lambda. 12485 DeclContext *DC = S.CurContext, *Prev = nullptr; 12486 // Decide whether the first capture was for a block or a lambda. 12487 while (DC) { 12488 // For init-capture, it is possible that the variable belongs to the 12489 // template pattern of the current context. 12490 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12491 if (var->isInitCapture() && 12492 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12493 break; 12494 if (DC == var->getDeclContext()) 12495 break; 12496 Prev = DC; 12497 DC = DC->getParent(); 12498 } 12499 // Unless we have an init-capture, we've gone one step too far. 12500 if (!var->isInitCapture()) 12501 DC = Prev; 12502 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12503 } 12504 12505 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12506 Ty = Ty.getNonReferenceType(); 12507 if (IsDereference && Ty->isPointerType()) 12508 Ty = Ty->getPointeeType(); 12509 return !Ty.isConstQualified(); 12510 } 12511 12512 // Update err_typecheck_assign_const and note_typecheck_assign_const 12513 // when this enum is changed. 12514 enum { 12515 ConstFunction, 12516 ConstVariable, 12517 ConstMember, 12518 ConstMethod, 12519 NestedConstMember, 12520 ConstUnknown, // Keep as last element 12521 }; 12522 12523 /// Emit the "read-only variable not assignable" error and print notes to give 12524 /// more information about why the variable is not assignable, such as pointing 12525 /// to the declaration of a const variable, showing that a method is const, or 12526 /// that the function is returning a const reference. 12527 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12528 SourceLocation Loc) { 12529 SourceRange ExprRange = E->getSourceRange(); 12530 12531 // Only emit one error on the first const found. All other consts will emit 12532 // a note to the error. 12533 bool DiagnosticEmitted = false; 12534 12535 // Track if the current expression is the result of a dereference, and if the 12536 // next checked expression is the result of a dereference. 12537 bool IsDereference = false; 12538 bool NextIsDereference = false; 12539 12540 // Loop to process MemberExpr chains. 12541 while (true) { 12542 IsDereference = NextIsDereference; 12543 12544 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12545 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12546 NextIsDereference = ME->isArrow(); 12547 const ValueDecl *VD = ME->getMemberDecl(); 12548 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12549 // Mutable fields can be modified even if the class is const. 12550 if (Field->isMutable()) { 12551 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12552 break; 12553 } 12554 12555 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12556 if (!DiagnosticEmitted) { 12557 S.Diag(Loc, diag::err_typecheck_assign_const) 12558 << ExprRange << ConstMember << false /*static*/ << Field 12559 << Field->getType(); 12560 DiagnosticEmitted = true; 12561 } 12562 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12563 << ConstMember << false /*static*/ << Field << Field->getType() 12564 << Field->getSourceRange(); 12565 } 12566 E = ME->getBase(); 12567 continue; 12568 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12569 if (VDecl->getType().isConstQualified()) { 12570 if (!DiagnosticEmitted) { 12571 S.Diag(Loc, diag::err_typecheck_assign_const) 12572 << ExprRange << ConstMember << true /*static*/ << VDecl 12573 << VDecl->getType(); 12574 DiagnosticEmitted = true; 12575 } 12576 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12577 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12578 << VDecl->getSourceRange(); 12579 } 12580 // Static fields do not inherit constness from parents. 12581 break; 12582 } 12583 break; // End MemberExpr 12584 } else if (const ArraySubscriptExpr *ASE = 12585 dyn_cast<ArraySubscriptExpr>(E)) { 12586 E = ASE->getBase()->IgnoreParenImpCasts(); 12587 continue; 12588 } else if (const ExtVectorElementExpr *EVE = 12589 dyn_cast<ExtVectorElementExpr>(E)) { 12590 E = EVE->getBase()->IgnoreParenImpCasts(); 12591 continue; 12592 } 12593 break; 12594 } 12595 12596 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12597 // Function calls 12598 const FunctionDecl *FD = CE->getDirectCallee(); 12599 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12600 if (!DiagnosticEmitted) { 12601 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12602 << ConstFunction << FD; 12603 DiagnosticEmitted = true; 12604 } 12605 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12606 diag::note_typecheck_assign_const) 12607 << ConstFunction << FD << FD->getReturnType() 12608 << FD->getReturnTypeSourceRange(); 12609 } 12610 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12611 // Point to variable declaration. 12612 if (const ValueDecl *VD = DRE->getDecl()) { 12613 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12614 if (!DiagnosticEmitted) { 12615 S.Diag(Loc, diag::err_typecheck_assign_const) 12616 << ExprRange << ConstVariable << VD << VD->getType(); 12617 DiagnosticEmitted = true; 12618 } 12619 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12620 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12621 } 12622 } 12623 } else if (isa<CXXThisExpr>(E)) { 12624 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12626 if (MD->isConst()) { 12627 if (!DiagnosticEmitted) { 12628 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12629 << ConstMethod << MD; 12630 DiagnosticEmitted = true; 12631 } 12632 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12633 << ConstMethod << MD << MD->getSourceRange(); 12634 } 12635 } 12636 } 12637 } 12638 12639 if (DiagnosticEmitted) 12640 return; 12641 12642 // Can't determine a more specific message, so display the generic error. 12643 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12644 } 12645 12646 enum OriginalExprKind { 12647 OEK_Variable, 12648 OEK_Member, 12649 OEK_LValue 12650 }; 12651 12652 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12653 const RecordType *Ty, 12654 SourceLocation Loc, SourceRange Range, 12655 OriginalExprKind OEK, 12656 bool &DiagnosticEmitted) { 12657 std::vector<const RecordType *> RecordTypeList; 12658 RecordTypeList.push_back(Ty); 12659 unsigned NextToCheckIndex = 0; 12660 // We walk the record hierarchy breadth-first to ensure that we print 12661 // diagnostics in field nesting order. 12662 while (RecordTypeList.size() > NextToCheckIndex) { 12663 bool IsNested = NextToCheckIndex > 0; 12664 for (const FieldDecl *Field : 12665 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12666 // First, check every field for constness. 12667 QualType FieldTy = Field->getType(); 12668 if (FieldTy.isConstQualified()) { 12669 if (!DiagnosticEmitted) { 12670 S.Diag(Loc, diag::err_typecheck_assign_const) 12671 << Range << NestedConstMember << OEK << VD 12672 << IsNested << Field; 12673 DiagnosticEmitted = true; 12674 } 12675 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12676 << NestedConstMember << IsNested << Field 12677 << FieldTy << Field->getSourceRange(); 12678 } 12679 12680 // Then we append it to the list to check next in order. 12681 FieldTy = FieldTy.getCanonicalType(); 12682 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12683 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12684 RecordTypeList.push_back(FieldRecTy); 12685 } 12686 } 12687 ++NextToCheckIndex; 12688 } 12689 } 12690 12691 /// Emit an error for the case where a record we are trying to assign to has a 12692 /// const-qualified field somewhere in its hierarchy. 12693 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12694 SourceLocation Loc) { 12695 QualType Ty = E->getType(); 12696 assert(Ty->isRecordType() && "lvalue was not record?"); 12697 SourceRange Range = E->getSourceRange(); 12698 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12699 bool DiagEmitted = false; 12700 12701 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12702 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12703 Range, OEK_Member, DiagEmitted); 12704 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12705 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12706 Range, OEK_Variable, DiagEmitted); 12707 else 12708 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12709 Range, OEK_LValue, DiagEmitted); 12710 if (!DiagEmitted) 12711 DiagnoseConstAssignment(S, E, Loc); 12712 } 12713 12714 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12715 /// emit an error and return true. If so, return false. 12716 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12717 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12718 12719 S.CheckShadowingDeclModification(E, Loc); 12720 12721 SourceLocation OrigLoc = Loc; 12722 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12723 &Loc); 12724 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12725 IsLV = Expr::MLV_InvalidMessageExpression; 12726 if (IsLV == Expr::MLV_Valid) 12727 return false; 12728 12729 unsigned DiagID = 0; 12730 bool NeedType = false; 12731 switch (IsLV) { // C99 6.5.16p2 12732 case Expr::MLV_ConstQualified: 12733 // Use a specialized diagnostic when we're assigning to an object 12734 // from an enclosing function or block. 12735 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12736 if (NCCK == NCCK_Block) 12737 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12738 else 12739 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12740 break; 12741 } 12742 12743 // In ARC, use some specialized diagnostics for occasions where we 12744 // infer 'const'. These are always pseudo-strong variables. 12745 if (S.getLangOpts().ObjCAutoRefCount) { 12746 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12747 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12748 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12749 12750 // Use the normal diagnostic if it's pseudo-__strong but the 12751 // user actually wrote 'const'. 12752 if (var->isARCPseudoStrong() && 12753 (!var->getTypeSourceInfo() || 12754 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12755 // There are three pseudo-strong cases: 12756 // - self 12757 ObjCMethodDecl *method = S.getCurMethodDecl(); 12758 if (method && var == method->getSelfDecl()) { 12759 DiagID = method->isClassMethod() 12760 ? diag::err_typecheck_arc_assign_self_class_method 12761 : diag::err_typecheck_arc_assign_self; 12762 12763 // - Objective-C externally_retained attribute. 12764 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12765 isa<ParmVarDecl>(var)) { 12766 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12767 12768 // - fast enumeration variables 12769 } else { 12770 DiagID = diag::err_typecheck_arr_assign_enumeration; 12771 } 12772 12773 SourceRange Assign; 12774 if (Loc != OrigLoc) 12775 Assign = SourceRange(OrigLoc, OrigLoc); 12776 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12777 // We need to preserve the AST regardless, so migration tool 12778 // can do its job. 12779 return false; 12780 } 12781 } 12782 } 12783 12784 // If none of the special cases above are triggered, then this is a 12785 // simple const assignment. 12786 if (DiagID == 0) { 12787 DiagnoseConstAssignment(S, E, Loc); 12788 return true; 12789 } 12790 12791 break; 12792 case Expr::MLV_ConstAddrSpace: 12793 DiagnoseConstAssignment(S, E, Loc); 12794 return true; 12795 case Expr::MLV_ConstQualifiedField: 12796 DiagnoseRecursiveConstFields(S, E, Loc); 12797 return true; 12798 case Expr::MLV_ArrayType: 12799 case Expr::MLV_ArrayTemporary: 12800 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12801 NeedType = true; 12802 break; 12803 case Expr::MLV_NotObjectType: 12804 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12805 NeedType = true; 12806 break; 12807 case Expr::MLV_LValueCast: 12808 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12809 break; 12810 case Expr::MLV_Valid: 12811 llvm_unreachable("did not take early return for MLV_Valid"); 12812 case Expr::MLV_InvalidExpression: 12813 case Expr::MLV_MemberFunction: 12814 case Expr::MLV_ClassTemporary: 12815 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12816 break; 12817 case Expr::MLV_IncompleteType: 12818 case Expr::MLV_IncompleteVoidType: 12819 return S.RequireCompleteType(Loc, E->getType(), 12820 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12821 case Expr::MLV_DuplicateVectorComponents: 12822 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12823 break; 12824 case Expr::MLV_NoSetterProperty: 12825 llvm_unreachable("readonly properties should be processed differently"); 12826 case Expr::MLV_InvalidMessageExpression: 12827 DiagID = diag::err_readonly_message_assignment; 12828 break; 12829 case Expr::MLV_SubObjCPropertySetting: 12830 DiagID = diag::err_no_subobject_property_setting; 12831 break; 12832 } 12833 12834 SourceRange Assign; 12835 if (Loc != OrigLoc) 12836 Assign = SourceRange(OrigLoc, OrigLoc); 12837 if (NeedType) 12838 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12839 else 12840 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12841 return true; 12842 } 12843 12844 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12845 SourceLocation Loc, 12846 Sema &Sema) { 12847 if (Sema.inTemplateInstantiation()) 12848 return; 12849 if (Sema.isUnevaluatedContext()) 12850 return; 12851 if (Loc.isInvalid() || Loc.isMacroID()) 12852 return; 12853 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12854 return; 12855 12856 // C / C++ fields 12857 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12858 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12859 if (ML && MR) { 12860 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12861 return; 12862 const ValueDecl *LHSDecl = 12863 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12864 const ValueDecl *RHSDecl = 12865 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12866 if (LHSDecl != RHSDecl) 12867 return; 12868 if (LHSDecl->getType().isVolatileQualified()) 12869 return; 12870 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12871 if (RefTy->getPointeeType().isVolatileQualified()) 12872 return; 12873 12874 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12875 } 12876 12877 // Objective-C instance variables 12878 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12879 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12880 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12881 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12882 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12883 if (RL && RR && RL->getDecl() == RR->getDecl()) 12884 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12885 } 12886 } 12887 12888 // C99 6.5.16.1 12889 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12890 SourceLocation Loc, 12891 QualType CompoundType) { 12892 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12893 12894 // Verify that LHS is a modifiable lvalue, and emit error if not. 12895 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12896 return QualType(); 12897 12898 QualType LHSType = LHSExpr->getType(); 12899 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12900 CompoundType; 12901 // OpenCL v1.2 s6.1.1.1 p2: 12902 // The half data type can only be used to declare a pointer to a buffer that 12903 // contains half values 12904 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12905 LHSType->isHalfType()) { 12906 Diag(Loc, diag::err_opencl_half_load_store) << 1 12907 << LHSType.getUnqualifiedType(); 12908 return QualType(); 12909 } 12910 12911 AssignConvertType ConvTy; 12912 if (CompoundType.isNull()) { 12913 Expr *RHSCheck = RHS.get(); 12914 12915 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12916 12917 QualType LHSTy(LHSType); 12918 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12919 if (RHS.isInvalid()) 12920 return QualType(); 12921 // Special case of NSObject attributes on c-style pointer types. 12922 if (ConvTy == IncompatiblePointer && 12923 ((Context.isObjCNSObjectType(LHSType) && 12924 RHSType->isObjCObjectPointerType()) || 12925 (Context.isObjCNSObjectType(RHSType) && 12926 LHSType->isObjCObjectPointerType()))) 12927 ConvTy = Compatible; 12928 12929 if (ConvTy == Compatible && 12930 LHSType->isObjCObjectType()) 12931 Diag(Loc, diag::err_objc_object_assignment) 12932 << LHSType; 12933 12934 // If the RHS is a unary plus or minus, check to see if they = and + are 12935 // right next to each other. If so, the user may have typo'd "x =+ 4" 12936 // instead of "x += 4". 12937 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12938 RHSCheck = ICE->getSubExpr(); 12939 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12940 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12941 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12942 // Only if the two operators are exactly adjacent. 12943 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12944 // And there is a space or other character before the subexpr of the 12945 // unary +/-. We don't want to warn on "x=-1". 12946 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12947 UO->getSubExpr()->getBeginLoc().isFileID()) { 12948 Diag(Loc, diag::warn_not_compound_assign) 12949 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12950 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12951 } 12952 } 12953 12954 if (ConvTy == Compatible) { 12955 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12956 // Warn about retain cycles where a block captures the LHS, but 12957 // not if the LHS is a simple variable into which the block is 12958 // being stored...unless that variable can be captured by reference! 12959 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12960 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12961 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12962 checkRetainCycles(LHSExpr, RHS.get()); 12963 } 12964 12965 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12966 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12967 // It is safe to assign a weak reference into a strong variable. 12968 // Although this code can still have problems: 12969 // id x = self.weakProp; 12970 // id y = self.weakProp; 12971 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12972 // paths through the function. This should be revisited if 12973 // -Wrepeated-use-of-weak is made flow-sensitive. 12974 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12975 // variable, which will be valid for the current autorelease scope. 12976 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12977 RHS.get()->getBeginLoc())) 12978 getCurFunction()->markSafeWeakUse(RHS.get()); 12979 12980 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12981 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12982 } 12983 } 12984 } else { 12985 // Compound assignment "x += y" 12986 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12987 } 12988 12989 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12990 RHS.get(), AA_Assigning)) 12991 return QualType(); 12992 12993 CheckForNullPointerDereference(*this, LHSExpr); 12994 12995 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12996 if (CompoundType.isNull()) { 12997 // C++2a [expr.ass]p5: 12998 // A simple-assignment whose left operand is of a volatile-qualified 12999 // type is deprecated unless the assignment is either a discarded-value 13000 // expression or an unevaluated operand 13001 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13002 } else { 13003 // C++2a [expr.ass]p6: 13004 // [Compound-assignment] expressions are deprecated if E1 has 13005 // volatile-qualified type 13006 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13007 } 13008 } 13009 13010 // C99 6.5.16p3: The type of an assignment expression is the type of the 13011 // left operand unless the left operand has qualified type, in which case 13012 // it is the unqualified version of the type of the left operand. 13013 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13014 // is converted to the type of the assignment expression (above). 13015 // C++ 5.17p1: the type of the assignment expression is that of its left 13016 // operand. 13017 return (getLangOpts().CPlusPlus 13018 ? LHSType : LHSType.getUnqualifiedType()); 13019 } 13020 13021 // Only ignore explicit casts to void. 13022 static bool IgnoreCommaOperand(const Expr *E) { 13023 E = E->IgnoreParens(); 13024 13025 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13026 if (CE->getCastKind() == CK_ToVoid) { 13027 return true; 13028 } 13029 13030 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13031 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13032 CE->getSubExpr()->getType()->isDependentType()) { 13033 return true; 13034 } 13035 } 13036 13037 return false; 13038 } 13039 13040 // Look for instances where it is likely the comma operator is confused with 13041 // another operator. There is an explicit list of acceptable expressions for 13042 // the left hand side of the comma operator, otherwise emit a warning. 13043 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13044 // No warnings in macros 13045 if (Loc.isMacroID()) 13046 return; 13047 13048 // Don't warn in template instantiations. 13049 if (inTemplateInstantiation()) 13050 return; 13051 13052 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13053 // instead, skip more than needed, then call back into here with the 13054 // CommaVisitor in SemaStmt.cpp. 13055 // The listed locations are the initialization and increment portions 13056 // of a for loop. The additional checks are on the condition of 13057 // if statements, do/while loops, and for loops. 13058 // Differences in scope flags for C89 mode requires the extra logic. 13059 const unsigned ForIncrementFlags = 13060 getLangOpts().C99 || getLangOpts().CPlusPlus 13061 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13062 : Scope::ContinueScope | Scope::BreakScope; 13063 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13064 const unsigned ScopeFlags = getCurScope()->getFlags(); 13065 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13066 (ScopeFlags & ForInitFlags) == ForInitFlags) 13067 return; 13068 13069 // If there are multiple comma operators used together, get the RHS of the 13070 // of the comma operator as the LHS. 13071 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13072 if (BO->getOpcode() != BO_Comma) 13073 break; 13074 LHS = BO->getRHS(); 13075 } 13076 13077 // Only allow some expressions on LHS to not warn. 13078 if (IgnoreCommaOperand(LHS)) 13079 return; 13080 13081 Diag(Loc, diag::warn_comma_operator); 13082 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13083 << LHS->getSourceRange() 13084 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13085 LangOpts.CPlusPlus ? "static_cast<void>(" 13086 : "(void)(") 13087 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13088 ")"); 13089 } 13090 13091 // C99 6.5.17 13092 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13093 SourceLocation Loc) { 13094 LHS = S.CheckPlaceholderExpr(LHS.get()); 13095 RHS = S.CheckPlaceholderExpr(RHS.get()); 13096 if (LHS.isInvalid() || RHS.isInvalid()) 13097 return QualType(); 13098 13099 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13100 // operands, but not unary promotions. 13101 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13102 13103 // So we treat the LHS as a ignored value, and in C++ we allow the 13104 // containing site to determine what should be done with the RHS. 13105 LHS = S.IgnoredValueConversions(LHS.get()); 13106 if (LHS.isInvalid()) 13107 return QualType(); 13108 13109 S.DiagnoseUnusedExprResult(LHS.get()); 13110 13111 if (!S.getLangOpts().CPlusPlus) { 13112 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13113 if (RHS.isInvalid()) 13114 return QualType(); 13115 if (!RHS.get()->getType()->isVoidType()) 13116 S.RequireCompleteType(Loc, RHS.get()->getType(), 13117 diag::err_incomplete_type); 13118 } 13119 13120 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13121 S.DiagnoseCommaOperator(LHS.get(), Loc); 13122 13123 return RHS.get()->getType(); 13124 } 13125 13126 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13127 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13128 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13129 ExprValueKind &VK, 13130 ExprObjectKind &OK, 13131 SourceLocation OpLoc, 13132 bool IsInc, bool IsPrefix) { 13133 if (Op->isTypeDependent()) 13134 return S.Context.DependentTy; 13135 13136 QualType ResType = Op->getType(); 13137 // Atomic types can be used for increment / decrement where the non-atomic 13138 // versions can, so ignore the _Atomic() specifier for the purpose of 13139 // checking. 13140 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13141 ResType = ResAtomicType->getValueType(); 13142 13143 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13144 13145 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13146 // Decrement of bool is not allowed. 13147 if (!IsInc) { 13148 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13149 return QualType(); 13150 } 13151 // Increment of bool sets it to true, but is deprecated. 13152 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13153 : diag::warn_increment_bool) 13154 << Op->getSourceRange(); 13155 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13156 // Error on enum increments and decrements in C++ mode 13157 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13158 return QualType(); 13159 } else if (ResType->isRealType()) { 13160 // OK! 13161 } else if (ResType->isPointerType()) { 13162 // C99 6.5.2.4p2, 6.5.6p2 13163 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13164 return QualType(); 13165 } else if (ResType->isObjCObjectPointerType()) { 13166 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13167 // Otherwise, we just need a complete type. 13168 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13169 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13170 return QualType(); 13171 } else if (ResType->isAnyComplexType()) { 13172 // C99 does not support ++/-- on complex types, we allow as an extension. 13173 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13174 << ResType << Op->getSourceRange(); 13175 } else if (ResType->isPlaceholderType()) { 13176 ExprResult PR = S.CheckPlaceholderExpr(Op); 13177 if (PR.isInvalid()) return QualType(); 13178 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13179 IsInc, IsPrefix); 13180 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13181 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13182 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13183 (ResType->castAs<VectorType>()->getVectorKind() != 13184 VectorType::AltiVecBool)) { 13185 // The z vector extensions allow ++ and -- for non-bool vectors. 13186 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13187 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13188 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13189 } else { 13190 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13191 << ResType << int(IsInc) << Op->getSourceRange(); 13192 return QualType(); 13193 } 13194 // At this point, we know we have a real, complex or pointer type. 13195 // Now make sure the operand is a modifiable lvalue. 13196 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13197 return QualType(); 13198 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13199 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13200 // An operand with volatile-qualified type is deprecated 13201 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13202 << IsInc << ResType; 13203 } 13204 // In C++, a prefix increment is the same type as the operand. Otherwise 13205 // (in C or with postfix), the increment is the unqualified type of the 13206 // operand. 13207 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13208 VK = VK_LValue; 13209 OK = Op->getObjectKind(); 13210 return ResType; 13211 } else { 13212 VK = VK_RValue; 13213 return ResType.getUnqualifiedType(); 13214 } 13215 } 13216 13217 13218 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13219 /// This routine allows us to typecheck complex/recursive expressions 13220 /// where the declaration is needed for type checking. We only need to 13221 /// handle cases when the expression references a function designator 13222 /// or is an lvalue. Here are some examples: 13223 /// - &(x) => x 13224 /// - &*****f => f for f a function designator. 13225 /// - &s.xx => s 13226 /// - &s.zz[1].yy -> s, if zz is an array 13227 /// - *(x + 1) -> x, if x is an array 13228 /// - &"123"[2] -> 0 13229 /// - & __real__ x -> x 13230 /// 13231 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13232 /// members. 13233 static ValueDecl *getPrimaryDecl(Expr *E) { 13234 switch (E->getStmtClass()) { 13235 case Stmt::DeclRefExprClass: 13236 return cast<DeclRefExpr>(E)->getDecl(); 13237 case Stmt::MemberExprClass: 13238 // If this is an arrow operator, the address is an offset from 13239 // the base's value, so the object the base refers to is 13240 // irrelevant. 13241 if (cast<MemberExpr>(E)->isArrow()) 13242 return nullptr; 13243 // Otherwise, the expression refers to a part of the base 13244 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13245 case Stmt::ArraySubscriptExprClass: { 13246 // FIXME: This code shouldn't be necessary! We should catch the implicit 13247 // promotion of register arrays earlier. 13248 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13249 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13250 if (ICE->getSubExpr()->getType()->isArrayType()) 13251 return getPrimaryDecl(ICE->getSubExpr()); 13252 } 13253 return nullptr; 13254 } 13255 case Stmt::UnaryOperatorClass: { 13256 UnaryOperator *UO = cast<UnaryOperator>(E); 13257 13258 switch(UO->getOpcode()) { 13259 case UO_Real: 13260 case UO_Imag: 13261 case UO_Extension: 13262 return getPrimaryDecl(UO->getSubExpr()); 13263 default: 13264 return nullptr; 13265 } 13266 } 13267 case Stmt::ParenExprClass: 13268 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13269 case Stmt::ImplicitCastExprClass: 13270 // If the result of an implicit cast is an l-value, we care about 13271 // the sub-expression; otherwise, the result here doesn't matter. 13272 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13273 case Stmt::CXXUuidofExprClass: 13274 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13275 default: 13276 return nullptr; 13277 } 13278 } 13279 13280 namespace { 13281 enum { 13282 AO_Bit_Field = 0, 13283 AO_Vector_Element = 1, 13284 AO_Property_Expansion = 2, 13285 AO_Register_Variable = 3, 13286 AO_Matrix_Element = 4, 13287 AO_No_Error = 5 13288 }; 13289 } 13290 /// Diagnose invalid operand for address of operations. 13291 /// 13292 /// \param Type The type of operand which cannot have its address taken. 13293 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13294 Expr *E, unsigned Type) { 13295 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13296 } 13297 13298 /// CheckAddressOfOperand - The operand of & must be either a function 13299 /// designator or an lvalue designating an object. If it is an lvalue, the 13300 /// object cannot be declared with storage class register or be a bit field. 13301 /// Note: The usual conversions are *not* applied to the operand of the & 13302 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13303 /// In C++, the operand might be an overloaded function name, in which case 13304 /// we allow the '&' but retain the overloaded-function type. 13305 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13306 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13307 if (PTy->getKind() == BuiltinType::Overload) { 13308 Expr *E = OrigOp.get()->IgnoreParens(); 13309 if (!isa<OverloadExpr>(E)) { 13310 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13311 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13312 << OrigOp.get()->getSourceRange(); 13313 return QualType(); 13314 } 13315 13316 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13317 if (isa<UnresolvedMemberExpr>(Ovl)) 13318 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13319 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13320 << OrigOp.get()->getSourceRange(); 13321 return QualType(); 13322 } 13323 13324 return Context.OverloadTy; 13325 } 13326 13327 if (PTy->getKind() == BuiltinType::UnknownAny) 13328 return Context.UnknownAnyTy; 13329 13330 if (PTy->getKind() == BuiltinType::BoundMember) { 13331 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13332 << OrigOp.get()->getSourceRange(); 13333 return QualType(); 13334 } 13335 13336 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13337 if (OrigOp.isInvalid()) return QualType(); 13338 } 13339 13340 if (OrigOp.get()->isTypeDependent()) 13341 return Context.DependentTy; 13342 13343 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13344 13345 // Make sure to ignore parentheses in subsequent checks 13346 Expr *op = OrigOp.get()->IgnoreParens(); 13347 13348 // In OpenCL captures for blocks called as lambda functions 13349 // are located in the private address space. Blocks used in 13350 // enqueue_kernel can be located in a different address space 13351 // depending on a vendor implementation. Thus preventing 13352 // taking an address of the capture to avoid invalid AS casts. 13353 if (LangOpts.OpenCL) { 13354 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13355 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13356 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13357 return QualType(); 13358 } 13359 } 13360 13361 if (getLangOpts().C99) { 13362 // Implement C99-only parts of addressof rules. 13363 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13364 if (uOp->getOpcode() == UO_Deref) 13365 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13366 // (assuming the deref expression is valid). 13367 return uOp->getSubExpr()->getType(); 13368 } 13369 // Technically, there should be a check for array subscript 13370 // expressions here, but the result of one is always an lvalue anyway. 13371 } 13372 ValueDecl *dcl = getPrimaryDecl(op); 13373 13374 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13375 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13376 op->getBeginLoc())) 13377 return QualType(); 13378 13379 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13380 unsigned AddressOfError = AO_No_Error; 13381 13382 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13383 bool sfinae = (bool)isSFINAEContext(); 13384 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13385 : diag::ext_typecheck_addrof_temporary) 13386 << op->getType() << op->getSourceRange(); 13387 if (sfinae) 13388 return QualType(); 13389 // Materialize the temporary as an lvalue so that we can take its address. 13390 OrigOp = op = 13391 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13392 } else if (isa<ObjCSelectorExpr>(op)) { 13393 return Context.getPointerType(op->getType()); 13394 } else if (lval == Expr::LV_MemberFunction) { 13395 // If it's an instance method, make a member pointer. 13396 // The expression must have exactly the form &A::foo. 13397 13398 // If the underlying expression isn't a decl ref, give up. 13399 if (!isa<DeclRefExpr>(op)) { 13400 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13401 << OrigOp.get()->getSourceRange(); 13402 return QualType(); 13403 } 13404 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13405 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13406 13407 // The id-expression was parenthesized. 13408 if (OrigOp.get() != DRE) { 13409 Diag(OpLoc, diag::err_parens_pointer_member_function) 13410 << OrigOp.get()->getSourceRange(); 13411 13412 // The method was named without a qualifier. 13413 } else if (!DRE->getQualifier()) { 13414 if (MD->getParent()->getName().empty()) 13415 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13416 << op->getSourceRange(); 13417 else { 13418 SmallString<32> Str; 13419 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13420 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13421 << op->getSourceRange() 13422 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13423 } 13424 } 13425 13426 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13427 if (isa<CXXDestructorDecl>(MD)) 13428 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13429 13430 QualType MPTy = Context.getMemberPointerType( 13431 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13432 // Under the MS ABI, lock down the inheritance model now. 13433 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13434 (void)isCompleteType(OpLoc, MPTy); 13435 return MPTy; 13436 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13437 // C99 6.5.3.2p1 13438 // The operand must be either an l-value or a function designator 13439 if (!op->getType()->isFunctionType()) { 13440 // Use a special diagnostic for loads from property references. 13441 if (isa<PseudoObjectExpr>(op)) { 13442 AddressOfError = AO_Property_Expansion; 13443 } else { 13444 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13445 << op->getType() << op->getSourceRange(); 13446 return QualType(); 13447 } 13448 } 13449 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13450 // The operand cannot be a bit-field 13451 AddressOfError = AO_Bit_Field; 13452 } else if (op->getObjectKind() == OK_VectorComponent) { 13453 // The operand cannot be an element of a vector 13454 AddressOfError = AO_Vector_Element; 13455 } else if (op->getObjectKind() == OK_MatrixComponent) { 13456 // The operand cannot be an element of a matrix. 13457 AddressOfError = AO_Matrix_Element; 13458 } else if (dcl) { // C99 6.5.3.2p1 13459 // We have an lvalue with a decl. Make sure the decl is not declared 13460 // with the register storage-class specifier. 13461 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13462 // in C++ it is not error to take address of a register 13463 // variable (c++03 7.1.1P3) 13464 if (vd->getStorageClass() == SC_Register && 13465 !getLangOpts().CPlusPlus) { 13466 AddressOfError = AO_Register_Variable; 13467 } 13468 } else if (isa<MSPropertyDecl>(dcl)) { 13469 AddressOfError = AO_Property_Expansion; 13470 } else if (isa<FunctionTemplateDecl>(dcl)) { 13471 return Context.OverloadTy; 13472 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13473 // Okay: we can take the address of a field. 13474 // Could be a pointer to member, though, if there is an explicit 13475 // scope qualifier for the class. 13476 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13477 DeclContext *Ctx = dcl->getDeclContext(); 13478 if (Ctx && Ctx->isRecord()) { 13479 if (dcl->getType()->isReferenceType()) { 13480 Diag(OpLoc, 13481 diag::err_cannot_form_pointer_to_member_of_reference_type) 13482 << dcl->getDeclName() << dcl->getType(); 13483 return QualType(); 13484 } 13485 13486 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13487 Ctx = Ctx->getParent(); 13488 13489 QualType MPTy = Context.getMemberPointerType( 13490 op->getType(), 13491 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13492 // Under the MS ABI, lock down the inheritance model now. 13493 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13494 (void)isCompleteType(OpLoc, MPTy); 13495 return MPTy; 13496 } 13497 } 13498 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13499 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13500 llvm_unreachable("Unknown/unexpected decl type"); 13501 } 13502 13503 if (AddressOfError != AO_No_Error) { 13504 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13505 return QualType(); 13506 } 13507 13508 if (lval == Expr::LV_IncompleteVoidType) { 13509 // Taking the address of a void variable is technically illegal, but we 13510 // allow it in cases which are otherwise valid. 13511 // Example: "extern void x; void* y = &x;". 13512 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13513 } 13514 13515 // If the operand has type "type", the result has type "pointer to type". 13516 if (op->getType()->isObjCObjectType()) 13517 return Context.getObjCObjectPointerType(op->getType()); 13518 13519 CheckAddressOfPackedMember(op); 13520 13521 return Context.getPointerType(op->getType()); 13522 } 13523 13524 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13525 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13526 if (!DRE) 13527 return; 13528 const Decl *D = DRE->getDecl(); 13529 if (!D) 13530 return; 13531 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13532 if (!Param) 13533 return; 13534 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13535 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13536 return; 13537 if (FunctionScopeInfo *FD = S.getCurFunction()) 13538 if (!FD->ModifiedNonNullParams.count(Param)) 13539 FD->ModifiedNonNullParams.insert(Param); 13540 } 13541 13542 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13543 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13544 SourceLocation OpLoc) { 13545 if (Op->isTypeDependent()) 13546 return S.Context.DependentTy; 13547 13548 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13549 if (ConvResult.isInvalid()) 13550 return QualType(); 13551 Op = ConvResult.get(); 13552 QualType OpTy = Op->getType(); 13553 QualType Result; 13554 13555 if (isa<CXXReinterpretCastExpr>(Op)) { 13556 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13557 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13558 Op->getSourceRange()); 13559 } 13560 13561 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13562 { 13563 Result = PT->getPointeeType(); 13564 } 13565 else if (const ObjCObjectPointerType *OPT = 13566 OpTy->getAs<ObjCObjectPointerType>()) 13567 Result = OPT->getPointeeType(); 13568 else { 13569 ExprResult PR = S.CheckPlaceholderExpr(Op); 13570 if (PR.isInvalid()) return QualType(); 13571 if (PR.get() != Op) 13572 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13573 } 13574 13575 if (Result.isNull()) { 13576 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13577 << OpTy << Op->getSourceRange(); 13578 return QualType(); 13579 } 13580 13581 // Note that per both C89 and C99, indirection is always legal, even if Result 13582 // is an incomplete type or void. It would be possible to warn about 13583 // dereferencing a void pointer, but it's completely well-defined, and such a 13584 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13585 // for pointers to 'void' but is fine for any other pointer type: 13586 // 13587 // C++ [expr.unary.op]p1: 13588 // [...] the expression to which [the unary * operator] is applied shall 13589 // be a pointer to an object type, or a pointer to a function type 13590 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13591 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13592 << OpTy << Op->getSourceRange(); 13593 13594 // Dereferences are usually l-values... 13595 VK = VK_LValue; 13596 13597 // ...except that certain expressions are never l-values in C. 13598 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13599 VK = VK_RValue; 13600 13601 return Result; 13602 } 13603 13604 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13605 BinaryOperatorKind Opc; 13606 switch (Kind) { 13607 default: llvm_unreachable("Unknown binop!"); 13608 case tok::periodstar: Opc = BO_PtrMemD; break; 13609 case tok::arrowstar: Opc = BO_PtrMemI; break; 13610 case tok::star: Opc = BO_Mul; break; 13611 case tok::slash: Opc = BO_Div; break; 13612 case tok::percent: Opc = BO_Rem; break; 13613 case tok::plus: Opc = BO_Add; break; 13614 case tok::minus: Opc = BO_Sub; break; 13615 case tok::lessless: Opc = BO_Shl; break; 13616 case tok::greatergreater: Opc = BO_Shr; break; 13617 case tok::lessequal: Opc = BO_LE; break; 13618 case tok::less: Opc = BO_LT; break; 13619 case tok::greaterequal: Opc = BO_GE; break; 13620 case tok::greater: Opc = BO_GT; break; 13621 case tok::exclaimequal: Opc = BO_NE; break; 13622 case tok::equalequal: Opc = BO_EQ; break; 13623 case tok::spaceship: Opc = BO_Cmp; break; 13624 case tok::amp: Opc = BO_And; break; 13625 case tok::caret: Opc = BO_Xor; break; 13626 case tok::pipe: Opc = BO_Or; break; 13627 case tok::ampamp: Opc = BO_LAnd; break; 13628 case tok::pipepipe: Opc = BO_LOr; break; 13629 case tok::equal: Opc = BO_Assign; break; 13630 case tok::starequal: Opc = BO_MulAssign; break; 13631 case tok::slashequal: Opc = BO_DivAssign; break; 13632 case tok::percentequal: Opc = BO_RemAssign; break; 13633 case tok::plusequal: Opc = BO_AddAssign; break; 13634 case tok::minusequal: Opc = BO_SubAssign; break; 13635 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13636 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13637 case tok::ampequal: Opc = BO_AndAssign; break; 13638 case tok::caretequal: Opc = BO_XorAssign; break; 13639 case tok::pipeequal: Opc = BO_OrAssign; break; 13640 case tok::comma: Opc = BO_Comma; break; 13641 } 13642 return Opc; 13643 } 13644 13645 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13646 tok::TokenKind Kind) { 13647 UnaryOperatorKind Opc; 13648 switch (Kind) { 13649 default: llvm_unreachable("Unknown unary op!"); 13650 case tok::plusplus: Opc = UO_PreInc; break; 13651 case tok::minusminus: Opc = UO_PreDec; break; 13652 case tok::amp: Opc = UO_AddrOf; break; 13653 case tok::star: Opc = UO_Deref; break; 13654 case tok::plus: Opc = UO_Plus; break; 13655 case tok::minus: Opc = UO_Minus; break; 13656 case tok::tilde: Opc = UO_Not; break; 13657 case tok::exclaim: Opc = UO_LNot; break; 13658 case tok::kw___real: Opc = UO_Real; break; 13659 case tok::kw___imag: Opc = UO_Imag; break; 13660 case tok::kw___extension__: Opc = UO_Extension; break; 13661 } 13662 return Opc; 13663 } 13664 13665 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13666 /// This warning suppressed in the event of macro expansions. 13667 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13668 SourceLocation OpLoc, bool IsBuiltin) { 13669 if (S.inTemplateInstantiation()) 13670 return; 13671 if (S.isUnevaluatedContext()) 13672 return; 13673 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13674 return; 13675 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13676 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13677 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13678 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13679 if (!LHSDeclRef || !RHSDeclRef || 13680 LHSDeclRef->getLocation().isMacroID() || 13681 RHSDeclRef->getLocation().isMacroID()) 13682 return; 13683 const ValueDecl *LHSDecl = 13684 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13685 const ValueDecl *RHSDecl = 13686 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13687 if (LHSDecl != RHSDecl) 13688 return; 13689 if (LHSDecl->getType().isVolatileQualified()) 13690 return; 13691 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13692 if (RefTy->getPointeeType().isVolatileQualified()) 13693 return; 13694 13695 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13696 : diag::warn_self_assignment_overloaded) 13697 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13698 << RHSExpr->getSourceRange(); 13699 } 13700 13701 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13702 /// is usually indicative of introspection within the Objective-C pointer. 13703 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13704 SourceLocation OpLoc) { 13705 if (!S.getLangOpts().ObjC) 13706 return; 13707 13708 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13709 const Expr *LHS = L.get(); 13710 const Expr *RHS = R.get(); 13711 13712 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13713 ObjCPointerExpr = LHS; 13714 OtherExpr = RHS; 13715 } 13716 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13717 ObjCPointerExpr = RHS; 13718 OtherExpr = LHS; 13719 } 13720 13721 // This warning is deliberately made very specific to reduce false 13722 // positives with logic that uses '&' for hashing. This logic mainly 13723 // looks for code trying to introspect into tagged pointers, which 13724 // code should generally never do. 13725 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13726 unsigned Diag = diag::warn_objc_pointer_masking; 13727 // Determine if we are introspecting the result of performSelectorXXX. 13728 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13729 // Special case messages to -performSelector and friends, which 13730 // can return non-pointer values boxed in a pointer value. 13731 // Some clients may wish to silence warnings in this subcase. 13732 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13733 Selector S = ME->getSelector(); 13734 StringRef SelArg0 = S.getNameForSlot(0); 13735 if (SelArg0.startswith("performSelector")) 13736 Diag = diag::warn_objc_pointer_masking_performSelector; 13737 } 13738 13739 S.Diag(OpLoc, Diag) 13740 << ObjCPointerExpr->getSourceRange(); 13741 } 13742 } 13743 13744 static NamedDecl *getDeclFromExpr(Expr *E) { 13745 if (!E) 13746 return nullptr; 13747 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13748 return DRE->getDecl(); 13749 if (auto *ME = dyn_cast<MemberExpr>(E)) 13750 return ME->getMemberDecl(); 13751 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13752 return IRE->getDecl(); 13753 return nullptr; 13754 } 13755 13756 // This helper function promotes a binary operator's operands (which are of a 13757 // half vector type) to a vector of floats and then truncates the result to 13758 // a vector of either half or short. 13759 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13760 BinaryOperatorKind Opc, QualType ResultTy, 13761 ExprValueKind VK, ExprObjectKind OK, 13762 bool IsCompAssign, SourceLocation OpLoc, 13763 FPOptionsOverride FPFeatures) { 13764 auto &Context = S.getASTContext(); 13765 assert((isVector(ResultTy, Context.HalfTy) || 13766 isVector(ResultTy, Context.ShortTy)) && 13767 "Result must be a vector of half or short"); 13768 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13769 isVector(RHS.get()->getType(), Context.HalfTy) && 13770 "both operands expected to be a half vector"); 13771 13772 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13773 QualType BinOpResTy = RHS.get()->getType(); 13774 13775 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13776 // change BinOpResTy to a vector of ints. 13777 if (isVector(ResultTy, Context.ShortTy)) 13778 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13779 13780 if (IsCompAssign) 13781 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13782 ResultTy, VK, OK, OpLoc, FPFeatures, 13783 BinOpResTy, BinOpResTy); 13784 13785 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13786 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13787 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13788 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13789 } 13790 13791 static std::pair<ExprResult, ExprResult> 13792 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13793 Expr *RHSExpr) { 13794 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13795 if (!S.Context.isDependenceAllowed()) { 13796 // C cannot handle TypoExpr nodes on either side of a binop because it 13797 // doesn't handle dependent types properly, so make sure any TypoExprs have 13798 // been dealt with before checking the operands. 13799 LHS = S.CorrectDelayedTyposInExpr(LHS); 13800 RHS = S.CorrectDelayedTyposInExpr( 13801 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13802 [Opc, LHS](Expr *E) { 13803 if (Opc != BO_Assign) 13804 return ExprResult(E); 13805 // Avoid correcting the RHS to the same Expr as the LHS. 13806 Decl *D = getDeclFromExpr(E); 13807 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13808 }); 13809 } 13810 return std::make_pair(LHS, RHS); 13811 } 13812 13813 /// Returns true if conversion between vectors of halfs and vectors of floats 13814 /// is needed. 13815 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13816 Expr *E0, Expr *E1 = nullptr) { 13817 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13818 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13819 return false; 13820 13821 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13822 QualType Ty = E->IgnoreImplicit()->getType(); 13823 13824 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13825 // to vectors of floats. Although the element type of the vectors is __fp16, 13826 // the vectors shouldn't be treated as storage-only types. See the 13827 // discussion here: https://reviews.llvm.org/rG825235c140e7 13828 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13829 if (VT->getVectorKind() == VectorType::NeonVector) 13830 return false; 13831 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13832 } 13833 return false; 13834 }; 13835 13836 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13837 } 13838 13839 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13840 /// operator @p Opc at location @c TokLoc. This routine only supports 13841 /// built-in operations; ActOnBinOp handles overloaded operators. 13842 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13843 BinaryOperatorKind Opc, 13844 Expr *LHSExpr, Expr *RHSExpr) { 13845 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13846 // The syntax only allows initializer lists on the RHS of assignment, 13847 // so we don't need to worry about accepting invalid code for 13848 // non-assignment operators. 13849 // C++11 5.17p9: 13850 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13851 // of x = {} is x = T(). 13852 InitializationKind Kind = InitializationKind::CreateDirectList( 13853 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13854 InitializedEntity Entity = 13855 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13856 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13857 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13858 if (Init.isInvalid()) 13859 return Init; 13860 RHSExpr = Init.get(); 13861 } 13862 13863 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13864 QualType ResultTy; // Result type of the binary operator. 13865 // The following two variables are used for compound assignment operators 13866 QualType CompLHSTy; // Type of LHS after promotions for computation 13867 QualType CompResultTy; // Type of computation result 13868 ExprValueKind VK = VK_RValue; 13869 ExprObjectKind OK = OK_Ordinary; 13870 bool ConvertHalfVec = false; 13871 13872 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13873 if (!LHS.isUsable() || !RHS.isUsable()) 13874 return ExprError(); 13875 13876 if (getLangOpts().OpenCL) { 13877 QualType LHSTy = LHSExpr->getType(); 13878 QualType RHSTy = RHSExpr->getType(); 13879 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13880 // the ATOMIC_VAR_INIT macro. 13881 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13882 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13883 if (BO_Assign == Opc) 13884 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13885 else 13886 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13887 return ExprError(); 13888 } 13889 13890 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13891 // only with a builtin functions and therefore should be disallowed here. 13892 if (LHSTy->isImageType() || RHSTy->isImageType() || 13893 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13894 LHSTy->isPipeType() || RHSTy->isPipeType() || 13895 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13896 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13897 return ExprError(); 13898 } 13899 } 13900 13901 switch (Opc) { 13902 case BO_Assign: 13903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13904 if (getLangOpts().CPlusPlus && 13905 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13906 VK = LHS.get()->getValueKind(); 13907 OK = LHS.get()->getObjectKind(); 13908 } 13909 if (!ResultTy.isNull()) { 13910 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13911 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13912 13913 // Avoid copying a block to the heap if the block is assigned to a local 13914 // auto variable that is declared in the same scope as the block. This 13915 // optimization is unsafe if the local variable is declared in an outer 13916 // scope. For example: 13917 // 13918 // BlockTy b; 13919 // { 13920 // b = ^{...}; 13921 // } 13922 // // It is unsafe to invoke the block here if it wasn't copied to the 13923 // // heap. 13924 // b(); 13925 13926 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13927 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13928 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13929 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13930 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13931 13932 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13933 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13934 NTCUC_Assignment, NTCUK_Copy); 13935 } 13936 RecordModifiableNonNullParam(*this, LHS.get()); 13937 break; 13938 case BO_PtrMemD: 13939 case BO_PtrMemI: 13940 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13941 Opc == BO_PtrMemI); 13942 break; 13943 case BO_Mul: 13944 case BO_Div: 13945 ConvertHalfVec = true; 13946 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13947 Opc == BO_Div); 13948 break; 13949 case BO_Rem: 13950 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13951 break; 13952 case BO_Add: 13953 ConvertHalfVec = true; 13954 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13955 break; 13956 case BO_Sub: 13957 ConvertHalfVec = true; 13958 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13959 break; 13960 case BO_Shl: 13961 case BO_Shr: 13962 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13963 break; 13964 case BO_LE: 13965 case BO_LT: 13966 case BO_GE: 13967 case BO_GT: 13968 ConvertHalfVec = true; 13969 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13970 break; 13971 case BO_EQ: 13972 case BO_NE: 13973 ConvertHalfVec = true; 13974 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13975 break; 13976 case BO_Cmp: 13977 ConvertHalfVec = true; 13978 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13979 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13980 break; 13981 case BO_And: 13982 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13983 LLVM_FALLTHROUGH; 13984 case BO_Xor: 13985 case BO_Or: 13986 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13987 break; 13988 case BO_LAnd: 13989 case BO_LOr: 13990 ConvertHalfVec = true; 13991 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13992 break; 13993 case BO_MulAssign: 13994 case BO_DivAssign: 13995 ConvertHalfVec = true; 13996 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13997 Opc == BO_DivAssign); 13998 CompLHSTy = CompResultTy; 13999 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14000 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14001 break; 14002 case BO_RemAssign: 14003 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14004 CompLHSTy = CompResultTy; 14005 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14006 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14007 break; 14008 case BO_AddAssign: 14009 ConvertHalfVec = true; 14010 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14011 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14012 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14013 break; 14014 case BO_SubAssign: 14015 ConvertHalfVec = true; 14016 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14017 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14018 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14019 break; 14020 case BO_ShlAssign: 14021 case BO_ShrAssign: 14022 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14023 CompLHSTy = CompResultTy; 14024 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14025 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14026 break; 14027 case BO_AndAssign: 14028 case BO_OrAssign: // fallthrough 14029 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14030 LLVM_FALLTHROUGH; 14031 case BO_XorAssign: 14032 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14033 CompLHSTy = CompResultTy; 14034 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14035 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14036 break; 14037 case BO_Comma: 14038 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14039 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14040 VK = RHS.get()->getValueKind(); 14041 OK = RHS.get()->getObjectKind(); 14042 } 14043 break; 14044 } 14045 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14046 return ExprError(); 14047 14048 // Some of the binary operations require promoting operands of half vector to 14049 // float vectors and truncating the result back to half vector. For now, we do 14050 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14051 // arm64). 14052 assert( 14053 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14054 isVector(LHS.get()->getType(), Context.HalfTy)) && 14055 "both sides are half vectors or neither sides are"); 14056 ConvertHalfVec = 14057 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14058 14059 // Check for array bounds violations for both sides of the BinaryOperator 14060 CheckArrayAccess(LHS.get()); 14061 CheckArrayAccess(RHS.get()); 14062 14063 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14064 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14065 &Context.Idents.get("object_setClass"), 14066 SourceLocation(), LookupOrdinaryName); 14067 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14068 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14069 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14070 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14071 "object_setClass(") 14072 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14073 ",") 14074 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14075 } 14076 else 14077 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14078 } 14079 else if (const ObjCIvarRefExpr *OIRE = 14080 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14081 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14082 14083 // Opc is not a compound assignment if CompResultTy is null. 14084 if (CompResultTy.isNull()) { 14085 if (ConvertHalfVec) 14086 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14087 OpLoc, CurFPFeatureOverrides()); 14088 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14089 VK, OK, OpLoc, CurFPFeatureOverrides()); 14090 } 14091 14092 // Handle compound assignments. 14093 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14094 OK_ObjCProperty) { 14095 VK = VK_LValue; 14096 OK = LHS.get()->getObjectKind(); 14097 } 14098 14099 // The LHS is not converted to the result type for fixed-point compound 14100 // assignment as the common type is computed on demand. Reset the CompLHSTy 14101 // to the LHS type we would have gotten after unary conversions. 14102 if (CompResultTy->isFixedPointType()) 14103 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14104 14105 if (ConvertHalfVec) 14106 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14107 OpLoc, CurFPFeatureOverrides()); 14108 14109 return CompoundAssignOperator::Create( 14110 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14111 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14112 } 14113 14114 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14115 /// operators are mixed in a way that suggests that the programmer forgot that 14116 /// comparison operators have higher precedence. The most typical example of 14117 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14118 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14119 SourceLocation OpLoc, Expr *LHSExpr, 14120 Expr *RHSExpr) { 14121 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14122 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14123 14124 // Check that one of the sides is a comparison operator and the other isn't. 14125 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14126 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14127 if (isLeftComp == isRightComp) 14128 return; 14129 14130 // Bitwise operations are sometimes used as eager logical ops. 14131 // Don't diagnose this. 14132 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14133 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14134 if (isLeftBitwise || isRightBitwise) 14135 return; 14136 14137 SourceRange DiagRange = isLeftComp 14138 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14139 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14140 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14141 SourceRange ParensRange = 14142 isLeftComp 14143 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14144 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14145 14146 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14147 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14148 SuggestParentheses(Self, OpLoc, 14149 Self.PDiag(diag::note_precedence_silence) << OpStr, 14150 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14151 SuggestParentheses(Self, OpLoc, 14152 Self.PDiag(diag::note_precedence_bitwise_first) 14153 << BinaryOperator::getOpcodeStr(Opc), 14154 ParensRange); 14155 } 14156 14157 /// It accepts a '&&' expr that is inside a '||' one. 14158 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14159 /// in parentheses. 14160 static void 14161 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14162 BinaryOperator *Bop) { 14163 assert(Bop->getOpcode() == BO_LAnd); 14164 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14165 << Bop->getSourceRange() << OpLoc; 14166 SuggestParentheses(Self, Bop->getOperatorLoc(), 14167 Self.PDiag(diag::note_precedence_silence) 14168 << Bop->getOpcodeStr(), 14169 Bop->getSourceRange()); 14170 } 14171 14172 /// Returns true if the given expression can be evaluated as a constant 14173 /// 'true'. 14174 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14175 bool Res; 14176 return !E->isValueDependent() && 14177 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14178 } 14179 14180 /// Returns true if the given expression can be evaluated as a constant 14181 /// 'false'. 14182 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14183 bool Res; 14184 return !E->isValueDependent() && 14185 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14186 } 14187 14188 /// Look for '&&' in the left hand of a '||' expr. 14189 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14190 Expr *LHSExpr, Expr *RHSExpr) { 14191 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14192 if (Bop->getOpcode() == BO_LAnd) { 14193 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14194 if (EvaluatesAsFalse(S, RHSExpr)) 14195 return; 14196 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14197 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14198 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14199 } else if (Bop->getOpcode() == BO_LOr) { 14200 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14201 // If it's "a || b && 1 || c" we didn't warn earlier for 14202 // "a || b && 1", but warn now. 14203 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14204 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14205 } 14206 } 14207 } 14208 } 14209 14210 /// Look for '&&' in the right hand of a '||' expr. 14211 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14212 Expr *LHSExpr, Expr *RHSExpr) { 14213 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14214 if (Bop->getOpcode() == BO_LAnd) { 14215 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14216 if (EvaluatesAsFalse(S, LHSExpr)) 14217 return; 14218 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14219 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14220 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14221 } 14222 } 14223 } 14224 14225 /// Look for bitwise op in the left or right hand of a bitwise op with 14226 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14227 /// the '&' expression in parentheses. 14228 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14229 SourceLocation OpLoc, Expr *SubExpr) { 14230 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14231 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14232 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14233 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14234 << Bop->getSourceRange() << OpLoc; 14235 SuggestParentheses(S, Bop->getOperatorLoc(), 14236 S.PDiag(diag::note_precedence_silence) 14237 << Bop->getOpcodeStr(), 14238 Bop->getSourceRange()); 14239 } 14240 } 14241 } 14242 14243 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14244 Expr *SubExpr, StringRef Shift) { 14245 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14246 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14247 StringRef Op = Bop->getOpcodeStr(); 14248 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14249 << Bop->getSourceRange() << OpLoc << Shift << Op; 14250 SuggestParentheses(S, Bop->getOperatorLoc(), 14251 S.PDiag(diag::note_precedence_silence) << Op, 14252 Bop->getSourceRange()); 14253 } 14254 } 14255 } 14256 14257 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14258 Expr *LHSExpr, Expr *RHSExpr) { 14259 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14260 if (!OCE) 14261 return; 14262 14263 FunctionDecl *FD = OCE->getDirectCallee(); 14264 if (!FD || !FD->isOverloadedOperator()) 14265 return; 14266 14267 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14268 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14269 return; 14270 14271 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14272 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14273 << (Kind == OO_LessLess); 14274 SuggestParentheses(S, OCE->getOperatorLoc(), 14275 S.PDiag(diag::note_precedence_silence) 14276 << (Kind == OO_LessLess ? "<<" : ">>"), 14277 OCE->getSourceRange()); 14278 SuggestParentheses( 14279 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14280 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14281 } 14282 14283 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14284 /// precedence. 14285 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14286 SourceLocation OpLoc, Expr *LHSExpr, 14287 Expr *RHSExpr){ 14288 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14289 if (BinaryOperator::isBitwiseOp(Opc)) 14290 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14291 14292 // Diagnose "arg1 & arg2 | arg3" 14293 if ((Opc == BO_Or || Opc == BO_Xor) && 14294 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14295 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14296 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14297 } 14298 14299 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14300 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14301 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14302 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14303 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14304 } 14305 14306 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14307 || Opc == BO_Shr) { 14308 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14309 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14310 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14311 } 14312 14313 // Warn on overloaded shift operators and comparisons, such as: 14314 // cout << 5 == 4; 14315 if (BinaryOperator::isComparisonOp(Opc)) 14316 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14317 } 14318 14319 // Binary Operators. 'Tok' is the token for the operator. 14320 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14321 tok::TokenKind Kind, 14322 Expr *LHSExpr, Expr *RHSExpr) { 14323 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14324 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14325 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14326 14327 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14328 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14329 14330 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14331 } 14332 14333 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14334 UnresolvedSetImpl &Functions) { 14335 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14336 if (OverOp != OO_None && OverOp != OO_Equal) 14337 LookupOverloadedOperatorName(OverOp, S, Functions); 14338 14339 // In C++20 onwards, we may have a second operator to look up. 14340 if (getLangOpts().CPlusPlus20) { 14341 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14342 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14343 } 14344 } 14345 14346 /// Build an overloaded binary operator expression in the given scope. 14347 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14348 BinaryOperatorKind Opc, 14349 Expr *LHS, Expr *RHS) { 14350 switch (Opc) { 14351 case BO_Assign: 14352 case BO_DivAssign: 14353 case BO_RemAssign: 14354 case BO_SubAssign: 14355 case BO_AndAssign: 14356 case BO_OrAssign: 14357 case BO_XorAssign: 14358 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14359 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14360 break; 14361 default: 14362 break; 14363 } 14364 14365 // Find all of the overloaded operators visible from this point. 14366 UnresolvedSet<16> Functions; 14367 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14368 14369 // Build the (potentially-overloaded, potentially-dependent) 14370 // binary operation. 14371 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14372 } 14373 14374 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14375 BinaryOperatorKind Opc, 14376 Expr *LHSExpr, Expr *RHSExpr) { 14377 ExprResult LHS, RHS; 14378 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14379 if (!LHS.isUsable() || !RHS.isUsable()) 14380 return ExprError(); 14381 LHSExpr = LHS.get(); 14382 RHSExpr = RHS.get(); 14383 14384 // We want to end up calling one of checkPseudoObjectAssignment 14385 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14386 // both expressions are overloadable or either is type-dependent), 14387 // or CreateBuiltinBinOp (in any other case). We also want to get 14388 // any placeholder types out of the way. 14389 14390 // Handle pseudo-objects in the LHS. 14391 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14392 // Assignments with a pseudo-object l-value need special analysis. 14393 if (pty->getKind() == BuiltinType::PseudoObject && 14394 BinaryOperator::isAssignmentOp(Opc)) 14395 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14396 14397 // Don't resolve overloads if the other type is overloadable. 14398 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14399 // We can't actually test that if we still have a placeholder, 14400 // though. Fortunately, none of the exceptions we see in that 14401 // code below are valid when the LHS is an overload set. Note 14402 // that an overload set can be dependently-typed, but it never 14403 // instantiates to having an overloadable type. 14404 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14405 if (resolvedRHS.isInvalid()) return ExprError(); 14406 RHSExpr = resolvedRHS.get(); 14407 14408 if (RHSExpr->isTypeDependent() || 14409 RHSExpr->getType()->isOverloadableType()) 14410 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14411 } 14412 14413 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14414 // template, diagnose the missing 'template' keyword instead of diagnosing 14415 // an invalid use of a bound member function. 14416 // 14417 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14418 // to C++1z [over.over]/1.4, but we already checked for that case above. 14419 if (Opc == BO_LT && inTemplateInstantiation() && 14420 (pty->getKind() == BuiltinType::BoundMember || 14421 pty->getKind() == BuiltinType::Overload)) { 14422 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14423 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14424 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14425 return isa<FunctionTemplateDecl>(ND); 14426 })) { 14427 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14428 : OE->getNameLoc(), 14429 diag::err_template_kw_missing) 14430 << OE->getName().getAsString() << ""; 14431 return ExprError(); 14432 } 14433 } 14434 14435 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14436 if (LHS.isInvalid()) return ExprError(); 14437 LHSExpr = LHS.get(); 14438 } 14439 14440 // Handle pseudo-objects in the RHS. 14441 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14442 // An overload in the RHS can potentially be resolved by the type 14443 // being assigned to. 14444 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14445 if (getLangOpts().CPlusPlus && 14446 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14447 LHSExpr->getType()->isOverloadableType())) 14448 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14449 14450 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14451 } 14452 14453 // Don't resolve overloads if the other type is overloadable. 14454 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14455 LHSExpr->getType()->isOverloadableType()) 14456 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14457 14458 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14459 if (!resolvedRHS.isUsable()) return ExprError(); 14460 RHSExpr = resolvedRHS.get(); 14461 } 14462 14463 if (getLangOpts().CPlusPlus) { 14464 // If either expression is type-dependent, always build an 14465 // overloaded op. 14466 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14467 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14468 14469 // Otherwise, build an overloaded op if either expression has an 14470 // overloadable type. 14471 if (LHSExpr->getType()->isOverloadableType() || 14472 RHSExpr->getType()->isOverloadableType()) 14473 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14474 } 14475 14476 if (getLangOpts().RecoveryAST && 14477 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14478 assert(!getLangOpts().CPlusPlus); 14479 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14480 "Should only occur in error-recovery path."); 14481 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14482 // C [6.15.16] p3: 14483 // An assignment expression has the value of the left operand after the 14484 // assignment, but is not an lvalue. 14485 return CompoundAssignOperator::Create( 14486 Context, LHSExpr, RHSExpr, Opc, 14487 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14488 OpLoc, CurFPFeatureOverrides()); 14489 QualType ResultType; 14490 switch (Opc) { 14491 case BO_Assign: 14492 ResultType = LHSExpr->getType().getUnqualifiedType(); 14493 break; 14494 case BO_LT: 14495 case BO_GT: 14496 case BO_LE: 14497 case BO_GE: 14498 case BO_EQ: 14499 case BO_NE: 14500 case BO_LAnd: 14501 case BO_LOr: 14502 // These operators have a fixed result type regardless of operands. 14503 ResultType = Context.IntTy; 14504 break; 14505 case BO_Comma: 14506 ResultType = RHSExpr->getType(); 14507 break; 14508 default: 14509 ResultType = Context.DependentTy; 14510 break; 14511 } 14512 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14513 VK_RValue, OK_Ordinary, OpLoc, 14514 CurFPFeatureOverrides()); 14515 } 14516 14517 // Build a built-in binary operation. 14518 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14519 } 14520 14521 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14522 if (T.isNull() || T->isDependentType()) 14523 return false; 14524 14525 if (!T->isPromotableIntegerType()) 14526 return true; 14527 14528 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14529 } 14530 14531 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14532 UnaryOperatorKind Opc, 14533 Expr *InputExpr) { 14534 ExprResult Input = InputExpr; 14535 ExprValueKind VK = VK_RValue; 14536 ExprObjectKind OK = OK_Ordinary; 14537 QualType resultType; 14538 bool CanOverflow = false; 14539 14540 bool ConvertHalfVec = false; 14541 if (getLangOpts().OpenCL) { 14542 QualType Ty = InputExpr->getType(); 14543 // The only legal unary operation for atomics is '&'. 14544 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14545 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14546 // only with a builtin functions and therefore should be disallowed here. 14547 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14548 || Ty->isBlockPointerType())) { 14549 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14550 << InputExpr->getType() 14551 << Input.get()->getSourceRange()); 14552 } 14553 } 14554 14555 switch (Opc) { 14556 case UO_PreInc: 14557 case UO_PreDec: 14558 case UO_PostInc: 14559 case UO_PostDec: 14560 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14561 OpLoc, 14562 Opc == UO_PreInc || 14563 Opc == UO_PostInc, 14564 Opc == UO_PreInc || 14565 Opc == UO_PreDec); 14566 CanOverflow = isOverflowingIntegerType(Context, resultType); 14567 break; 14568 case UO_AddrOf: 14569 resultType = CheckAddressOfOperand(Input, OpLoc); 14570 CheckAddressOfNoDeref(InputExpr); 14571 RecordModifiableNonNullParam(*this, InputExpr); 14572 break; 14573 case UO_Deref: { 14574 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14575 if (Input.isInvalid()) return ExprError(); 14576 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14577 break; 14578 } 14579 case UO_Plus: 14580 case UO_Minus: 14581 CanOverflow = Opc == UO_Minus && 14582 isOverflowingIntegerType(Context, Input.get()->getType()); 14583 Input = UsualUnaryConversions(Input.get()); 14584 if (Input.isInvalid()) return ExprError(); 14585 // Unary plus and minus require promoting an operand of half vector to a 14586 // float vector and truncating the result back to a half vector. For now, we 14587 // do this only when HalfArgsAndReturns is set (that is, when the target is 14588 // arm or arm64). 14589 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14590 14591 // If the operand is a half vector, promote it to a float vector. 14592 if (ConvertHalfVec) 14593 Input = convertVector(Input.get(), Context.FloatTy, *this); 14594 resultType = Input.get()->getType(); 14595 if (resultType->isDependentType()) 14596 break; 14597 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14598 break; 14599 else if (resultType->isVectorType() && 14600 // The z vector extensions don't allow + or - with bool vectors. 14601 (!Context.getLangOpts().ZVector || 14602 resultType->castAs<VectorType>()->getVectorKind() != 14603 VectorType::AltiVecBool)) 14604 break; 14605 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14606 Opc == UO_Plus && 14607 resultType->isPointerType()) 14608 break; 14609 14610 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14611 << resultType << Input.get()->getSourceRange()); 14612 14613 case UO_Not: // bitwise complement 14614 Input = UsualUnaryConversions(Input.get()); 14615 if (Input.isInvalid()) 14616 return ExprError(); 14617 resultType = Input.get()->getType(); 14618 if (resultType->isDependentType()) 14619 break; 14620 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14621 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14622 // C99 does not support '~' for complex conjugation. 14623 Diag(OpLoc, diag::ext_integer_complement_complex) 14624 << resultType << Input.get()->getSourceRange(); 14625 else if (resultType->hasIntegerRepresentation()) 14626 break; 14627 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14628 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14629 // on vector float types. 14630 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14631 if (!T->isIntegerType()) 14632 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14633 << resultType << Input.get()->getSourceRange()); 14634 } else { 14635 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14636 << resultType << Input.get()->getSourceRange()); 14637 } 14638 break; 14639 14640 case UO_LNot: // logical negation 14641 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14642 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14643 if (Input.isInvalid()) return ExprError(); 14644 resultType = Input.get()->getType(); 14645 14646 // Though we still have to promote half FP to float... 14647 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14648 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14649 resultType = Context.FloatTy; 14650 } 14651 14652 if (resultType->isDependentType()) 14653 break; 14654 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14655 // C99 6.5.3.3p1: ok, fallthrough; 14656 if (Context.getLangOpts().CPlusPlus) { 14657 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14658 // operand contextually converted to bool. 14659 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14660 ScalarTypeToBooleanCastKind(resultType)); 14661 } else if (Context.getLangOpts().OpenCL && 14662 Context.getLangOpts().OpenCLVersion < 120) { 14663 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14664 // operate on scalar float types. 14665 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14666 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14667 << resultType << Input.get()->getSourceRange()); 14668 } 14669 } else if (resultType->isExtVectorType()) { 14670 if (Context.getLangOpts().OpenCL && 14671 Context.getLangOpts().OpenCLVersion < 120 && 14672 !Context.getLangOpts().OpenCLCPlusPlus) { 14673 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14674 // operate on vector float types. 14675 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14676 if (!T->isIntegerType()) 14677 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14678 << resultType << Input.get()->getSourceRange()); 14679 } 14680 // Vector logical not returns the signed variant of the operand type. 14681 resultType = GetSignedVectorType(resultType); 14682 break; 14683 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14684 const VectorType *VTy = resultType->castAs<VectorType>(); 14685 if (VTy->getVectorKind() != VectorType::GenericVector) 14686 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14687 << resultType << Input.get()->getSourceRange()); 14688 14689 // Vector logical not returns the signed variant of the operand type. 14690 resultType = GetSignedVectorType(resultType); 14691 break; 14692 } else { 14693 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14694 << resultType << Input.get()->getSourceRange()); 14695 } 14696 14697 // LNot always has type int. C99 6.5.3.3p5. 14698 // In C++, it's bool. C++ 5.3.1p8 14699 resultType = Context.getLogicalOperationType(); 14700 break; 14701 case UO_Real: 14702 case UO_Imag: 14703 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14704 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14705 // complex l-values to ordinary l-values and all other values to r-values. 14706 if (Input.isInvalid()) return ExprError(); 14707 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14708 if (Input.get()->getValueKind() != VK_RValue && 14709 Input.get()->getObjectKind() == OK_Ordinary) 14710 VK = Input.get()->getValueKind(); 14711 } else if (!getLangOpts().CPlusPlus) { 14712 // In C, a volatile scalar is read by __imag. In C++, it is not. 14713 Input = DefaultLvalueConversion(Input.get()); 14714 } 14715 break; 14716 case UO_Extension: 14717 resultType = Input.get()->getType(); 14718 VK = Input.get()->getValueKind(); 14719 OK = Input.get()->getObjectKind(); 14720 break; 14721 case UO_Coawait: 14722 // It's unnecessary to represent the pass-through operator co_await in the 14723 // AST; just return the input expression instead. 14724 assert(!Input.get()->getType()->isDependentType() && 14725 "the co_await expression must be non-dependant before " 14726 "building operator co_await"); 14727 return Input; 14728 } 14729 if (resultType.isNull() || Input.isInvalid()) 14730 return ExprError(); 14731 14732 // Check for array bounds violations in the operand of the UnaryOperator, 14733 // except for the '*' and '&' operators that have to be handled specially 14734 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14735 // that are explicitly defined as valid by the standard). 14736 if (Opc != UO_AddrOf && Opc != UO_Deref) 14737 CheckArrayAccess(Input.get()); 14738 14739 auto *UO = 14740 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14741 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14742 14743 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14744 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14745 !isUnevaluatedContext()) 14746 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14747 14748 // Convert the result back to a half vector. 14749 if (ConvertHalfVec) 14750 return convertVector(UO, Context.HalfTy, *this); 14751 return UO; 14752 } 14753 14754 /// Determine whether the given expression is a qualified member 14755 /// access expression, of a form that could be turned into a pointer to member 14756 /// with the address-of operator. 14757 bool Sema::isQualifiedMemberAccess(Expr *E) { 14758 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14759 if (!DRE->getQualifier()) 14760 return false; 14761 14762 ValueDecl *VD = DRE->getDecl(); 14763 if (!VD->isCXXClassMember()) 14764 return false; 14765 14766 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14767 return true; 14768 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14769 return Method->isInstance(); 14770 14771 return false; 14772 } 14773 14774 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14775 if (!ULE->getQualifier()) 14776 return false; 14777 14778 for (NamedDecl *D : ULE->decls()) { 14779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14780 if (Method->isInstance()) 14781 return true; 14782 } else { 14783 // Overload set does not contain methods. 14784 break; 14785 } 14786 } 14787 14788 return false; 14789 } 14790 14791 return false; 14792 } 14793 14794 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14795 UnaryOperatorKind Opc, Expr *Input) { 14796 // First things first: handle placeholders so that the 14797 // overloaded-operator check considers the right type. 14798 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14799 // Increment and decrement of pseudo-object references. 14800 if (pty->getKind() == BuiltinType::PseudoObject && 14801 UnaryOperator::isIncrementDecrementOp(Opc)) 14802 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14803 14804 // extension is always a builtin operator. 14805 if (Opc == UO_Extension) 14806 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14807 14808 // & gets special logic for several kinds of placeholder. 14809 // The builtin code knows what to do. 14810 if (Opc == UO_AddrOf && 14811 (pty->getKind() == BuiltinType::Overload || 14812 pty->getKind() == BuiltinType::UnknownAny || 14813 pty->getKind() == BuiltinType::BoundMember)) 14814 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14815 14816 // Anything else needs to be handled now. 14817 ExprResult Result = CheckPlaceholderExpr(Input); 14818 if (Result.isInvalid()) return ExprError(); 14819 Input = Result.get(); 14820 } 14821 14822 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14823 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14824 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14825 // Find all of the overloaded operators visible from this point. 14826 UnresolvedSet<16> Functions; 14827 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14828 if (S && OverOp != OO_None) 14829 LookupOverloadedOperatorName(OverOp, S, Functions); 14830 14831 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14832 } 14833 14834 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14835 } 14836 14837 // Unary Operators. 'Tok' is the token for the operator. 14838 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14839 tok::TokenKind Op, Expr *Input) { 14840 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14841 } 14842 14843 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14844 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14845 LabelDecl *TheDecl) { 14846 TheDecl->markUsed(Context); 14847 // Create the AST node. The address of a label always has type 'void*'. 14848 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14849 Context.getPointerType(Context.VoidTy)); 14850 } 14851 14852 void Sema::ActOnStartStmtExpr() { 14853 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14854 } 14855 14856 void Sema::ActOnStmtExprError() { 14857 // Note that function is also called by TreeTransform when leaving a 14858 // StmtExpr scope without rebuilding anything. 14859 14860 DiscardCleanupsInEvaluationContext(); 14861 PopExpressionEvaluationContext(); 14862 } 14863 14864 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14865 SourceLocation RPLoc) { 14866 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14867 } 14868 14869 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14870 SourceLocation RPLoc, unsigned TemplateDepth) { 14871 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14872 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14873 14874 if (hasAnyUnrecoverableErrorsInThisFunction()) 14875 DiscardCleanupsInEvaluationContext(); 14876 assert(!Cleanup.exprNeedsCleanups() && 14877 "cleanups within StmtExpr not correctly bound!"); 14878 PopExpressionEvaluationContext(); 14879 14880 // FIXME: there are a variety of strange constraints to enforce here, for 14881 // example, it is not possible to goto into a stmt expression apparently. 14882 // More semantic analysis is needed. 14883 14884 // If there are sub-stmts in the compound stmt, take the type of the last one 14885 // as the type of the stmtexpr. 14886 QualType Ty = Context.VoidTy; 14887 bool StmtExprMayBindToTemp = false; 14888 if (!Compound->body_empty()) { 14889 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14890 if (const auto *LastStmt = 14891 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14892 if (const Expr *Value = LastStmt->getExprStmt()) { 14893 StmtExprMayBindToTemp = true; 14894 Ty = Value->getType(); 14895 } 14896 } 14897 } 14898 14899 // FIXME: Check that expression type is complete/non-abstract; statement 14900 // expressions are not lvalues. 14901 Expr *ResStmtExpr = 14902 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14903 if (StmtExprMayBindToTemp) 14904 return MaybeBindToTemporary(ResStmtExpr); 14905 return ResStmtExpr; 14906 } 14907 14908 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14909 if (ER.isInvalid()) 14910 return ExprError(); 14911 14912 // Do function/array conversion on the last expression, but not 14913 // lvalue-to-rvalue. However, initialize an unqualified type. 14914 ER = DefaultFunctionArrayConversion(ER.get()); 14915 if (ER.isInvalid()) 14916 return ExprError(); 14917 Expr *E = ER.get(); 14918 14919 if (E->isTypeDependent()) 14920 return E; 14921 14922 // In ARC, if the final expression ends in a consume, splice 14923 // the consume out and bind it later. In the alternate case 14924 // (when dealing with a retainable type), the result 14925 // initialization will create a produce. In both cases the 14926 // result will be +1, and we'll need to balance that out with 14927 // a bind. 14928 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14929 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14930 return Cast->getSubExpr(); 14931 14932 // FIXME: Provide a better location for the initialization. 14933 return PerformCopyInitialization( 14934 InitializedEntity::InitializeStmtExprResult( 14935 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14936 SourceLocation(), E); 14937 } 14938 14939 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14940 TypeSourceInfo *TInfo, 14941 ArrayRef<OffsetOfComponent> Components, 14942 SourceLocation RParenLoc) { 14943 QualType ArgTy = TInfo->getType(); 14944 bool Dependent = ArgTy->isDependentType(); 14945 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14946 14947 // We must have at least one component that refers to the type, and the first 14948 // one is known to be a field designator. Verify that the ArgTy represents 14949 // a struct/union/class. 14950 if (!Dependent && !ArgTy->isRecordType()) 14951 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14952 << ArgTy << TypeRange); 14953 14954 // Type must be complete per C99 7.17p3 because a declaring a variable 14955 // with an incomplete type would be ill-formed. 14956 if (!Dependent 14957 && RequireCompleteType(BuiltinLoc, ArgTy, 14958 diag::err_offsetof_incomplete_type, TypeRange)) 14959 return ExprError(); 14960 14961 bool DidWarnAboutNonPOD = false; 14962 QualType CurrentType = ArgTy; 14963 SmallVector<OffsetOfNode, 4> Comps; 14964 SmallVector<Expr*, 4> Exprs; 14965 for (const OffsetOfComponent &OC : Components) { 14966 if (OC.isBrackets) { 14967 // Offset of an array sub-field. TODO: Should we allow vector elements? 14968 if (!CurrentType->isDependentType()) { 14969 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14970 if(!AT) 14971 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14972 << CurrentType); 14973 CurrentType = AT->getElementType(); 14974 } else 14975 CurrentType = Context.DependentTy; 14976 14977 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14978 if (IdxRval.isInvalid()) 14979 return ExprError(); 14980 Expr *Idx = IdxRval.get(); 14981 14982 // The expression must be an integral expression. 14983 // FIXME: An integral constant expression? 14984 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14985 !Idx->getType()->isIntegerType()) 14986 return ExprError( 14987 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14988 << Idx->getSourceRange()); 14989 14990 // Record this array index. 14991 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14992 Exprs.push_back(Idx); 14993 continue; 14994 } 14995 14996 // Offset of a field. 14997 if (CurrentType->isDependentType()) { 14998 // We have the offset of a field, but we can't look into the dependent 14999 // type. Just record the identifier of the field. 15000 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15001 CurrentType = Context.DependentTy; 15002 continue; 15003 } 15004 15005 // We need to have a complete type to look into. 15006 if (RequireCompleteType(OC.LocStart, CurrentType, 15007 diag::err_offsetof_incomplete_type)) 15008 return ExprError(); 15009 15010 // Look for the designated field. 15011 const RecordType *RC = CurrentType->getAs<RecordType>(); 15012 if (!RC) 15013 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15014 << CurrentType); 15015 RecordDecl *RD = RC->getDecl(); 15016 15017 // C++ [lib.support.types]p5: 15018 // The macro offsetof accepts a restricted set of type arguments in this 15019 // International Standard. type shall be a POD structure or a POD union 15020 // (clause 9). 15021 // C++11 [support.types]p4: 15022 // If type is not a standard-layout class (Clause 9), the results are 15023 // undefined. 15024 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15025 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15026 unsigned DiagID = 15027 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15028 : diag::ext_offsetof_non_pod_type; 15029 15030 if (!IsSafe && !DidWarnAboutNonPOD && 15031 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15032 PDiag(DiagID) 15033 << SourceRange(Components[0].LocStart, OC.LocEnd) 15034 << CurrentType)) 15035 DidWarnAboutNonPOD = true; 15036 } 15037 15038 // Look for the field. 15039 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15040 LookupQualifiedName(R, RD); 15041 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15042 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15043 if (!MemberDecl) { 15044 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15045 MemberDecl = IndirectMemberDecl->getAnonField(); 15046 } 15047 15048 if (!MemberDecl) 15049 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15050 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15051 OC.LocEnd)); 15052 15053 // C99 7.17p3: 15054 // (If the specified member is a bit-field, the behavior is undefined.) 15055 // 15056 // We diagnose this as an error. 15057 if (MemberDecl->isBitField()) { 15058 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15059 << MemberDecl->getDeclName() 15060 << SourceRange(BuiltinLoc, RParenLoc); 15061 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15062 return ExprError(); 15063 } 15064 15065 RecordDecl *Parent = MemberDecl->getParent(); 15066 if (IndirectMemberDecl) 15067 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15068 15069 // If the member was found in a base class, introduce OffsetOfNodes for 15070 // the base class indirections. 15071 CXXBasePaths Paths; 15072 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15073 Paths)) { 15074 if (Paths.getDetectedVirtual()) { 15075 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15076 << MemberDecl->getDeclName() 15077 << SourceRange(BuiltinLoc, RParenLoc); 15078 return ExprError(); 15079 } 15080 15081 CXXBasePath &Path = Paths.front(); 15082 for (const CXXBasePathElement &B : Path) 15083 Comps.push_back(OffsetOfNode(B.Base)); 15084 } 15085 15086 if (IndirectMemberDecl) { 15087 for (auto *FI : IndirectMemberDecl->chain()) { 15088 assert(isa<FieldDecl>(FI)); 15089 Comps.push_back(OffsetOfNode(OC.LocStart, 15090 cast<FieldDecl>(FI), OC.LocEnd)); 15091 } 15092 } else 15093 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15094 15095 CurrentType = MemberDecl->getType().getNonReferenceType(); 15096 } 15097 15098 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15099 Comps, Exprs, RParenLoc); 15100 } 15101 15102 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15103 SourceLocation BuiltinLoc, 15104 SourceLocation TypeLoc, 15105 ParsedType ParsedArgTy, 15106 ArrayRef<OffsetOfComponent> Components, 15107 SourceLocation RParenLoc) { 15108 15109 TypeSourceInfo *ArgTInfo; 15110 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15111 if (ArgTy.isNull()) 15112 return ExprError(); 15113 15114 if (!ArgTInfo) 15115 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15116 15117 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15118 } 15119 15120 15121 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15122 Expr *CondExpr, 15123 Expr *LHSExpr, Expr *RHSExpr, 15124 SourceLocation RPLoc) { 15125 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15126 15127 ExprValueKind VK = VK_RValue; 15128 ExprObjectKind OK = OK_Ordinary; 15129 QualType resType; 15130 bool CondIsTrue = false; 15131 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15132 resType = Context.DependentTy; 15133 } else { 15134 // The conditional expression is required to be a constant expression. 15135 llvm::APSInt condEval(32); 15136 ExprResult CondICE = VerifyIntegerConstantExpression( 15137 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15138 if (CondICE.isInvalid()) 15139 return ExprError(); 15140 CondExpr = CondICE.get(); 15141 CondIsTrue = condEval.getZExtValue(); 15142 15143 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15144 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15145 15146 resType = ActiveExpr->getType(); 15147 VK = ActiveExpr->getValueKind(); 15148 OK = ActiveExpr->getObjectKind(); 15149 } 15150 15151 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15152 resType, VK, OK, RPLoc, CondIsTrue); 15153 } 15154 15155 //===----------------------------------------------------------------------===// 15156 // Clang Extensions. 15157 //===----------------------------------------------------------------------===// 15158 15159 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15160 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15161 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15162 15163 if (LangOpts.CPlusPlus) { 15164 MangleNumberingContext *MCtx; 15165 Decl *ManglingContextDecl; 15166 std::tie(MCtx, ManglingContextDecl) = 15167 getCurrentMangleNumberContext(Block->getDeclContext()); 15168 if (MCtx) { 15169 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15170 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15171 } 15172 } 15173 15174 PushBlockScope(CurScope, Block); 15175 CurContext->addDecl(Block); 15176 if (CurScope) 15177 PushDeclContext(CurScope, Block); 15178 else 15179 CurContext = Block; 15180 15181 getCurBlock()->HasImplicitReturnType = true; 15182 15183 // Enter a new evaluation context to insulate the block from any 15184 // cleanups from the enclosing full-expression. 15185 PushExpressionEvaluationContext( 15186 ExpressionEvaluationContext::PotentiallyEvaluated); 15187 } 15188 15189 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15190 Scope *CurScope) { 15191 assert(ParamInfo.getIdentifier() == nullptr && 15192 "block-id should have no identifier!"); 15193 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15194 BlockScopeInfo *CurBlock = getCurBlock(); 15195 15196 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15197 QualType T = Sig->getType(); 15198 15199 // FIXME: We should allow unexpanded parameter packs here, but that would, 15200 // in turn, make the block expression contain unexpanded parameter packs. 15201 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15202 // Drop the parameters. 15203 FunctionProtoType::ExtProtoInfo EPI; 15204 EPI.HasTrailingReturn = false; 15205 EPI.TypeQuals.addConst(); 15206 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15207 Sig = Context.getTrivialTypeSourceInfo(T); 15208 } 15209 15210 // GetTypeForDeclarator always produces a function type for a block 15211 // literal signature. Furthermore, it is always a FunctionProtoType 15212 // unless the function was written with a typedef. 15213 assert(T->isFunctionType() && 15214 "GetTypeForDeclarator made a non-function block signature"); 15215 15216 // Look for an explicit signature in that function type. 15217 FunctionProtoTypeLoc ExplicitSignature; 15218 15219 if ((ExplicitSignature = Sig->getTypeLoc() 15220 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15221 15222 // Check whether that explicit signature was synthesized by 15223 // GetTypeForDeclarator. If so, don't save that as part of the 15224 // written signature. 15225 if (ExplicitSignature.getLocalRangeBegin() == 15226 ExplicitSignature.getLocalRangeEnd()) { 15227 // This would be much cheaper if we stored TypeLocs instead of 15228 // TypeSourceInfos. 15229 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15230 unsigned Size = Result.getFullDataSize(); 15231 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15232 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15233 15234 ExplicitSignature = FunctionProtoTypeLoc(); 15235 } 15236 } 15237 15238 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15239 CurBlock->FunctionType = T; 15240 15241 const auto *Fn = T->castAs<FunctionType>(); 15242 QualType RetTy = Fn->getReturnType(); 15243 bool isVariadic = 15244 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15245 15246 CurBlock->TheDecl->setIsVariadic(isVariadic); 15247 15248 // Context.DependentTy is used as a placeholder for a missing block 15249 // return type. TODO: what should we do with declarators like: 15250 // ^ * { ... } 15251 // If the answer is "apply template argument deduction".... 15252 if (RetTy != Context.DependentTy) { 15253 CurBlock->ReturnType = RetTy; 15254 CurBlock->TheDecl->setBlockMissingReturnType(false); 15255 CurBlock->HasImplicitReturnType = false; 15256 } 15257 15258 // Push block parameters from the declarator if we had them. 15259 SmallVector<ParmVarDecl*, 8> Params; 15260 if (ExplicitSignature) { 15261 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15262 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15263 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15264 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15265 // Diagnose this as an extension in C17 and earlier. 15266 if (!getLangOpts().C2x) 15267 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15268 } 15269 Params.push_back(Param); 15270 } 15271 15272 // Fake up parameter variables if we have a typedef, like 15273 // ^ fntype { ... } 15274 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15275 for (const auto &I : Fn->param_types()) { 15276 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15277 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15278 Params.push_back(Param); 15279 } 15280 } 15281 15282 // Set the parameters on the block decl. 15283 if (!Params.empty()) { 15284 CurBlock->TheDecl->setParams(Params); 15285 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15286 /*CheckParameterNames=*/false); 15287 } 15288 15289 // Finally we can process decl attributes. 15290 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15291 15292 // Put the parameter variables in scope. 15293 for (auto AI : CurBlock->TheDecl->parameters()) { 15294 AI->setOwningFunction(CurBlock->TheDecl); 15295 15296 // If this has an identifier, add it to the scope stack. 15297 if (AI->getIdentifier()) { 15298 CheckShadow(CurBlock->TheScope, AI); 15299 15300 PushOnScopeChains(AI, CurBlock->TheScope); 15301 } 15302 } 15303 } 15304 15305 /// ActOnBlockError - If there is an error parsing a block, this callback 15306 /// is invoked to pop the information about the block from the action impl. 15307 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15308 // Leave the expression-evaluation context. 15309 DiscardCleanupsInEvaluationContext(); 15310 PopExpressionEvaluationContext(); 15311 15312 // Pop off CurBlock, handle nested blocks. 15313 PopDeclContext(); 15314 PopFunctionScopeInfo(); 15315 } 15316 15317 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15318 /// literal was successfully completed. ^(int x){...} 15319 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15320 Stmt *Body, Scope *CurScope) { 15321 // If blocks are disabled, emit an error. 15322 if (!LangOpts.Blocks) 15323 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15324 15325 // Leave the expression-evaluation context. 15326 if (hasAnyUnrecoverableErrorsInThisFunction()) 15327 DiscardCleanupsInEvaluationContext(); 15328 assert(!Cleanup.exprNeedsCleanups() && 15329 "cleanups within block not correctly bound!"); 15330 PopExpressionEvaluationContext(); 15331 15332 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15333 BlockDecl *BD = BSI->TheDecl; 15334 15335 if (BSI->HasImplicitReturnType) 15336 deduceClosureReturnType(*BSI); 15337 15338 QualType RetTy = Context.VoidTy; 15339 if (!BSI->ReturnType.isNull()) 15340 RetTy = BSI->ReturnType; 15341 15342 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15343 QualType BlockTy; 15344 15345 // If the user wrote a function type in some form, try to use that. 15346 if (!BSI->FunctionType.isNull()) { 15347 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15348 15349 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15350 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15351 15352 // Turn protoless block types into nullary block types. 15353 if (isa<FunctionNoProtoType>(FTy)) { 15354 FunctionProtoType::ExtProtoInfo EPI; 15355 EPI.ExtInfo = Ext; 15356 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15357 15358 // Otherwise, if we don't need to change anything about the function type, 15359 // preserve its sugar structure. 15360 } else if (FTy->getReturnType() == RetTy && 15361 (!NoReturn || FTy->getNoReturnAttr())) { 15362 BlockTy = BSI->FunctionType; 15363 15364 // Otherwise, make the minimal modifications to the function type. 15365 } else { 15366 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15367 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15368 EPI.TypeQuals = Qualifiers(); 15369 EPI.ExtInfo = Ext; 15370 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15371 } 15372 15373 // If we don't have a function type, just build one from nothing. 15374 } else { 15375 FunctionProtoType::ExtProtoInfo EPI; 15376 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15377 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15378 } 15379 15380 DiagnoseUnusedParameters(BD->parameters()); 15381 BlockTy = Context.getBlockPointerType(BlockTy); 15382 15383 // If needed, diagnose invalid gotos and switches in the block. 15384 if (getCurFunction()->NeedsScopeChecking() && 15385 !PP.isCodeCompletionEnabled()) 15386 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15387 15388 BD->setBody(cast<CompoundStmt>(Body)); 15389 15390 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15391 DiagnoseUnguardedAvailabilityViolations(BD); 15392 15393 // Try to apply the named return value optimization. We have to check again 15394 // if we can do this, though, because blocks keep return statements around 15395 // to deduce an implicit return type. 15396 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15397 !BD->isDependentContext()) 15398 computeNRVO(Body, BSI); 15399 15400 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15401 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15402 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15403 NTCUK_Destruct|NTCUK_Copy); 15404 15405 PopDeclContext(); 15406 15407 // Set the captured variables on the block. 15408 SmallVector<BlockDecl::Capture, 4> Captures; 15409 for (Capture &Cap : BSI->Captures) { 15410 if (Cap.isInvalid() || Cap.isThisCapture()) 15411 continue; 15412 15413 VarDecl *Var = Cap.getVariable(); 15414 Expr *CopyExpr = nullptr; 15415 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15416 if (const RecordType *Record = 15417 Cap.getCaptureType()->getAs<RecordType>()) { 15418 // The capture logic needs the destructor, so make sure we mark it. 15419 // Usually this is unnecessary because most local variables have 15420 // their destructors marked at declaration time, but parameters are 15421 // an exception because it's technically only the call site that 15422 // actually requires the destructor. 15423 if (isa<ParmVarDecl>(Var)) 15424 FinalizeVarWithDestructor(Var, Record); 15425 15426 // Enter a separate potentially-evaluated context while building block 15427 // initializers to isolate their cleanups from those of the block 15428 // itself. 15429 // FIXME: Is this appropriate even when the block itself occurs in an 15430 // unevaluated operand? 15431 EnterExpressionEvaluationContext EvalContext( 15432 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15433 15434 SourceLocation Loc = Cap.getLocation(); 15435 15436 ExprResult Result = BuildDeclarationNameExpr( 15437 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15438 15439 // According to the blocks spec, the capture of a variable from 15440 // the stack requires a const copy constructor. This is not true 15441 // of the copy/move done to move a __block variable to the heap. 15442 if (!Result.isInvalid() && 15443 !Result.get()->getType().isConstQualified()) { 15444 Result = ImpCastExprToType(Result.get(), 15445 Result.get()->getType().withConst(), 15446 CK_NoOp, VK_LValue); 15447 } 15448 15449 if (!Result.isInvalid()) { 15450 Result = PerformCopyInitialization( 15451 InitializedEntity::InitializeBlock(Var->getLocation(), 15452 Cap.getCaptureType(), false), 15453 Loc, Result.get()); 15454 } 15455 15456 // Build a full-expression copy expression if initialization 15457 // succeeded and used a non-trivial constructor. Recover from 15458 // errors by pretending that the copy isn't necessary. 15459 if (!Result.isInvalid() && 15460 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15461 ->isTrivial()) { 15462 Result = MaybeCreateExprWithCleanups(Result); 15463 CopyExpr = Result.get(); 15464 } 15465 } 15466 } 15467 15468 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15469 CopyExpr); 15470 Captures.push_back(NewCap); 15471 } 15472 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15473 15474 // Pop the block scope now but keep it alive to the end of this function. 15475 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15476 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15477 15478 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15479 15480 // If the block isn't obviously global, i.e. it captures anything at 15481 // all, then we need to do a few things in the surrounding context: 15482 if (Result->getBlockDecl()->hasCaptures()) { 15483 // First, this expression has a new cleanup object. 15484 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15485 Cleanup.setExprNeedsCleanups(true); 15486 15487 // It also gets a branch-protected scope if any of the captured 15488 // variables needs destruction. 15489 for (const auto &CI : Result->getBlockDecl()->captures()) { 15490 const VarDecl *var = CI.getVariable(); 15491 if (var->getType().isDestructedType() != QualType::DK_none) { 15492 setFunctionHasBranchProtectedScope(); 15493 break; 15494 } 15495 } 15496 } 15497 15498 if (getCurFunction()) 15499 getCurFunction()->addBlock(BD); 15500 15501 return Result; 15502 } 15503 15504 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15505 SourceLocation RPLoc) { 15506 TypeSourceInfo *TInfo; 15507 GetTypeFromParser(Ty, &TInfo); 15508 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15509 } 15510 15511 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15512 Expr *E, TypeSourceInfo *TInfo, 15513 SourceLocation RPLoc) { 15514 Expr *OrigExpr = E; 15515 bool IsMS = false; 15516 15517 // CUDA device code does not support varargs. 15518 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15519 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15520 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15521 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15522 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15523 } 15524 } 15525 15526 // NVPTX does not support va_arg expression. 15527 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15528 Context.getTargetInfo().getTriple().isNVPTX()) 15529 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15530 15531 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15532 // as Microsoft ABI on an actual Microsoft platform, where 15533 // __builtin_ms_va_list and __builtin_va_list are the same.) 15534 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15535 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15536 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15537 if (Context.hasSameType(MSVaListType, E->getType())) { 15538 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15539 return ExprError(); 15540 IsMS = true; 15541 } 15542 } 15543 15544 // Get the va_list type 15545 QualType VaListType = Context.getBuiltinVaListType(); 15546 if (!IsMS) { 15547 if (VaListType->isArrayType()) { 15548 // Deal with implicit array decay; for example, on x86-64, 15549 // va_list is an array, but it's supposed to decay to 15550 // a pointer for va_arg. 15551 VaListType = Context.getArrayDecayedType(VaListType); 15552 // Make sure the input expression also decays appropriately. 15553 ExprResult Result = UsualUnaryConversions(E); 15554 if (Result.isInvalid()) 15555 return ExprError(); 15556 E = Result.get(); 15557 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15558 // If va_list is a record type and we are compiling in C++ mode, 15559 // check the argument using reference binding. 15560 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15561 Context, Context.getLValueReferenceType(VaListType), false); 15562 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15563 if (Init.isInvalid()) 15564 return ExprError(); 15565 E = Init.getAs<Expr>(); 15566 } else { 15567 // Otherwise, the va_list argument must be an l-value because 15568 // it is modified by va_arg. 15569 if (!E->isTypeDependent() && 15570 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15571 return ExprError(); 15572 } 15573 } 15574 15575 if (!IsMS && !E->isTypeDependent() && 15576 !Context.hasSameType(VaListType, E->getType())) 15577 return ExprError( 15578 Diag(E->getBeginLoc(), 15579 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15580 << OrigExpr->getType() << E->getSourceRange()); 15581 15582 if (!TInfo->getType()->isDependentType()) { 15583 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15584 diag::err_second_parameter_to_va_arg_incomplete, 15585 TInfo->getTypeLoc())) 15586 return ExprError(); 15587 15588 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15589 TInfo->getType(), 15590 diag::err_second_parameter_to_va_arg_abstract, 15591 TInfo->getTypeLoc())) 15592 return ExprError(); 15593 15594 if (!TInfo->getType().isPODType(Context)) { 15595 Diag(TInfo->getTypeLoc().getBeginLoc(), 15596 TInfo->getType()->isObjCLifetimeType() 15597 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15598 : diag::warn_second_parameter_to_va_arg_not_pod) 15599 << TInfo->getType() 15600 << TInfo->getTypeLoc().getSourceRange(); 15601 } 15602 15603 // Check for va_arg where arguments of the given type will be promoted 15604 // (i.e. this va_arg is guaranteed to have undefined behavior). 15605 QualType PromoteType; 15606 if (TInfo->getType()->isPromotableIntegerType()) { 15607 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15608 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15609 PromoteType = QualType(); 15610 } 15611 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15612 PromoteType = Context.DoubleTy; 15613 if (!PromoteType.isNull()) 15614 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15615 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15616 << TInfo->getType() 15617 << PromoteType 15618 << TInfo->getTypeLoc().getSourceRange()); 15619 } 15620 15621 QualType T = TInfo->getType().getNonLValueExprType(Context); 15622 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15623 } 15624 15625 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15626 // The type of __null will be int or long, depending on the size of 15627 // pointers on the target. 15628 QualType Ty; 15629 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15630 if (pw == Context.getTargetInfo().getIntWidth()) 15631 Ty = Context.IntTy; 15632 else if (pw == Context.getTargetInfo().getLongWidth()) 15633 Ty = Context.LongTy; 15634 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15635 Ty = Context.LongLongTy; 15636 else { 15637 llvm_unreachable("I don't know size of pointer!"); 15638 } 15639 15640 return new (Context) GNUNullExpr(Ty, TokenLoc); 15641 } 15642 15643 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15644 SourceLocation BuiltinLoc, 15645 SourceLocation RPLoc) { 15646 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15647 } 15648 15649 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15650 SourceLocation BuiltinLoc, 15651 SourceLocation RPLoc, 15652 DeclContext *ParentContext) { 15653 return new (Context) 15654 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15655 } 15656 15657 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15658 bool Diagnose) { 15659 if (!getLangOpts().ObjC) 15660 return false; 15661 15662 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15663 if (!PT) 15664 return false; 15665 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15666 15667 // Ignore any parens, implicit casts (should only be 15668 // array-to-pointer decays), and not-so-opaque values. The last is 15669 // important for making this trigger for property assignments. 15670 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15671 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15672 if (OV->getSourceExpr()) 15673 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15674 15675 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15676 if (!PT->isObjCIdType() && 15677 !(ID && ID->getIdentifier()->isStr("NSString"))) 15678 return false; 15679 if (!SL->isAscii()) 15680 return false; 15681 15682 if (Diagnose) { 15683 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15684 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15685 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15686 } 15687 return true; 15688 } 15689 15690 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15691 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15692 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15693 !SrcExpr->isNullPointerConstant( 15694 getASTContext(), Expr::NPC_NeverValueDependent)) { 15695 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15696 return false; 15697 if (Diagnose) { 15698 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15699 << /*number*/1 15700 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15701 Expr *NumLit = 15702 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15703 if (NumLit) 15704 Exp = NumLit; 15705 } 15706 return true; 15707 } 15708 15709 return false; 15710 } 15711 15712 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15713 const Expr *SrcExpr) { 15714 if (!DstType->isFunctionPointerType() || 15715 !SrcExpr->getType()->isFunctionType()) 15716 return false; 15717 15718 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15719 if (!DRE) 15720 return false; 15721 15722 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15723 if (!FD) 15724 return false; 15725 15726 return !S.checkAddressOfFunctionIsAvailable(FD, 15727 /*Complain=*/true, 15728 SrcExpr->getBeginLoc()); 15729 } 15730 15731 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15732 SourceLocation Loc, 15733 QualType DstType, QualType SrcType, 15734 Expr *SrcExpr, AssignmentAction Action, 15735 bool *Complained) { 15736 if (Complained) 15737 *Complained = false; 15738 15739 // Decode the result (notice that AST's are still created for extensions). 15740 bool CheckInferredResultType = false; 15741 bool isInvalid = false; 15742 unsigned DiagKind = 0; 15743 ConversionFixItGenerator ConvHints; 15744 bool MayHaveConvFixit = false; 15745 bool MayHaveFunctionDiff = false; 15746 const ObjCInterfaceDecl *IFace = nullptr; 15747 const ObjCProtocolDecl *PDecl = nullptr; 15748 15749 switch (ConvTy) { 15750 case Compatible: 15751 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15752 return false; 15753 15754 case PointerToInt: 15755 if (getLangOpts().CPlusPlus) { 15756 DiagKind = diag::err_typecheck_convert_pointer_int; 15757 isInvalid = true; 15758 } else { 15759 DiagKind = diag::ext_typecheck_convert_pointer_int; 15760 } 15761 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15762 MayHaveConvFixit = true; 15763 break; 15764 case IntToPointer: 15765 if (getLangOpts().CPlusPlus) { 15766 DiagKind = diag::err_typecheck_convert_int_pointer; 15767 isInvalid = true; 15768 } else { 15769 DiagKind = diag::ext_typecheck_convert_int_pointer; 15770 } 15771 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15772 MayHaveConvFixit = true; 15773 break; 15774 case IncompatibleFunctionPointer: 15775 if (getLangOpts().CPlusPlus) { 15776 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15777 isInvalid = true; 15778 } else { 15779 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15780 } 15781 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15782 MayHaveConvFixit = true; 15783 break; 15784 case IncompatiblePointer: 15785 if (Action == AA_Passing_CFAudited) { 15786 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15787 } else if (getLangOpts().CPlusPlus) { 15788 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15789 isInvalid = true; 15790 } else { 15791 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15792 } 15793 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15794 SrcType->isObjCObjectPointerType(); 15795 if (!CheckInferredResultType) { 15796 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15797 } else if (CheckInferredResultType) { 15798 SrcType = SrcType.getUnqualifiedType(); 15799 DstType = DstType.getUnqualifiedType(); 15800 } 15801 MayHaveConvFixit = true; 15802 break; 15803 case IncompatiblePointerSign: 15804 if (getLangOpts().CPlusPlus) { 15805 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15806 isInvalid = true; 15807 } else { 15808 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15809 } 15810 break; 15811 case FunctionVoidPointer: 15812 if (getLangOpts().CPlusPlus) { 15813 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15814 isInvalid = true; 15815 } else { 15816 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15817 } 15818 break; 15819 case IncompatiblePointerDiscardsQualifiers: { 15820 // Perform array-to-pointer decay if necessary. 15821 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15822 15823 isInvalid = true; 15824 15825 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15826 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15827 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15828 DiagKind = diag::err_typecheck_incompatible_address_space; 15829 break; 15830 15831 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15832 DiagKind = diag::err_typecheck_incompatible_ownership; 15833 break; 15834 } 15835 15836 llvm_unreachable("unknown error case for discarding qualifiers!"); 15837 // fallthrough 15838 } 15839 case CompatiblePointerDiscardsQualifiers: 15840 // If the qualifiers lost were because we were applying the 15841 // (deprecated) C++ conversion from a string literal to a char* 15842 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15843 // Ideally, this check would be performed in 15844 // checkPointerTypesForAssignment. However, that would require a 15845 // bit of refactoring (so that the second argument is an 15846 // expression, rather than a type), which should be done as part 15847 // of a larger effort to fix checkPointerTypesForAssignment for 15848 // C++ semantics. 15849 if (getLangOpts().CPlusPlus && 15850 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15851 return false; 15852 if (getLangOpts().CPlusPlus) { 15853 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15854 isInvalid = true; 15855 } else { 15856 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15857 } 15858 15859 break; 15860 case IncompatibleNestedPointerQualifiers: 15861 if (getLangOpts().CPlusPlus) { 15862 isInvalid = true; 15863 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15864 } else { 15865 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15866 } 15867 break; 15868 case IncompatibleNestedPointerAddressSpaceMismatch: 15869 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15870 isInvalid = true; 15871 break; 15872 case IntToBlockPointer: 15873 DiagKind = diag::err_int_to_block_pointer; 15874 isInvalid = true; 15875 break; 15876 case IncompatibleBlockPointer: 15877 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15878 isInvalid = true; 15879 break; 15880 case IncompatibleObjCQualifiedId: { 15881 if (SrcType->isObjCQualifiedIdType()) { 15882 const ObjCObjectPointerType *srcOPT = 15883 SrcType->castAs<ObjCObjectPointerType>(); 15884 for (auto *srcProto : srcOPT->quals()) { 15885 PDecl = srcProto; 15886 break; 15887 } 15888 if (const ObjCInterfaceType *IFaceT = 15889 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15890 IFace = IFaceT->getDecl(); 15891 } 15892 else if (DstType->isObjCQualifiedIdType()) { 15893 const ObjCObjectPointerType *dstOPT = 15894 DstType->castAs<ObjCObjectPointerType>(); 15895 for (auto *dstProto : dstOPT->quals()) { 15896 PDecl = dstProto; 15897 break; 15898 } 15899 if (const ObjCInterfaceType *IFaceT = 15900 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15901 IFace = IFaceT->getDecl(); 15902 } 15903 if (getLangOpts().CPlusPlus) { 15904 DiagKind = diag::err_incompatible_qualified_id; 15905 isInvalid = true; 15906 } else { 15907 DiagKind = diag::warn_incompatible_qualified_id; 15908 } 15909 break; 15910 } 15911 case IncompatibleVectors: 15912 if (getLangOpts().CPlusPlus) { 15913 DiagKind = diag::err_incompatible_vectors; 15914 isInvalid = true; 15915 } else { 15916 DiagKind = diag::warn_incompatible_vectors; 15917 } 15918 break; 15919 case IncompatibleObjCWeakRef: 15920 DiagKind = diag::err_arc_weak_unavailable_assign; 15921 isInvalid = true; 15922 break; 15923 case Incompatible: 15924 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15925 if (Complained) 15926 *Complained = true; 15927 return true; 15928 } 15929 15930 DiagKind = diag::err_typecheck_convert_incompatible; 15931 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15932 MayHaveConvFixit = true; 15933 isInvalid = true; 15934 MayHaveFunctionDiff = true; 15935 break; 15936 } 15937 15938 QualType FirstType, SecondType; 15939 switch (Action) { 15940 case AA_Assigning: 15941 case AA_Initializing: 15942 // The destination type comes first. 15943 FirstType = DstType; 15944 SecondType = SrcType; 15945 break; 15946 15947 case AA_Returning: 15948 case AA_Passing: 15949 case AA_Passing_CFAudited: 15950 case AA_Converting: 15951 case AA_Sending: 15952 case AA_Casting: 15953 // The source type comes first. 15954 FirstType = SrcType; 15955 SecondType = DstType; 15956 break; 15957 } 15958 15959 PartialDiagnostic FDiag = PDiag(DiagKind); 15960 if (Action == AA_Passing_CFAudited) 15961 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15962 else 15963 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15964 15965 // If we can fix the conversion, suggest the FixIts. 15966 if (!ConvHints.isNull()) { 15967 for (FixItHint &H : ConvHints.Hints) 15968 FDiag << H; 15969 } 15970 15971 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15972 15973 if (MayHaveFunctionDiff) 15974 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15975 15976 Diag(Loc, FDiag); 15977 if ((DiagKind == diag::warn_incompatible_qualified_id || 15978 DiagKind == diag::err_incompatible_qualified_id) && 15979 PDecl && IFace && !IFace->hasDefinition()) 15980 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15981 << IFace << PDecl; 15982 15983 if (SecondType == Context.OverloadTy) 15984 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15985 FirstType, /*TakingAddress=*/true); 15986 15987 if (CheckInferredResultType) 15988 EmitRelatedResultTypeNote(SrcExpr); 15989 15990 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15991 EmitRelatedResultTypeNoteForReturn(DstType); 15992 15993 if (Complained) 15994 *Complained = true; 15995 return isInvalid; 15996 } 15997 15998 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15999 llvm::APSInt *Result, 16000 AllowFoldKind CanFold) { 16001 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16002 public: 16003 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16004 QualType T) override { 16005 return S.Diag(Loc, diag::err_ice_not_integral) 16006 << T << S.LangOpts.CPlusPlus; 16007 } 16008 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16009 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16010 } 16011 } Diagnoser; 16012 16013 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16014 } 16015 16016 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16017 llvm::APSInt *Result, 16018 unsigned DiagID, 16019 AllowFoldKind CanFold) { 16020 class IDDiagnoser : public VerifyICEDiagnoser { 16021 unsigned DiagID; 16022 16023 public: 16024 IDDiagnoser(unsigned DiagID) 16025 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16026 16027 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16028 return S.Diag(Loc, DiagID); 16029 } 16030 } Diagnoser(DiagID); 16031 16032 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16033 } 16034 16035 Sema::SemaDiagnosticBuilder 16036 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16037 QualType T) { 16038 return diagnoseNotICE(S, Loc); 16039 } 16040 16041 Sema::SemaDiagnosticBuilder 16042 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16043 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16044 } 16045 16046 ExprResult 16047 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16048 VerifyICEDiagnoser &Diagnoser, 16049 AllowFoldKind CanFold) { 16050 SourceLocation DiagLoc = E->getBeginLoc(); 16051 16052 if (getLangOpts().CPlusPlus11) { 16053 // C++11 [expr.const]p5: 16054 // If an expression of literal class type is used in a context where an 16055 // integral constant expression is required, then that class type shall 16056 // have a single non-explicit conversion function to an integral or 16057 // unscoped enumeration type 16058 ExprResult Converted; 16059 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16060 VerifyICEDiagnoser &BaseDiagnoser; 16061 public: 16062 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16063 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16064 BaseDiagnoser.Suppress, true), 16065 BaseDiagnoser(BaseDiagnoser) {} 16066 16067 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16068 QualType T) override { 16069 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16070 } 16071 16072 SemaDiagnosticBuilder diagnoseIncomplete( 16073 Sema &S, SourceLocation Loc, QualType T) override { 16074 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16075 } 16076 16077 SemaDiagnosticBuilder diagnoseExplicitConv( 16078 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16079 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16080 } 16081 16082 SemaDiagnosticBuilder noteExplicitConv( 16083 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16084 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16085 << ConvTy->isEnumeralType() << ConvTy; 16086 } 16087 16088 SemaDiagnosticBuilder diagnoseAmbiguous( 16089 Sema &S, SourceLocation Loc, QualType T) override { 16090 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16091 } 16092 16093 SemaDiagnosticBuilder noteAmbiguous( 16094 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16095 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16096 << ConvTy->isEnumeralType() << ConvTy; 16097 } 16098 16099 SemaDiagnosticBuilder diagnoseConversion( 16100 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16101 llvm_unreachable("conversion functions are permitted"); 16102 } 16103 } ConvertDiagnoser(Diagnoser); 16104 16105 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16106 ConvertDiagnoser); 16107 if (Converted.isInvalid()) 16108 return Converted; 16109 E = Converted.get(); 16110 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16111 return ExprError(); 16112 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16113 // An ICE must be of integral or unscoped enumeration type. 16114 if (!Diagnoser.Suppress) 16115 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16116 << E->getSourceRange(); 16117 return ExprError(); 16118 } 16119 16120 ExprResult RValueExpr = DefaultLvalueConversion(E); 16121 if (RValueExpr.isInvalid()) 16122 return ExprError(); 16123 16124 E = RValueExpr.get(); 16125 16126 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16127 // in the non-ICE case. 16128 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16129 if (Result) 16130 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16131 if (!isa<ConstantExpr>(E)) 16132 E = ConstantExpr::Create(Context, E); 16133 return E; 16134 } 16135 16136 Expr::EvalResult EvalResult; 16137 SmallVector<PartialDiagnosticAt, 8> Notes; 16138 EvalResult.Diag = &Notes; 16139 16140 // Try to evaluate the expression, and produce diagnostics explaining why it's 16141 // not a constant expression as a side-effect. 16142 bool Folded = 16143 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16144 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16145 16146 if (!isa<ConstantExpr>(E)) 16147 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16148 16149 // In C++11, we can rely on diagnostics being produced for any expression 16150 // which is not a constant expression. If no diagnostics were produced, then 16151 // this is a constant expression. 16152 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16153 if (Result) 16154 *Result = EvalResult.Val.getInt(); 16155 return E; 16156 } 16157 16158 // If our only note is the usual "invalid subexpression" note, just point 16159 // the caret at its location rather than producing an essentially 16160 // redundant note. 16161 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16162 diag::note_invalid_subexpr_in_const_expr) { 16163 DiagLoc = Notes[0].first; 16164 Notes.clear(); 16165 } 16166 16167 if (!Folded || !CanFold) { 16168 if (!Diagnoser.Suppress) { 16169 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16170 for (const PartialDiagnosticAt &Note : Notes) 16171 Diag(Note.first, Note.second); 16172 } 16173 16174 return ExprError(); 16175 } 16176 16177 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16178 for (const PartialDiagnosticAt &Note : Notes) 16179 Diag(Note.first, Note.second); 16180 16181 if (Result) 16182 *Result = EvalResult.Val.getInt(); 16183 return E; 16184 } 16185 16186 namespace { 16187 // Handle the case where we conclude a expression which we speculatively 16188 // considered to be unevaluated is actually evaluated. 16189 class TransformToPE : public TreeTransform<TransformToPE> { 16190 typedef TreeTransform<TransformToPE> BaseTransform; 16191 16192 public: 16193 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16194 16195 // Make sure we redo semantic analysis 16196 bool AlwaysRebuild() { return true; } 16197 bool ReplacingOriginal() { return true; } 16198 16199 // We need to special-case DeclRefExprs referring to FieldDecls which 16200 // are not part of a member pointer formation; normal TreeTransforming 16201 // doesn't catch this case because of the way we represent them in the AST. 16202 // FIXME: This is a bit ugly; is it really the best way to handle this 16203 // case? 16204 // 16205 // Error on DeclRefExprs referring to FieldDecls. 16206 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16207 if (isa<FieldDecl>(E->getDecl()) && 16208 !SemaRef.isUnevaluatedContext()) 16209 return SemaRef.Diag(E->getLocation(), 16210 diag::err_invalid_non_static_member_use) 16211 << E->getDecl() << E->getSourceRange(); 16212 16213 return BaseTransform::TransformDeclRefExpr(E); 16214 } 16215 16216 // Exception: filter out member pointer formation 16217 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16218 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16219 return E; 16220 16221 return BaseTransform::TransformUnaryOperator(E); 16222 } 16223 16224 // The body of a lambda-expression is in a separate expression evaluation 16225 // context so never needs to be transformed. 16226 // FIXME: Ideally we wouldn't transform the closure type either, and would 16227 // just recreate the capture expressions and lambda expression. 16228 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16229 return SkipLambdaBody(E, Body); 16230 } 16231 }; 16232 } 16233 16234 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16235 assert(isUnevaluatedContext() && 16236 "Should only transform unevaluated expressions"); 16237 ExprEvalContexts.back().Context = 16238 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16239 if (isUnevaluatedContext()) 16240 return E; 16241 return TransformToPE(*this).TransformExpr(E); 16242 } 16243 16244 void 16245 Sema::PushExpressionEvaluationContext( 16246 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16247 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16248 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16249 LambdaContextDecl, ExprContext); 16250 Cleanup.reset(); 16251 if (!MaybeODRUseExprs.empty()) 16252 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16253 } 16254 16255 void 16256 Sema::PushExpressionEvaluationContext( 16257 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16258 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16259 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16260 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16261 } 16262 16263 namespace { 16264 16265 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16266 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16267 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16268 if (E->getOpcode() == UO_Deref) 16269 return CheckPossibleDeref(S, E->getSubExpr()); 16270 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16271 return CheckPossibleDeref(S, E->getBase()); 16272 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16273 return CheckPossibleDeref(S, E->getBase()); 16274 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16275 QualType Inner; 16276 QualType Ty = E->getType(); 16277 if (const auto *Ptr = Ty->getAs<PointerType>()) 16278 Inner = Ptr->getPointeeType(); 16279 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16280 Inner = Arr->getElementType(); 16281 else 16282 return nullptr; 16283 16284 if (Inner->hasAttr(attr::NoDeref)) 16285 return E; 16286 } 16287 return nullptr; 16288 } 16289 16290 } // namespace 16291 16292 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16293 for (const Expr *E : Rec.PossibleDerefs) { 16294 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16295 if (DeclRef) { 16296 const ValueDecl *Decl = DeclRef->getDecl(); 16297 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16298 << Decl->getName() << E->getSourceRange(); 16299 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16300 } else { 16301 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16302 << E->getSourceRange(); 16303 } 16304 } 16305 Rec.PossibleDerefs.clear(); 16306 } 16307 16308 /// Check whether E, which is either a discarded-value expression or an 16309 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16310 /// and if so, remove it from the list of volatile-qualified assignments that 16311 /// we are going to warn are deprecated. 16312 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16313 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16314 return; 16315 16316 // Note: ignoring parens here is not justified by the standard rules, but 16317 // ignoring parentheses seems like a more reasonable approach, and this only 16318 // drives a deprecation warning so doesn't affect conformance. 16319 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16320 if (BO->getOpcode() == BO_Assign) { 16321 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16322 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16323 LHSs.end()); 16324 } 16325 } 16326 } 16327 16328 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16329 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16330 RebuildingImmediateInvocation) 16331 return E; 16332 16333 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16334 /// It's OK if this fails; we'll also remove this in 16335 /// HandleImmediateInvocations, but catching it here allows us to avoid 16336 /// walking the AST looking for it in simple cases. 16337 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16338 if (auto *DeclRef = 16339 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16340 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16341 16342 E = MaybeCreateExprWithCleanups(E); 16343 16344 ConstantExpr *Res = ConstantExpr::Create( 16345 getASTContext(), E.get(), 16346 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16347 getASTContext()), 16348 /*IsImmediateInvocation*/ true); 16349 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16350 return Res; 16351 } 16352 16353 static void EvaluateAndDiagnoseImmediateInvocation( 16354 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16355 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16356 Expr::EvalResult Eval; 16357 Eval.Diag = &Notes; 16358 ConstantExpr *CE = Candidate.getPointer(); 16359 bool Result = CE->EvaluateAsConstantExpr( 16360 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16361 if (!Result || !Notes.empty()) { 16362 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16363 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16364 InnerExpr = FunctionalCast->getSubExpr(); 16365 FunctionDecl *FD = nullptr; 16366 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16367 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16368 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16369 FD = Call->getConstructor(); 16370 else 16371 llvm_unreachable("unhandled decl kind"); 16372 assert(FD->isConsteval()); 16373 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16374 for (auto &Note : Notes) 16375 SemaRef.Diag(Note.first, Note.second); 16376 return; 16377 } 16378 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16379 } 16380 16381 static void RemoveNestedImmediateInvocation( 16382 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16383 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16384 struct ComplexRemove : TreeTransform<ComplexRemove> { 16385 using Base = TreeTransform<ComplexRemove>; 16386 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16387 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16388 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16389 CurrentII; 16390 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16391 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16392 SmallVector<Sema::ImmediateInvocationCandidate, 16393 4>::reverse_iterator Current) 16394 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16395 void RemoveImmediateInvocation(ConstantExpr* E) { 16396 auto It = std::find_if(CurrentII, IISet.rend(), 16397 [E](Sema::ImmediateInvocationCandidate Elem) { 16398 return Elem.getPointer() == E; 16399 }); 16400 assert(It != IISet.rend() && 16401 "ConstantExpr marked IsImmediateInvocation should " 16402 "be present"); 16403 It->setInt(1); // Mark as deleted 16404 } 16405 ExprResult TransformConstantExpr(ConstantExpr *E) { 16406 if (!E->isImmediateInvocation()) 16407 return Base::TransformConstantExpr(E); 16408 RemoveImmediateInvocation(E); 16409 return Base::TransformExpr(E->getSubExpr()); 16410 } 16411 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16412 /// we need to remove its DeclRefExpr from the DRSet. 16413 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16414 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16415 return Base::TransformCXXOperatorCallExpr(E); 16416 } 16417 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16418 /// here. 16419 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16420 if (!Init) 16421 return Init; 16422 /// ConstantExpr are the first layer of implicit node to be removed so if 16423 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16424 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16425 if (CE->isImmediateInvocation()) 16426 RemoveImmediateInvocation(CE); 16427 return Base::TransformInitializer(Init, NotCopyInit); 16428 } 16429 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16430 DRSet.erase(E); 16431 return E; 16432 } 16433 bool AlwaysRebuild() { return false; } 16434 bool ReplacingOriginal() { return true; } 16435 bool AllowSkippingCXXConstructExpr() { 16436 bool Res = AllowSkippingFirstCXXConstructExpr; 16437 AllowSkippingFirstCXXConstructExpr = true; 16438 return Res; 16439 } 16440 bool AllowSkippingFirstCXXConstructExpr = true; 16441 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16442 Rec.ImmediateInvocationCandidates, It); 16443 16444 /// CXXConstructExpr with a single argument are getting skipped by 16445 /// TreeTransform in some situtation because they could be implicit. This 16446 /// can only occur for the top-level CXXConstructExpr because it is used 16447 /// nowhere in the expression being transformed therefore will not be rebuilt. 16448 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16449 /// skipping the first CXXConstructExpr. 16450 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16451 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16452 16453 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16454 assert(Res.isUsable()); 16455 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16456 It->getPointer()->setSubExpr(Res.get()); 16457 } 16458 16459 static void 16460 HandleImmediateInvocations(Sema &SemaRef, 16461 Sema::ExpressionEvaluationContextRecord &Rec) { 16462 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16463 Rec.ReferenceToConsteval.size() == 0) || 16464 SemaRef.RebuildingImmediateInvocation) 16465 return; 16466 16467 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16468 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16469 /// need to remove ReferenceToConsteval in the immediate invocation. 16470 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16471 16472 /// Prevent sema calls during the tree transform from adding pointers that 16473 /// are already in the sets. 16474 llvm::SaveAndRestore<bool> DisableIITracking( 16475 SemaRef.RebuildingImmediateInvocation, true); 16476 16477 /// Prevent diagnostic during tree transfrom as they are duplicates 16478 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16479 16480 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16481 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16482 if (!It->getInt()) 16483 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16484 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16485 Rec.ReferenceToConsteval.size()) { 16486 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16487 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16488 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16489 bool VisitDeclRefExpr(DeclRefExpr *E) { 16490 DRSet.erase(E); 16491 return DRSet.size(); 16492 } 16493 } Visitor(Rec.ReferenceToConsteval); 16494 Visitor.TraverseStmt( 16495 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16496 } 16497 for (auto CE : Rec.ImmediateInvocationCandidates) 16498 if (!CE.getInt()) 16499 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16500 for (auto DR : Rec.ReferenceToConsteval) { 16501 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16502 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16503 << FD; 16504 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16505 } 16506 } 16507 16508 void Sema::PopExpressionEvaluationContext() { 16509 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16510 unsigned NumTypos = Rec.NumTypos; 16511 16512 if (!Rec.Lambdas.empty()) { 16513 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16514 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16515 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16516 unsigned D; 16517 if (Rec.isUnevaluated()) { 16518 // C++11 [expr.prim.lambda]p2: 16519 // A lambda-expression shall not appear in an unevaluated operand 16520 // (Clause 5). 16521 D = diag::err_lambda_unevaluated_operand; 16522 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16523 // C++1y [expr.const]p2: 16524 // A conditional-expression e is a core constant expression unless the 16525 // evaluation of e, following the rules of the abstract machine, would 16526 // evaluate [...] a lambda-expression. 16527 D = diag::err_lambda_in_constant_expression; 16528 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16529 // C++17 [expr.prim.lamda]p2: 16530 // A lambda-expression shall not appear [...] in a template-argument. 16531 D = diag::err_lambda_in_invalid_context; 16532 } else 16533 llvm_unreachable("Couldn't infer lambda error message."); 16534 16535 for (const auto *L : Rec.Lambdas) 16536 Diag(L->getBeginLoc(), D); 16537 } 16538 } 16539 16540 WarnOnPendingNoDerefs(Rec); 16541 HandleImmediateInvocations(*this, Rec); 16542 16543 // Warn on any volatile-qualified simple-assignments that are not discarded- 16544 // value expressions nor unevaluated operands (those cases get removed from 16545 // this list by CheckUnusedVolatileAssignment). 16546 for (auto *BO : Rec.VolatileAssignmentLHSs) 16547 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16548 << BO->getType(); 16549 16550 // When are coming out of an unevaluated context, clear out any 16551 // temporaries that we may have created as part of the evaluation of 16552 // the expression in that context: they aren't relevant because they 16553 // will never be constructed. 16554 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16555 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16556 ExprCleanupObjects.end()); 16557 Cleanup = Rec.ParentCleanup; 16558 CleanupVarDeclMarking(); 16559 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16560 // Otherwise, merge the contexts together. 16561 } else { 16562 Cleanup.mergeFrom(Rec.ParentCleanup); 16563 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16564 Rec.SavedMaybeODRUseExprs.end()); 16565 } 16566 16567 // Pop the current expression evaluation context off the stack. 16568 ExprEvalContexts.pop_back(); 16569 16570 // The global expression evaluation context record is never popped. 16571 ExprEvalContexts.back().NumTypos += NumTypos; 16572 } 16573 16574 void Sema::DiscardCleanupsInEvaluationContext() { 16575 ExprCleanupObjects.erase( 16576 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16577 ExprCleanupObjects.end()); 16578 Cleanup.reset(); 16579 MaybeODRUseExprs.clear(); 16580 } 16581 16582 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16583 ExprResult Result = CheckPlaceholderExpr(E); 16584 if (Result.isInvalid()) 16585 return ExprError(); 16586 E = Result.get(); 16587 if (!E->getType()->isVariablyModifiedType()) 16588 return E; 16589 return TransformToPotentiallyEvaluated(E); 16590 } 16591 16592 /// Are we in a context that is potentially constant evaluated per C++20 16593 /// [expr.const]p12? 16594 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16595 /// C++2a [expr.const]p12: 16596 // An expression or conversion is potentially constant evaluated if it is 16597 switch (SemaRef.ExprEvalContexts.back().Context) { 16598 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16599 // -- a manifestly constant-evaluated expression, 16600 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16601 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16602 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16603 // -- a potentially-evaluated expression, 16604 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16605 // -- an immediate subexpression of a braced-init-list, 16606 16607 // -- [FIXME] an expression of the form & cast-expression that occurs 16608 // within a templated entity 16609 // -- a subexpression of one of the above that is not a subexpression of 16610 // a nested unevaluated operand. 16611 return true; 16612 16613 case Sema::ExpressionEvaluationContext::Unevaluated: 16614 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16615 // Expressions in this context are never evaluated. 16616 return false; 16617 } 16618 llvm_unreachable("Invalid context"); 16619 } 16620 16621 /// Return true if this function has a calling convention that requires mangling 16622 /// in the size of the parameter pack. 16623 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16624 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16625 // we don't need parameter type sizes. 16626 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16627 if (!TT.isOSWindows() || !TT.isX86()) 16628 return false; 16629 16630 // If this is C++ and this isn't an extern "C" function, parameters do not 16631 // need to be complete. In this case, C++ mangling will apply, which doesn't 16632 // use the size of the parameters. 16633 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16634 return false; 16635 16636 // Stdcall, fastcall, and vectorcall need this special treatment. 16637 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16638 switch (CC) { 16639 case CC_X86StdCall: 16640 case CC_X86FastCall: 16641 case CC_X86VectorCall: 16642 return true; 16643 default: 16644 break; 16645 } 16646 return false; 16647 } 16648 16649 /// Require that all of the parameter types of function be complete. Normally, 16650 /// parameter types are only required to be complete when a function is called 16651 /// or defined, but to mangle functions with certain calling conventions, the 16652 /// mangler needs to know the size of the parameter list. In this situation, 16653 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16654 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16655 /// result in a linker error. Clang doesn't implement this behavior, and instead 16656 /// attempts to error at compile time. 16657 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16658 SourceLocation Loc) { 16659 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16660 FunctionDecl *FD; 16661 ParmVarDecl *Param; 16662 16663 public: 16664 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16665 : FD(FD), Param(Param) {} 16666 16667 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16668 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16669 StringRef CCName; 16670 switch (CC) { 16671 case CC_X86StdCall: 16672 CCName = "stdcall"; 16673 break; 16674 case CC_X86FastCall: 16675 CCName = "fastcall"; 16676 break; 16677 case CC_X86VectorCall: 16678 CCName = "vectorcall"; 16679 break; 16680 default: 16681 llvm_unreachable("CC does not need mangling"); 16682 } 16683 16684 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16685 << Param->getDeclName() << FD->getDeclName() << CCName; 16686 } 16687 }; 16688 16689 for (ParmVarDecl *Param : FD->parameters()) { 16690 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16691 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16692 } 16693 } 16694 16695 namespace { 16696 enum class OdrUseContext { 16697 /// Declarations in this context are not odr-used. 16698 None, 16699 /// Declarations in this context are formally odr-used, but this is a 16700 /// dependent context. 16701 Dependent, 16702 /// Declarations in this context are odr-used but not actually used (yet). 16703 FormallyOdrUsed, 16704 /// Declarations in this context are used. 16705 Used 16706 }; 16707 } 16708 16709 /// Are we within a context in which references to resolved functions or to 16710 /// variables result in odr-use? 16711 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16712 OdrUseContext Result; 16713 16714 switch (SemaRef.ExprEvalContexts.back().Context) { 16715 case Sema::ExpressionEvaluationContext::Unevaluated: 16716 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16717 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16718 return OdrUseContext::None; 16719 16720 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16721 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16722 Result = OdrUseContext::Used; 16723 break; 16724 16725 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16726 Result = OdrUseContext::FormallyOdrUsed; 16727 break; 16728 16729 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16730 // A default argument formally results in odr-use, but doesn't actually 16731 // result in a use in any real sense until it itself is used. 16732 Result = OdrUseContext::FormallyOdrUsed; 16733 break; 16734 } 16735 16736 if (SemaRef.CurContext->isDependentContext()) 16737 return OdrUseContext::Dependent; 16738 16739 return Result; 16740 } 16741 16742 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16743 if (!Func->isConstexpr()) 16744 return false; 16745 16746 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16747 return true; 16748 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16749 return CCD && CCD->getInheritedConstructor(); 16750 } 16751 16752 /// Mark a function referenced, and check whether it is odr-used 16753 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16754 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16755 bool MightBeOdrUse) { 16756 assert(Func && "No function?"); 16757 16758 Func->setReferenced(); 16759 16760 // Recursive functions aren't really used until they're used from some other 16761 // context. 16762 bool IsRecursiveCall = CurContext == Func; 16763 16764 // C++11 [basic.def.odr]p3: 16765 // A function whose name appears as a potentially-evaluated expression is 16766 // odr-used if it is the unique lookup result or the selected member of a 16767 // set of overloaded functions [...]. 16768 // 16769 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16770 // can just check that here. 16771 OdrUseContext OdrUse = 16772 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16773 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16774 OdrUse = OdrUseContext::FormallyOdrUsed; 16775 16776 // Trivial default constructors and destructors are never actually used. 16777 // FIXME: What about other special members? 16778 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16779 OdrUse == OdrUseContext::Used) { 16780 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16781 if (Constructor->isDefaultConstructor()) 16782 OdrUse = OdrUseContext::FormallyOdrUsed; 16783 if (isa<CXXDestructorDecl>(Func)) 16784 OdrUse = OdrUseContext::FormallyOdrUsed; 16785 } 16786 16787 // C++20 [expr.const]p12: 16788 // A function [...] is needed for constant evaluation if it is [...] a 16789 // constexpr function that is named by an expression that is potentially 16790 // constant evaluated 16791 bool NeededForConstantEvaluation = 16792 isPotentiallyConstantEvaluatedContext(*this) && 16793 isImplicitlyDefinableConstexprFunction(Func); 16794 16795 // Determine whether we require a function definition to exist, per 16796 // C++11 [temp.inst]p3: 16797 // Unless a function template specialization has been explicitly 16798 // instantiated or explicitly specialized, the function template 16799 // specialization is implicitly instantiated when the specialization is 16800 // referenced in a context that requires a function definition to exist. 16801 // C++20 [temp.inst]p7: 16802 // The existence of a definition of a [...] function is considered to 16803 // affect the semantics of the program if the [...] function is needed for 16804 // constant evaluation by an expression 16805 // C++20 [basic.def.odr]p10: 16806 // Every program shall contain exactly one definition of every non-inline 16807 // function or variable that is odr-used in that program outside of a 16808 // discarded statement 16809 // C++20 [special]p1: 16810 // The implementation will implicitly define [defaulted special members] 16811 // if they are odr-used or needed for constant evaluation. 16812 // 16813 // Note that we skip the implicit instantiation of templates that are only 16814 // used in unused default arguments or by recursive calls to themselves. 16815 // This is formally non-conforming, but seems reasonable in practice. 16816 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16817 NeededForConstantEvaluation); 16818 16819 // C++14 [temp.expl.spec]p6: 16820 // If a template [...] is explicitly specialized then that specialization 16821 // shall be declared before the first use of that specialization that would 16822 // cause an implicit instantiation to take place, in every translation unit 16823 // in which such a use occurs 16824 if (NeedDefinition && 16825 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16826 Func->getMemberSpecializationInfo())) 16827 checkSpecializationVisibility(Loc, Func); 16828 16829 if (getLangOpts().CUDA) 16830 CheckCUDACall(Loc, Func); 16831 16832 if (getLangOpts().SYCLIsDevice) 16833 checkSYCLDeviceFunction(Loc, Func); 16834 16835 // If we need a definition, try to create one. 16836 if (NeedDefinition && !Func->getBody()) { 16837 runWithSufficientStackSpace(Loc, [&] { 16838 if (CXXConstructorDecl *Constructor = 16839 dyn_cast<CXXConstructorDecl>(Func)) { 16840 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16841 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16842 if (Constructor->isDefaultConstructor()) { 16843 if (Constructor->isTrivial() && 16844 !Constructor->hasAttr<DLLExportAttr>()) 16845 return; 16846 DefineImplicitDefaultConstructor(Loc, Constructor); 16847 } else if (Constructor->isCopyConstructor()) { 16848 DefineImplicitCopyConstructor(Loc, Constructor); 16849 } else if (Constructor->isMoveConstructor()) { 16850 DefineImplicitMoveConstructor(Loc, Constructor); 16851 } 16852 } else if (Constructor->getInheritedConstructor()) { 16853 DefineInheritingConstructor(Loc, Constructor); 16854 } 16855 } else if (CXXDestructorDecl *Destructor = 16856 dyn_cast<CXXDestructorDecl>(Func)) { 16857 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16858 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16859 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16860 return; 16861 DefineImplicitDestructor(Loc, Destructor); 16862 } 16863 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16864 MarkVTableUsed(Loc, Destructor->getParent()); 16865 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16866 if (MethodDecl->isOverloadedOperator() && 16867 MethodDecl->getOverloadedOperator() == OO_Equal) { 16868 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16869 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16870 if (MethodDecl->isCopyAssignmentOperator()) 16871 DefineImplicitCopyAssignment(Loc, MethodDecl); 16872 else if (MethodDecl->isMoveAssignmentOperator()) 16873 DefineImplicitMoveAssignment(Loc, MethodDecl); 16874 } 16875 } else if (isa<CXXConversionDecl>(MethodDecl) && 16876 MethodDecl->getParent()->isLambda()) { 16877 CXXConversionDecl *Conversion = 16878 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16879 if (Conversion->isLambdaToBlockPointerConversion()) 16880 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16881 else 16882 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16883 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16884 MarkVTableUsed(Loc, MethodDecl->getParent()); 16885 } 16886 16887 if (Func->isDefaulted() && !Func->isDeleted()) { 16888 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16889 if (DCK != DefaultedComparisonKind::None) 16890 DefineDefaultedComparison(Loc, Func, DCK); 16891 } 16892 16893 // Implicit instantiation of function templates and member functions of 16894 // class templates. 16895 if (Func->isImplicitlyInstantiable()) { 16896 TemplateSpecializationKind TSK = 16897 Func->getTemplateSpecializationKindForInstantiation(); 16898 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16899 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16900 if (FirstInstantiation) { 16901 PointOfInstantiation = Loc; 16902 if (auto *MSI = Func->getMemberSpecializationInfo()) 16903 MSI->setPointOfInstantiation(Loc); 16904 // FIXME: Notify listener. 16905 else 16906 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16907 } else if (TSK != TSK_ImplicitInstantiation) { 16908 // Use the point of use as the point of instantiation, instead of the 16909 // point of explicit instantiation (which we track as the actual point 16910 // of instantiation). This gives better backtraces in diagnostics. 16911 PointOfInstantiation = Loc; 16912 } 16913 16914 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16915 Func->isConstexpr()) { 16916 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16917 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16918 CodeSynthesisContexts.size()) 16919 PendingLocalImplicitInstantiations.push_back( 16920 std::make_pair(Func, PointOfInstantiation)); 16921 else if (Func->isConstexpr()) 16922 // Do not defer instantiations of constexpr functions, to avoid the 16923 // expression evaluator needing to call back into Sema if it sees a 16924 // call to such a function. 16925 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16926 else { 16927 Func->setInstantiationIsPending(true); 16928 PendingInstantiations.push_back( 16929 std::make_pair(Func, PointOfInstantiation)); 16930 // Notify the consumer that a function was implicitly instantiated. 16931 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16932 } 16933 } 16934 } else { 16935 // Walk redefinitions, as some of them may be instantiable. 16936 for (auto i : Func->redecls()) { 16937 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16938 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16939 } 16940 } 16941 }); 16942 } 16943 16944 // C++14 [except.spec]p17: 16945 // An exception-specification is considered to be needed when: 16946 // - the function is odr-used or, if it appears in an unevaluated operand, 16947 // would be odr-used if the expression were potentially-evaluated; 16948 // 16949 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16950 // function is a pure virtual function we're calling, and in that case the 16951 // function was selected by overload resolution and we need to resolve its 16952 // exception specification for a different reason. 16953 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16954 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16955 ResolveExceptionSpec(Loc, FPT); 16956 16957 // If this is the first "real" use, act on that. 16958 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16959 // Keep track of used but undefined functions. 16960 if (!Func->isDefined()) { 16961 if (mightHaveNonExternalLinkage(Func)) 16962 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16963 else if (Func->getMostRecentDecl()->isInlined() && 16964 !LangOpts.GNUInline && 16965 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16966 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16967 else if (isExternalWithNoLinkageType(Func)) 16968 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16969 } 16970 16971 // Some x86 Windows calling conventions mangle the size of the parameter 16972 // pack into the name. Computing the size of the parameters requires the 16973 // parameter types to be complete. Check that now. 16974 if (funcHasParameterSizeMangling(*this, Func)) 16975 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16976 16977 // In the MS C++ ABI, the compiler emits destructor variants where they are 16978 // used. If the destructor is used here but defined elsewhere, mark the 16979 // virtual base destructors referenced. If those virtual base destructors 16980 // are inline, this will ensure they are defined when emitting the complete 16981 // destructor variant. This checking may be redundant if the destructor is 16982 // provided later in this TU. 16983 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16984 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16985 CXXRecordDecl *Parent = Dtor->getParent(); 16986 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16987 CheckCompleteDestructorVariant(Loc, Dtor); 16988 } 16989 } 16990 16991 Func->markUsed(Context); 16992 } 16993 } 16994 16995 /// Directly mark a variable odr-used. Given a choice, prefer to use 16996 /// MarkVariableReferenced since it does additional checks and then 16997 /// calls MarkVarDeclODRUsed. 16998 /// If the variable must be captured: 16999 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17000 /// - else capture it in the DeclContext that maps to the 17001 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17002 static void 17003 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17004 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17005 // Keep track of used but undefined variables. 17006 // FIXME: We shouldn't suppress this warning for static data members. 17007 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17008 (!Var->isExternallyVisible() || Var->isInline() || 17009 SemaRef.isExternalWithNoLinkageType(Var)) && 17010 !(Var->isStaticDataMember() && Var->hasInit())) { 17011 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17012 if (old.isInvalid()) 17013 old = Loc; 17014 } 17015 QualType CaptureType, DeclRefType; 17016 if (SemaRef.LangOpts.OpenMP) 17017 SemaRef.tryCaptureOpenMPLambdas(Var); 17018 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17019 /*EllipsisLoc*/ SourceLocation(), 17020 /*BuildAndDiagnose*/ true, 17021 CaptureType, DeclRefType, 17022 FunctionScopeIndexToStopAt); 17023 17024 Var->markUsed(SemaRef.Context); 17025 } 17026 17027 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17028 SourceLocation Loc, 17029 unsigned CapturingScopeIndex) { 17030 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17031 } 17032 17033 static void 17034 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17035 ValueDecl *var, DeclContext *DC) { 17036 DeclContext *VarDC = var->getDeclContext(); 17037 17038 // If the parameter still belongs to the translation unit, then 17039 // we're actually just using one parameter in the declaration of 17040 // the next. 17041 if (isa<ParmVarDecl>(var) && 17042 isa<TranslationUnitDecl>(VarDC)) 17043 return; 17044 17045 // For C code, don't diagnose about capture if we're not actually in code 17046 // right now; it's impossible to write a non-constant expression outside of 17047 // function context, so we'll get other (more useful) diagnostics later. 17048 // 17049 // For C++, things get a bit more nasty... it would be nice to suppress this 17050 // diagnostic for certain cases like using a local variable in an array bound 17051 // for a member of a local class, but the correct predicate is not obvious. 17052 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17053 return; 17054 17055 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17056 unsigned ContextKind = 3; // unknown 17057 if (isa<CXXMethodDecl>(VarDC) && 17058 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17059 ContextKind = 2; 17060 } else if (isa<FunctionDecl>(VarDC)) { 17061 ContextKind = 0; 17062 } else if (isa<BlockDecl>(VarDC)) { 17063 ContextKind = 1; 17064 } 17065 17066 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17067 << var << ValueKind << ContextKind << VarDC; 17068 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17069 << var; 17070 17071 // FIXME: Add additional diagnostic info about class etc. which prevents 17072 // capture. 17073 } 17074 17075 17076 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17077 bool &SubCapturesAreNested, 17078 QualType &CaptureType, 17079 QualType &DeclRefType) { 17080 // Check whether we've already captured it. 17081 if (CSI->CaptureMap.count(Var)) { 17082 // If we found a capture, any subcaptures are nested. 17083 SubCapturesAreNested = true; 17084 17085 // Retrieve the capture type for this variable. 17086 CaptureType = CSI->getCapture(Var).getCaptureType(); 17087 17088 // Compute the type of an expression that refers to this variable. 17089 DeclRefType = CaptureType.getNonReferenceType(); 17090 17091 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17092 // are mutable in the sense that user can change their value - they are 17093 // private instances of the captured declarations. 17094 const Capture &Cap = CSI->getCapture(Var); 17095 if (Cap.isCopyCapture() && 17096 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17097 !(isa<CapturedRegionScopeInfo>(CSI) && 17098 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17099 DeclRefType.addConst(); 17100 return true; 17101 } 17102 return false; 17103 } 17104 17105 // Only block literals, captured statements, and lambda expressions can 17106 // capture; other scopes don't work. 17107 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17108 SourceLocation Loc, 17109 const bool Diagnose, Sema &S) { 17110 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17111 return getLambdaAwareParentOfDeclContext(DC); 17112 else if (Var->hasLocalStorage()) { 17113 if (Diagnose) 17114 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17115 } 17116 return nullptr; 17117 } 17118 17119 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17120 // certain types of variables (unnamed, variably modified types etc.) 17121 // so check for eligibility. 17122 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17123 SourceLocation Loc, 17124 const bool Diagnose, Sema &S) { 17125 17126 bool IsBlock = isa<BlockScopeInfo>(CSI); 17127 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17128 17129 // Lambdas are not allowed to capture unnamed variables 17130 // (e.g. anonymous unions). 17131 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17132 // assuming that's the intent. 17133 if (IsLambda && !Var->getDeclName()) { 17134 if (Diagnose) { 17135 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17136 S.Diag(Var->getLocation(), diag::note_declared_at); 17137 } 17138 return false; 17139 } 17140 17141 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17142 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17143 if (Diagnose) { 17144 S.Diag(Loc, diag::err_ref_vm_type); 17145 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17146 } 17147 return false; 17148 } 17149 // Prohibit structs with flexible array members too. 17150 // We cannot capture what is in the tail end of the struct. 17151 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17152 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17153 if (Diagnose) { 17154 if (IsBlock) 17155 S.Diag(Loc, diag::err_ref_flexarray_type); 17156 else 17157 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17158 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17159 } 17160 return false; 17161 } 17162 } 17163 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17164 // Lambdas and captured statements are not allowed to capture __block 17165 // variables; they don't support the expected semantics. 17166 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17167 if (Diagnose) { 17168 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17169 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17170 } 17171 return false; 17172 } 17173 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17174 if (S.getLangOpts().OpenCL && IsBlock && 17175 Var->getType()->isBlockPointerType()) { 17176 if (Diagnose) 17177 S.Diag(Loc, diag::err_opencl_block_ref_block); 17178 return false; 17179 } 17180 17181 return true; 17182 } 17183 17184 // Returns true if the capture by block was successful. 17185 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17186 SourceLocation Loc, 17187 const bool BuildAndDiagnose, 17188 QualType &CaptureType, 17189 QualType &DeclRefType, 17190 const bool Nested, 17191 Sema &S, bool Invalid) { 17192 bool ByRef = false; 17193 17194 // Blocks are not allowed to capture arrays, excepting OpenCL. 17195 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17196 // (decayed to pointers). 17197 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17198 if (BuildAndDiagnose) { 17199 S.Diag(Loc, diag::err_ref_array_type); 17200 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17201 Invalid = true; 17202 } else { 17203 return false; 17204 } 17205 } 17206 17207 // Forbid the block-capture of autoreleasing variables. 17208 if (!Invalid && 17209 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17210 if (BuildAndDiagnose) { 17211 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17212 << /*block*/ 0; 17213 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17214 Invalid = true; 17215 } else { 17216 return false; 17217 } 17218 } 17219 17220 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17221 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17222 QualType PointeeTy = PT->getPointeeType(); 17223 17224 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17225 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17226 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17227 if (BuildAndDiagnose) { 17228 SourceLocation VarLoc = Var->getLocation(); 17229 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17230 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17231 } 17232 } 17233 } 17234 17235 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17236 if (HasBlocksAttr || CaptureType->isReferenceType() || 17237 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17238 // Block capture by reference does not change the capture or 17239 // declaration reference types. 17240 ByRef = true; 17241 } else { 17242 // Block capture by copy introduces 'const'. 17243 CaptureType = CaptureType.getNonReferenceType().withConst(); 17244 DeclRefType = CaptureType; 17245 } 17246 17247 // Actually capture the variable. 17248 if (BuildAndDiagnose) 17249 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17250 CaptureType, Invalid); 17251 17252 return !Invalid; 17253 } 17254 17255 17256 /// Capture the given variable in the captured region. 17257 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17258 VarDecl *Var, 17259 SourceLocation Loc, 17260 const bool BuildAndDiagnose, 17261 QualType &CaptureType, 17262 QualType &DeclRefType, 17263 const bool RefersToCapturedVariable, 17264 Sema &S, bool Invalid) { 17265 // By default, capture variables by reference. 17266 bool ByRef = true; 17267 // Using an LValue reference type is consistent with Lambdas (see below). 17268 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17269 if (S.isOpenMPCapturedDecl(Var)) { 17270 bool HasConst = DeclRefType.isConstQualified(); 17271 DeclRefType = DeclRefType.getUnqualifiedType(); 17272 // Don't lose diagnostics about assignments to const. 17273 if (HasConst) 17274 DeclRefType.addConst(); 17275 } 17276 // Do not capture firstprivates in tasks. 17277 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17278 OMPC_unknown) 17279 return true; 17280 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17281 RSI->OpenMPCaptureLevel); 17282 } 17283 17284 if (ByRef) 17285 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17286 else 17287 CaptureType = DeclRefType; 17288 17289 // Actually capture the variable. 17290 if (BuildAndDiagnose) 17291 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17292 Loc, SourceLocation(), CaptureType, Invalid); 17293 17294 return !Invalid; 17295 } 17296 17297 /// Capture the given variable in the lambda. 17298 static bool captureInLambda(LambdaScopeInfo *LSI, 17299 VarDecl *Var, 17300 SourceLocation Loc, 17301 const bool BuildAndDiagnose, 17302 QualType &CaptureType, 17303 QualType &DeclRefType, 17304 const bool RefersToCapturedVariable, 17305 const Sema::TryCaptureKind Kind, 17306 SourceLocation EllipsisLoc, 17307 const bool IsTopScope, 17308 Sema &S, bool Invalid) { 17309 // Determine whether we are capturing by reference or by value. 17310 bool ByRef = false; 17311 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17312 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17313 } else { 17314 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17315 } 17316 17317 // Compute the type of the field that will capture this variable. 17318 if (ByRef) { 17319 // C++11 [expr.prim.lambda]p15: 17320 // An entity is captured by reference if it is implicitly or 17321 // explicitly captured but not captured by copy. It is 17322 // unspecified whether additional unnamed non-static data 17323 // members are declared in the closure type for entities 17324 // captured by reference. 17325 // 17326 // FIXME: It is not clear whether we want to build an lvalue reference 17327 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17328 // to do the former, while EDG does the latter. Core issue 1249 will 17329 // clarify, but for now we follow GCC because it's a more permissive and 17330 // easily defensible position. 17331 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17332 } else { 17333 // C++11 [expr.prim.lambda]p14: 17334 // For each entity captured by copy, an unnamed non-static 17335 // data member is declared in the closure type. The 17336 // declaration order of these members is unspecified. The type 17337 // of such a data member is the type of the corresponding 17338 // captured entity if the entity is not a reference to an 17339 // object, or the referenced type otherwise. [Note: If the 17340 // captured entity is a reference to a function, the 17341 // corresponding data member is also a reference to a 17342 // function. - end note ] 17343 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17344 if (!RefType->getPointeeType()->isFunctionType()) 17345 CaptureType = RefType->getPointeeType(); 17346 } 17347 17348 // Forbid the lambda copy-capture of autoreleasing variables. 17349 if (!Invalid && 17350 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17351 if (BuildAndDiagnose) { 17352 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17353 S.Diag(Var->getLocation(), diag::note_previous_decl) 17354 << Var->getDeclName(); 17355 Invalid = true; 17356 } else { 17357 return false; 17358 } 17359 } 17360 17361 // Make sure that by-copy captures are of a complete and non-abstract type. 17362 if (!Invalid && BuildAndDiagnose) { 17363 if (!CaptureType->isDependentType() && 17364 S.RequireCompleteSizedType( 17365 Loc, CaptureType, 17366 diag::err_capture_of_incomplete_or_sizeless_type, 17367 Var->getDeclName())) 17368 Invalid = true; 17369 else if (S.RequireNonAbstractType(Loc, CaptureType, 17370 diag::err_capture_of_abstract_type)) 17371 Invalid = true; 17372 } 17373 } 17374 17375 // Compute the type of a reference to this captured variable. 17376 if (ByRef) 17377 DeclRefType = CaptureType.getNonReferenceType(); 17378 else { 17379 // C++ [expr.prim.lambda]p5: 17380 // The closure type for a lambda-expression has a public inline 17381 // function call operator [...]. This function call operator is 17382 // declared const (9.3.1) if and only if the lambda-expression's 17383 // parameter-declaration-clause is not followed by mutable. 17384 DeclRefType = CaptureType.getNonReferenceType(); 17385 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17386 DeclRefType.addConst(); 17387 } 17388 17389 // Add the capture. 17390 if (BuildAndDiagnose) 17391 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17392 Loc, EllipsisLoc, CaptureType, Invalid); 17393 17394 return !Invalid; 17395 } 17396 17397 bool Sema::tryCaptureVariable( 17398 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17399 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17400 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17401 // An init-capture is notionally from the context surrounding its 17402 // declaration, but its parent DC is the lambda class. 17403 DeclContext *VarDC = Var->getDeclContext(); 17404 if (Var->isInitCapture()) 17405 VarDC = VarDC->getParent(); 17406 17407 DeclContext *DC = CurContext; 17408 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17409 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17410 // We need to sync up the Declaration Context with the 17411 // FunctionScopeIndexToStopAt 17412 if (FunctionScopeIndexToStopAt) { 17413 unsigned FSIndex = FunctionScopes.size() - 1; 17414 while (FSIndex != MaxFunctionScopesIndex) { 17415 DC = getLambdaAwareParentOfDeclContext(DC); 17416 --FSIndex; 17417 } 17418 } 17419 17420 17421 // If the variable is declared in the current context, there is no need to 17422 // capture it. 17423 if (VarDC == DC) return true; 17424 17425 // Capture global variables if it is required to use private copy of this 17426 // variable. 17427 bool IsGlobal = !Var->hasLocalStorage(); 17428 if (IsGlobal && 17429 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17430 MaxFunctionScopesIndex))) 17431 return true; 17432 Var = Var->getCanonicalDecl(); 17433 17434 // Walk up the stack to determine whether we can capture the variable, 17435 // performing the "simple" checks that don't depend on type. We stop when 17436 // we've either hit the declared scope of the variable or find an existing 17437 // capture of that variable. We start from the innermost capturing-entity 17438 // (the DC) and ensure that all intervening capturing-entities 17439 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17440 // declcontext can either capture the variable or have already captured 17441 // the variable. 17442 CaptureType = Var->getType(); 17443 DeclRefType = CaptureType.getNonReferenceType(); 17444 bool Nested = false; 17445 bool Explicit = (Kind != TryCapture_Implicit); 17446 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17447 do { 17448 // Only block literals, captured statements, and lambda expressions can 17449 // capture; other scopes don't work. 17450 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17451 ExprLoc, 17452 BuildAndDiagnose, 17453 *this); 17454 // We need to check for the parent *first* because, if we *have* 17455 // private-captured a global variable, we need to recursively capture it in 17456 // intermediate blocks, lambdas, etc. 17457 if (!ParentDC) { 17458 if (IsGlobal) { 17459 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17460 break; 17461 } 17462 return true; 17463 } 17464 17465 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17466 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17467 17468 17469 // Check whether we've already captured it. 17470 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17471 DeclRefType)) { 17472 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17473 break; 17474 } 17475 // If we are instantiating a generic lambda call operator body, 17476 // we do not want to capture new variables. What was captured 17477 // during either a lambdas transformation or initial parsing 17478 // should be used. 17479 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17480 if (BuildAndDiagnose) { 17481 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17482 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17483 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17484 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17485 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17486 } else 17487 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17488 } 17489 return true; 17490 } 17491 17492 // Try to capture variable-length arrays types. 17493 if (Var->getType()->isVariablyModifiedType()) { 17494 // We're going to walk down into the type and look for VLA 17495 // expressions. 17496 QualType QTy = Var->getType(); 17497 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17498 QTy = PVD->getOriginalType(); 17499 captureVariablyModifiedType(Context, QTy, CSI); 17500 } 17501 17502 if (getLangOpts().OpenMP) { 17503 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17504 // OpenMP private variables should not be captured in outer scope, so 17505 // just break here. Similarly, global variables that are captured in a 17506 // target region should not be captured outside the scope of the region. 17507 if (RSI->CapRegionKind == CR_OpenMP) { 17508 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17509 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17510 // If the variable is private (i.e. not captured) and has variably 17511 // modified type, we still need to capture the type for correct 17512 // codegen in all regions, associated with the construct. Currently, 17513 // it is captured in the innermost captured region only. 17514 if (IsOpenMPPrivateDecl != OMPC_unknown && 17515 Var->getType()->isVariablyModifiedType()) { 17516 QualType QTy = Var->getType(); 17517 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17518 QTy = PVD->getOriginalType(); 17519 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17520 I < E; ++I) { 17521 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17522 FunctionScopes[FunctionScopesIndex - I]); 17523 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17524 "Wrong number of captured regions associated with the " 17525 "OpenMP construct."); 17526 captureVariablyModifiedType(Context, QTy, OuterRSI); 17527 } 17528 } 17529 bool IsTargetCap = 17530 IsOpenMPPrivateDecl != OMPC_private && 17531 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17532 RSI->OpenMPCaptureLevel); 17533 // Do not capture global if it is not privatized in outer regions. 17534 bool IsGlobalCap = 17535 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17536 RSI->OpenMPCaptureLevel); 17537 17538 // When we detect target captures we are looking from inside the 17539 // target region, therefore we need to propagate the capture from the 17540 // enclosing region. Therefore, the capture is not initially nested. 17541 if (IsTargetCap) 17542 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17543 17544 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17545 (IsGlobal && !IsGlobalCap)) { 17546 Nested = !IsTargetCap; 17547 bool HasConst = DeclRefType.isConstQualified(); 17548 DeclRefType = DeclRefType.getUnqualifiedType(); 17549 // Don't lose diagnostics about assignments to const. 17550 if (HasConst) 17551 DeclRefType.addConst(); 17552 CaptureType = Context.getLValueReferenceType(DeclRefType); 17553 break; 17554 } 17555 } 17556 } 17557 } 17558 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17559 // No capture-default, and this is not an explicit capture 17560 // so cannot capture this variable. 17561 if (BuildAndDiagnose) { 17562 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17563 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17564 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17565 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17566 diag::note_lambda_decl); 17567 // FIXME: If we error out because an outer lambda can not implicitly 17568 // capture a variable that an inner lambda explicitly captures, we 17569 // should have the inner lambda do the explicit capture - because 17570 // it makes for cleaner diagnostics later. This would purely be done 17571 // so that the diagnostic does not misleadingly claim that a variable 17572 // can not be captured by a lambda implicitly even though it is captured 17573 // explicitly. Suggestion: 17574 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17575 // at the function head 17576 // - cache the StartingDeclContext - this must be a lambda 17577 // - captureInLambda in the innermost lambda the variable. 17578 } 17579 return true; 17580 } 17581 17582 FunctionScopesIndex--; 17583 DC = ParentDC; 17584 Explicit = false; 17585 } while (!VarDC->Equals(DC)); 17586 17587 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17588 // computing the type of the capture at each step, checking type-specific 17589 // requirements, and adding captures if requested. 17590 // If the variable had already been captured previously, we start capturing 17591 // at the lambda nested within that one. 17592 bool Invalid = false; 17593 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17594 ++I) { 17595 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17596 17597 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17598 // certain types of variables (unnamed, variably modified types etc.) 17599 // so check for eligibility. 17600 if (!Invalid) 17601 Invalid = 17602 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17603 17604 // After encountering an error, if we're actually supposed to capture, keep 17605 // capturing in nested contexts to suppress any follow-on diagnostics. 17606 if (Invalid && !BuildAndDiagnose) 17607 return true; 17608 17609 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17610 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17611 DeclRefType, Nested, *this, Invalid); 17612 Nested = true; 17613 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17614 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17615 CaptureType, DeclRefType, Nested, 17616 *this, Invalid); 17617 Nested = true; 17618 } else { 17619 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17620 Invalid = 17621 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17622 DeclRefType, Nested, Kind, EllipsisLoc, 17623 /*IsTopScope*/ I == N - 1, *this, Invalid); 17624 Nested = true; 17625 } 17626 17627 if (Invalid && !BuildAndDiagnose) 17628 return true; 17629 } 17630 return Invalid; 17631 } 17632 17633 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17634 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17635 QualType CaptureType; 17636 QualType DeclRefType; 17637 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17638 /*BuildAndDiagnose=*/true, CaptureType, 17639 DeclRefType, nullptr); 17640 } 17641 17642 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17643 QualType CaptureType; 17644 QualType DeclRefType; 17645 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17646 /*BuildAndDiagnose=*/false, CaptureType, 17647 DeclRefType, nullptr); 17648 } 17649 17650 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17651 QualType CaptureType; 17652 QualType DeclRefType; 17653 17654 // Determine whether we can capture this variable. 17655 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17656 /*BuildAndDiagnose=*/false, CaptureType, 17657 DeclRefType, nullptr)) 17658 return QualType(); 17659 17660 return DeclRefType; 17661 } 17662 17663 namespace { 17664 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17665 // The produced TemplateArgumentListInfo* points to data stored within this 17666 // object, so should only be used in contexts where the pointer will not be 17667 // used after the CopiedTemplateArgs object is destroyed. 17668 class CopiedTemplateArgs { 17669 bool HasArgs; 17670 TemplateArgumentListInfo TemplateArgStorage; 17671 public: 17672 template<typename RefExpr> 17673 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17674 if (HasArgs) 17675 E->copyTemplateArgumentsInto(TemplateArgStorage); 17676 } 17677 operator TemplateArgumentListInfo*() 17678 #ifdef __has_cpp_attribute 17679 #if __has_cpp_attribute(clang::lifetimebound) 17680 [[clang::lifetimebound]] 17681 #endif 17682 #endif 17683 { 17684 return HasArgs ? &TemplateArgStorage : nullptr; 17685 } 17686 }; 17687 } 17688 17689 /// Walk the set of potential results of an expression and mark them all as 17690 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17691 /// 17692 /// \return A new expression if we found any potential results, ExprEmpty() if 17693 /// not, and ExprError() if we diagnosed an error. 17694 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17695 NonOdrUseReason NOUR) { 17696 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17697 // an object that satisfies the requirements for appearing in a 17698 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17699 // is immediately applied." This function handles the lvalue-to-rvalue 17700 // conversion part. 17701 // 17702 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17703 // transform it into the relevant kind of non-odr-use node and rebuild the 17704 // tree of nodes leading to it. 17705 // 17706 // This is a mini-TreeTransform that only transforms a restricted subset of 17707 // nodes (and only certain operands of them). 17708 17709 // Rebuild a subexpression. 17710 auto Rebuild = [&](Expr *Sub) { 17711 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17712 }; 17713 17714 // Check whether a potential result satisfies the requirements of NOUR. 17715 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17716 // Any entity other than a VarDecl is always odr-used whenever it's named 17717 // in a potentially-evaluated expression. 17718 auto *VD = dyn_cast<VarDecl>(D); 17719 if (!VD) 17720 return true; 17721 17722 // C++2a [basic.def.odr]p4: 17723 // A variable x whose name appears as a potentially-evalauted expression 17724 // e is odr-used by e unless 17725 // -- x is a reference that is usable in constant expressions, or 17726 // -- x is a variable of non-reference type that is usable in constant 17727 // expressions and has no mutable subobjects, and e is an element of 17728 // the set of potential results of an expression of 17729 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17730 // conversion is applied, or 17731 // -- x is a variable of non-reference type, and e is an element of the 17732 // set of potential results of a discarded-value expression to which 17733 // the lvalue-to-rvalue conversion is not applied 17734 // 17735 // We check the first bullet and the "potentially-evaluated" condition in 17736 // BuildDeclRefExpr. We check the type requirements in the second bullet 17737 // in CheckLValueToRValueConversionOperand below. 17738 switch (NOUR) { 17739 case NOUR_None: 17740 case NOUR_Unevaluated: 17741 llvm_unreachable("unexpected non-odr-use-reason"); 17742 17743 case NOUR_Constant: 17744 // Constant references were handled when they were built. 17745 if (VD->getType()->isReferenceType()) 17746 return true; 17747 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17748 if (RD->hasMutableFields()) 17749 return true; 17750 if (!VD->isUsableInConstantExpressions(S.Context)) 17751 return true; 17752 break; 17753 17754 case NOUR_Discarded: 17755 if (VD->getType()->isReferenceType()) 17756 return true; 17757 break; 17758 } 17759 return false; 17760 }; 17761 17762 // Mark that this expression does not constitute an odr-use. 17763 auto MarkNotOdrUsed = [&] { 17764 S.MaybeODRUseExprs.remove(E); 17765 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17766 LSI->markVariableExprAsNonODRUsed(E); 17767 }; 17768 17769 // C++2a [basic.def.odr]p2: 17770 // The set of potential results of an expression e is defined as follows: 17771 switch (E->getStmtClass()) { 17772 // -- If e is an id-expression, ... 17773 case Expr::DeclRefExprClass: { 17774 auto *DRE = cast<DeclRefExpr>(E); 17775 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17776 break; 17777 17778 // Rebuild as a non-odr-use DeclRefExpr. 17779 MarkNotOdrUsed(); 17780 return DeclRefExpr::Create( 17781 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17782 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17783 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17784 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17785 } 17786 17787 case Expr::FunctionParmPackExprClass: { 17788 auto *FPPE = cast<FunctionParmPackExpr>(E); 17789 // If any of the declarations in the pack is odr-used, then the expression 17790 // as a whole constitutes an odr-use. 17791 for (VarDecl *D : *FPPE) 17792 if (IsPotentialResultOdrUsed(D)) 17793 return ExprEmpty(); 17794 17795 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17796 // nothing cares about whether we marked this as an odr-use, but it might 17797 // be useful for non-compiler tools. 17798 MarkNotOdrUsed(); 17799 break; 17800 } 17801 17802 // -- If e is a subscripting operation with an array operand... 17803 case Expr::ArraySubscriptExprClass: { 17804 auto *ASE = cast<ArraySubscriptExpr>(E); 17805 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17806 if (!OldBase->getType()->isArrayType()) 17807 break; 17808 ExprResult Base = Rebuild(OldBase); 17809 if (!Base.isUsable()) 17810 return Base; 17811 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17812 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17813 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17814 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17815 ASE->getRBracketLoc()); 17816 } 17817 17818 case Expr::MemberExprClass: { 17819 auto *ME = cast<MemberExpr>(E); 17820 // -- If e is a class member access expression [...] naming a non-static 17821 // data member... 17822 if (isa<FieldDecl>(ME->getMemberDecl())) { 17823 ExprResult Base = Rebuild(ME->getBase()); 17824 if (!Base.isUsable()) 17825 return Base; 17826 return MemberExpr::Create( 17827 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17828 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17829 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17830 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17831 ME->getObjectKind(), ME->isNonOdrUse()); 17832 } 17833 17834 if (ME->getMemberDecl()->isCXXInstanceMember()) 17835 break; 17836 17837 // -- If e is a class member access expression naming a static data member, 17838 // ... 17839 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17840 break; 17841 17842 // Rebuild as a non-odr-use MemberExpr. 17843 MarkNotOdrUsed(); 17844 return MemberExpr::Create( 17845 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17846 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17847 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17848 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17849 return ExprEmpty(); 17850 } 17851 17852 case Expr::BinaryOperatorClass: { 17853 auto *BO = cast<BinaryOperator>(E); 17854 Expr *LHS = BO->getLHS(); 17855 Expr *RHS = BO->getRHS(); 17856 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17857 if (BO->getOpcode() == BO_PtrMemD) { 17858 ExprResult Sub = Rebuild(LHS); 17859 if (!Sub.isUsable()) 17860 return Sub; 17861 LHS = Sub.get(); 17862 // -- If e is a comma expression, ... 17863 } else if (BO->getOpcode() == BO_Comma) { 17864 ExprResult Sub = Rebuild(RHS); 17865 if (!Sub.isUsable()) 17866 return Sub; 17867 RHS = Sub.get(); 17868 } else { 17869 break; 17870 } 17871 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17872 LHS, RHS); 17873 } 17874 17875 // -- If e has the form (e1)... 17876 case Expr::ParenExprClass: { 17877 auto *PE = cast<ParenExpr>(E); 17878 ExprResult Sub = Rebuild(PE->getSubExpr()); 17879 if (!Sub.isUsable()) 17880 return Sub; 17881 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17882 } 17883 17884 // -- If e is a glvalue conditional expression, ... 17885 // We don't apply this to a binary conditional operator. FIXME: Should we? 17886 case Expr::ConditionalOperatorClass: { 17887 auto *CO = cast<ConditionalOperator>(E); 17888 ExprResult LHS = Rebuild(CO->getLHS()); 17889 if (LHS.isInvalid()) 17890 return ExprError(); 17891 ExprResult RHS = Rebuild(CO->getRHS()); 17892 if (RHS.isInvalid()) 17893 return ExprError(); 17894 if (!LHS.isUsable() && !RHS.isUsable()) 17895 return ExprEmpty(); 17896 if (!LHS.isUsable()) 17897 LHS = CO->getLHS(); 17898 if (!RHS.isUsable()) 17899 RHS = CO->getRHS(); 17900 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17901 CO->getCond(), LHS.get(), RHS.get()); 17902 } 17903 17904 // [Clang extension] 17905 // -- If e has the form __extension__ e1... 17906 case Expr::UnaryOperatorClass: { 17907 auto *UO = cast<UnaryOperator>(E); 17908 if (UO->getOpcode() != UO_Extension) 17909 break; 17910 ExprResult Sub = Rebuild(UO->getSubExpr()); 17911 if (!Sub.isUsable()) 17912 return Sub; 17913 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17914 Sub.get()); 17915 } 17916 17917 // [Clang extension] 17918 // -- If e has the form _Generic(...), the set of potential results is the 17919 // union of the sets of potential results of the associated expressions. 17920 case Expr::GenericSelectionExprClass: { 17921 auto *GSE = cast<GenericSelectionExpr>(E); 17922 17923 SmallVector<Expr *, 4> AssocExprs; 17924 bool AnyChanged = false; 17925 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17926 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17927 if (AssocExpr.isInvalid()) 17928 return ExprError(); 17929 if (AssocExpr.isUsable()) { 17930 AssocExprs.push_back(AssocExpr.get()); 17931 AnyChanged = true; 17932 } else { 17933 AssocExprs.push_back(OrigAssocExpr); 17934 } 17935 } 17936 17937 return AnyChanged ? S.CreateGenericSelectionExpr( 17938 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17939 GSE->getRParenLoc(), GSE->getControllingExpr(), 17940 GSE->getAssocTypeSourceInfos(), AssocExprs) 17941 : ExprEmpty(); 17942 } 17943 17944 // [Clang extension] 17945 // -- If e has the form __builtin_choose_expr(...), the set of potential 17946 // results is the union of the sets of potential results of the 17947 // second and third subexpressions. 17948 case Expr::ChooseExprClass: { 17949 auto *CE = cast<ChooseExpr>(E); 17950 17951 ExprResult LHS = Rebuild(CE->getLHS()); 17952 if (LHS.isInvalid()) 17953 return ExprError(); 17954 17955 ExprResult RHS = Rebuild(CE->getLHS()); 17956 if (RHS.isInvalid()) 17957 return ExprError(); 17958 17959 if (!LHS.get() && !RHS.get()) 17960 return ExprEmpty(); 17961 if (!LHS.isUsable()) 17962 LHS = CE->getLHS(); 17963 if (!RHS.isUsable()) 17964 RHS = CE->getRHS(); 17965 17966 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17967 RHS.get(), CE->getRParenLoc()); 17968 } 17969 17970 // Step through non-syntactic nodes. 17971 case Expr::ConstantExprClass: { 17972 auto *CE = cast<ConstantExpr>(E); 17973 ExprResult Sub = Rebuild(CE->getSubExpr()); 17974 if (!Sub.isUsable()) 17975 return Sub; 17976 return ConstantExpr::Create(S.Context, Sub.get()); 17977 } 17978 17979 // We could mostly rely on the recursive rebuilding to rebuild implicit 17980 // casts, but not at the top level, so rebuild them here. 17981 case Expr::ImplicitCastExprClass: { 17982 auto *ICE = cast<ImplicitCastExpr>(E); 17983 // Only step through the narrow set of cast kinds we expect to encounter. 17984 // Anything else suggests we've left the region in which potential results 17985 // can be found. 17986 switch (ICE->getCastKind()) { 17987 case CK_NoOp: 17988 case CK_DerivedToBase: 17989 case CK_UncheckedDerivedToBase: { 17990 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17991 if (!Sub.isUsable()) 17992 return Sub; 17993 CXXCastPath Path(ICE->path()); 17994 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17995 ICE->getValueKind(), &Path); 17996 } 17997 17998 default: 17999 break; 18000 } 18001 break; 18002 } 18003 18004 default: 18005 break; 18006 } 18007 18008 // Can't traverse through this node. Nothing to do. 18009 return ExprEmpty(); 18010 } 18011 18012 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18013 // Check whether the operand is or contains an object of non-trivial C union 18014 // type. 18015 if (E->getType().isVolatileQualified() && 18016 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18017 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18018 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18019 Sema::NTCUC_LValueToRValueVolatile, 18020 NTCUK_Destruct|NTCUK_Copy); 18021 18022 // C++2a [basic.def.odr]p4: 18023 // [...] an expression of non-volatile-qualified non-class type to which 18024 // the lvalue-to-rvalue conversion is applied [...] 18025 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18026 return E; 18027 18028 ExprResult Result = 18029 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18030 if (Result.isInvalid()) 18031 return ExprError(); 18032 return Result.get() ? Result : E; 18033 } 18034 18035 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18036 Res = CorrectDelayedTyposInExpr(Res); 18037 18038 if (!Res.isUsable()) 18039 return Res; 18040 18041 // If a constant-expression is a reference to a variable where we delay 18042 // deciding whether it is an odr-use, just assume we will apply the 18043 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18044 // (a non-type template argument), we have special handling anyway. 18045 return CheckLValueToRValueConversionOperand(Res.get()); 18046 } 18047 18048 void Sema::CleanupVarDeclMarking() { 18049 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18050 // call. 18051 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18052 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18053 18054 for (Expr *E : LocalMaybeODRUseExprs) { 18055 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18056 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18057 DRE->getLocation(), *this); 18058 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18059 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18060 *this); 18061 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18062 for (VarDecl *VD : *FP) 18063 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18064 } else { 18065 llvm_unreachable("Unexpected expression"); 18066 } 18067 } 18068 18069 assert(MaybeODRUseExprs.empty() && 18070 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18071 } 18072 18073 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18074 VarDecl *Var, Expr *E) { 18075 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18076 isa<FunctionParmPackExpr>(E)) && 18077 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18078 Var->setReferenced(); 18079 18080 if (Var->isInvalidDecl()) 18081 return; 18082 18083 // Record a CUDA/HIP static device/constant variable if it is referenced 18084 // by host code. This is done conservatively, when the variable is referenced 18085 // in any of the following contexts: 18086 // - a non-function context 18087 // - a host function 18088 // - a host device function 18089 // This also requires the reference of the static device/constant variable by 18090 // host code to be visible in the device compilation for the compiler to be 18091 // able to externalize the static device/constant variable. 18092 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18093 auto *CurContext = SemaRef.CurContext; 18094 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18095 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18096 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18097 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18098 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18099 } 18100 18101 auto *MSI = Var->getMemberSpecializationInfo(); 18102 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18103 : Var->getTemplateSpecializationKind(); 18104 18105 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18106 bool UsableInConstantExpr = 18107 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18108 18109 // C++20 [expr.const]p12: 18110 // A variable [...] is needed for constant evaluation if it is [...] a 18111 // variable whose name appears as a potentially constant evaluated 18112 // expression that is either a contexpr variable or is of non-volatile 18113 // const-qualified integral type or of reference type 18114 bool NeededForConstantEvaluation = 18115 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18116 18117 bool NeedDefinition = 18118 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18119 18120 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18121 "Can't instantiate a partial template specialization."); 18122 18123 // If this might be a member specialization of a static data member, check 18124 // the specialization is visible. We already did the checks for variable 18125 // template specializations when we created them. 18126 if (NeedDefinition && TSK != TSK_Undeclared && 18127 !isa<VarTemplateSpecializationDecl>(Var)) 18128 SemaRef.checkSpecializationVisibility(Loc, Var); 18129 18130 // Perform implicit instantiation of static data members, static data member 18131 // templates of class templates, and variable template specializations. Delay 18132 // instantiations of variable templates, except for those that could be used 18133 // in a constant expression. 18134 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18135 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18136 // instantiation declaration if a variable is usable in a constant 18137 // expression (among other cases). 18138 bool TryInstantiating = 18139 TSK == TSK_ImplicitInstantiation || 18140 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18141 18142 if (TryInstantiating) { 18143 SourceLocation PointOfInstantiation = 18144 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18145 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18146 if (FirstInstantiation) { 18147 PointOfInstantiation = Loc; 18148 if (MSI) 18149 MSI->setPointOfInstantiation(PointOfInstantiation); 18150 // FIXME: Notify listener. 18151 else 18152 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18153 } 18154 18155 if (UsableInConstantExpr) { 18156 // Do not defer instantiations of variables that could be used in a 18157 // constant expression. 18158 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18159 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18160 }); 18161 18162 // Re-set the member to trigger a recomputation of the dependence bits 18163 // for the expression. 18164 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18165 DRE->setDecl(DRE->getDecl()); 18166 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18167 ME->setMemberDecl(ME->getMemberDecl()); 18168 } else if (FirstInstantiation || 18169 isa<VarTemplateSpecializationDecl>(Var)) { 18170 // FIXME: For a specialization of a variable template, we don't 18171 // distinguish between "declaration and type implicitly instantiated" 18172 // and "implicit instantiation of definition requested", so we have 18173 // no direct way to avoid enqueueing the pending instantiation 18174 // multiple times. 18175 SemaRef.PendingInstantiations 18176 .push_back(std::make_pair(Var, PointOfInstantiation)); 18177 } 18178 } 18179 } 18180 18181 // C++2a [basic.def.odr]p4: 18182 // A variable x whose name appears as a potentially-evaluated expression e 18183 // is odr-used by e unless 18184 // -- x is a reference that is usable in constant expressions 18185 // -- x is a variable of non-reference type that is usable in constant 18186 // expressions and has no mutable subobjects [FIXME], and e is an 18187 // element of the set of potential results of an expression of 18188 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18189 // conversion is applied 18190 // -- x is a variable of non-reference type, and e is an element of the set 18191 // of potential results of a discarded-value expression to which the 18192 // lvalue-to-rvalue conversion is not applied [FIXME] 18193 // 18194 // We check the first part of the second bullet here, and 18195 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18196 // FIXME: To get the third bullet right, we need to delay this even for 18197 // variables that are not usable in constant expressions. 18198 18199 // If we already know this isn't an odr-use, there's nothing more to do. 18200 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18201 if (DRE->isNonOdrUse()) 18202 return; 18203 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18204 if (ME->isNonOdrUse()) 18205 return; 18206 18207 switch (OdrUse) { 18208 case OdrUseContext::None: 18209 assert((!E || isa<FunctionParmPackExpr>(E)) && 18210 "missing non-odr-use marking for unevaluated decl ref"); 18211 break; 18212 18213 case OdrUseContext::FormallyOdrUsed: 18214 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18215 // behavior. 18216 break; 18217 18218 case OdrUseContext::Used: 18219 // If we might later find that this expression isn't actually an odr-use, 18220 // delay the marking. 18221 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18222 SemaRef.MaybeODRUseExprs.insert(E); 18223 else 18224 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18225 break; 18226 18227 case OdrUseContext::Dependent: 18228 // If this is a dependent context, we don't need to mark variables as 18229 // odr-used, but we may still need to track them for lambda capture. 18230 // FIXME: Do we also need to do this inside dependent typeid expressions 18231 // (which are modeled as unevaluated at this point)? 18232 const bool RefersToEnclosingScope = 18233 (SemaRef.CurContext != Var->getDeclContext() && 18234 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18235 if (RefersToEnclosingScope) { 18236 LambdaScopeInfo *const LSI = 18237 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18238 if (LSI && (!LSI->CallOperator || 18239 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18240 // If a variable could potentially be odr-used, defer marking it so 18241 // until we finish analyzing the full expression for any 18242 // lvalue-to-rvalue 18243 // or discarded value conversions that would obviate odr-use. 18244 // Add it to the list of potential captures that will be analyzed 18245 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18246 // unless the variable is a reference that was initialized by a constant 18247 // expression (this will never need to be captured or odr-used). 18248 // 18249 // FIXME: We can simplify this a lot after implementing P0588R1. 18250 assert(E && "Capture variable should be used in an expression."); 18251 if (!Var->getType()->isReferenceType() || 18252 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18253 LSI->addPotentialCapture(E->IgnoreParens()); 18254 } 18255 } 18256 break; 18257 } 18258 } 18259 18260 /// Mark a variable referenced, and check whether it is odr-used 18261 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18262 /// used directly for normal expressions referring to VarDecl. 18263 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18264 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18265 } 18266 18267 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18268 Decl *D, Expr *E, bool MightBeOdrUse) { 18269 if (SemaRef.isInOpenMPDeclareTargetContext()) 18270 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18271 18272 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18273 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18274 return; 18275 } 18276 18277 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18278 18279 // If this is a call to a method via a cast, also mark the method in the 18280 // derived class used in case codegen can devirtualize the call. 18281 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18282 if (!ME) 18283 return; 18284 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18285 if (!MD) 18286 return; 18287 // Only attempt to devirtualize if this is truly a virtual call. 18288 bool IsVirtualCall = MD->isVirtual() && 18289 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18290 if (!IsVirtualCall) 18291 return; 18292 18293 // If it's possible to devirtualize the call, mark the called function 18294 // referenced. 18295 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18296 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18297 if (DM) 18298 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18299 } 18300 18301 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18302 /// 18303 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18304 /// handled with care if the DeclRefExpr is not newly-created. 18305 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18306 // TODO: update this with DR# once a defect report is filed. 18307 // C++11 defect. The address of a pure member should not be an ODR use, even 18308 // if it's a qualified reference. 18309 bool OdrUse = true; 18310 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18311 if (Method->isVirtual() && 18312 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18313 OdrUse = false; 18314 18315 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18316 if (!isConstantEvaluated() && FD->isConsteval() && 18317 !RebuildingImmediateInvocation) 18318 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18319 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18320 } 18321 18322 /// Perform reference-marking and odr-use handling for a MemberExpr. 18323 void Sema::MarkMemberReferenced(MemberExpr *E) { 18324 // C++11 [basic.def.odr]p2: 18325 // A non-overloaded function whose name appears as a potentially-evaluated 18326 // expression or a member of a set of candidate functions, if selected by 18327 // overload resolution when referred to from a potentially-evaluated 18328 // expression, is odr-used, unless it is a pure virtual function and its 18329 // name is not explicitly qualified. 18330 bool MightBeOdrUse = true; 18331 if (E->performsVirtualDispatch(getLangOpts())) { 18332 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18333 if (Method->isPure()) 18334 MightBeOdrUse = false; 18335 } 18336 SourceLocation Loc = 18337 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18338 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18339 } 18340 18341 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18342 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18343 for (VarDecl *VD : *E) 18344 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18345 } 18346 18347 /// Perform marking for a reference to an arbitrary declaration. It 18348 /// marks the declaration referenced, and performs odr-use checking for 18349 /// functions and variables. This method should not be used when building a 18350 /// normal expression which refers to a variable. 18351 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18352 bool MightBeOdrUse) { 18353 if (MightBeOdrUse) { 18354 if (auto *VD = dyn_cast<VarDecl>(D)) { 18355 MarkVariableReferenced(Loc, VD); 18356 return; 18357 } 18358 } 18359 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18360 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18361 return; 18362 } 18363 D->setReferenced(); 18364 } 18365 18366 namespace { 18367 // Mark all of the declarations used by a type as referenced. 18368 // FIXME: Not fully implemented yet! We need to have a better understanding 18369 // of when we're entering a context we should not recurse into. 18370 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18371 // TreeTransforms rebuilding the type in a new context. Rather than 18372 // duplicating the TreeTransform logic, we should consider reusing it here. 18373 // Currently that causes problems when rebuilding LambdaExprs. 18374 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18375 Sema &S; 18376 SourceLocation Loc; 18377 18378 public: 18379 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18380 18381 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18382 18383 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18384 }; 18385 } 18386 18387 bool MarkReferencedDecls::TraverseTemplateArgument( 18388 const TemplateArgument &Arg) { 18389 { 18390 // A non-type template argument is a constant-evaluated context. 18391 EnterExpressionEvaluationContext Evaluated( 18392 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18393 if (Arg.getKind() == TemplateArgument::Declaration) { 18394 if (Decl *D = Arg.getAsDecl()) 18395 S.MarkAnyDeclReferenced(Loc, D, true); 18396 } else if (Arg.getKind() == TemplateArgument::Expression) { 18397 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18398 } 18399 } 18400 18401 return Inherited::TraverseTemplateArgument(Arg); 18402 } 18403 18404 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18405 MarkReferencedDecls Marker(*this, Loc); 18406 Marker.TraverseType(T); 18407 } 18408 18409 namespace { 18410 /// Helper class that marks all of the declarations referenced by 18411 /// potentially-evaluated subexpressions as "referenced". 18412 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18413 public: 18414 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18415 bool SkipLocalVariables; 18416 18417 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18418 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18419 18420 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18421 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18422 } 18423 18424 void VisitDeclRefExpr(DeclRefExpr *E) { 18425 // If we were asked not to visit local variables, don't. 18426 if (SkipLocalVariables) { 18427 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18428 if (VD->hasLocalStorage()) 18429 return; 18430 } 18431 18432 // FIXME: This can trigger the instantiation of the initializer of a 18433 // variable, which can cause the expression to become value-dependent 18434 // or error-dependent. Do we need to propagate the new dependence bits? 18435 S.MarkDeclRefReferenced(E); 18436 } 18437 18438 void VisitMemberExpr(MemberExpr *E) { 18439 S.MarkMemberReferenced(E); 18440 Visit(E->getBase()); 18441 } 18442 }; 18443 } // namespace 18444 18445 /// Mark any declarations that appear within this expression or any 18446 /// potentially-evaluated subexpressions as "referenced". 18447 /// 18448 /// \param SkipLocalVariables If true, don't mark local variables as 18449 /// 'referenced'. 18450 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18451 bool SkipLocalVariables) { 18452 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18453 } 18454 18455 /// Emit a diagnostic that describes an effect on the run-time behavior 18456 /// of the program being compiled. 18457 /// 18458 /// This routine emits the given diagnostic when the code currently being 18459 /// type-checked is "potentially evaluated", meaning that there is a 18460 /// possibility that the code will actually be executable. Code in sizeof() 18461 /// expressions, code used only during overload resolution, etc., are not 18462 /// potentially evaluated. This routine will suppress such diagnostics or, 18463 /// in the absolutely nutty case of potentially potentially evaluated 18464 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18465 /// later. 18466 /// 18467 /// This routine should be used for all diagnostics that describe the run-time 18468 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18469 /// Failure to do so will likely result in spurious diagnostics or failures 18470 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18471 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18472 const PartialDiagnostic &PD) { 18473 switch (ExprEvalContexts.back().Context) { 18474 case ExpressionEvaluationContext::Unevaluated: 18475 case ExpressionEvaluationContext::UnevaluatedList: 18476 case ExpressionEvaluationContext::UnevaluatedAbstract: 18477 case ExpressionEvaluationContext::DiscardedStatement: 18478 // The argument will never be evaluated, so don't complain. 18479 break; 18480 18481 case ExpressionEvaluationContext::ConstantEvaluated: 18482 // Relevant diagnostics should be produced by constant evaluation. 18483 break; 18484 18485 case ExpressionEvaluationContext::PotentiallyEvaluated: 18486 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18487 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18488 FunctionScopes.back()->PossiblyUnreachableDiags. 18489 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18490 return true; 18491 } 18492 18493 // The initializer of a constexpr variable or of the first declaration of a 18494 // static data member is not syntactically a constant evaluated constant, 18495 // but nonetheless is always required to be a constant expression, so we 18496 // can skip diagnosing. 18497 // FIXME: Using the mangling context here is a hack. 18498 if (auto *VD = dyn_cast_or_null<VarDecl>( 18499 ExprEvalContexts.back().ManglingContextDecl)) { 18500 if (VD->isConstexpr() || 18501 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18502 break; 18503 // FIXME: For any other kind of variable, we should build a CFG for its 18504 // initializer and check whether the context in question is reachable. 18505 } 18506 18507 Diag(Loc, PD); 18508 return true; 18509 } 18510 18511 return false; 18512 } 18513 18514 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18515 const PartialDiagnostic &PD) { 18516 return DiagRuntimeBehavior( 18517 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18518 } 18519 18520 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18521 CallExpr *CE, FunctionDecl *FD) { 18522 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18523 return false; 18524 18525 // If we're inside a decltype's expression, don't check for a valid return 18526 // type or construct temporaries until we know whether this is the last call. 18527 if (ExprEvalContexts.back().ExprContext == 18528 ExpressionEvaluationContextRecord::EK_Decltype) { 18529 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18530 return false; 18531 } 18532 18533 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18534 FunctionDecl *FD; 18535 CallExpr *CE; 18536 18537 public: 18538 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18539 : FD(FD), CE(CE) { } 18540 18541 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18542 if (!FD) { 18543 S.Diag(Loc, diag::err_call_incomplete_return) 18544 << T << CE->getSourceRange(); 18545 return; 18546 } 18547 18548 S.Diag(Loc, diag::err_call_function_incomplete_return) 18549 << CE->getSourceRange() << FD << T; 18550 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18551 << FD->getDeclName(); 18552 } 18553 } Diagnoser(FD, CE); 18554 18555 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18556 return true; 18557 18558 return false; 18559 } 18560 18561 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18562 // will prevent this condition from triggering, which is what we want. 18563 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18564 SourceLocation Loc; 18565 18566 unsigned diagnostic = diag::warn_condition_is_assignment; 18567 bool IsOrAssign = false; 18568 18569 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18570 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18571 return; 18572 18573 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18574 18575 // Greylist some idioms by putting them into a warning subcategory. 18576 if (ObjCMessageExpr *ME 18577 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18578 Selector Sel = ME->getSelector(); 18579 18580 // self = [<foo> init...] 18581 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18582 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18583 18584 // <foo> = [<bar> nextObject] 18585 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18586 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18587 } 18588 18589 Loc = Op->getOperatorLoc(); 18590 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18591 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18592 return; 18593 18594 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18595 Loc = Op->getOperatorLoc(); 18596 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18597 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18598 else { 18599 // Not an assignment. 18600 return; 18601 } 18602 18603 Diag(Loc, diagnostic) << E->getSourceRange(); 18604 18605 SourceLocation Open = E->getBeginLoc(); 18606 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18607 Diag(Loc, diag::note_condition_assign_silence) 18608 << FixItHint::CreateInsertion(Open, "(") 18609 << FixItHint::CreateInsertion(Close, ")"); 18610 18611 if (IsOrAssign) 18612 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18613 << FixItHint::CreateReplacement(Loc, "!="); 18614 else 18615 Diag(Loc, diag::note_condition_assign_to_comparison) 18616 << FixItHint::CreateReplacement(Loc, "=="); 18617 } 18618 18619 /// Redundant parentheses over an equality comparison can indicate 18620 /// that the user intended an assignment used as condition. 18621 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18622 // Don't warn if the parens came from a macro. 18623 SourceLocation parenLoc = ParenE->getBeginLoc(); 18624 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18625 return; 18626 // Don't warn for dependent expressions. 18627 if (ParenE->isTypeDependent()) 18628 return; 18629 18630 Expr *E = ParenE->IgnoreParens(); 18631 18632 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18633 if (opE->getOpcode() == BO_EQ && 18634 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18635 == Expr::MLV_Valid) { 18636 SourceLocation Loc = opE->getOperatorLoc(); 18637 18638 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18639 SourceRange ParenERange = ParenE->getSourceRange(); 18640 Diag(Loc, diag::note_equality_comparison_silence) 18641 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18642 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18643 Diag(Loc, diag::note_equality_comparison_to_assign) 18644 << FixItHint::CreateReplacement(Loc, "="); 18645 } 18646 } 18647 18648 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18649 bool IsConstexpr) { 18650 DiagnoseAssignmentAsCondition(E); 18651 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18652 DiagnoseEqualityWithExtraParens(parenE); 18653 18654 ExprResult result = CheckPlaceholderExpr(E); 18655 if (result.isInvalid()) return ExprError(); 18656 E = result.get(); 18657 18658 if (!E->isTypeDependent()) { 18659 if (getLangOpts().CPlusPlus) 18660 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18661 18662 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18663 if (ERes.isInvalid()) 18664 return ExprError(); 18665 E = ERes.get(); 18666 18667 QualType T = E->getType(); 18668 if (!T->isScalarType()) { // C99 6.8.4.1p1 18669 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18670 << T << E->getSourceRange(); 18671 return ExprError(); 18672 } 18673 CheckBoolLikeConversion(E, Loc); 18674 } 18675 18676 return E; 18677 } 18678 18679 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18680 Expr *SubExpr, ConditionKind CK) { 18681 // Empty conditions are valid in for-statements. 18682 if (!SubExpr) 18683 return ConditionResult(); 18684 18685 ExprResult Cond; 18686 switch (CK) { 18687 case ConditionKind::Boolean: 18688 Cond = CheckBooleanCondition(Loc, SubExpr); 18689 break; 18690 18691 case ConditionKind::ConstexprIf: 18692 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18693 break; 18694 18695 case ConditionKind::Switch: 18696 Cond = CheckSwitchCondition(Loc, SubExpr); 18697 break; 18698 } 18699 if (Cond.isInvalid()) { 18700 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18701 {SubExpr}); 18702 if (!Cond.get()) 18703 return ConditionError(); 18704 } 18705 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18706 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18707 if (!FullExpr.get()) 18708 return ConditionError(); 18709 18710 return ConditionResult(*this, nullptr, FullExpr, 18711 CK == ConditionKind::ConstexprIf); 18712 } 18713 18714 namespace { 18715 /// A visitor for rebuilding a call to an __unknown_any expression 18716 /// to have an appropriate type. 18717 struct RebuildUnknownAnyFunction 18718 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18719 18720 Sema &S; 18721 18722 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18723 18724 ExprResult VisitStmt(Stmt *S) { 18725 llvm_unreachable("unexpected statement!"); 18726 } 18727 18728 ExprResult VisitExpr(Expr *E) { 18729 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18730 << E->getSourceRange(); 18731 return ExprError(); 18732 } 18733 18734 /// Rebuild an expression which simply semantically wraps another 18735 /// expression which it shares the type and value kind of. 18736 template <class T> ExprResult rebuildSugarExpr(T *E) { 18737 ExprResult SubResult = Visit(E->getSubExpr()); 18738 if (SubResult.isInvalid()) return ExprError(); 18739 18740 Expr *SubExpr = SubResult.get(); 18741 E->setSubExpr(SubExpr); 18742 E->setType(SubExpr->getType()); 18743 E->setValueKind(SubExpr->getValueKind()); 18744 assert(E->getObjectKind() == OK_Ordinary); 18745 return E; 18746 } 18747 18748 ExprResult VisitParenExpr(ParenExpr *E) { 18749 return rebuildSugarExpr(E); 18750 } 18751 18752 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18753 return rebuildSugarExpr(E); 18754 } 18755 18756 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18757 ExprResult SubResult = Visit(E->getSubExpr()); 18758 if (SubResult.isInvalid()) return ExprError(); 18759 18760 Expr *SubExpr = SubResult.get(); 18761 E->setSubExpr(SubExpr); 18762 E->setType(S.Context.getPointerType(SubExpr->getType())); 18763 assert(E->getValueKind() == VK_RValue); 18764 assert(E->getObjectKind() == OK_Ordinary); 18765 return E; 18766 } 18767 18768 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18769 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18770 18771 E->setType(VD->getType()); 18772 18773 assert(E->getValueKind() == VK_RValue); 18774 if (S.getLangOpts().CPlusPlus && 18775 !(isa<CXXMethodDecl>(VD) && 18776 cast<CXXMethodDecl>(VD)->isInstance())) 18777 E->setValueKind(VK_LValue); 18778 18779 return E; 18780 } 18781 18782 ExprResult VisitMemberExpr(MemberExpr *E) { 18783 return resolveDecl(E, E->getMemberDecl()); 18784 } 18785 18786 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18787 return resolveDecl(E, E->getDecl()); 18788 } 18789 }; 18790 } 18791 18792 /// Given a function expression of unknown-any type, try to rebuild it 18793 /// to have a function type. 18794 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18795 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18796 if (Result.isInvalid()) return ExprError(); 18797 return S.DefaultFunctionArrayConversion(Result.get()); 18798 } 18799 18800 namespace { 18801 /// A visitor for rebuilding an expression of type __unknown_anytype 18802 /// into one which resolves the type directly on the referring 18803 /// expression. Strict preservation of the original source 18804 /// structure is not a goal. 18805 struct RebuildUnknownAnyExpr 18806 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18807 18808 Sema &S; 18809 18810 /// The current destination type. 18811 QualType DestType; 18812 18813 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18814 : S(S), DestType(CastType) {} 18815 18816 ExprResult VisitStmt(Stmt *S) { 18817 llvm_unreachable("unexpected statement!"); 18818 } 18819 18820 ExprResult VisitExpr(Expr *E) { 18821 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18822 << E->getSourceRange(); 18823 return ExprError(); 18824 } 18825 18826 ExprResult VisitCallExpr(CallExpr *E); 18827 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18828 18829 /// Rebuild an expression which simply semantically wraps another 18830 /// expression which it shares the type and value kind of. 18831 template <class T> ExprResult rebuildSugarExpr(T *E) { 18832 ExprResult SubResult = Visit(E->getSubExpr()); 18833 if (SubResult.isInvalid()) return ExprError(); 18834 Expr *SubExpr = SubResult.get(); 18835 E->setSubExpr(SubExpr); 18836 E->setType(SubExpr->getType()); 18837 E->setValueKind(SubExpr->getValueKind()); 18838 assert(E->getObjectKind() == OK_Ordinary); 18839 return E; 18840 } 18841 18842 ExprResult VisitParenExpr(ParenExpr *E) { 18843 return rebuildSugarExpr(E); 18844 } 18845 18846 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18847 return rebuildSugarExpr(E); 18848 } 18849 18850 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18851 const PointerType *Ptr = DestType->getAs<PointerType>(); 18852 if (!Ptr) { 18853 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18854 << E->getSourceRange(); 18855 return ExprError(); 18856 } 18857 18858 if (isa<CallExpr>(E->getSubExpr())) { 18859 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18860 << E->getSourceRange(); 18861 return ExprError(); 18862 } 18863 18864 assert(E->getValueKind() == VK_RValue); 18865 assert(E->getObjectKind() == OK_Ordinary); 18866 E->setType(DestType); 18867 18868 // Build the sub-expression as if it were an object of the pointee type. 18869 DestType = Ptr->getPointeeType(); 18870 ExprResult SubResult = Visit(E->getSubExpr()); 18871 if (SubResult.isInvalid()) return ExprError(); 18872 E->setSubExpr(SubResult.get()); 18873 return E; 18874 } 18875 18876 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18877 18878 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18879 18880 ExprResult VisitMemberExpr(MemberExpr *E) { 18881 return resolveDecl(E, E->getMemberDecl()); 18882 } 18883 18884 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18885 return resolveDecl(E, E->getDecl()); 18886 } 18887 }; 18888 } 18889 18890 /// Rebuilds a call expression which yielded __unknown_anytype. 18891 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18892 Expr *CalleeExpr = E->getCallee(); 18893 18894 enum FnKind { 18895 FK_MemberFunction, 18896 FK_FunctionPointer, 18897 FK_BlockPointer 18898 }; 18899 18900 FnKind Kind; 18901 QualType CalleeType = CalleeExpr->getType(); 18902 if (CalleeType == S.Context.BoundMemberTy) { 18903 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18904 Kind = FK_MemberFunction; 18905 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18906 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18907 CalleeType = Ptr->getPointeeType(); 18908 Kind = FK_FunctionPointer; 18909 } else { 18910 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18911 Kind = FK_BlockPointer; 18912 } 18913 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18914 18915 // Verify that this is a legal result type of a function. 18916 if (DestType->isArrayType() || DestType->isFunctionType()) { 18917 unsigned diagID = diag::err_func_returning_array_function; 18918 if (Kind == FK_BlockPointer) 18919 diagID = diag::err_block_returning_array_function; 18920 18921 S.Diag(E->getExprLoc(), diagID) 18922 << DestType->isFunctionType() << DestType; 18923 return ExprError(); 18924 } 18925 18926 // Otherwise, go ahead and set DestType as the call's result. 18927 E->setType(DestType.getNonLValueExprType(S.Context)); 18928 E->setValueKind(Expr::getValueKindForType(DestType)); 18929 assert(E->getObjectKind() == OK_Ordinary); 18930 18931 // Rebuild the function type, replacing the result type with DestType. 18932 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18933 if (Proto) { 18934 // __unknown_anytype(...) is a special case used by the debugger when 18935 // it has no idea what a function's signature is. 18936 // 18937 // We want to build this call essentially under the K&R 18938 // unprototyped rules, but making a FunctionNoProtoType in C++ 18939 // would foul up all sorts of assumptions. However, we cannot 18940 // simply pass all arguments as variadic arguments, nor can we 18941 // portably just call the function under a non-variadic type; see 18942 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18943 // However, it turns out that in practice it is generally safe to 18944 // call a function declared as "A foo(B,C,D);" under the prototype 18945 // "A foo(B,C,D,...);". The only known exception is with the 18946 // Windows ABI, where any variadic function is implicitly cdecl 18947 // regardless of its normal CC. Therefore we change the parameter 18948 // types to match the types of the arguments. 18949 // 18950 // This is a hack, but it is far superior to moving the 18951 // corresponding target-specific code from IR-gen to Sema/AST. 18952 18953 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18954 SmallVector<QualType, 8> ArgTypes; 18955 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18956 ArgTypes.reserve(E->getNumArgs()); 18957 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18958 Expr *Arg = E->getArg(i); 18959 QualType ArgType = Arg->getType(); 18960 if (E->isLValue()) { 18961 ArgType = S.Context.getLValueReferenceType(ArgType); 18962 } else if (E->isXValue()) { 18963 ArgType = S.Context.getRValueReferenceType(ArgType); 18964 } 18965 ArgTypes.push_back(ArgType); 18966 } 18967 ParamTypes = ArgTypes; 18968 } 18969 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18970 Proto->getExtProtoInfo()); 18971 } else { 18972 DestType = S.Context.getFunctionNoProtoType(DestType, 18973 FnType->getExtInfo()); 18974 } 18975 18976 // Rebuild the appropriate pointer-to-function type. 18977 switch (Kind) { 18978 case FK_MemberFunction: 18979 // Nothing to do. 18980 break; 18981 18982 case FK_FunctionPointer: 18983 DestType = S.Context.getPointerType(DestType); 18984 break; 18985 18986 case FK_BlockPointer: 18987 DestType = S.Context.getBlockPointerType(DestType); 18988 break; 18989 } 18990 18991 // Finally, we can recurse. 18992 ExprResult CalleeResult = Visit(CalleeExpr); 18993 if (!CalleeResult.isUsable()) return ExprError(); 18994 E->setCallee(CalleeResult.get()); 18995 18996 // Bind a temporary if necessary. 18997 return S.MaybeBindToTemporary(E); 18998 } 18999 19000 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19001 // Verify that this is a legal result type of a call. 19002 if (DestType->isArrayType() || DestType->isFunctionType()) { 19003 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19004 << DestType->isFunctionType() << DestType; 19005 return ExprError(); 19006 } 19007 19008 // Rewrite the method result type if available. 19009 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19010 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19011 Method->setReturnType(DestType); 19012 } 19013 19014 // Change the type of the message. 19015 E->setType(DestType.getNonReferenceType()); 19016 E->setValueKind(Expr::getValueKindForType(DestType)); 19017 19018 return S.MaybeBindToTemporary(E); 19019 } 19020 19021 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19022 // The only case we should ever see here is a function-to-pointer decay. 19023 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19024 assert(E->getValueKind() == VK_RValue); 19025 assert(E->getObjectKind() == OK_Ordinary); 19026 19027 E->setType(DestType); 19028 19029 // Rebuild the sub-expression as the pointee (function) type. 19030 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19031 19032 ExprResult Result = Visit(E->getSubExpr()); 19033 if (!Result.isUsable()) return ExprError(); 19034 19035 E->setSubExpr(Result.get()); 19036 return E; 19037 } else if (E->getCastKind() == CK_LValueToRValue) { 19038 assert(E->getValueKind() == VK_RValue); 19039 assert(E->getObjectKind() == OK_Ordinary); 19040 19041 assert(isa<BlockPointerType>(E->getType())); 19042 19043 E->setType(DestType); 19044 19045 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19046 DestType = S.Context.getLValueReferenceType(DestType); 19047 19048 ExprResult Result = Visit(E->getSubExpr()); 19049 if (!Result.isUsable()) return ExprError(); 19050 19051 E->setSubExpr(Result.get()); 19052 return E; 19053 } else { 19054 llvm_unreachable("Unhandled cast type!"); 19055 } 19056 } 19057 19058 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19059 ExprValueKind ValueKind = VK_LValue; 19060 QualType Type = DestType; 19061 19062 // We know how to make this work for certain kinds of decls: 19063 19064 // - functions 19065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19066 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19067 DestType = Ptr->getPointeeType(); 19068 ExprResult Result = resolveDecl(E, VD); 19069 if (Result.isInvalid()) return ExprError(); 19070 return S.ImpCastExprToType(Result.get(), Type, 19071 CK_FunctionToPointerDecay, VK_RValue); 19072 } 19073 19074 if (!Type->isFunctionType()) { 19075 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19076 << VD << E->getSourceRange(); 19077 return ExprError(); 19078 } 19079 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19080 // We must match the FunctionDecl's type to the hack introduced in 19081 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19082 // type. See the lengthy commentary in that routine. 19083 QualType FDT = FD->getType(); 19084 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19085 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19086 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19087 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19088 SourceLocation Loc = FD->getLocation(); 19089 FunctionDecl *NewFD = FunctionDecl::Create( 19090 S.Context, FD->getDeclContext(), Loc, Loc, 19091 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19092 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19093 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19094 19095 if (FD->getQualifier()) 19096 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19097 19098 SmallVector<ParmVarDecl*, 16> Params; 19099 for (const auto &AI : FT->param_types()) { 19100 ParmVarDecl *Param = 19101 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19102 Param->setScopeInfo(0, Params.size()); 19103 Params.push_back(Param); 19104 } 19105 NewFD->setParams(Params); 19106 DRE->setDecl(NewFD); 19107 VD = DRE->getDecl(); 19108 } 19109 } 19110 19111 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19112 if (MD->isInstance()) { 19113 ValueKind = VK_RValue; 19114 Type = S.Context.BoundMemberTy; 19115 } 19116 19117 // Function references aren't l-values in C. 19118 if (!S.getLangOpts().CPlusPlus) 19119 ValueKind = VK_RValue; 19120 19121 // - variables 19122 } else if (isa<VarDecl>(VD)) { 19123 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19124 Type = RefTy->getPointeeType(); 19125 } else if (Type->isFunctionType()) { 19126 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19127 << VD << E->getSourceRange(); 19128 return ExprError(); 19129 } 19130 19131 // - nothing else 19132 } else { 19133 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19134 << VD << E->getSourceRange(); 19135 return ExprError(); 19136 } 19137 19138 // Modifying the declaration like this is friendly to IR-gen but 19139 // also really dangerous. 19140 VD->setType(DestType); 19141 E->setType(Type); 19142 E->setValueKind(ValueKind); 19143 return E; 19144 } 19145 19146 /// Check a cast of an unknown-any type. We intentionally only 19147 /// trigger this for C-style casts. 19148 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19149 Expr *CastExpr, CastKind &CastKind, 19150 ExprValueKind &VK, CXXCastPath &Path) { 19151 // The type we're casting to must be either void or complete. 19152 if (!CastType->isVoidType() && 19153 RequireCompleteType(TypeRange.getBegin(), CastType, 19154 diag::err_typecheck_cast_to_incomplete)) 19155 return ExprError(); 19156 19157 // Rewrite the casted expression from scratch. 19158 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19159 if (!result.isUsable()) return ExprError(); 19160 19161 CastExpr = result.get(); 19162 VK = CastExpr->getValueKind(); 19163 CastKind = CK_NoOp; 19164 19165 return CastExpr; 19166 } 19167 19168 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19169 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19170 } 19171 19172 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19173 Expr *arg, QualType ¶mType) { 19174 // If the syntactic form of the argument is not an explicit cast of 19175 // any sort, just do default argument promotion. 19176 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19177 if (!castArg) { 19178 ExprResult result = DefaultArgumentPromotion(arg); 19179 if (result.isInvalid()) return ExprError(); 19180 paramType = result.get()->getType(); 19181 return result; 19182 } 19183 19184 // Otherwise, use the type that was written in the explicit cast. 19185 assert(!arg->hasPlaceholderType()); 19186 paramType = castArg->getTypeAsWritten(); 19187 19188 // Copy-initialize a parameter of that type. 19189 InitializedEntity entity = 19190 InitializedEntity::InitializeParameter(Context, paramType, 19191 /*consumed*/ false); 19192 return PerformCopyInitialization(entity, callLoc, arg); 19193 } 19194 19195 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19196 Expr *orig = E; 19197 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19198 while (true) { 19199 E = E->IgnoreParenImpCasts(); 19200 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19201 E = call->getCallee(); 19202 diagID = diag::err_uncasted_call_of_unknown_any; 19203 } else { 19204 break; 19205 } 19206 } 19207 19208 SourceLocation loc; 19209 NamedDecl *d; 19210 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19211 loc = ref->getLocation(); 19212 d = ref->getDecl(); 19213 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19214 loc = mem->getMemberLoc(); 19215 d = mem->getMemberDecl(); 19216 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19217 diagID = diag::err_uncasted_call_of_unknown_any; 19218 loc = msg->getSelectorStartLoc(); 19219 d = msg->getMethodDecl(); 19220 if (!d) { 19221 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19222 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19223 << orig->getSourceRange(); 19224 return ExprError(); 19225 } 19226 } else { 19227 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19228 << E->getSourceRange(); 19229 return ExprError(); 19230 } 19231 19232 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19233 19234 // Never recoverable. 19235 return ExprError(); 19236 } 19237 19238 /// Check for operands with placeholder types and complain if found. 19239 /// Returns ExprError() if there was an error and no recovery was possible. 19240 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19241 if (!Context.isDependenceAllowed()) { 19242 // C cannot handle TypoExpr nodes on either side of a binop because it 19243 // doesn't handle dependent types properly, so make sure any TypoExprs have 19244 // been dealt with before checking the operands. 19245 ExprResult Result = CorrectDelayedTyposInExpr(E); 19246 if (!Result.isUsable()) return ExprError(); 19247 E = Result.get(); 19248 } 19249 19250 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19251 if (!placeholderType) return E; 19252 19253 switch (placeholderType->getKind()) { 19254 19255 // Overloaded expressions. 19256 case BuiltinType::Overload: { 19257 // Try to resolve a single function template specialization. 19258 // This is obligatory. 19259 ExprResult Result = E; 19260 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19261 return Result; 19262 19263 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19264 // leaves Result unchanged on failure. 19265 Result = E; 19266 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19267 return Result; 19268 19269 // If that failed, try to recover with a call. 19270 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19271 /*complain*/ true); 19272 return Result; 19273 } 19274 19275 // Bound member functions. 19276 case BuiltinType::BoundMember: { 19277 ExprResult result = E; 19278 const Expr *BME = E->IgnoreParens(); 19279 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19280 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19281 if (isa<CXXPseudoDestructorExpr>(BME)) { 19282 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19283 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19284 if (ME->getMemberNameInfo().getName().getNameKind() == 19285 DeclarationName::CXXDestructorName) 19286 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19287 } 19288 tryToRecoverWithCall(result, PD, 19289 /*complain*/ true); 19290 return result; 19291 } 19292 19293 // ARC unbridged casts. 19294 case BuiltinType::ARCUnbridgedCast: { 19295 Expr *realCast = stripARCUnbridgedCast(E); 19296 diagnoseARCUnbridgedCast(realCast); 19297 return realCast; 19298 } 19299 19300 // Expressions of unknown type. 19301 case BuiltinType::UnknownAny: 19302 return diagnoseUnknownAnyExpr(*this, E); 19303 19304 // Pseudo-objects. 19305 case BuiltinType::PseudoObject: 19306 return checkPseudoObjectRValue(E); 19307 19308 case BuiltinType::BuiltinFn: { 19309 // Accept __noop without parens by implicitly converting it to a call expr. 19310 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19311 if (DRE) { 19312 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19313 if (FD->getBuiltinID() == Builtin::BI__noop) { 19314 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19315 CK_BuiltinFnToFnPtr) 19316 .get(); 19317 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19318 VK_RValue, SourceLocation(), 19319 FPOptionsOverride()); 19320 } 19321 } 19322 19323 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19324 return ExprError(); 19325 } 19326 19327 case BuiltinType::IncompleteMatrixIdx: 19328 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19329 ->getRowIdx() 19330 ->getBeginLoc(), 19331 diag::err_matrix_incomplete_index); 19332 return ExprError(); 19333 19334 // Expressions of unknown type. 19335 case BuiltinType::OMPArraySection: 19336 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19337 return ExprError(); 19338 19339 // Expressions of unknown type. 19340 case BuiltinType::OMPArrayShaping: 19341 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19342 19343 case BuiltinType::OMPIterator: 19344 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19345 19346 // Everything else should be impossible. 19347 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19348 case BuiltinType::Id: 19349 #include "clang/Basic/OpenCLImageTypes.def" 19350 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19351 case BuiltinType::Id: 19352 #include "clang/Basic/OpenCLExtensionTypes.def" 19353 #define SVE_TYPE(Name, Id, SingletonId) \ 19354 case BuiltinType::Id: 19355 #include "clang/Basic/AArch64SVEACLETypes.def" 19356 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19357 case BuiltinType::Id: 19358 #include "clang/Basic/PPCTypes.def" 19359 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19360 #define PLACEHOLDER_TYPE(Id, SingletonId) 19361 #include "clang/AST/BuiltinTypes.def" 19362 break; 19363 } 19364 19365 llvm_unreachable("invalid placeholder type!"); 19366 } 19367 19368 bool Sema::CheckCaseExpression(Expr *E) { 19369 if (E->isTypeDependent()) 19370 return true; 19371 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19372 return E->getType()->isIntegralOrEnumerationType(); 19373 return false; 19374 } 19375 19376 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19377 ExprResult 19378 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19379 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19380 "Unknown Objective-C Boolean value!"); 19381 QualType BoolT = Context.ObjCBuiltinBoolTy; 19382 if (!Context.getBOOLDecl()) { 19383 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19384 Sema::LookupOrdinaryName); 19385 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19386 NamedDecl *ND = Result.getFoundDecl(); 19387 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19388 Context.setBOOLDecl(TD); 19389 } 19390 } 19391 if (Context.getBOOLDecl()) 19392 BoolT = Context.getBOOLType(); 19393 return new (Context) 19394 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19395 } 19396 19397 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19398 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19399 SourceLocation RParen) { 19400 19401 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19402 19403 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19404 return Spec.getPlatform() == Platform; 19405 }); 19406 19407 VersionTuple Version; 19408 if (Spec != AvailSpecs.end()) 19409 Version = Spec->getVersion(); 19410 19411 // The use of `@available` in the enclosing function should be analyzed to 19412 // warn when it's used inappropriately (i.e. not if(@available)). 19413 if (getCurFunctionOrMethodDecl()) 19414 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19415 else if (getCurBlock() || getCurLambda()) 19416 getCurFunction()->HasPotentialAvailabilityViolations = true; 19417 19418 return new (Context) 19419 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19420 } 19421 19422 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19423 ArrayRef<Expr *> SubExprs, QualType T) { 19424 if (!Context.getLangOpts().RecoveryAST) 19425 return ExprError(); 19426 19427 if (isSFINAEContext()) 19428 return ExprError(); 19429 19430 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19431 // We don't know the concrete type, fallback to dependent type. 19432 T = Context.DependentTy; 19433 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19434 } 19435