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 (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.setImplicitSelfParam(&II); 2855 CXXScopeSpec SelfScopeSpec; 2856 SourceLocation TemplateKWLoc; 2857 ExprResult SelfExpr = 2858 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2859 /*HasTrailingLParen=*/false, 2860 /*IsAddressOfOperand=*/false); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2865 if (SelfExpr.isInvalid()) 2866 return ExprError(); 2867 2868 MarkAnyDeclReferenced(Loc, IV, true); 2869 2870 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2871 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2872 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2873 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2874 2875 ObjCIvarRefExpr *Result = new (Context) 2876 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2877 IV->getLocation(), SelfExpr.get(), true, true); 2878 2879 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2880 if (!isUnevaluatedContext() && 2881 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2882 getCurFunction()->recordUseOfWeak(Result); 2883 } 2884 if (getLangOpts().ObjCAutoRefCount) 2885 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2886 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2887 2888 return Result; 2889 } 2890 2891 /// The parser has read a name in, and Sema has detected that we're currently 2892 /// inside an ObjC method. Perform some additional checks and determine if we 2893 /// should form a reference to an ivar. If so, build an expression referencing 2894 /// that ivar. 2895 ExprResult 2896 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2897 IdentifierInfo *II, bool AllowBuiltinCreation) { 2898 // FIXME: Integrate this lookup step into LookupParsedName. 2899 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2900 if (Ivar.isInvalid()) 2901 return ExprError(); 2902 if (Ivar.isUsable()) 2903 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2904 cast<ObjCIvarDecl>(Ivar.get())); 2905 2906 if (Lookup.empty() && II && AllowBuiltinCreation) 2907 LookupBuiltin(Lookup); 2908 2909 // Sentinel value saying that we didn't do anything special. 2910 return ExprResult(false); 2911 } 2912 2913 /// Cast a base object to a member's actual type. 2914 /// 2915 /// There are two relevant checks: 2916 /// 2917 /// C++ [class.access.base]p7: 2918 /// 2919 /// If a class member access operator [...] is used to access a non-static 2920 /// data member or non-static member function, the reference is ill-formed if 2921 /// the left operand [...] cannot be implicitly converted to a pointer to the 2922 /// naming class of the right operand. 2923 /// 2924 /// C++ [expr.ref]p7: 2925 /// 2926 /// If E2 is a non-static data member or a non-static member function, the 2927 /// program is ill-formed if the class of which E2 is directly a member is an 2928 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2929 /// 2930 /// Note that the latter check does not consider access; the access of the 2931 /// "real" base class is checked as appropriate when checking the access of the 2932 /// member name. 2933 ExprResult 2934 Sema::PerformObjectMemberConversion(Expr *From, 2935 NestedNameSpecifier *Qualifier, 2936 NamedDecl *FoundDecl, 2937 NamedDecl *Member) { 2938 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2939 if (!RD) 2940 return From; 2941 2942 QualType DestRecordType; 2943 QualType DestType; 2944 QualType FromRecordType; 2945 QualType FromType = From->getType(); 2946 bool PointerConversions = false; 2947 if (isa<FieldDecl>(Member)) { 2948 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2949 auto FromPtrType = FromType->getAs<PointerType>(); 2950 DestRecordType = Context.getAddrSpaceQualType( 2951 DestRecordType, FromPtrType 2952 ? FromType->getPointeeType().getAddressSpace() 2953 : FromType.getAddressSpace()); 2954 2955 if (FromPtrType) { 2956 DestType = Context.getPointerType(DestRecordType); 2957 FromRecordType = FromPtrType->getPointeeType(); 2958 PointerConversions = true; 2959 } else { 2960 DestType = DestRecordType; 2961 FromRecordType = FromType; 2962 } 2963 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2964 if (Method->isStatic()) 2965 return From; 2966 2967 DestType = Method->getThisType(); 2968 DestRecordType = DestType->getPointeeType(); 2969 2970 if (FromType->getAs<PointerType>()) { 2971 FromRecordType = FromType->getPointeeType(); 2972 PointerConversions = true; 2973 } else { 2974 FromRecordType = FromType; 2975 DestType = DestRecordType; 2976 } 2977 2978 LangAS FromAS = FromRecordType.getAddressSpace(); 2979 LangAS DestAS = DestRecordType.getAddressSpace(); 2980 if (FromAS != DestAS) { 2981 QualType FromRecordTypeWithoutAS = 2982 Context.removeAddrSpaceQualType(FromRecordType); 2983 QualType FromTypeWithDestAS = 2984 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2985 if (PointerConversions) 2986 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2987 From = ImpCastExprToType(From, FromTypeWithDestAS, 2988 CK_AddressSpaceConversion, From->getValueKind()) 2989 .get(); 2990 } 2991 } else { 2992 // No conversion necessary. 2993 return From; 2994 } 2995 2996 if (DestType->isDependentType() || FromType->isDependentType()) 2997 return From; 2998 2999 // If the unqualified types are the same, no conversion is necessary. 3000 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3001 return From; 3002 3003 SourceRange FromRange = From->getSourceRange(); 3004 SourceLocation FromLoc = FromRange.getBegin(); 3005 3006 ExprValueKind VK = From->getValueKind(); 3007 3008 // C++ [class.member.lookup]p8: 3009 // [...] Ambiguities can often be resolved by qualifying a name with its 3010 // class name. 3011 // 3012 // If the member was a qualified name and the qualified referred to a 3013 // specific base subobject type, we'll cast to that intermediate type 3014 // first and then to the object in which the member is declared. That allows 3015 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3016 // 3017 // class Base { public: int x; }; 3018 // class Derived1 : public Base { }; 3019 // class Derived2 : public Base { }; 3020 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3021 // 3022 // void VeryDerived::f() { 3023 // x = 17; // error: ambiguous base subobjects 3024 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3025 // } 3026 if (Qualifier && Qualifier->getAsType()) { 3027 QualType QType = QualType(Qualifier->getAsType(), 0); 3028 assert(QType->isRecordType() && "lookup done with non-record type"); 3029 3030 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3031 3032 // In C++98, the qualifier type doesn't actually have to be a base 3033 // type of the object type, in which case we just ignore it. 3034 // Otherwise build the appropriate casts. 3035 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3036 CXXCastPath BasePath; 3037 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3038 FromLoc, FromRange, &BasePath)) 3039 return ExprError(); 3040 3041 if (PointerConversions) 3042 QType = Context.getPointerType(QType); 3043 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3044 VK, &BasePath).get(); 3045 3046 FromType = QType; 3047 FromRecordType = QRecordType; 3048 3049 // If the qualifier type was the same as the destination type, 3050 // we're done. 3051 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3052 return From; 3053 } 3054 } 3055 3056 CXXCastPath BasePath; 3057 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3058 FromLoc, FromRange, &BasePath, 3059 /*IgnoreAccess=*/true)) 3060 return ExprError(); 3061 3062 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3063 VK, &BasePath); 3064 } 3065 3066 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3067 const LookupResult &R, 3068 bool HasTrailingLParen) { 3069 // Only when used directly as the postfix-expression of a call. 3070 if (!HasTrailingLParen) 3071 return false; 3072 3073 // Never if a scope specifier was provided. 3074 if (SS.isSet()) 3075 return false; 3076 3077 // Only in C++ or ObjC++. 3078 if (!getLangOpts().CPlusPlus) 3079 return false; 3080 3081 // Turn off ADL when we find certain kinds of declarations during 3082 // normal lookup: 3083 for (NamedDecl *D : R) { 3084 // C++0x [basic.lookup.argdep]p3: 3085 // -- a declaration of a class member 3086 // Since using decls preserve this property, we check this on the 3087 // original decl. 3088 if (D->isCXXClassMember()) 3089 return false; 3090 3091 // C++0x [basic.lookup.argdep]p3: 3092 // -- a block-scope function declaration that is not a 3093 // using-declaration 3094 // NOTE: we also trigger this for function templates (in fact, we 3095 // don't check the decl type at all, since all other decl types 3096 // turn off ADL anyway). 3097 if (isa<UsingShadowDecl>(D)) 3098 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3099 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3100 return false; 3101 3102 // C++0x [basic.lookup.argdep]p3: 3103 // -- a declaration that is neither a function or a function 3104 // template 3105 // And also for builtin functions. 3106 if (isa<FunctionDecl>(D)) { 3107 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3108 3109 // But also builtin functions. 3110 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3111 return false; 3112 } else if (!isa<FunctionTemplateDecl>(D)) 3113 return false; 3114 } 3115 3116 return true; 3117 } 3118 3119 3120 /// Diagnoses obvious problems with the use of the given declaration 3121 /// as an expression. This is only actually called for lookups that 3122 /// were not overloaded, and it doesn't promise that the declaration 3123 /// will in fact be used. 3124 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3125 if (D->isInvalidDecl()) 3126 return true; 3127 3128 if (isa<TypedefNameDecl>(D)) { 3129 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3130 return true; 3131 } 3132 3133 if (isa<ObjCInterfaceDecl>(D)) { 3134 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3135 return true; 3136 } 3137 3138 if (isa<NamespaceDecl>(D)) { 3139 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3140 return true; 3141 } 3142 3143 return false; 3144 } 3145 3146 // Certain multiversion types should be treated as overloaded even when there is 3147 // only one result. 3148 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3149 assert(R.isSingleResult() && "Expected only a single result"); 3150 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3151 return FD && 3152 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3153 } 3154 3155 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3156 LookupResult &R, bool NeedsADL, 3157 bool AcceptInvalidDecl) { 3158 // If this is a single, fully-resolved result and we don't need ADL, 3159 // just build an ordinary singleton decl ref. 3160 if (!NeedsADL && R.isSingleResult() && 3161 !R.getAsSingle<FunctionTemplateDecl>() && 3162 !ShouldLookupResultBeMultiVersionOverload(R)) 3163 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3164 R.getRepresentativeDecl(), nullptr, 3165 AcceptInvalidDecl); 3166 3167 // We only need to check the declaration if there's exactly one 3168 // result, because in the overloaded case the results can only be 3169 // functions and function templates. 3170 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3171 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3172 return ExprError(); 3173 3174 // Otherwise, just build an unresolved lookup expression. Suppress 3175 // any lookup-related diagnostics; we'll hash these out later, when 3176 // we've picked a target. 3177 R.suppressDiagnostics(); 3178 3179 UnresolvedLookupExpr *ULE 3180 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3181 SS.getWithLocInContext(Context), 3182 R.getLookupNameInfo(), 3183 NeedsADL, R.isOverloadedResult(), 3184 R.begin(), R.end()); 3185 3186 return ULE; 3187 } 3188 3189 static void 3190 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3191 ValueDecl *var, DeclContext *DC); 3192 3193 /// Complete semantic analysis for a reference to the given declaration. 3194 ExprResult Sema::BuildDeclarationNameExpr( 3195 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3196 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3197 bool AcceptInvalidDecl) { 3198 assert(D && "Cannot refer to a NULL declaration"); 3199 assert(!isa<FunctionTemplateDecl>(D) && 3200 "Cannot refer unambiguously to a function template"); 3201 3202 SourceLocation Loc = NameInfo.getLoc(); 3203 if (CheckDeclInExpr(*this, Loc, D)) 3204 return ExprError(); 3205 3206 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3207 // Specifically diagnose references to class templates that are missing 3208 // a template argument list. 3209 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3210 return ExprError(); 3211 } 3212 3213 // Make sure that we're referring to a value. 3214 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3215 if (!VD) { 3216 Diag(Loc, diag::err_ref_non_value) 3217 << D << SS.getRange(); 3218 Diag(D->getLocation(), diag::note_declared_at); 3219 return ExprError(); 3220 } 3221 3222 // Check whether this declaration can be used. Note that we suppress 3223 // this check when we're going to perform argument-dependent lookup 3224 // on this function name, because this might not be the function 3225 // that overload resolution actually selects. 3226 if (DiagnoseUseOfDecl(VD, Loc)) 3227 return ExprError(); 3228 3229 // Only create DeclRefExpr's for valid Decl's. 3230 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3231 return ExprError(); 3232 3233 // Handle members of anonymous structs and unions. If we got here, 3234 // and the reference is to a class member indirect field, then this 3235 // must be the subject of a pointer-to-member expression. 3236 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3237 if (!indirectField->isCXXClassMember()) 3238 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3239 indirectField); 3240 3241 { 3242 QualType type = VD->getType(); 3243 if (type.isNull()) 3244 return ExprError(); 3245 ExprValueKind valueKind = VK_RValue; 3246 3247 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3248 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3249 // is expanded by some outer '...' in the context of the use. 3250 type = type.getNonPackExpansionType(); 3251 3252 switch (D->getKind()) { 3253 // Ignore all the non-ValueDecl kinds. 3254 #define ABSTRACT_DECL(kind) 3255 #define VALUE(type, base) 3256 #define DECL(type, base) \ 3257 case Decl::type: 3258 #include "clang/AST/DeclNodes.inc" 3259 llvm_unreachable("invalid value decl kind"); 3260 3261 // These shouldn't make it here. 3262 case Decl::ObjCAtDefsField: 3263 llvm_unreachable("forming non-member reference to ivar?"); 3264 3265 // Enum constants are always r-values and never references. 3266 // Unresolved using declarations are dependent. 3267 case Decl::EnumConstant: 3268 case Decl::UnresolvedUsingValue: 3269 case Decl::OMPDeclareReduction: 3270 case Decl::OMPDeclareMapper: 3271 valueKind = VK_RValue; 3272 break; 3273 3274 // Fields and indirect fields that got here must be for 3275 // pointer-to-member expressions; we just call them l-values for 3276 // internal consistency, because this subexpression doesn't really 3277 // exist in the high-level semantics. 3278 case Decl::Field: 3279 case Decl::IndirectField: 3280 case Decl::ObjCIvar: 3281 assert(getLangOpts().CPlusPlus && 3282 "building reference to field in C?"); 3283 3284 // These can't have reference type in well-formed programs, but 3285 // for internal consistency we do this anyway. 3286 type = type.getNonReferenceType(); 3287 valueKind = VK_LValue; 3288 break; 3289 3290 // Non-type template parameters are either l-values or r-values 3291 // depending on the type. 3292 case Decl::NonTypeTemplateParm: { 3293 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3294 type = reftype->getPointeeType(); 3295 valueKind = VK_LValue; // even if the parameter is an r-value reference 3296 break; 3297 } 3298 3299 // [expr.prim.id.unqual]p2: 3300 // If the entity is a template parameter object for a template 3301 // parameter of type T, the type of the expression is const T. 3302 // [...] The expression is an lvalue if the entity is a [...] template 3303 // parameter object. 3304 if (type->isRecordType()) { 3305 type = type.getUnqualifiedType().withConst(); 3306 valueKind = VK_LValue; 3307 break; 3308 } 3309 3310 // For non-references, we need to strip qualifiers just in case 3311 // the template parameter was declared as 'const int' or whatever. 3312 valueKind = VK_RValue; 3313 type = type.getUnqualifiedType(); 3314 break; 3315 } 3316 3317 case Decl::Var: 3318 case Decl::VarTemplateSpecialization: 3319 case Decl::VarTemplatePartialSpecialization: 3320 case Decl::Decomposition: 3321 case Decl::OMPCapturedExpr: 3322 // In C, "extern void blah;" is valid and is an r-value. 3323 if (!getLangOpts().CPlusPlus && 3324 !type.hasQualifiers() && 3325 type->isVoidType()) { 3326 valueKind = VK_RValue; 3327 break; 3328 } 3329 LLVM_FALLTHROUGH; 3330 3331 case Decl::ImplicitParam: 3332 case Decl::ParmVar: { 3333 // These are always l-values. 3334 valueKind = VK_LValue; 3335 type = type.getNonReferenceType(); 3336 3337 // FIXME: Does the addition of const really only apply in 3338 // potentially-evaluated contexts? Since the variable isn't actually 3339 // captured in an unevaluated context, it seems that the answer is no. 3340 if (!isUnevaluatedContext()) { 3341 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3342 if (!CapturedType.isNull()) 3343 type = CapturedType; 3344 } 3345 3346 break; 3347 } 3348 3349 case Decl::Binding: { 3350 // These are always lvalues. 3351 valueKind = VK_LValue; 3352 type = type.getNonReferenceType(); 3353 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3354 // decides how that's supposed to work. 3355 auto *BD = cast<BindingDecl>(VD); 3356 if (BD->getDeclContext() != CurContext) { 3357 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3358 if (DD && DD->hasLocalStorage()) 3359 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3360 } 3361 break; 3362 } 3363 3364 case Decl::Function: { 3365 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3366 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3367 type = Context.BuiltinFnTy; 3368 valueKind = VK_RValue; 3369 break; 3370 } 3371 } 3372 3373 const FunctionType *fty = type->castAs<FunctionType>(); 3374 3375 // If we're referring to a function with an __unknown_anytype 3376 // result type, make the entire expression __unknown_anytype. 3377 if (fty->getReturnType() == Context.UnknownAnyTy) { 3378 type = Context.UnknownAnyTy; 3379 valueKind = VK_RValue; 3380 break; 3381 } 3382 3383 // Functions are l-values in C++. 3384 if (getLangOpts().CPlusPlus) { 3385 valueKind = VK_LValue; 3386 break; 3387 } 3388 3389 // C99 DR 316 says that, if a function type comes from a 3390 // function definition (without a prototype), that type is only 3391 // used for checking compatibility. Therefore, when referencing 3392 // the function, we pretend that we don't have the full function 3393 // type. 3394 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3395 isa<FunctionProtoType>(fty)) 3396 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3397 fty->getExtInfo()); 3398 3399 // Functions are r-values in C. 3400 valueKind = VK_RValue; 3401 break; 3402 } 3403 3404 case Decl::CXXDeductionGuide: 3405 llvm_unreachable("building reference to deduction guide"); 3406 3407 case Decl::MSProperty: 3408 case Decl::MSGuid: 3409 case Decl::TemplateParamObject: 3410 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3411 // capture in OpenMP, or duplicated between host and device? 3412 valueKind = VK_LValue; 3413 break; 3414 3415 case Decl::CXXMethod: 3416 // If we're referring to a method with an __unknown_anytype 3417 // result type, make the entire expression __unknown_anytype. 3418 // This should only be possible with a type written directly. 3419 if (const FunctionProtoType *proto 3420 = dyn_cast<FunctionProtoType>(VD->getType())) 3421 if (proto->getReturnType() == Context.UnknownAnyTy) { 3422 type = Context.UnknownAnyTy; 3423 valueKind = VK_RValue; 3424 break; 3425 } 3426 3427 // C++ methods are l-values if static, r-values if non-static. 3428 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3429 valueKind = VK_LValue; 3430 break; 3431 } 3432 LLVM_FALLTHROUGH; 3433 3434 case Decl::CXXConversion: 3435 case Decl::CXXDestructor: 3436 case Decl::CXXConstructor: 3437 valueKind = VK_RValue; 3438 break; 3439 } 3440 3441 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3442 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3443 TemplateArgs); 3444 } 3445 } 3446 3447 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3448 SmallString<32> &Target) { 3449 Target.resize(CharByteWidth * (Source.size() + 1)); 3450 char *ResultPtr = &Target[0]; 3451 const llvm::UTF8 *ErrorPtr; 3452 bool success = 3453 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3454 (void)success; 3455 assert(success); 3456 Target.resize(ResultPtr - &Target[0]); 3457 } 3458 3459 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3460 PredefinedExpr::IdentKind IK) { 3461 // Pick the current block, lambda, captured statement or function. 3462 Decl *currentDecl = nullptr; 3463 if (const BlockScopeInfo *BSI = getCurBlock()) 3464 currentDecl = BSI->TheDecl; 3465 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3466 currentDecl = LSI->CallOperator; 3467 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3468 currentDecl = CSI->TheCapturedDecl; 3469 else 3470 currentDecl = getCurFunctionOrMethodDecl(); 3471 3472 if (!currentDecl) { 3473 Diag(Loc, diag::ext_predef_outside_function); 3474 currentDecl = Context.getTranslationUnitDecl(); 3475 } 3476 3477 QualType ResTy; 3478 StringLiteral *SL = nullptr; 3479 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3480 ResTy = Context.DependentTy; 3481 else { 3482 // Pre-defined identifiers are of type char[x], where x is the length of 3483 // the string. 3484 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3485 unsigned Length = Str.length(); 3486 3487 llvm::APInt LengthI(32, Length + 1); 3488 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3489 ResTy = 3490 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3491 SmallString<32> RawChars; 3492 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3493 Str, RawChars); 3494 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3495 ArrayType::Normal, 3496 /*IndexTypeQuals*/ 0); 3497 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3498 /*Pascal*/ false, ResTy, Loc); 3499 } else { 3500 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3501 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3502 ArrayType::Normal, 3503 /*IndexTypeQuals*/ 0); 3504 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3505 /*Pascal*/ false, ResTy, Loc); 3506 } 3507 } 3508 3509 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3510 } 3511 3512 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3513 PredefinedExpr::IdentKind IK; 3514 3515 switch (Kind) { 3516 default: llvm_unreachable("Unknown simple primary expr!"); 3517 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3518 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3519 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3520 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3521 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3522 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3523 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3524 } 3525 3526 return BuildPredefinedExpr(Loc, IK); 3527 } 3528 3529 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3530 SmallString<16> CharBuffer; 3531 bool Invalid = false; 3532 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3533 if (Invalid) 3534 return ExprError(); 3535 3536 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3537 PP, Tok.getKind()); 3538 if (Literal.hadError()) 3539 return ExprError(); 3540 3541 QualType Ty; 3542 if (Literal.isWide()) 3543 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3544 else if (Literal.isUTF8() && getLangOpts().Char8) 3545 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3546 else if (Literal.isUTF16()) 3547 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3548 else if (Literal.isUTF32()) 3549 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3550 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3551 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3552 else 3553 Ty = Context.CharTy; // 'x' -> char in C++ 3554 3555 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3556 if (Literal.isWide()) 3557 Kind = CharacterLiteral::Wide; 3558 else if (Literal.isUTF16()) 3559 Kind = CharacterLiteral::UTF16; 3560 else if (Literal.isUTF32()) 3561 Kind = CharacterLiteral::UTF32; 3562 else if (Literal.isUTF8()) 3563 Kind = CharacterLiteral::UTF8; 3564 3565 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3566 Tok.getLocation()); 3567 3568 if (Literal.getUDSuffix().empty()) 3569 return Lit; 3570 3571 // We're building a user-defined literal. 3572 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3573 SourceLocation UDSuffixLoc = 3574 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3575 3576 // Make sure we're allowed user-defined literals here. 3577 if (!UDLScope) 3578 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3579 3580 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3581 // operator "" X (ch) 3582 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3583 Lit, Tok.getLocation()); 3584 } 3585 3586 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3587 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3588 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3589 Context.IntTy, Loc); 3590 } 3591 3592 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3593 QualType Ty, SourceLocation Loc) { 3594 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3595 3596 using llvm::APFloat; 3597 APFloat Val(Format); 3598 3599 APFloat::opStatus result = Literal.GetFloatValue(Val); 3600 3601 // Overflow is always an error, but underflow is only an error if 3602 // we underflowed to zero (APFloat reports denormals as underflow). 3603 if ((result & APFloat::opOverflow) || 3604 ((result & APFloat::opUnderflow) && Val.isZero())) { 3605 unsigned diagnostic; 3606 SmallString<20> buffer; 3607 if (result & APFloat::opOverflow) { 3608 diagnostic = diag::warn_float_overflow; 3609 APFloat::getLargest(Format).toString(buffer); 3610 } else { 3611 diagnostic = diag::warn_float_underflow; 3612 APFloat::getSmallest(Format).toString(buffer); 3613 } 3614 3615 S.Diag(Loc, diagnostic) 3616 << Ty 3617 << StringRef(buffer.data(), buffer.size()); 3618 } 3619 3620 bool isExact = (result == APFloat::opOK); 3621 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3622 } 3623 3624 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3625 assert(E && "Invalid expression"); 3626 3627 if (E->isValueDependent()) 3628 return false; 3629 3630 QualType QT = E->getType(); 3631 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3632 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3633 return true; 3634 } 3635 3636 llvm::APSInt ValueAPS; 3637 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3638 3639 if (R.isInvalid()) 3640 return true; 3641 3642 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3643 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3644 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3645 << ValueAPS.toString(10) << ValueIsPositive; 3646 return true; 3647 } 3648 3649 return false; 3650 } 3651 3652 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3653 // Fast path for a single digit (which is quite common). A single digit 3654 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3655 if (Tok.getLength() == 1) { 3656 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3657 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3658 } 3659 3660 SmallString<128> SpellingBuffer; 3661 // NumericLiteralParser wants to overread by one character. Add padding to 3662 // the buffer in case the token is copied to the buffer. If getSpelling() 3663 // returns a StringRef to the memory buffer, it should have a null char at 3664 // the EOF, so it is also safe. 3665 SpellingBuffer.resize(Tok.getLength() + 1); 3666 3667 // Get the spelling of the token, which eliminates trigraphs, etc. 3668 bool Invalid = false; 3669 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3670 if (Invalid) 3671 return ExprError(); 3672 3673 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3674 PP.getSourceManager(), PP.getLangOpts(), 3675 PP.getTargetInfo(), PP.getDiagnostics()); 3676 if (Literal.hadError) 3677 return ExprError(); 3678 3679 if (Literal.hasUDSuffix()) { 3680 // We're building a user-defined literal. 3681 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3682 SourceLocation UDSuffixLoc = 3683 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3684 3685 // Make sure we're allowed user-defined literals here. 3686 if (!UDLScope) 3687 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3688 3689 QualType CookedTy; 3690 if (Literal.isFloatingLiteral()) { 3691 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3692 // long double, the literal is treated as a call of the form 3693 // operator "" X (f L) 3694 CookedTy = Context.LongDoubleTy; 3695 } else { 3696 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3697 // unsigned long long, the literal is treated as a call of the form 3698 // operator "" X (n ULL) 3699 CookedTy = Context.UnsignedLongLongTy; 3700 } 3701 3702 DeclarationName OpName = 3703 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3704 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3705 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3706 3707 SourceLocation TokLoc = Tok.getLocation(); 3708 3709 // Perform literal operator lookup to determine if we're building a raw 3710 // literal or a cooked one. 3711 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3712 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3713 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3714 /*AllowStringTemplatePack*/ false, 3715 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3716 case LOLR_ErrorNoDiagnostic: 3717 // Lookup failure for imaginary constants isn't fatal, there's still the 3718 // GNU extension producing _Complex types. 3719 break; 3720 case LOLR_Error: 3721 return ExprError(); 3722 case LOLR_Cooked: { 3723 Expr *Lit; 3724 if (Literal.isFloatingLiteral()) { 3725 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3726 } else { 3727 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3728 if (Literal.GetIntegerValue(ResultVal)) 3729 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3730 << /* Unsigned */ 1; 3731 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3732 Tok.getLocation()); 3733 } 3734 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3735 } 3736 3737 case LOLR_Raw: { 3738 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3739 // literal is treated as a call of the form 3740 // operator "" X ("n") 3741 unsigned Length = Literal.getUDSuffixOffset(); 3742 QualType StrTy = Context.getConstantArrayType( 3743 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3744 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3745 Expr *Lit = StringLiteral::Create( 3746 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3747 /*Pascal*/false, StrTy, &TokLoc, 1); 3748 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3749 } 3750 3751 case LOLR_Template: { 3752 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3753 // template), L is treated as a call fo the form 3754 // operator "" X <'c1', 'c2', ... 'ck'>() 3755 // where n is the source character sequence c1 c2 ... ck. 3756 TemplateArgumentListInfo ExplicitArgs; 3757 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3758 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3759 llvm::APSInt Value(CharBits, CharIsUnsigned); 3760 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3761 Value = TokSpelling[I]; 3762 TemplateArgument Arg(Context, Value, Context.CharTy); 3763 TemplateArgumentLocInfo ArgInfo; 3764 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3765 } 3766 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3767 &ExplicitArgs); 3768 } 3769 case LOLR_StringTemplatePack: 3770 llvm_unreachable("unexpected literal operator lookup result"); 3771 } 3772 } 3773 3774 Expr *Res; 3775 3776 if (Literal.isFixedPointLiteral()) { 3777 QualType Ty; 3778 3779 if (Literal.isAccum) { 3780 if (Literal.isHalf) { 3781 Ty = Context.ShortAccumTy; 3782 } else if (Literal.isLong) { 3783 Ty = Context.LongAccumTy; 3784 } else { 3785 Ty = Context.AccumTy; 3786 } 3787 } else if (Literal.isFract) { 3788 if (Literal.isHalf) { 3789 Ty = Context.ShortFractTy; 3790 } else if (Literal.isLong) { 3791 Ty = Context.LongFractTy; 3792 } else { 3793 Ty = Context.FractTy; 3794 } 3795 } 3796 3797 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3798 3799 bool isSigned = !Literal.isUnsigned; 3800 unsigned scale = Context.getFixedPointScale(Ty); 3801 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3802 3803 llvm::APInt Val(bit_width, 0, isSigned); 3804 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3805 bool ValIsZero = Val.isNullValue() && !Overflowed; 3806 3807 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3808 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3809 // Clause 6.4.4 - The value of a constant shall be in the range of 3810 // representable values for its type, with exception for constants of a 3811 // fract type with a value of exactly 1; such a constant shall denote 3812 // the maximal value for the type. 3813 --Val; 3814 else if (Val.ugt(MaxVal) || Overflowed) 3815 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3816 3817 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3818 Tok.getLocation(), scale); 3819 } else if (Literal.isFloatingLiteral()) { 3820 QualType Ty; 3821 if (Literal.isHalf){ 3822 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3823 Ty = Context.HalfTy; 3824 else { 3825 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3826 return ExprError(); 3827 } 3828 } else if (Literal.isFloat) 3829 Ty = Context.FloatTy; 3830 else if (Literal.isLong) 3831 Ty = Context.LongDoubleTy; 3832 else if (Literal.isFloat16) 3833 Ty = Context.Float16Ty; 3834 else if (Literal.isFloat128) 3835 Ty = Context.Float128Ty; 3836 else 3837 Ty = Context.DoubleTy; 3838 3839 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3840 3841 if (Ty == Context.DoubleTy) { 3842 if (getLangOpts().SinglePrecisionConstants) { 3843 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3844 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3845 } 3846 } else if (getLangOpts().OpenCL && 3847 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3848 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3849 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3850 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3851 } 3852 } 3853 } else if (!Literal.isIntegerLiteral()) { 3854 return ExprError(); 3855 } else { 3856 QualType Ty; 3857 3858 // 'long long' is a C99 or C++11 feature. 3859 if (!getLangOpts().C99 && Literal.isLongLong) { 3860 if (getLangOpts().CPlusPlus) 3861 Diag(Tok.getLocation(), 3862 getLangOpts().CPlusPlus11 ? 3863 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3864 else 3865 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3866 } 3867 3868 // Get the value in the widest-possible width. 3869 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3870 llvm::APInt ResultVal(MaxWidth, 0); 3871 3872 if (Literal.GetIntegerValue(ResultVal)) { 3873 // If this value didn't fit into uintmax_t, error and force to ull. 3874 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3875 << /* Unsigned */ 1; 3876 Ty = Context.UnsignedLongLongTy; 3877 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3878 "long long is not intmax_t?"); 3879 } else { 3880 // If this value fits into a ULL, try to figure out what else it fits into 3881 // according to the rules of C99 6.4.4.1p5. 3882 3883 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3884 // be an unsigned int. 3885 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3886 3887 // Check from smallest to largest, picking the smallest type we can. 3888 unsigned Width = 0; 3889 3890 // Microsoft specific integer suffixes are explicitly sized. 3891 if (Literal.MicrosoftInteger) { 3892 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3893 Width = 8; 3894 Ty = Context.CharTy; 3895 } else { 3896 Width = Literal.MicrosoftInteger; 3897 Ty = Context.getIntTypeForBitwidth(Width, 3898 /*Signed=*/!Literal.isUnsigned); 3899 } 3900 } 3901 3902 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3903 // Are int/unsigned possibilities? 3904 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3905 3906 // Does it fit in a unsigned int? 3907 if (ResultVal.isIntN(IntSize)) { 3908 // Does it fit in a signed int? 3909 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3910 Ty = Context.IntTy; 3911 else if (AllowUnsigned) 3912 Ty = Context.UnsignedIntTy; 3913 Width = IntSize; 3914 } 3915 } 3916 3917 // Are long/unsigned long possibilities? 3918 if (Ty.isNull() && !Literal.isLongLong) { 3919 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3920 3921 // Does it fit in a unsigned long? 3922 if (ResultVal.isIntN(LongSize)) { 3923 // Does it fit in a signed long? 3924 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3925 Ty = Context.LongTy; 3926 else if (AllowUnsigned) 3927 Ty = Context.UnsignedLongTy; 3928 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3929 // is compatible. 3930 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3931 const unsigned LongLongSize = 3932 Context.getTargetInfo().getLongLongWidth(); 3933 Diag(Tok.getLocation(), 3934 getLangOpts().CPlusPlus 3935 ? Literal.isLong 3936 ? diag::warn_old_implicitly_unsigned_long_cxx 3937 : /*C++98 UB*/ diag:: 3938 ext_old_implicitly_unsigned_long_cxx 3939 : diag::warn_old_implicitly_unsigned_long) 3940 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3941 : /*will be ill-formed*/ 1); 3942 Ty = Context.UnsignedLongTy; 3943 } 3944 Width = LongSize; 3945 } 3946 } 3947 3948 // Check long long if needed. 3949 if (Ty.isNull()) { 3950 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3951 3952 // Does it fit in a unsigned long long? 3953 if (ResultVal.isIntN(LongLongSize)) { 3954 // Does it fit in a signed long long? 3955 // To be compatible with MSVC, hex integer literals ending with the 3956 // LL or i64 suffix are always signed in Microsoft mode. 3957 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3958 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3959 Ty = Context.LongLongTy; 3960 else if (AllowUnsigned) 3961 Ty = Context.UnsignedLongLongTy; 3962 Width = LongLongSize; 3963 } 3964 } 3965 3966 // If we still couldn't decide a type, we probably have something that 3967 // does not fit in a signed long long, but has no U suffix. 3968 if (Ty.isNull()) { 3969 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3970 Ty = Context.UnsignedLongLongTy; 3971 Width = Context.getTargetInfo().getLongLongWidth(); 3972 } 3973 3974 if (ResultVal.getBitWidth() != Width) 3975 ResultVal = ResultVal.trunc(Width); 3976 } 3977 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3978 } 3979 3980 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3981 if (Literal.isImaginary) { 3982 Res = new (Context) ImaginaryLiteral(Res, 3983 Context.getComplexType(Res->getType())); 3984 3985 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3986 } 3987 return Res; 3988 } 3989 3990 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3991 assert(E && "ActOnParenExpr() missing expr"); 3992 return new (Context) ParenExpr(L, R, E); 3993 } 3994 3995 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3996 SourceLocation Loc, 3997 SourceRange ArgRange) { 3998 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3999 // scalar or vector data type argument..." 4000 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4001 // type (C99 6.2.5p18) or void. 4002 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4003 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4004 << T << ArgRange; 4005 return true; 4006 } 4007 4008 assert((T->isVoidType() || !T->isIncompleteType()) && 4009 "Scalar types should always be complete"); 4010 return false; 4011 } 4012 4013 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4014 SourceLocation Loc, 4015 SourceRange ArgRange, 4016 UnaryExprOrTypeTrait TraitKind) { 4017 // Invalid types must be hard errors for SFINAE in C++. 4018 if (S.LangOpts.CPlusPlus) 4019 return true; 4020 4021 // C99 6.5.3.4p1: 4022 if (T->isFunctionType() && 4023 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4024 TraitKind == UETT_PreferredAlignOf)) { 4025 // sizeof(function)/alignof(function) is allowed as an extension. 4026 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4027 << getTraitSpelling(TraitKind) << ArgRange; 4028 return false; 4029 } 4030 4031 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4032 // this is an error (OpenCL v1.1 s6.3.k) 4033 if (T->isVoidType()) { 4034 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4035 : diag::ext_sizeof_alignof_void_type; 4036 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4037 return false; 4038 } 4039 4040 return true; 4041 } 4042 4043 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4044 SourceLocation Loc, 4045 SourceRange ArgRange, 4046 UnaryExprOrTypeTrait TraitKind) { 4047 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4048 // runtime doesn't allow it. 4049 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4050 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4051 << T << (TraitKind == UETT_SizeOf) 4052 << ArgRange; 4053 return true; 4054 } 4055 4056 return false; 4057 } 4058 4059 /// Check whether E is a pointer from a decayed array type (the decayed 4060 /// pointer type is equal to T) and emit a warning if it is. 4061 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4062 Expr *E) { 4063 // Don't warn if the operation changed the type. 4064 if (T != E->getType()) 4065 return; 4066 4067 // Now look for array decays. 4068 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4069 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4070 return; 4071 4072 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4073 << ICE->getType() 4074 << ICE->getSubExpr()->getType(); 4075 } 4076 4077 /// Check the constraints on expression operands to unary type expression 4078 /// and type traits. 4079 /// 4080 /// Completes any types necessary and validates the constraints on the operand 4081 /// expression. The logic mostly mirrors the type-based overload, but may modify 4082 /// the expression as it completes the type for that expression through template 4083 /// instantiation, etc. 4084 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4085 UnaryExprOrTypeTrait ExprKind) { 4086 QualType ExprTy = E->getType(); 4087 assert(!ExprTy->isReferenceType()); 4088 4089 bool IsUnevaluatedOperand = 4090 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4091 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4092 if (IsUnevaluatedOperand) { 4093 ExprResult Result = CheckUnevaluatedOperand(E); 4094 if (Result.isInvalid()) 4095 return true; 4096 E = Result.get(); 4097 } 4098 4099 // The operand for sizeof and alignof is in an unevaluated expression context, 4100 // so side effects could result in unintended consequences. 4101 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4102 // used to build SFINAE gadgets. 4103 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4104 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4105 !E->isInstantiationDependent() && 4106 E->HasSideEffects(Context, false)) 4107 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4108 4109 if (ExprKind == UETT_VecStep) 4110 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4111 E->getSourceRange()); 4112 4113 // Explicitly list some types as extensions. 4114 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4115 E->getSourceRange(), ExprKind)) 4116 return false; 4117 4118 // 'alignof' applied to an expression only requires the base element type of 4119 // the expression to be complete. 'sizeof' requires the expression's type to 4120 // be complete (and will attempt to complete it if it's an array of unknown 4121 // bound). 4122 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4123 if (RequireCompleteSizedType( 4124 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4125 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4126 getTraitSpelling(ExprKind), E->getSourceRange())) 4127 return true; 4128 } else { 4129 if (RequireCompleteSizedExprType( 4130 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4131 getTraitSpelling(ExprKind), E->getSourceRange())) 4132 return true; 4133 } 4134 4135 // Completing the expression's type may have changed it. 4136 ExprTy = E->getType(); 4137 assert(!ExprTy->isReferenceType()); 4138 4139 if (ExprTy->isFunctionType()) { 4140 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4141 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4142 return true; 4143 } 4144 4145 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4146 E->getSourceRange(), ExprKind)) 4147 return true; 4148 4149 if (ExprKind == UETT_SizeOf) { 4150 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4151 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4152 QualType OType = PVD->getOriginalType(); 4153 QualType Type = PVD->getType(); 4154 if (Type->isPointerType() && OType->isArrayType()) { 4155 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4156 << Type << OType; 4157 Diag(PVD->getLocation(), diag::note_declared_at); 4158 } 4159 } 4160 } 4161 4162 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4163 // decays into a pointer and returns an unintended result. This is most 4164 // likely a typo for "sizeof(array) op x". 4165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4166 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4167 BO->getLHS()); 4168 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4169 BO->getRHS()); 4170 } 4171 } 4172 4173 return false; 4174 } 4175 4176 /// Check the constraints on operands to unary expression and type 4177 /// traits. 4178 /// 4179 /// This will complete any types necessary, and validate the various constraints 4180 /// on those operands. 4181 /// 4182 /// The UsualUnaryConversions() function is *not* called by this routine. 4183 /// C99 6.3.2.1p[2-4] all state: 4184 /// Except when it is the operand of the sizeof operator ... 4185 /// 4186 /// C++ [expr.sizeof]p4 4187 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4188 /// standard conversions are not applied to the operand of sizeof. 4189 /// 4190 /// This policy is followed for all of the unary trait expressions. 4191 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4192 SourceLocation OpLoc, 4193 SourceRange ExprRange, 4194 UnaryExprOrTypeTrait ExprKind) { 4195 if (ExprType->isDependentType()) 4196 return false; 4197 4198 // C++ [expr.sizeof]p2: 4199 // When applied to a reference or a reference type, the result 4200 // is the size of the referenced type. 4201 // C++11 [expr.alignof]p3: 4202 // When alignof is applied to a reference type, the result 4203 // shall be the alignment of the referenced type. 4204 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4205 ExprType = Ref->getPointeeType(); 4206 4207 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4208 // When alignof or _Alignof is applied to an array type, the result 4209 // is the alignment of the element type. 4210 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4211 ExprKind == UETT_OpenMPRequiredSimdAlign) 4212 ExprType = Context.getBaseElementType(ExprType); 4213 4214 if (ExprKind == UETT_VecStep) 4215 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4216 4217 // Explicitly list some types as extensions. 4218 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4219 ExprKind)) 4220 return false; 4221 4222 if (RequireCompleteSizedType( 4223 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4224 getTraitSpelling(ExprKind), ExprRange)) 4225 return true; 4226 4227 if (ExprType->isFunctionType()) { 4228 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4229 << getTraitSpelling(ExprKind) << ExprRange; 4230 return true; 4231 } 4232 4233 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4234 ExprKind)) 4235 return true; 4236 4237 return false; 4238 } 4239 4240 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4241 // Cannot know anything else if the expression is dependent. 4242 if (E->isTypeDependent()) 4243 return false; 4244 4245 if (E->getObjectKind() == OK_BitField) { 4246 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4247 << 1 << E->getSourceRange(); 4248 return true; 4249 } 4250 4251 ValueDecl *D = nullptr; 4252 Expr *Inner = E->IgnoreParens(); 4253 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4254 D = DRE->getDecl(); 4255 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4256 D = ME->getMemberDecl(); 4257 } 4258 4259 // If it's a field, require the containing struct to have a 4260 // complete definition so that we can compute the layout. 4261 // 4262 // This can happen in C++11 onwards, either by naming the member 4263 // in a way that is not transformed into a member access expression 4264 // (in an unevaluated operand, for instance), or by naming the member 4265 // in a trailing-return-type. 4266 // 4267 // For the record, since __alignof__ on expressions is a GCC 4268 // extension, GCC seems to permit this but always gives the 4269 // nonsensical answer 0. 4270 // 4271 // We don't really need the layout here --- we could instead just 4272 // directly check for all the appropriate alignment-lowing 4273 // attributes --- but that would require duplicating a lot of 4274 // logic that just isn't worth duplicating for such a marginal 4275 // use-case. 4276 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4277 // Fast path this check, since we at least know the record has a 4278 // definition if we can find a member of it. 4279 if (!FD->getParent()->isCompleteDefinition()) { 4280 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4281 << E->getSourceRange(); 4282 return true; 4283 } 4284 4285 // Otherwise, if it's a field, and the field doesn't have 4286 // reference type, then it must have a complete type (or be a 4287 // flexible array member, which we explicitly want to 4288 // white-list anyway), which makes the following checks trivial. 4289 if (!FD->getType()->isReferenceType()) 4290 return false; 4291 } 4292 4293 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4294 } 4295 4296 bool Sema::CheckVecStepExpr(Expr *E) { 4297 E = E->IgnoreParens(); 4298 4299 // Cannot know anything else if the expression is dependent. 4300 if (E->isTypeDependent()) 4301 return false; 4302 4303 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4304 } 4305 4306 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4307 CapturingScopeInfo *CSI) { 4308 assert(T->isVariablyModifiedType()); 4309 assert(CSI != nullptr); 4310 4311 // We're going to walk down into the type and look for VLA expressions. 4312 do { 4313 const Type *Ty = T.getTypePtr(); 4314 switch (Ty->getTypeClass()) { 4315 #define TYPE(Class, Base) 4316 #define ABSTRACT_TYPE(Class, Base) 4317 #define NON_CANONICAL_TYPE(Class, Base) 4318 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4319 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4320 #include "clang/AST/TypeNodes.inc" 4321 T = QualType(); 4322 break; 4323 // These types are never variably-modified. 4324 case Type::Builtin: 4325 case Type::Complex: 4326 case Type::Vector: 4327 case Type::ExtVector: 4328 case Type::ConstantMatrix: 4329 case Type::Record: 4330 case Type::Enum: 4331 case Type::Elaborated: 4332 case Type::TemplateSpecialization: 4333 case Type::ObjCObject: 4334 case Type::ObjCInterface: 4335 case Type::ObjCObjectPointer: 4336 case Type::ObjCTypeParam: 4337 case Type::Pipe: 4338 case Type::ExtInt: 4339 llvm_unreachable("type class is never variably-modified!"); 4340 case Type::Adjusted: 4341 T = cast<AdjustedType>(Ty)->getOriginalType(); 4342 break; 4343 case Type::Decayed: 4344 T = cast<DecayedType>(Ty)->getPointeeType(); 4345 break; 4346 case Type::Pointer: 4347 T = cast<PointerType>(Ty)->getPointeeType(); 4348 break; 4349 case Type::BlockPointer: 4350 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4351 break; 4352 case Type::LValueReference: 4353 case Type::RValueReference: 4354 T = cast<ReferenceType>(Ty)->getPointeeType(); 4355 break; 4356 case Type::MemberPointer: 4357 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4358 break; 4359 case Type::ConstantArray: 4360 case Type::IncompleteArray: 4361 // Losing element qualification here is fine. 4362 T = cast<ArrayType>(Ty)->getElementType(); 4363 break; 4364 case Type::VariableArray: { 4365 // Losing element qualification here is fine. 4366 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4367 4368 // Unknown size indication requires no size computation. 4369 // Otherwise, evaluate and record it. 4370 auto Size = VAT->getSizeExpr(); 4371 if (Size && !CSI->isVLATypeCaptured(VAT) && 4372 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4373 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4374 4375 T = VAT->getElementType(); 4376 break; 4377 } 4378 case Type::FunctionProto: 4379 case Type::FunctionNoProto: 4380 T = cast<FunctionType>(Ty)->getReturnType(); 4381 break; 4382 case Type::Paren: 4383 case Type::TypeOf: 4384 case Type::UnaryTransform: 4385 case Type::Attributed: 4386 case Type::SubstTemplateTypeParm: 4387 case Type::MacroQualified: 4388 // Keep walking after single level desugaring. 4389 T = T.getSingleStepDesugaredType(Context); 4390 break; 4391 case Type::Typedef: 4392 T = cast<TypedefType>(Ty)->desugar(); 4393 break; 4394 case Type::Decltype: 4395 T = cast<DecltypeType>(Ty)->desugar(); 4396 break; 4397 case Type::Auto: 4398 case Type::DeducedTemplateSpecialization: 4399 T = cast<DeducedType>(Ty)->getDeducedType(); 4400 break; 4401 case Type::TypeOfExpr: 4402 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4403 break; 4404 case Type::Atomic: 4405 T = cast<AtomicType>(Ty)->getValueType(); 4406 break; 4407 } 4408 } while (!T.isNull() && T->isVariablyModifiedType()); 4409 } 4410 4411 /// Build a sizeof or alignof expression given a type operand. 4412 ExprResult 4413 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4414 SourceLocation OpLoc, 4415 UnaryExprOrTypeTrait ExprKind, 4416 SourceRange R) { 4417 if (!TInfo) 4418 return ExprError(); 4419 4420 QualType T = TInfo->getType(); 4421 4422 if (!T->isDependentType() && 4423 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4424 return ExprError(); 4425 4426 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4427 if (auto *TT = T->getAs<TypedefType>()) { 4428 for (auto I = FunctionScopes.rbegin(), 4429 E = std::prev(FunctionScopes.rend()); 4430 I != E; ++I) { 4431 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4432 if (CSI == nullptr) 4433 break; 4434 DeclContext *DC = nullptr; 4435 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4436 DC = LSI->CallOperator; 4437 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4438 DC = CRSI->TheCapturedDecl; 4439 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4440 DC = BSI->TheDecl; 4441 if (DC) { 4442 if (DC->containsDecl(TT->getDecl())) 4443 break; 4444 captureVariablyModifiedType(Context, T, CSI); 4445 } 4446 } 4447 } 4448 } 4449 4450 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4451 return new (Context) UnaryExprOrTypeTraitExpr( 4452 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4453 } 4454 4455 /// Build a sizeof or alignof expression given an expression 4456 /// operand. 4457 ExprResult 4458 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4459 UnaryExprOrTypeTrait ExprKind) { 4460 ExprResult PE = CheckPlaceholderExpr(E); 4461 if (PE.isInvalid()) 4462 return ExprError(); 4463 4464 E = PE.get(); 4465 4466 // Verify that the operand is valid. 4467 bool isInvalid = false; 4468 if (E->isTypeDependent()) { 4469 // Delay type-checking for type-dependent expressions. 4470 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4471 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4472 } else if (ExprKind == UETT_VecStep) { 4473 isInvalid = CheckVecStepExpr(E); 4474 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4475 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4476 isInvalid = true; 4477 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4478 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4479 isInvalid = true; 4480 } else { 4481 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4482 } 4483 4484 if (isInvalid) 4485 return ExprError(); 4486 4487 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4488 PE = TransformToPotentiallyEvaluated(E); 4489 if (PE.isInvalid()) return ExprError(); 4490 E = PE.get(); 4491 } 4492 4493 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4494 return new (Context) UnaryExprOrTypeTraitExpr( 4495 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4496 } 4497 4498 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4499 /// expr and the same for @c alignof and @c __alignof 4500 /// Note that the ArgRange is invalid if isType is false. 4501 ExprResult 4502 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4503 UnaryExprOrTypeTrait ExprKind, bool IsType, 4504 void *TyOrEx, SourceRange ArgRange) { 4505 // If error parsing type, ignore. 4506 if (!TyOrEx) return ExprError(); 4507 4508 if (IsType) { 4509 TypeSourceInfo *TInfo; 4510 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4511 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4512 } 4513 4514 Expr *ArgEx = (Expr *)TyOrEx; 4515 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4516 return Result; 4517 } 4518 4519 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4520 bool IsReal) { 4521 if (V.get()->isTypeDependent()) 4522 return S.Context.DependentTy; 4523 4524 // _Real and _Imag are only l-values for normal l-values. 4525 if (V.get()->getObjectKind() != OK_Ordinary) { 4526 V = S.DefaultLvalueConversion(V.get()); 4527 if (V.isInvalid()) 4528 return QualType(); 4529 } 4530 4531 // These operators return the element type of a complex type. 4532 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4533 return CT->getElementType(); 4534 4535 // Otherwise they pass through real integer and floating point types here. 4536 if (V.get()->getType()->isArithmeticType()) 4537 return V.get()->getType(); 4538 4539 // Test for placeholders. 4540 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4541 if (PR.isInvalid()) return QualType(); 4542 if (PR.get() != V.get()) { 4543 V = PR; 4544 return CheckRealImagOperand(S, V, Loc, IsReal); 4545 } 4546 4547 // Reject anything else. 4548 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4549 << (IsReal ? "__real" : "__imag"); 4550 return QualType(); 4551 } 4552 4553 4554 4555 ExprResult 4556 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4557 tok::TokenKind Kind, Expr *Input) { 4558 UnaryOperatorKind Opc; 4559 switch (Kind) { 4560 default: llvm_unreachable("Unknown unary op!"); 4561 case tok::plusplus: Opc = UO_PostInc; break; 4562 case tok::minusminus: Opc = UO_PostDec; break; 4563 } 4564 4565 // Since this might is a postfix expression, get rid of ParenListExprs. 4566 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4567 if (Result.isInvalid()) return ExprError(); 4568 Input = Result.get(); 4569 4570 return BuildUnaryOp(S, OpLoc, Opc, Input); 4571 } 4572 4573 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4574 /// 4575 /// \return true on error 4576 static bool checkArithmeticOnObjCPointer(Sema &S, 4577 SourceLocation opLoc, 4578 Expr *op) { 4579 assert(op->getType()->isObjCObjectPointerType()); 4580 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4581 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4582 return false; 4583 4584 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4585 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4586 << op->getSourceRange(); 4587 return true; 4588 } 4589 4590 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4591 auto *BaseNoParens = Base->IgnoreParens(); 4592 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4593 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4594 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4595 } 4596 4597 ExprResult 4598 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4599 Expr *idx, SourceLocation rbLoc) { 4600 if (base && !base->getType().isNull() && 4601 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4602 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4603 SourceLocation(), /*Length*/ nullptr, 4604 /*Stride=*/nullptr, rbLoc); 4605 4606 // Since this might be a postfix expression, get rid of ParenListExprs. 4607 if (isa<ParenListExpr>(base)) { 4608 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4609 if (result.isInvalid()) return ExprError(); 4610 base = result.get(); 4611 } 4612 4613 // Check if base and idx form a MatrixSubscriptExpr. 4614 // 4615 // Helper to check for comma expressions, which are not allowed as indices for 4616 // matrix subscript expressions. 4617 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4618 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4619 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4620 << SourceRange(base->getBeginLoc(), rbLoc); 4621 return true; 4622 } 4623 return false; 4624 }; 4625 // The matrix subscript operator ([][])is considered a single operator. 4626 // Separating the index expressions by parenthesis is not allowed. 4627 if (base->getType()->isSpecificPlaceholderType( 4628 BuiltinType::IncompleteMatrixIdx) && 4629 !isa<MatrixSubscriptExpr>(base)) { 4630 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4631 << SourceRange(base->getBeginLoc(), rbLoc); 4632 return ExprError(); 4633 } 4634 // If the base is a MatrixSubscriptExpr, try to create a new 4635 // MatrixSubscriptExpr. 4636 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4637 if (matSubscriptE) { 4638 if (CheckAndReportCommaError(idx)) 4639 return ExprError(); 4640 4641 assert(matSubscriptE->isIncomplete() && 4642 "base has to be an incomplete matrix subscript"); 4643 return CreateBuiltinMatrixSubscriptExpr( 4644 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4645 } 4646 4647 // Handle any non-overload placeholder types in the base and index 4648 // expressions. We can't handle overloads here because the other 4649 // operand might be an overloadable type, in which case the overload 4650 // resolution for the operator overload should get the first crack 4651 // at the overload. 4652 bool IsMSPropertySubscript = false; 4653 if (base->getType()->isNonOverloadPlaceholderType()) { 4654 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4655 if (!IsMSPropertySubscript) { 4656 ExprResult result = CheckPlaceholderExpr(base); 4657 if (result.isInvalid()) 4658 return ExprError(); 4659 base = result.get(); 4660 } 4661 } 4662 4663 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4664 if (base->getType()->isMatrixType()) { 4665 if (CheckAndReportCommaError(idx)) 4666 return ExprError(); 4667 4668 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4669 } 4670 4671 // A comma-expression as the index is deprecated in C++2a onwards. 4672 if (getLangOpts().CPlusPlus20 && 4673 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4674 (isa<CXXOperatorCallExpr>(idx) && 4675 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4676 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4677 << SourceRange(base->getBeginLoc(), rbLoc); 4678 } 4679 4680 if (idx->getType()->isNonOverloadPlaceholderType()) { 4681 ExprResult result = CheckPlaceholderExpr(idx); 4682 if (result.isInvalid()) return ExprError(); 4683 idx = result.get(); 4684 } 4685 4686 // Build an unanalyzed expression if either operand is type-dependent. 4687 if (getLangOpts().CPlusPlus && 4688 (base->isTypeDependent() || idx->isTypeDependent())) { 4689 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4690 VK_LValue, OK_Ordinary, rbLoc); 4691 } 4692 4693 // MSDN, property (C++) 4694 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4695 // This attribute can also be used in the declaration of an empty array in a 4696 // class or structure definition. For example: 4697 // __declspec(property(get=GetX, put=PutX)) int x[]; 4698 // The above statement indicates that x[] can be used with one or more array 4699 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4700 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4701 if (IsMSPropertySubscript) { 4702 // Build MS property subscript expression if base is MS property reference 4703 // or MS property subscript. 4704 return new (Context) MSPropertySubscriptExpr( 4705 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4706 } 4707 4708 // Use C++ overloaded-operator rules if either operand has record 4709 // type. The spec says to do this if either type is *overloadable*, 4710 // but enum types can't declare subscript operators or conversion 4711 // operators, so there's nothing interesting for overload resolution 4712 // to do if there aren't any record types involved. 4713 // 4714 // ObjC pointers have their own subscripting logic that is not tied 4715 // to overload resolution and so should not take this path. 4716 if (getLangOpts().CPlusPlus && 4717 (base->getType()->isRecordType() || 4718 (!base->getType()->isObjCObjectPointerType() && 4719 idx->getType()->isRecordType()))) { 4720 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4721 } 4722 4723 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4724 4725 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4726 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4727 4728 return Res; 4729 } 4730 4731 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4732 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4733 InitializationKind Kind = 4734 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4735 InitializationSequence InitSeq(*this, Entity, Kind, E); 4736 return InitSeq.Perform(*this, Entity, Kind, E); 4737 } 4738 4739 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4740 Expr *ColumnIdx, 4741 SourceLocation RBLoc) { 4742 ExprResult BaseR = CheckPlaceholderExpr(Base); 4743 if (BaseR.isInvalid()) 4744 return BaseR; 4745 Base = BaseR.get(); 4746 4747 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4748 if (RowR.isInvalid()) 4749 return RowR; 4750 RowIdx = RowR.get(); 4751 4752 if (!ColumnIdx) 4753 return new (Context) MatrixSubscriptExpr( 4754 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4755 4756 // Build an unanalyzed expression if any of the operands is type-dependent. 4757 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4758 ColumnIdx->isTypeDependent()) 4759 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4760 Context.DependentTy, RBLoc); 4761 4762 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4763 if (ColumnR.isInvalid()) 4764 return ColumnR; 4765 ColumnIdx = ColumnR.get(); 4766 4767 // Check that IndexExpr is an integer expression. If it is a constant 4768 // expression, check that it is less than Dim (= the number of elements in the 4769 // corresponding dimension). 4770 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4771 bool IsColumnIdx) -> Expr * { 4772 if (!IndexExpr->getType()->isIntegerType() && 4773 !IndexExpr->isTypeDependent()) { 4774 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4775 << IsColumnIdx; 4776 return nullptr; 4777 } 4778 4779 if (Optional<llvm::APSInt> Idx = 4780 IndexExpr->getIntegerConstantExpr(Context)) { 4781 if ((*Idx < 0 || *Idx >= Dim)) { 4782 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4783 << IsColumnIdx << Dim; 4784 return nullptr; 4785 } 4786 } 4787 4788 ExprResult ConvExpr = 4789 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4790 assert(!ConvExpr.isInvalid() && 4791 "should be able to convert any integer type to size type"); 4792 return ConvExpr.get(); 4793 }; 4794 4795 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4796 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4797 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4798 if (!RowIdx || !ColumnIdx) 4799 return ExprError(); 4800 4801 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4802 MTy->getElementType(), RBLoc); 4803 } 4804 4805 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4806 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4807 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4808 4809 // For expressions like `&(*s).b`, the base is recorded and what should be 4810 // checked. 4811 const MemberExpr *Member = nullptr; 4812 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4813 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4814 4815 LastRecord.PossibleDerefs.erase(StrippedExpr); 4816 } 4817 4818 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4819 if (isUnevaluatedContext()) 4820 return; 4821 4822 QualType ResultTy = E->getType(); 4823 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4824 4825 // Bail if the element is an array since it is not memory access. 4826 if (isa<ArrayType>(ResultTy)) 4827 return; 4828 4829 if (ResultTy->hasAttr(attr::NoDeref)) { 4830 LastRecord.PossibleDerefs.insert(E); 4831 return; 4832 } 4833 4834 // Check if the base type is a pointer to a member access of a struct 4835 // marked with noderef. 4836 const Expr *Base = E->getBase(); 4837 QualType BaseTy = Base->getType(); 4838 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4839 // Not a pointer access 4840 return; 4841 4842 const MemberExpr *Member = nullptr; 4843 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4844 Member->isArrow()) 4845 Base = Member->getBase(); 4846 4847 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4848 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4849 LastRecord.PossibleDerefs.insert(E); 4850 } 4851 } 4852 4853 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4854 Expr *LowerBound, 4855 SourceLocation ColonLocFirst, 4856 SourceLocation ColonLocSecond, 4857 Expr *Length, Expr *Stride, 4858 SourceLocation RBLoc) { 4859 if (Base->getType()->isPlaceholderType() && 4860 !Base->getType()->isSpecificPlaceholderType( 4861 BuiltinType::OMPArraySection)) { 4862 ExprResult Result = CheckPlaceholderExpr(Base); 4863 if (Result.isInvalid()) 4864 return ExprError(); 4865 Base = Result.get(); 4866 } 4867 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4868 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4869 if (Result.isInvalid()) 4870 return ExprError(); 4871 Result = DefaultLvalueConversion(Result.get()); 4872 if (Result.isInvalid()) 4873 return ExprError(); 4874 LowerBound = Result.get(); 4875 } 4876 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4877 ExprResult Result = CheckPlaceholderExpr(Length); 4878 if (Result.isInvalid()) 4879 return ExprError(); 4880 Result = DefaultLvalueConversion(Result.get()); 4881 if (Result.isInvalid()) 4882 return ExprError(); 4883 Length = Result.get(); 4884 } 4885 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4886 ExprResult Result = CheckPlaceholderExpr(Stride); 4887 if (Result.isInvalid()) 4888 return ExprError(); 4889 Result = DefaultLvalueConversion(Result.get()); 4890 if (Result.isInvalid()) 4891 return ExprError(); 4892 Stride = Result.get(); 4893 } 4894 4895 // Build an unanalyzed expression if either operand is type-dependent. 4896 if (Base->isTypeDependent() || 4897 (LowerBound && 4898 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4899 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4900 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4901 return new (Context) OMPArraySectionExpr( 4902 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4903 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4904 } 4905 4906 // Perform default conversions. 4907 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4908 QualType ResultTy; 4909 if (OriginalTy->isAnyPointerType()) { 4910 ResultTy = OriginalTy->getPointeeType(); 4911 } else if (OriginalTy->isArrayType()) { 4912 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4913 } else { 4914 return ExprError( 4915 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4916 << Base->getSourceRange()); 4917 } 4918 // C99 6.5.2.1p1 4919 if (LowerBound) { 4920 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4921 LowerBound); 4922 if (Res.isInvalid()) 4923 return ExprError(Diag(LowerBound->getExprLoc(), 4924 diag::err_omp_typecheck_section_not_integer) 4925 << 0 << LowerBound->getSourceRange()); 4926 LowerBound = Res.get(); 4927 4928 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4929 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4930 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4931 << 0 << LowerBound->getSourceRange(); 4932 } 4933 if (Length) { 4934 auto Res = 4935 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4936 if (Res.isInvalid()) 4937 return ExprError(Diag(Length->getExprLoc(), 4938 diag::err_omp_typecheck_section_not_integer) 4939 << 1 << Length->getSourceRange()); 4940 Length = Res.get(); 4941 4942 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4943 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4944 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4945 << 1 << Length->getSourceRange(); 4946 } 4947 if (Stride) { 4948 ExprResult Res = 4949 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4950 if (Res.isInvalid()) 4951 return ExprError(Diag(Stride->getExprLoc(), 4952 diag::err_omp_typecheck_section_not_integer) 4953 << 1 << Stride->getSourceRange()); 4954 Stride = Res.get(); 4955 4956 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4957 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4958 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4959 << 1 << Stride->getSourceRange(); 4960 } 4961 4962 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4963 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4964 // type. Note that functions are not objects, and that (in C99 parlance) 4965 // incomplete types are not object types. 4966 if (ResultTy->isFunctionType()) { 4967 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4968 << ResultTy << Base->getSourceRange(); 4969 return ExprError(); 4970 } 4971 4972 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4973 diag::err_omp_section_incomplete_type, Base)) 4974 return ExprError(); 4975 4976 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4977 Expr::EvalResult Result; 4978 if (LowerBound->EvaluateAsInt(Result, Context)) { 4979 // OpenMP 5.0, [2.1.5 Array Sections] 4980 // The array section must be a subset of the original array. 4981 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4982 if (LowerBoundValue.isNegative()) { 4983 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4984 << LowerBound->getSourceRange(); 4985 return ExprError(); 4986 } 4987 } 4988 } 4989 4990 if (Length) { 4991 Expr::EvalResult Result; 4992 if (Length->EvaluateAsInt(Result, Context)) { 4993 // OpenMP 5.0, [2.1.5 Array Sections] 4994 // The length must evaluate to non-negative integers. 4995 llvm::APSInt LengthValue = Result.Val.getInt(); 4996 if (LengthValue.isNegative()) { 4997 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4998 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4999 << Length->getSourceRange(); 5000 return ExprError(); 5001 } 5002 } 5003 } else if (ColonLocFirst.isValid() && 5004 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5005 !OriginalTy->isVariableArrayType()))) { 5006 // OpenMP 5.0, [2.1.5 Array Sections] 5007 // When the size of the array dimension is not known, the length must be 5008 // specified explicitly. 5009 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5010 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5011 return ExprError(); 5012 } 5013 5014 if (Stride) { 5015 Expr::EvalResult Result; 5016 if (Stride->EvaluateAsInt(Result, Context)) { 5017 // OpenMP 5.0, [2.1.5 Array Sections] 5018 // The stride must evaluate to a positive integer. 5019 llvm::APSInt StrideValue = Result.Val.getInt(); 5020 if (!StrideValue.isStrictlyPositive()) { 5021 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5022 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5023 << Stride->getSourceRange(); 5024 return ExprError(); 5025 } 5026 } 5027 } 5028 5029 if (!Base->getType()->isSpecificPlaceholderType( 5030 BuiltinType::OMPArraySection)) { 5031 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5032 if (Result.isInvalid()) 5033 return ExprError(); 5034 Base = Result.get(); 5035 } 5036 return new (Context) OMPArraySectionExpr( 5037 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5038 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5039 } 5040 5041 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5042 SourceLocation RParenLoc, 5043 ArrayRef<Expr *> Dims, 5044 ArrayRef<SourceRange> Brackets) { 5045 if (Base->getType()->isPlaceholderType()) { 5046 ExprResult Result = CheckPlaceholderExpr(Base); 5047 if (Result.isInvalid()) 5048 return ExprError(); 5049 Result = DefaultLvalueConversion(Result.get()); 5050 if (Result.isInvalid()) 5051 return ExprError(); 5052 Base = Result.get(); 5053 } 5054 QualType BaseTy = Base->getType(); 5055 // Delay analysis of the types/expressions if instantiation/specialization is 5056 // required. 5057 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5058 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5059 LParenLoc, RParenLoc, Dims, Brackets); 5060 if (!BaseTy->isPointerType() || 5061 (!Base->isTypeDependent() && 5062 BaseTy->getPointeeType()->isIncompleteType())) 5063 return ExprError(Diag(Base->getExprLoc(), 5064 diag::err_omp_non_pointer_type_array_shaping_base) 5065 << Base->getSourceRange()); 5066 5067 SmallVector<Expr *, 4> NewDims; 5068 bool ErrorFound = false; 5069 for (Expr *Dim : Dims) { 5070 if (Dim->getType()->isPlaceholderType()) { 5071 ExprResult Result = CheckPlaceholderExpr(Dim); 5072 if (Result.isInvalid()) { 5073 ErrorFound = true; 5074 continue; 5075 } 5076 Result = DefaultLvalueConversion(Result.get()); 5077 if (Result.isInvalid()) { 5078 ErrorFound = true; 5079 continue; 5080 } 5081 Dim = Result.get(); 5082 } 5083 if (!Dim->isTypeDependent()) { 5084 ExprResult Result = 5085 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5086 if (Result.isInvalid()) { 5087 ErrorFound = true; 5088 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5089 << Dim->getSourceRange(); 5090 continue; 5091 } 5092 Dim = Result.get(); 5093 Expr::EvalResult EvResult; 5094 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5095 // OpenMP 5.0, [2.1.4 Array Shaping] 5096 // Each si is an integral type expression that must evaluate to a 5097 // positive integer. 5098 llvm::APSInt Value = EvResult.Val.getInt(); 5099 if (!Value.isStrictlyPositive()) { 5100 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5101 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5102 << Dim->getSourceRange(); 5103 ErrorFound = true; 5104 continue; 5105 } 5106 } 5107 } 5108 NewDims.push_back(Dim); 5109 } 5110 if (ErrorFound) 5111 return ExprError(); 5112 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5113 LParenLoc, RParenLoc, NewDims, Brackets); 5114 } 5115 5116 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5117 SourceLocation LLoc, SourceLocation RLoc, 5118 ArrayRef<OMPIteratorData> Data) { 5119 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5120 bool IsCorrect = true; 5121 for (const OMPIteratorData &D : Data) { 5122 TypeSourceInfo *TInfo = nullptr; 5123 SourceLocation StartLoc; 5124 QualType DeclTy; 5125 if (!D.Type.getAsOpaquePtr()) { 5126 // OpenMP 5.0, 2.1.6 Iterators 5127 // In an iterator-specifier, if the iterator-type is not specified then 5128 // the type of that iterator is of int type. 5129 DeclTy = Context.IntTy; 5130 StartLoc = D.DeclIdentLoc; 5131 } else { 5132 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5133 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5134 } 5135 5136 bool IsDeclTyDependent = DeclTy->isDependentType() || 5137 DeclTy->containsUnexpandedParameterPack() || 5138 DeclTy->isInstantiationDependentType(); 5139 if (!IsDeclTyDependent) { 5140 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5141 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5142 // The iterator-type must be an integral or pointer type. 5143 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5144 << DeclTy; 5145 IsCorrect = false; 5146 continue; 5147 } 5148 if (DeclTy.isConstant(Context)) { 5149 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5150 // The iterator-type must not be const qualified. 5151 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5152 << DeclTy; 5153 IsCorrect = false; 5154 continue; 5155 } 5156 } 5157 5158 // Iterator declaration. 5159 assert(D.DeclIdent && "Identifier expected."); 5160 // Always try to create iterator declarator to avoid extra error messages 5161 // about unknown declarations use. 5162 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5163 D.DeclIdent, DeclTy, TInfo, SC_None); 5164 VD->setImplicit(); 5165 if (S) { 5166 // Check for conflicting previous declaration. 5167 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5168 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5169 ForVisibleRedeclaration); 5170 Previous.suppressDiagnostics(); 5171 LookupName(Previous, S); 5172 5173 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5174 /*AllowInlineNamespace=*/false); 5175 if (!Previous.empty()) { 5176 NamedDecl *Old = Previous.getRepresentativeDecl(); 5177 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5178 Diag(Old->getLocation(), diag::note_previous_definition); 5179 } else { 5180 PushOnScopeChains(VD, S); 5181 } 5182 } else { 5183 CurContext->addDecl(VD); 5184 } 5185 Expr *Begin = D.Range.Begin; 5186 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5187 ExprResult BeginRes = 5188 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5189 Begin = BeginRes.get(); 5190 } 5191 Expr *End = D.Range.End; 5192 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5193 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5194 End = EndRes.get(); 5195 } 5196 Expr *Step = D.Range.Step; 5197 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5198 if (!Step->getType()->isIntegralType(Context)) { 5199 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5200 << Step << Step->getSourceRange(); 5201 IsCorrect = false; 5202 continue; 5203 } 5204 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5205 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5206 // If the step expression of a range-specification equals zero, the 5207 // behavior is unspecified. 5208 if (Result && Result->isNullValue()) { 5209 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5210 << Step << Step->getSourceRange(); 5211 IsCorrect = false; 5212 continue; 5213 } 5214 } 5215 if (!Begin || !End || !IsCorrect) { 5216 IsCorrect = false; 5217 continue; 5218 } 5219 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5220 IDElem.IteratorDecl = VD; 5221 IDElem.AssignmentLoc = D.AssignLoc; 5222 IDElem.Range.Begin = Begin; 5223 IDElem.Range.End = End; 5224 IDElem.Range.Step = Step; 5225 IDElem.ColonLoc = D.ColonLoc; 5226 IDElem.SecondColonLoc = D.SecColonLoc; 5227 } 5228 if (!IsCorrect) { 5229 // Invalidate all created iterator declarations if error is found. 5230 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5231 if (Decl *ID = D.IteratorDecl) 5232 ID->setInvalidDecl(); 5233 } 5234 return ExprError(); 5235 } 5236 SmallVector<OMPIteratorHelperData, 4> Helpers; 5237 if (!CurContext->isDependentContext()) { 5238 // Build number of ityeration for each iteration range. 5239 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5240 // ((Begini-Stepi-1-Endi) / -Stepi); 5241 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5242 // (Endi - Begini) 5243 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5244 D.Range.Begin); 5245 if(!Res.isUsable()) { 5246 IsCorrect = false; 5247 continue; 5248 } 5249 ExprResult St, St1; 5250 if (D.Range.Step) { 5251 St = D.Range.Step; 5252 // (Endi - Begini) + Stepi 5253 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5254 if (!Res.isUsable()) { 5255 IsCorrect = false; 5256 continue; 5257 } 5258 // (Endi - Begini) + Stepi - 1 5259 Res = 5260 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5261 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5262 if (!Res.isUsable()) { 5263 IsCorrect = false; 5264 continue; 5265 } 5266 // ((Endi - Begini) + Stepi - 1) / Stepi 5267 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5268 if (!Res.isUsable()) { 5269 IsCorrect = false; 5270 continue; 5271 } 5272 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5273 // (Begini - Endi) 5274 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5275 D.Range.Begin, D.Range.End); 5276 if (!Res1.isUsable()) { 5277 IsCorrect = false; 5278 continue; 5279 } 5280 // (Begini - Endi) - Stepi 5281 Res1 = 5282 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5283 if (!Res1.isUsable()) { 5284 IsCorrect = false; 5285 continue; 5286 } 5287 // (Begini - Endi) - Stepi - 1 5288 Res1 = 5289 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5290 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5291 if (!Res1.isUsable()) { 5292 IsCorrect = false; 5293 continue; 5294 } 5295 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5296 Res1 = 5297 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5298 if (!Res1.isUsable()) { 5299 IsCorrect = false; 5300 continue; 5301 } 5302 // Stepi > 0. 5303 ExprResult CmpRes = 5304 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5305 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5306 if (!CmpRes.isUsable()) { 5307 IsCorrect = false; 5308 continue; 5309 } 5310 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5311 Res.get(), Res1.get()); 5312 if (!Res.isUsable()) { 5313 IsCorrect = false; 5314 continue; 5315 } 5316 } 5317 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5318 if (!Res.isUsable()) { 5319 IsCorrect = false; 5320 continue; 5321 } 5322 5323 // Build counter update. 5324 // Build counter. 5325 auto *CounterVD = 5326 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5327 D.IteratorDecl->getBeginLoc(), nullptr, 5328 Res.get()->getType(), nullptr, SC_None); 5329 CounterVD->setImplicit(); 5330 ExprResult RefRes = 5331 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5332 D.IteratorDecl->getBeginLoc()); 5333 // Build counter update. 5334 // I = Begini + counter * Stepi; 5335 ExprResult UpdateRes; 5336 if (D.Range.Step) { 5337 UpdateRes = CreateBuiltinBinOp( 5338 D.AssignmentLoc, BO_Mul, 5339 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5340 } else { 5341 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5342 } 5343 if (!UpdateRes.isUsable()) { 5344 IsCorrect = false; 5345 continue; 5346 } 5347 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5348 UpdateRes.get()); 5349 if (!UpdateRes.isUsable()) { 5350 IsCorrect = false; 5351 continue; 5352 } 5353 ExprResult VDRes = 5354 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5355 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5356 D.IteratorDecl->getBeginLoc()); 5357 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5358 UpdateRes.get()); 5359 if (!UpdateRes.isUsable()) { 5360 IsCorrect = false; 5361 continue; 5362 } 5363 UpdateRes = 5364 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5365 if (!UpdateRes.isUsable()) { 5366 IsCorrect = false; 5367 continue; 5368 } 5369 ExprResult CounterUpdateRes = 5370 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5371 if (!CounterUpdateRes.isUsable()) { 5372 IsCorrect = false; 5373 continue; 5374 } 5375 CounterUpdateRes = 5376 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5377 if (!CounterUpdateRes.isUsable()) { 5378 IsCorrect = false; 5379 continue; 5380 } 5381 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5382 HD.CounterVD = CounterVD; 5383 HD.Upper = Res.get(); 5384 HD.Update = UpdateRes.get(); 5385 HD.CounterUpdate = CounterUpdateRes.get(); 5386 } 5387 } else { 5388 Helpers.assign(ID.size(), {}); 5389 } 5390 if (!IsCorrect) { 5391 // Invalidate all created iterator declarations if error is found. 5392 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5393 if (Decl *ID = D.IteratorDecl) 5394 ID->setInvalidDecl(); 5395 } 5396 return ExprError(); 5397 } 5398 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5399 LLoc, RLoc, ID, Helpers); 5400 } 5401 5402 ExprResult 5403 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5404 Expr *Idx, SourceLocation RLoc) { 5405 Expr *LHSExp = Base; 5406 Expr *RHSExp = Idx; 5407 5408 ExprValueKind VK = VK_LValue; 5409 ExprObjectKind OK = OK_Ordinary; 5410 5411 // Per C++ core issue 1213, the result is an xvalue if either operand is 5412 // a non-lvalue array, and an lvalue otherwise. 5413 if (getLangOpts().CPlusPlus11) { 5414 for (auto *Op : {LHSExp, RHSExp}) { 5415 Op = Op->IgnoreImplicit(); 5416 if (Op->getType()->isArrayType() && !Op->isLValue()) 5417 VK = VK_XValue; 5418 } 5419 } 5420 5421 // Perform default conversions. 5422 if (!LHSExp->getType()->getAs<VectorType>()) { 5423 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5424 if (Result.isInvalid()) 5425 return ExprError(); 5426 LHSExp = Result.get(); 5427 } 5428 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5429 if (Result.isInvalid()) 5430 return ExprError(); 5431 RHSExp = Result.get(); 5432 5433 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5434 5435 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5436 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5437 // in the subscript position. As a result, we need to derive the array base 5438 // and index from the expression types. 5439 Expr *BaseExpr, *IndexExpr; 5440 QualType ResultType; 5441 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5442 BaseExpr = LHSExp; 5443 IndexExpr = RHSExp; 5444 ResultType = Context.DependentTy; 5445 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5446 BaseExpr = LHSExp; 5447 IndexExpr = RHSExp; 5448 ResultType = PTy->getPointeeType(); 5449 } else if (const ObjCObjectPointerType *PTy = 5450 LHSTy->getAs<ObjCObjectPointerType>()) { 5451 BaseExpr = LHSExp; 5452 IndexExpr = RHSExp; 5453 5454 // Use custom logic if this should be the pseudo-object subscript 5455 // expression. 5456 if (!LangOpts.isSubscriptPointerArithmetic()) 5457 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5458 nullptr); 5459 5460 ResultType = PTy->getPointeeType(); 5461 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5462 // Handle the uncommon case of "123[Ptr]". 5463 BaseExpr = RHSExp; 5464 IndexExpr = LHSExp; 5465 ResultType = PTy->getPointeeType(); 5466 } else if (const ObjCObjectPointerType *PTy = 5467 RHSTy->getAs<ObjCObjectPointerType>()) { 5468 // Handle the uncommon case of "123[Ptr]". 5469 BaseExpr = RHSExp; 5470 IndexExpr = LHSExp; 5471 ResultType = PTy->getPointeeType(); 5472 if (!LangOpts.isSubscriptPointerArithmetic()) { 5473 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5474 << ResultType << BaseExpr->getSourceRange(); 5475 return ExprError(); 5476 } 5477 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5478 BaseExpr = LHSExp; // vectors: V[123] 5479 IndexExpr = RHSExp; 5480 // We apply C++ DR1213 to vector subscripting too. 5481 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5482 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5483 if (Materialized.isInvalid()) 5484 return ExprError(); 5485 LHSExp = Materialized.get(); 5486 } 5487 VK = LHSExp->getValueKind(); 5488 if (VK != VK_RValue) 5489 OK = OK_VectorComponent; 5490 5491 ResultType = VTy->getElementType(); 5492 QualType BaseType = BaseExpr->getType(); 5493 Qualifiers BaseQuals = BaseType.getQualifiers(); 5494 Qualifiers MemberQuals = ResultType.getQualifiers(); 5495 Qualifiers Combined = BaseQuals + MemberQuals; 5496 if (Combined != MemberQuals) 5497 ResultType = Context.getQualifiedType(ResultType, Combined); 5498 } else if (LHSTy->isArrayType()) { 5499 // If we see an array that wasn't promoted by 5500 // DefaultFunctionArrayLvalueConversion, it must be an array that 5501 // wasn't promoted because of the C90 rule that doesn't 5502 // allow promoting non-lvalue arrays. Warn, then 5503 // force the promotion here. 5504 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5505 << LHSExp->getSourceRange(); 5506 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5507 CK_ArrayToPointerDecay).get(); 5508 LHSTy = LHSExp->getType(); 5509 5510 BaseExpr = LHSExp; 5511 IndexExpr = RHSExp; 5512 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5513 } else if (RHSTy->isArrayType()) { 5514 // Same as previous, except for 123[f().a] case 5515 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5516 << RHSExp->getSourceRange(); 5517 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5518 CK_ArrayToPointerDecay).get(); 5519 RHSTy = RHSExp->getType(); 5520 5521 BaseExpr = RHSExp; 5522 IndexExpr = LHSExp; 5523 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5524 } else { 5525 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5526 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5527 } 5528 // C99 6.5.2.1p1 5529 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5530 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5531 << IndexExpr->getSourceRange()); 5532 5533 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5534 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5535 && !IndexExpr->isTypeDependent()) 5536 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5537 5538 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5539 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5540 // type. Note that Functions are not objects, and that (in C99 parlance) 5541 // incomplete types are not object types. 5542 if (ResultType->isFunctionType()) { 5543 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5544 << ResultType << BaseExpr->getSourceRange(); 5545 return ExprError(); 5546 } 5547 5548 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5549 // GNU extension: subscripting on pointer to void 5550 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5551 << BaseExpr->getSourceRange(); 5552 5553 // C forbids expressions of unqualified void type from being l-values. 5554 // See IsCForbiddenLValueType. 5555 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5556 } else if (!ResultType->isDependentType() && 5557 RequireCompleteSizedType( 5558 LLoc, ResultType, 5559 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5560 return ExprError(); 5561 5562 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5563 !ResultType.isCForbiddenLValueType()); 5564 5565 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5566 FunctionScopes.size() > 1) { 5567 if (auto *TT = 5568 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5569 for (auto I = FunctionScopes.rbegin(), 5570 E = std::prev(FunctionScopes.rend()); 5571 I != E; ++I) { 5572 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5573 if (CSI == nullptr) 5574 break; 5575 DeclContext *DC = nullptr; 5576 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5577 DC = LSI->CallOperator; 5578 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5579 DC = CRSI->TheCapturedDecl; 5580 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5581 DC = BSI->TheDecl; 5582 if (DC) { 5583 if (DC->containsDecl(TT->getDecl())) 5584 break; 5585 captureVariablyModifiedType( 5586 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5587 } 5588 } 5589 } 5590 } 5591 5592 return new (Context) 5593 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5594 } 5595 5596 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5597 ParmVarDecl *Param) { 5598 if (Param->hasUnparsedDefaultArg()) { 5599 // If we've already cleared out the location for the default argument, 5600 // that means we're parsing it right now. 5601 if (!UnparsedDefaultArgLocs.count(Param)) { 5602 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5603 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5604 Param->setInvalidDecl(); 5605 return true; 5606 } 5607 5608 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5609 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5610 Diag(UnparsedDefaultArgLocs[Param], 5611 diag::note_default_argument_declared_here); 5612 return true; 5613 } 5614 5615 if (Param->hasUninstantiatedDefaultArg() && 5616 InstantiateDefaultArgument(CallLoc, FD, Param)) 5617 return true; 5618 5619 assert(Param->hasInit() && "default argument but no initializer?"); 5620 5621 // If the default expression creates temporaries, we need to 5622 // push them to the current stack of expression temporaries so they'll 5623 // be properly destroyed. 5624 // FIXME: We should really be rebuilding the default argument with new 5625 // bound temporaries; see the comment in PR5810. 5626 // We don't need to do that with block decls, though, because 5627 // blocks in default argument expression can never capture anything. 5628 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5629 // Set the "needs cleanups" bit regardless of whether there are 5630 // any explicit objects. 5631 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5632 5633 // Append all the objects to the cleanup list. Right now, this 5634 // should always be a no-op, because blocks in default argument 5635 // expressions should never be able to capture anything. 5636 assert(!Init->getNumObjects() && 5637 "default argument expression has capturing blocks?"); 5638 } 5639 5640 // We already type-checked the argument, so we know it works. 5641 // Just mark all of the declarations in this potentially-evaluated expression 5642 // as being "referenced". 5643 EnterExpressionEvaluationContext EvalContext( 5644 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5645 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5646 /*SkipLocalVariables=*/true); 5647 return false; 5648 } 5649 5650 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5651 FunctionDecl *FD, ParmVarDecl *Param) { 5652 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5653 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5654 return ExprError(); 5655 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5656 } 5657 5658 Sema::VariadicCallType 5659 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5660 Expr *Fn) { 5661 if (Proto && Proto->isVariadic()) { 5662 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5663 return VariadicConstructor; 5664 else if (Fn && Fn->getType()->isBlockPointerType()) 5665 return VariadicBlock; 5666 else if (FDecl) { 5667 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5668 if (Method->isInstance()) 5669 return VariadicMethod; 5670 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5671 return VariadicMethod; 5672 return VariadicFunction; 5673 } 5674 return VariadicDoesNotApply; 5675 } 5676 5677 namespace { 5678 class FunctionCallCCC final : public FunctionCallFilterCCC { 5679 public: 5680 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5681 unsigned NumArgs, MemberExpr *ME) 5682 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5683 FunctionName(FuncName) {} 5684 5685 bool ValidateCandidate(const TypoCorrection &candidate) override { 5686 if (!candidate.getCorrectionSpecifier() || 5687 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5688 return false; 5689 } 5690 5691 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5692 } 5693 5694 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5695 return std::make_unique<FunctionCallCCC>(*this); 5696 } 5697 5698 private: 5699 const IdentifierInfo *const FunctionName; 5700 }; 5701 } 5702 5703 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5704 FunctionDecl *FDecl, 5705 ArrayRef<Expr *> Args) { 5706 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5707 DeclarationName FuncName = FDecl->getDeclName(); 5708 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5709 5710 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5711 if (TypoCorrection Corrected = S.CorrectTypo( 5712 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5713 S.getScopeForContext(S.CurContext), nullptr, CCC, 5714 Sema::CTK_ErrorRecovery)) { 5715 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5716 if (Corrected.isOverloaded()) { 5717 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5718 OverloadCandidateSet::iterator Best; 5719 for (NamedDecl *CD : Corrected) { 5720 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5721 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5722 OCS); 5723 } 5724 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5725 case OR_Success: 5726 ND = Best->FoundDecl; 5727 Corrected.setCorrectionDecl(ND); 5728 break; 5729 default: 5730 break; 5731 } 5732 } 5733 ND = ND->getUnderlyingDecl(); 5734 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5735 return Corrected; 5736 } 5737 } 5738 return TypoCorrection(); 5739 } 5740 5741 /// ConvertArgumentsForCall - Converts the arguments specified in 5742 /// Args/NumArgs to the parameter types of the function FDecl with 5743 /// function prototype Proto. Call is the call expression itself, and 5744 /// Fn is the function expression. For a C++ member function, this 5745 /// routine does not attempt to convert the object argument. Returns 5746 /// true if the call is ill-formed. 5747 bool 5748 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5749 FunctionDecl *FDecl, 5750 const FunctionProtoType *Proto, 5751 ArrayRef<Expr *> Args, 5752 SourceLocation RParenLoc, 5753 bool IsExecConfig) { 5754 // Bail out early if calling a builtin with custom typechecking. 5755 if (FDecl) 5756 if (unsigned ID = FDecl->getBuiltinID()) 5757 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5758 return false; 5759 5760 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5761 // assignment, to the types of the corresponding parameter, ... 5762 unsigned NumParams = Proto->getNumParams(); 5763 bool Invalid = false; 5764 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5765 unsigned FnKind = Fn->getType()->isBlockPointerType() 5766 ? 1 /* block */ 5767 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5768 : 0 /* function */); 5769 5770 // If too few arguments are available (and we don't have default 5771 // arguments for the remaining parameters), don't make the call. 5772 if (Args.size() < NumParams) { 5773 if (Args.size() < MinArgs) { 5774 TypoCorrection TC; 5775 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5776 unsigned diag_id = 5777 MinArgs == NumParams && !Proto->isVariadic() 5778 ? diag::err_typecheck_call_too_few_args_suggest 5779 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5780 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5781 << static_cast<unsigned>(Args.size()) 5782 << TC.getCorrectionRange()); 5783 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5784 Diag(RParenLoc, 5785 MinArgs == NumParams && !Proto->isVariadic() 5786 ? diag::err_typecheck_call_too_few_args_one 5787 : diag::err_typecheck_call_too_few_args_at_least_one) 5788 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5789 else 5790 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5791 ? diag::err_typecheck_call_too_few_args 5792 : diag::err_typecheck_call_too_few_args_at_least) 5793 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5794 << Fn->getSourceRange(); 5795 5796 // Emit the location of the prototype. 5797 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5798 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5799 5800 return true; 5801 } 5802 // We reserve space for the default arguments when we create 5803 // the call expression, before calling ConvertArgumentsForCall. 5804 assert((Call->getNumArgs() == NumParams) && 5805 "We should have reserved space for the default arguments before!"); 5806 } 5807 5808 // If too many are passed and not variadic, error on the extras and drop 5809 // them. 5810 if (Args.size() > NumParams) { 5811 if (!Proto->isVariadic()) { 5812 TypoCorrection TC; 5813 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5814 unsigned diag_id = 5815 MinArgs == NumParams && !Proto->isVariadic() 5816 ? diag::err_typecheck_call_too_many_args_suggest 5817 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5818 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5819 << static_cast<unsigned>(Args.size()) 5820 << TC.getCorrectionRange()); 5821 } else if (NumParams == 1 && FDecl && 5822 FDecl->getParamDecl(0)->getDeclName()) 5823 Diag(Args[NumParams]->getBeginLoc(), 5824 MinArgs == NumParams 5825 ? diag::err_typecheck_call_too_many_args_one 5826 : diag::err_typecheck_call_too_many_args_at_most_one) 5827 << FnKind << FDecl->getParamDecl(0) 5828 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5829 << SourceRange(Args[NumParams]->getBeginLoc(), 5830 Args.back()->getEndLoc()); 5831 else 5832 Diag(Args[NumParams]->getBeginLoc(), 5833 MinArgs == NumParams 5834 ? diag::err_typecheck_call_too_many_args 5835 : diag::err_typecheck_call_too_many_args_at_most) 5836 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5837 << Fn->getSourceRange() 5838 << SourceRange(Args[NumParams]->getBeginLoc(), 5839 Args.back()->getEndLoc()); 5840 5841 // Emit the location of the prototype. 5842 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5843 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5844 5845 // This deletes the extra arguments. 5846 Call->shrinkNumArgs(NumParams); 5847 return true; 5848 } 5849 } 5850 SmallVector<Expr *, 8> AllArgs; 5851 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5852 5853 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5854 AllArgs, CallType); 5855 if (Invalid) 5856 return true; 5857 unsigned TotalNumArgs = AllArgs.size(); 5858 for (unsigned i = 0; i < TotalNumArgs; ++i) 5859 Call->setArg(i, AllArgs[i]); 5860 5861 return false; 5862 } 5863 5864 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5865 const FunctionProtoType *Proto, 5866 unsigned FirstParam, ArrayRef<Expr *> Args, 5867 SmallVectorImpl<Expr *> &AllArgs, 5868 VariadicCallType CallType, bool AllowExplicit, 5869 bool IsListInitialization) { 5870 unsigned NumParams = Proto->getNumParams(); 5871 bool Invalid = false; 5872 size_t ArgIx = 0; 5873 // Continue to check argument types (even if we have too few/many args). 5874 for (unsigned i = FirstParam; i < NumParams; i++) { 5875 QualType ProtoArgType = Proto->getParamType(i); 5876 5877 Expr *Arg; 5878 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5879 if (ArgIx < Args.size()) { 5880 Arg = Args[ArgIx++]; 5881 5882 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5883 diag::err_call_incomplete_argument, Arg)) 5884 return true; 5885 5886 // Strip the unbridged-cast placeholder expression off, if applicable. 5887 bool CFAudited = false; 5888 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5889 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5890 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5891 Arg = stripARCUnbridgedCast(Arg); 5892 else if (getLangOpts().ObjCAutoRefCount && 5893 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5894 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5895 CFAudited = true; 5896 5897 if (Proto->getExtParameterInfo(i).isNoEscape()) 5898 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5899 BE->getBlockDecl()->setDoesNotEscape(); 5900 5901 InitializedEntity Entity = 5902 Param ? InitializedEntity::InitializeParameter(Context, Param, 5903 ProtoArgType) 5904 : InitializedEntity::InitializeParameter( 5905 Context, ProtoArgType, Proto->isParamConsumed(i)); 5906 5907 // Remember that parameter belongs to a CF audited API. 5908 if (CFAudited) 5909 Entity.setParameterCFAudited(); 5910 5911 ExprResult ArgE = PerformCopyInitialization( 5912 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5913 if (ArgE.isInvalid()) 5914 return true; 5915 5916 Arg = ArgE.getAs<Expr>(); 5917 } else { 5918 assert(Param && "can't use default arguments without a known callee"); 5919 5920 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5921 if (ArgExpr.isInvalid()) 5922 return true; 5923 5924 Arg = ArgExpr.getAs<Expr>(); 5925 } 5926 5927 // Check for array bounds violations for each argument to the call. This 5928 // check only triggers warnings when the argument isn't a more complex Expr 5929 // with its own checking, such as a BinaryOperator. 5930 CheckArrayAccess(Arg); 5931 5932 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5933 CheckStaticArrayArgument(CallLoc, Param, Arg); 5934 5935 AllArgs.push_back(Arg); 5936 } 5937 5938 // If this is a variadic call, handle args passed through "...". 5939 if (CallType != VariadicDoesNotApply) { 5940 // Assume that extern "C" functions with variadic arguments that 5941 // return __unknown_anytype aren't *really* variadic. 5942 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5943 FDecl->isExternC()) { 5944 for (Expr *A : Args.slice(ArgIx)) { 5945 QualType paramType; // ignored 5946 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5947 Invalid |= arg.isInvalid(); 5948 AllArgs.push_back(arg.get()); 5949 } 5950 5951 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5952 } else { 5953 for (Expr *A : Args.slice(ArgIx)) { 5954 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5955 Invalid |= Arg.isInvalid(); 5956 AllArgs.push_back(Arg.get()); 5957 } 5958 } 5959 5960 // Check for array bounds violations. 5961 for (Expr *A : Args.slice(ArgIx)) 5962 CheckArrayAccess(A); 5963 } 5964 return Invalid; 5965 } 5966 5967 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5968 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5969 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5970 TL = DTL.getOriginalLoc(); 5971 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5972 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5973 << ATL.getLocalSourceRange(); 5974 } 5975 5976 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5977 /// array parameter, check that it is non-null, and that if it is formed by 5978 /// array-to-pointer decay, the underlying array is sufficiently large. 5979 /// 5980 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5981 /// array type derivation, then for each call to the function, the value of the 5982 /// corresponding actual argument shall provide access to the first element of 5983 /// an array with at least as many elements as specified by the size expression. 5984 void 5985 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5986 ParmVarDecl *Param, 5987 const Expr *ArgExpr) { 5988 // Static array parameters are not supported in C++. 5989 if (!Param || getLangOpts().CPlusPlus) 5990 return; 5991 5992 QualType OrigTy = Param->getOriginalType(); 5993 5994 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5995 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5996 return; 5997 5998 if (ArgExpr->isNullPointerConstant(Context, 5999 Expr::NPC_NeverValueDependent)) { 6000 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6001 DiagnoseCalleeStaticArrayParam(*this, Param); 6002 return; 6003 } 6004 6005 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6006 if (!CAT) 6007 return; 6008 6009 const ConstantArrayType *ArgCAT = 6010 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6011 if (!ArgCAT) 6012 return; 6013 6014 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6015 ArgCAT->getElementType())) { 6016 if (ArgCAT->getSize().ult(CAT->getSize())) { 6017 Diag(CallLoc, diag::warn_static_array_too_small) 6018 << ArgExpr->getSourceRange() 6019 << (unsigned)ArgCAT->getSize().getZExtValue() 6020 << (unsigned)CAT->getSize().getZExtValue() << 0; 6021 DiagnoseCalleeStaticArrayParam(*this, Param); 6022 } 6023 return; 6024 } 6025 6026 Optional<CharUnits> ArgSize = 6027 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6028 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6029 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6030 Diag(CallLoc, diag::warn_static_array_too_small) 6031 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6032 << (unsigned)ParmSize->getQuantity() << 1; 6033 DiagnoseCalleeStaticArrayParam(*this, Param); 6034 } 6035 } 6036 6037 /// Given a function expression of unknown-any type, try to rebuild it 6038 /// to have a function type. 6039 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6040 6041 /// Is the given type a placeholder that we need to lower out 6042 /// immediately during argument processing? 6043 static bool isPlaceholderToRemoveAsArg(QualType type) { 6044 // Placeholders are never sugared. 6045 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6046 if (!placeholder) return false; 6047 6048 switch (placeholder->getKind()) { 6049 // Ignore all the non-placeholder types. 6050 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6051 case BuiltinType::Id: 6052 #include "clang/Basic/OpenCLImageTypes.def" 6053 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6054 case BuiltinType::Id: 6055 #include "clang/Basic/OpenCLExtensionTypes.def" 6056 // In practice we'll never use this, since all SVE types are sugared 6057 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6058 #define SVE_TYPE(Name, Id, SingletonId) \ 6059 case BuiltinType::Id: 6060 #include "clang/Basic/AArch64SVEACLETypes.def" 6061 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6062 case BuiltinType::Id: 6063 #include "clang/Basic/PPCTypes.def" 6064 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6065 #include "clang/Basic/RISCVVTypes.def" 6066 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6067 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6068 #include "clang/AST/BuiltinTypes.def" 6069 return false; 6070 6071 // We cannot lower out overload sets; they might validly be resolved 6072 // by the call machinery. 6073 case BuiltinType::Overload: 6074 return false; 6075 6076 // Unbridged casts in ARC can be handled in some call positions and 6077 // should be left in place. 6078 case BuiltinType::ARCUnbridgedCast: 6079 return false; 6080 6081 // Pseudo-objects should be converted as soon as possible. 6082 case BuiltinType::PseudoObject: 6083 return true; 6084 6085 // The debugger mode could theoretically but currently does not try 6086 // to resolve unknown-typed arguments based on known parameter types. 6087 case BuiltinType::UnknownAny: 6088 return true; 6089 6090 // These are always invalid as call arguments and should be reported. 6091 case BuiltinType::BoundMember: 6092 case BuiltinType::BuiltinFn: 6093 case BuiltinType::IncompleteMatrixIdx: 6094 case BuiltinType::OMPArraySection: 6095 case BuiltinType::OMPArrayShaping: 6096 case BuiltinType::OMPIterator: 6097 return true; 6098 6099 } 6100 llvm_unreachable("bad builtin type kind"); 6101 } 6102 6103 /// Check an argument list for placeholders that we won't try to 6104 /// handle later. 6105 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6106 // Apply this processing to all the arguments at once instead of 6107 // dying at the first failure. 6108 bool hasInvalid = false; 6109 for (size_t i = 0, e = args.size(); i != e; i++) { 6110 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6111 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6112 if (result.isInvalid()) hasInvalid = true; 6113 else args[i] = result.get(); 6114 } 6115 } 6116 return hasInvalid; 6117 } 6118 6119 /// If a builtin function has a pointer argument with no explicit address 6120 /// space, then it should be able to accept a pointer to any address 6121 /// space as input. In order to do this, we need to replace the 6122 /// standard builtin declaration with one that uses the same address space 6123 /// as the call. 6124 /// 6125 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6126 /// it does not contain any pointer arguments without 6127 /// an address space qualifer. Otherwise the rewritten 6128 /// FunctionDecl is returned. 6129 /// TODO: Handle pointer return types. 6130 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6131 FunctionDecl *FDecl, 6132 MultiExprArg ArgExprs) { 6133 6134 QualType DeclType = FDecl->getType(); 6135 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6136 6137 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6138 ArgExprs.size() < FT->getNumParams()) 6139 return nullptr; 6140 6141 bool NeedsNewDecl = false; 6142 unsigned i = 0; 6143 SmallVector<QualType, 8> OverloadParams; 6144 6145 for (QualType ParamType : FT->param_types()) { 6146 6147 // Convert array arguments to pointer to simplify type lookup. 6148 ExprResult ArgRes = 6149 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6150 if (ArgRes.isInvalid()) 6151 return nullptr; 6152 Expr *Arg = ArgRes.get(); 6153 QualType ArgType = Arg->getType(); 6154 if (!ParamType->isPointerType() || 6155 ParamType.hasAddressSpace() || 6156 !ArgType->isPointerType() || 6157 !ArgType->getPointeeType().hasAddressSpace()) { 6158 OverloadParams.push_back(ParamType); 6159 continue; 6160 } 6161 6162 QualType PointeeType = ParamType->getPointeeType(); 6163 if (PointeeType.hasAddressSpace()) 6164 continue; 6165 6166 NeedsNewDecl = true; 6167 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6168 6169 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6170 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6171 } 6172 6173 if (!NeedsNewDecl) 6174 return nullptr; 6175 6176 FunctionProtoType::ExtProtoInfo EPI; 6177 EPI.Variadic = FT->isVariadic(); 6178 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6179 OverloadParams, EPI); 6180 DeclContext *Parent = FDecl->getParent(); 6181 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6182 FDecl->getLocation(), 6183 FDecl->getLocation(), 6184 FDecl->getIdentifier(), 6185 OverloadTy, 6186 /*TInfo=*/nullptr, 6187 SC_Extern, false, 6188 /*hasPrototype=*/true); 6189 SmallVector<ParmVarDecl*, 16> Params; 6190 FT = cast<FunctionProtoType>(OverloadTy); 6191 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6192 QualType ParamType = FT->getParamType(i); 6193 ParmVarDecl *Parm = 6194 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6195 SourceLocation(), nullptr, ParamType, 6196 /*TInfo=*/nullptr, SC_None, nullptr); 6197 Parm->setScopeInfo(0, i); 6198 Params.push_back(Parm); 6199 } 6200 OverloadDecl->setParams(Params); 6201 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6202 return OverloadDecl; 6203 } 6204 6205 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6206 FunctionDecl *Callee, 6207 MultiExprArg ArgExprs) { 6208 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6209 // similar attributes) really don't like it when functions are called with an 6210 // invalid number of args. 6211 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6212 /*PartialOverloading=*/false) && 6213 !Callee->isVariadic()) 6214 return; 6215 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6216 return; 6217 6218 if (const EnableIfAttr *Attr = 6219 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6220 S.Diag(Fn->getBeginLoc(), 6221 isa<CXXMethodDecl>(Callee) 6222 ? diag::err_ovl_no_viable_member_function_in_call 6223 : diag::err_ovl_no_viable_function_in_call) 6224 << Callee << Callee->getSourceRange(); 6225 S.Diag(Callee->getLocation(), 6226 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6227 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6228 return; 6229 } 6230 } 6231 6232 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6233 const UnresolvedMemberExpr *const UME, Sema &S) { 6234 6235 const auto GetFunctionLevelDCIfCXXClass = 6236 [](Sema &S) -> const CXXRecordDecl * { 6237 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6238 if (!DC || !DC->getParent()) 6239 return nullptr; 6240 6241 // If the call to some member function was made from within a member 6242 // function body 'M' return return 'M's parent. 6243 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6244 return MD->getParent()->getCanonicalDecl(); 6245 // else the call was made from within a default member initializer of a 6246 // class, so return the class. 6247 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6248 return RD->getCanonicalDecl(); 6249 return nullptr; 6250 }; 6251 // If our DeclContext is neither a member function nor a class (in the 6252 // case of a lambda in a default member initializer), we can't have an 6253 // enclosing 'this'. 6254 6255 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6256 if (!CurParentClass) 6257 return false; 6258 6259 // The naming class for implicit member functions call is the class in which 6260 // name lookup starts. 6261 const CXXRecordDecl *const NamingClass = 6262 UME->getNamingClass()->getCanonicalDecl(); 6263 assert(NamingClass && "Must have naming class even for implicit access"); 6264 6265 // If the unresolved member functions were found in a 'naming class' that is 6266 // related (either the same or derived from) to the class that contains the 6267 // member function that itself contained the implicit member access. 6268 6269 return CurParentClass == NamingClass || 6270 CurParentClass->isDerivedFrom(NamingClass); 6271 } 6272 6273 static void 6274 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6275 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6276 6277 if (!UME) 6278 return; 6279 6280 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6281 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6282 // already been captured, or if this is an implicit member function call (if 6283 // it isn't, an attempt to capture 'this' should already have been made). 6284 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6285 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6286 return; 6287 6288 // Check if the naming class in which the unresolved members were found is 6289 // related (same as or is a base of) to the enclosing class. 6290 6291 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6292 return; 6293 6294 6295 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6296 // If the enclosing function is not dependent, then this lambda is 6297 // capture ready, so if we can capture this, do so. 6298 if (!EnclosingFunctionCtx->isDependentContext()) { 6299 // If the current lambda and all enclosing lambdas can capture 'this' - 6300 // then go ahead and capture 'this' (since our unresolved overload set 6301 // contains at least one non-static member function). 6302 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6303 S.CheckCXXThisCapture(CallLoc); 6304 } else if (S.CurContext->isDependentContext()) { 6305 // ... since this is an implicit member reference, that might potentially 6306 // involve a 'this' capture, mark 'this' for potential capture in 6307 // enclosing lambdas. 6308 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6309 CurLSI->addPotentialThisCapture(CallLoc); 6310 } 6311 } 6312 6313 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6314 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6315 Expr *ExecConfig) { 6316 ExprResult Call = 6317 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6318 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6319 if (Call.isInvalid()) 6320 return Call; 6321 6322 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6323 // language modes. 6324 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6325 if (ULE->hasExplicitTemplateArgs() && 6326 ULE->decls_begin() == ULE->decls_end()) { 6327 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6328 ? diag::warn_cxx17_compat_adl_only_template_id 6329 : diag::ext_adl_only_template_id) 6330 << ULE->getName(); 6331 } 6332 } 6333 6334 if (LangOpts.OpenMP) 6335 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6336 ExecConfig); 6337 6338 return Call; 6339 } 6340 6341 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6342 /// This provides the location of the left/right parens and a list of comma 6343 /// locations. 6344 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6345 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6346 Expr *ExecConfig, bool IsExecConfig, 6347 bool AllowRecovery) { 6348 // Since this might be a postfix expression, get rid of ParenListExprs. 6349 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6350 if (Result.isInvalid()) return ExprError(); 6351 Fn = Result.get(); 6352 6353 if (checkArgsForPlaceholders(*this, ArgExprs)) 6354 return ExprError(); 6355 6356 if (getLangOpts().CPlusPlus) { 6357 // If this is a pseudo-destructor expression, build the call immediately. 6358 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6359 if (!ArgExprs.empty()) { 6360 // Pseudo-destructor calls should not have any arguments. 6361 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6362 << FixItHint::CreateRemoval( 6363 SourceRange(ArgExprs.front()->getBeginLoc(), 6364 ArgExprs.back()->getEndLoc())); 6365 } 6366 6367 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6368 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6369 } 6370 if (Fn->getType() == Context.PseudoObjectTy) { 6371 ExprResult result = CheckPlaceholderExpr(Fn); 6372 if (result.isInvalid()) return ExprError(); 6373 Fn = result.get(); 6374 } 6375 6376 // Determine whether this is a dependent call inside a C++ template, 6377 // in which case we won't do any semantic analysis now. 6378 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6379 if (ExecConfig) { 6380 return CUDAKernelCallExpr::Create( 6381 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6382 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6383 } else { 6384 6385 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6386 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6387 Fn->getBeginLoc()); 6388 6389 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6390 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6391 } 6392 } 6393 6394 // Determine whether this is a call to an object (C++ [over.call.object]). 6395 if (Fn->getType()->isRecordType()) 6396 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6397 RParenLoc); 6398 6399 if (Fn->getType() == Context.UnknownAnyTy) { 6400 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6401 if (result.isInvalid()) return ExprError(); 6402 Fn = result.get(); 6403 } 6404 6405 if (Fn->getType() == Context.BoundMemberTy) { 6406 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6407 RParenLoc, AllowRecovery); 6408 } 6409 } 6410 6411 // Check for overloaded calls. This can happen even in C due to extensions. 6412 if (Fn->getType() == Context.OverloadTy) { 6413 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6414 6415 // We aren't supposed to apply this logic if there's an '&' involved. 6416 if (!find.HasFormOfMemberPointer) { 6417 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6418 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6419 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6420 OverloadExpr *ovl = find.Expression; 6421 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6422 return BuildOverloadedCallExpr( 6423 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6424 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6425 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6426 RParenLoc, AllowRecovery); 6427 } 6428 } 6429 6430 // If we're directly calling a function, get the appropriate declaration. 6431 if (Fn->getType() == Context.UnknownAnyTy) { 6432 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6433 if (result.isInvalid()) return ExprError(); 6434 Fn = result.get(); 6435 } 6436 6437 Expr *NakedFn = Fn->IgnoreParens(); 6438 6439 bool CallingNDeclIndirectly = false; 6440 NamedDecl *NDecl = nullptr; 6441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6442 if (UnOp->getOpcode() == UO_AddrOf) { 6443 CallingNDeclIndirectly = true; 6444 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6445 } 6446 } 6447 6448 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6449 NDecl = DRE->getDecl(); 6450 6451 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6452 if (FDecl && FDecl->getBuiltinID()) { 6453 // Rewrite the function decl for this builtin by replacing parameters 6454 // with no explicit address space with the address space of the arguments 6455 // in ArgExprs. 6456 if ((FDecl = 6457 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6458 NDecl = FDecl; 6459 Fn = DeclRefExpr::Create( 6460 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6461 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6462 nullptr, DRE->isNonOdrUse()); 6463 } 6464 } 6465 } else if (isa<MemberExpr>(NakedFn)) 6466 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6467 6468 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6469 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6470 FD, /*Complain=*/true, Fn->getBeginLoc())) 6471 return ExprError(); 6472 6473 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6474 return ExprError(); 6475 6476 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6477 } 6478 6479 if (Context.isDependenceAllowed() && 6480 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6481 assert(!getLangOpts().CPlusPlus); 6482 assert((Fn->containsErrors() || 6483 llvm::any_of(ArgExprs, 6484 [](clang::Expr *E) { return E->containsErrors(); })) && 6485 "should only occur in error-recovery path."); 6486 QualType ReturnType = 6487 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6488 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6489 : Context.DependentTy; 6490 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6491 Expr::getValueKindForType(ReturnType), RParenLoc, 6492 CurFPFeatureOverrides()); 6493 } 6494 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6495 ExecConfig, IsExecConfig); 6496 } 6497 6498 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6499 /// 6500 /// __builtin_astype( value, dst type ) 6501 /// 6502 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6503 SourceLocation BuiltinLoc, 6504 SourceLocation RParenLoc) { 6505 ExprValueKind VK = VK_RValue; 6506 ExprObjectKind OK = OK_Ordinary; 6507 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6508 QualType SrcTy = E->getType(); 6509 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6510 return ExprError(Diag(BuiltinLoc, 6511 diag::err_invalid_astype_of_different_size) 6512 << DstTy 6513 << SrcTy 6514 << E->getSourceRange()); 6515 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6516 } 6517 6518 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6519 /// provided arguments. 6520 /// 6521 /// __builtin_convertvector( value, dst type ) 6522 /// 6523 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6524 SourceLocation BuiltinLoc, 6525 SourceLocation RParenLoc) { 6526 TypeSourceInfo *TInfo; 6527 GetTypeFromParser(ParsedDestTy, &TInfo); 6528 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6529 } 6530 6531 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6532 /// i.e. an expression not of \p OverloadTy. The expression should 6533 /// unary-convert to an expression of function-pointer or 6534 /// block-pointer type. 6535 /// 6536 /// \param NDecl the declaration being called, if available 6537 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6538 SourceLocation LParenLoc, 6539 ArrayRef<Expr *> Args, 6540 SourceLocation RParenLoc, Expr *Config, 6541 bool IsExecConfig, ADLCallKind UsesADL) { 6542 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6543 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6544 6545 // Functions with 'interrupt' attribute cannot be called directly. 6546 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6547 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6548 return ExprError(); 6549 } 6550 6551 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6552 // so there's some risk when calling out to non-interrupt handler functions 6553 // that the callee might not preserve them. This is easy to diagnose here, 6554 // but can be very challenging to debug. 6555 if (auto *Caller = getCurFunctionDecl()) 6556 if (Caller->hasAttr<ARMInterruptAttr>()) { 6557 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6558 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6559 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6560 } 6561 6562 // Promote the function operand. 6563 // We special-case function promotion here because we only allow promoting 6564 // builtin functions to function pointers in the callee of a call. 6565 ExprResult Result; 6566 QualType ResultTy; 6567 if (BuiltinID && 6568 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6569 // Extract the return type from the (builtin) function pointer type. 6570 // FIXME Several builtins still have setType in 6571 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6572 // Builtins.def to ensure they are correct before removing setType calls. 6573 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6574 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6575 ResultTy = FDecl->getCallResultType(); 6576 } else { 6577 Result = CallExprUnaryConversions(Fn); 6578 ResultTy = Context.BoolTy; 6579 } 6580 if (Result.isInvalid()) 6581 return ExprError(); 6582 Fn = Result.get(); 6583 6584 // Check for a valid function type, but only if it is not a builtin which 6585 // requires custom type checking. These will be handled by 6586 // CheckBuiltinFunctionCall below just after creation of the call expression. 6587 const FunctionType *FuncT = nullptr; 6588 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6589 retry: 6590 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6591 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6592 // have type pointer to function". 6593 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6594 if (!FuncT) 6595 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6596 << Fn->getType() << Fn->getSourceRange()); 6597 } else if (const BlockPointerType *BPT = 6598 Fn->getType()->getAs<BlockPointerType>()) { 6599 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6600 } else { 6601 // Handle calls to expressions of unknown-any type. 6602 if (Fn->getType() == Context.UnknownAnyTy) { 6603 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6604 if (rewrite.isInvalid()) 6605 return ExprError(); 6606 Fn = rewrite.get(); 6607 goto retry; 6608 } 6609 6610 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6611 << Fn->getType() << Fn->getSourceRange()); 6612 } 6613 } 6614 6615 // Get the number of parameters in the function prototype, if any. 6616 // We will allocate space for max(Args.size(), NumParams) arguments 6617 // in the call expression. 6618 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6619 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6620 6621 CallExpr *TheCall; 6622 if (Config) { 6623 assert(UsesADL == ADLCallKind::NotADL && 6624 "CUDAKernelCallExpr should not use ADL"); 6625 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6626 Args, ResultTy, VK_RValue, RParenLoc, 6627 CurFPFeatureOverrides(), NumParams); 6628 } else { 6629 TheCall = 6630 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6631 CurFPFeatureOverrides(), NumParams, UsesADL); 6632 } 6633 6634 if (!Context.isDependenceAllowed()) { 6635 // Forget about the nulled arguments since typo correction 6636 // do not handle them well. 6637 TheCall->shrinkNumArgs(Args.size()); 6638 // C cannot always handle TypoExpr nodes in builtin calls and direct 6639 // function calls as their argument checking don't necessarily handle 6640 // dependent types properly, so make sure any TypoExprs have been 6641 // dealt with. 6642 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6643 if (!Result.isUsable()) return ExprError(); 6644 CallExpr *TheOldCall = TheCall; 6645 TheCall = dyn_cast<CallExpr>(Result.get()); 6646 bool CorrectedTypos = TheCall != TheOldCall; 6647 if (!TheCall) return Result; 6648 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6649 6650 // A new call expression node was created if some typos were corrected. 6651 // However it may not have been constructed with enough storage. In this 6652 // case, rebuild the node with enough storage. The waste of space is 6653 // immaterial since this only happens when some typos were corrected. 6654 if (CorrectedTypos && Args.size() < NumParams) { 6655 if (Config) 6656 TheCall = CUDAKernelCallExpr::Create( 6657 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6658 RParenLoc, CurFPFeatureOverrides(), NumParams); 6659 else 6660 TheCall = 6661 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6662 CurFPFeatureOverrides(), NumParams, UsesADL); 6663 } 6664 // We can now handle the nulled arguments for the default arguments. 6665 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6666 } 6667 6668 // Bail out early if calling a builtin with custom type checking. 6669 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6670 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6671 6672 if (getLangOpts().CUDA) { 6673 if (Config) { 6674 // CUDA: Kernel calls must be to global functions 6675 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6676 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6677 << FDecl << Fn->getSourceRange()); 6678 6679 // CUDA: Kernel function must have 'void' return type 6680 if (!FuncT->getReturnType()->isVoidType() && 6681 !FuncT->getReturnType()->getAs<AutoType>() && 6682 !FuncT->getReturnType()->isInstantiationDependentType()) 6683 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6684 << Fn->getType() << Fn->getSourceRange()); 6685 } else { 6686 // CUDA: Calls to global functions must be configured 6687 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6688 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6689 << FDecl << Fn->getSourceRange()); 6690 } 6691 } 6692 6693 // Check for a valid return type 6694 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6695 FDecl)) 6696 return ExprError(); 6697 6698 // We know the result type of the call, set it. 6699 TheCall->setType(FuncT->getCallResultType(Context)); 6700 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6701 6702 if (Proto) { 6703 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6704 IsExecConfig)) 6705 return ExprError(); 6706 } else { 6707 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6708 6709 if (FDecl) { 6710 // Check if we have too few/too many template arguments, based 6711 // on our knowledge of the function definition. 6712 const FunctionDecl *Def = nullptr; 6713 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6714 Proto = Def->getType()->getAs<FunctionProtoType>(); 6715 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6716 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6717 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6718 } 6719 6720 // If the function we're calling isn't a function prototype, but we have 6721 // a function prototype from a prior declaratiom, use that prototype. 6722 if (!FDecl->hasPrototype()) 6723 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6724 } 6725 6726 // Promote the arguments (C99 6.5.2.2p6). 6727 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6728 Expr *Arg = Args[i]; 6729 6730 if (Proto && i < Proto->getNumParams()) { 6731 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6732 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6733 ExprResult ArgE = 6734 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6735 if (ArgE.isInvalid()) 6736 return true; 6737 6738 Arg = ArgE.getAs<Expr>(); 6739 6740 } else { 6741 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6742 6743 if (ArgE.isInvalid()) 6744 return true; 6745 6746 Arg = ArgE.getAs<Expr>(); 6747 } 6748 6749 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6750 diag::err_call_incomplete_argument, Arg)) 6751 return ExprError(); 6752 6753 TheCall->setArg(i, Arg); 6754 } 6755 } 6756 6757 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6758 if (!Method->isStatic()) 6759 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6760 << Fn->getSourceRange()); 6761 6762 // Check for sentinels 6763 if (NDecl) 6764 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6765 6766 // Warn for unions passing across security boundary (CMSE). 6767 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6768 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6769 if (const auto *RT = 6770 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6771 if (RT->getDecl()->isOrContainsUnion()) 6772 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6773 << 0 << i; 6774 } 6775 } 6776 } 6777 6778 // Do special checking on direct calls to functions. 6779 if (FDecl) { 6780 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6781 return ExprError(); 6782 6783 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6784 6785 if (BuiltinID) 6786 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6787 } else if (NDecl) { 6788 if (CheckPointerCall(NDecl, TheCall, Proto)) 6789 return ExprError(); 6790 } else { 6791 if (CheckOtherCall(TheCall, Proto)) 6792 return ExprError(); 6793 } 6794 6795 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6796 } 6797 6798 ExprResult 6799 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6800 SourceLocation RParenLoc, Expr *InitExpr) { 6801 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6802 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6803 6804 TypeSourceInfo *TInfo; 6805 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6806 if (!TInfo) 6807 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6808 6809 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6810 } 6811 6812 ExprResult 6813 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6814 SourceLocation RParenLoc, Expr *LiteralExpr) { 6815 QualType literalType = TInfo->getType(); 6816 6817 if (literalType->isArrayType()) { 6818 if (RequireCompleteSizedType( 6819 LParenLoc, Context.getBaseElementType(literalType), 6820 diag::err_array_incomplete_or_sizeless_type, 6821 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6822 return ExprError(); 6823 if (literalType->isVariableArrayType()) 6824 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6825 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6826 } else if (!literalType->isDependentType() && 6827 RequireCompleteType(LParenLoc, literalType, 6828 diag::err_typecheck_decl_incomplete_type, 6829 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6830 return ExprError(); 6831 6832 InitializedEntity Entity 6833 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6834 InitializationKind Kind 6835 = InitializationKind::CreateCStyleCast(LParenLoc, 6836 SourceRange(LParenLoc, RParenLoc), 6837 /*InitList=*/true); 6838 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6839 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6840 &literalType); 6841 if (Result.isInvalid()) 6842 return ExprError(); 6843 LiteralExpr = Result.get(); 6844 6845 bool isFileScope = !CurContext->isFunctionOrMethod(); 6846 6847 // In C, compound literals are l-values for some reason. 6848 // For GCC compatibility, in C++, file-scope array compound literals with 6849 // constant initializers are also l-values, and compound literals are 6850 // otherwise prvalues. 6851 // 6852 // (GCC also treats C++ list-initialized file-scope array prvalues with 6853 // constant initializers as l-values, but that's non-conforming, so we don't 6854 // follow it there.) 6855 // 6856 // FIXME: It would be better to handle the lvalue cases as materializing and 6857 // lifetime-extending a temporary object, but our materialized temporaries 6858 // representation only supports lifetime extension from a variable, not "out 6859 // of thin air". 6860 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6861 // is bound to the result of applying array-to-pointer decay to the compound 6862 // literal. 6863 // FIXME: GCC supports compound literals of reference type, which should 6864 // obviously have a value kind derived from the kind of reference involved. 6865 ExprValueKind VK = 6866 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6867 ? VK_RValue 6868 : VK_LValue; 6869 6870 if (isFileScope) 6871 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6872 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6873 Expr *Init = ILE->getInit(i); 6874 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6875 } 6876 6877 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6878 VK, LiteralExpr, isFileScope); 6879 if (isFileScope) { 6880 if (!LiteralExpr->isTypeDependent() && 6881 !LiteralExpr->isValueDependent() && 6882 !literalType->isDependentType()) // C99 6.5.2.5p3 6883 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6884 return ExprError(); 6885 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6886 literalType.getAddressSpace() != LangAS::Default) { 6887 // Embedded-C extensions to C99 6.5.2.5: 6888 // "If the compound literal occurs inside the body of a function, the 6889 // type name shall not be qualified by an address-space qualifier." 6890 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6891 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6892 return ExprError(); 6893 } 6894 6895 if (!isFileScope && !getLangOpts().CPlusPlus) { 6896 // Compound literals that have automatic storage duration are destroyed at 6897 // the end of the scope in C; in C++, they're just temporaries. 6898 6899 // Emit diagnostics if it is or contains a C union type that is non-trivial 6900 // to destruct. 6901 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6902 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6903 NTCUC_CompoundLiteral, NTCUK_Destruct); 6904 6905 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6906 if (literalType.isDestructedType()) { 6907 Cleanup.setExprNeedsCleanups(true); 6908 ExprCleanupObjects.push_back(E); 6909 getCurFunction()->setHasBranchProtectedScope(); 6910 } 6911 } 6912 6913 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6914 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6915 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6916 E->getInitializer()->getExprLoc()); 6917 6918 return MaybeBindToTemporary(E); 6919 } 6920 6921 ExprResult 6922 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6923 SourceLocation RBraceLoc) { 6924 // Only produce each kind of designated initialization diagnostic once. 6925 SourceLocation FirstDesignator; 6926 bool DiagnosedArrayDesignator = false; 6927 bool DiagnosedNestedDesignator = false; 6928 bool DiagnosedMixedDesignator = false; 6929 6930 // Check that any designated initializers are syntactically valid in the 6931 // current language mode. 6932 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6933 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6934 if (FirstDesignator.isInvalid()) 6935 FirstDesignator = DIE->getBeginLoc(); 6936 6937 if (!getLangOpts().CPlusPlus) 6938 break; 6939 6940 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6941 DiagnosedNestedDesignator = true; 6942 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6943 << DIE->getDesignatorsSourceRange(); 6944 } 6945 6946 for (auto &Desig : DIE->designators()) { 6947 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6948 DiagnosedArrayDesignator = true; 6949 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6950 << Desig.getSourceRange(); 6951 } 6952 } 6953 6954 if (!DiagnosedMixedDesignator && 6955 !isa<DesignatedInitExpr>(InitArgList[0])) { 6956 DiagnosedMixedDesignator = true; 6957 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6958 << DIE->getSourceRange(); 6959 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6960 << InitArgList[0]->getSourceRange(); 6961 } 6962 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6963 isa<DesignatedInitExpr>(InitArgList[0])) { 6964 DiagnosedMixedDesignator = true; 6965 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6966 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6967 << DIE->getSourceRange(); 6968 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6969 << InitArgList[I]->getSourceRange(); 6970 } 6971 } 6972 6973 if (FirstDesignator.isValid()) { 6974 // Only diagnose designated initiaization as a C++20 extension if we didn't 6975 // already diagnose use of (non-C++20) C99 designator syntax. 6976 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6977 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6978 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6979 ? diag::warn_cxx17_compat_designated_init 6980 : diag::ext_cxx_designated_init); 6981 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6982 Diag(FirstDesignator, diag::ext_designated_init); 6983 } 6984 } 6985 6986 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6987 } 6988 6989 ExprResult 6990 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6991 SourceLocation RBraceLoc) { 6992 // Semantic analysis for initializers is done by ActOnDeclarator() and 6993 // CheckInitializer() - it requires knowledge of the object being initialized. 6994 6995 // Immediately handle non-overload placeholders. Overloads can be 6996 // resolved contextually, but everything else here can't. 6997 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6998 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6999 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7000 7001 // Ignore failures; dropping the entire initializer list because 7002 // of one failure would be terrible for indexing/etc. 7003 if (result.isInvalid()) continue; 7004 7005 InitArgList[I] = result.get(); 7006 } 7007 } 7008 7009 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7010 RBraceLoc); 7011 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7012 return E; 7013 } 7014 7015 /// Do an explicit extend of the given block pointer if we're in ARC. 7016 void Sema::maybeExtendBlockObject(ExprResult &E) { 7017 assert(E.get()->getType()->isBlockPointerType()); 7018 assert(E.get()->isRValue()); 7019 7020 // Only do this in an r-value context. 7021 if (!getLangOpts().ObjCAutoRefCount) return; 7022 7023 E = ImplicitCastExpr::Create( 7024 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7025 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7026 Cleanup.setExprNeedsCleanups(true); 7027 } 7028 7029 /// Prepare a conversion of the given expression to an ObjC object 7030 /// pointer type. 7031 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7032 QualType type = E.get()->getType(); 7033 if (type->isObjCObjectPointerType()) { 7034 return CK_BitCast; 7035 } else if (type->isBlockPointerType()) { 7036 maybeExtendBlockObject(E); 7037 return CK_BlockPointerToObjCPointerCast; 7038 } else { 7039 assert(type->isPointerType()); 7040 return CK_CPointerToObjCPointerCast; 7041 } 7042 } 7043 7044 /// Prepares for a scalar cast, performing all the necessary stages 7045 /// except the final cast and returning the kind required. 7046 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7047 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7048 // Also, callers should have filtered out the invalid cases with 7049 // pointers. Everything else should be possible. 7050 7051 QualType SrcTy = Src.get()->getType(); 7052 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7053 return CK_NoOp; 7054 7055 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7056 case Type::STK_MemberPointer: 7057 llvm_unreachable("member pointer type in C"); 7058 7059 case Type::STK_CPointer: 7060 case Type::STK_BlockPointer: 7061 case Type::STK_ObjCObjectPointer: 7062 switch (DestTy->getScalarTypeKind()) { 7063 case Type::STK_CPointer: { 7064 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7065 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7066 if (SrcAS != DestAS) 7067 return CK_AddressSpaceConversion; 7068 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7069 return CK_NoOp; 7070 return CK_BitCast; 7071 } 7072 case Type::STK_BlockPointer: 7073 return (SrcKind == Type::STK_BlockPointer 7074 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7075 case Type::STK_ObjCObjectPointer: 7076 if (SrcKind == Type::STK_ObjCObjectPointer) 7077 return CK_BitCast; 7078 if (SrcKind == Type::STK_CPointer) 7079 return CK_CPointerToObjCPointerCast; 7080 maybeExtendBlockObject(Src); 7081 return CK_BlockPointerToObjCPointerCast; 7082 case Type::STK_Bool: 7083 return CK_PointerToBoolean; 7084 case Type::STK_Integral: 7085 return CK_PointerToIntegral; 7086 case Type::STK_Floating: 7087 case Type::STK_FloatingComplex: 7088 case Type::STK_IntegralComplex: 7089 case Type::STK_MemberPointer: 7090 case Type::STK_FixedPoint: 7091 llvm_unreachable("illegal cast from pointer"); 7092 } 7093 llvm_unreachable("Should have returned before this"); 7094 7095 case Type::STK_FixedPoint: 7096 switch (DestTy->getScalarTypeKind()) { 7097 case Type::STK_FixedPoint: 7098 return CK_FixedPointCast; 7099 case Type::STK_Bool: 7100 return CK_FixedPointToBoolean; 7101 case Type::STK_Integral: 7102 return CK_FixedPointToIntegral; 7103 case Type::STK_Floating: 7104 return CK_FixedPointToFloating; 7105 case Type::STK_IntegralComplex: 7106 case Type::STK_FloatingComplex: 7107 Diag(Src.get()->getExprLoc(), 7108 diag::err_unimplemented_conversion_with_fixed_point_type) 7109 << DestTy; 7110 return CK_IntegralCast; 7111 case Type::STK_CPointer: 7112 case Type::STK_ObjCObjectPointer: 7113 case Type::STK_BlockPointer: 7114 case Type::STK_MemberPointer: 7115 llvm_unreachable("illegal cast to pointer type"); 7116 } 7117 llvm_unreachable("Should have returned before this"); 7118 7119 case Type::STK_Bool: // casting from bool is like casting from an integer 7120 case Type::STK_Integral: 7121 switch (DestTy->getScalarTypeKind()) { 7122 case Type::STK_CPointer: 7123 case Type::STK_ObjCObjectPointer: 7124 case Type::STK_BlockPointer: 7125 if (Src.get()->isNullPointerConstant(Context, 7126 Expr::NPC_ValueDependentIsNull)) 7127 return CK_NullToPointer; 7128 return CK_IntegralToPointer; 7129 case Type::STK_Bool: 7130 return CK_IntegralToBoolean; 7131 case Type::STK_Integral: 7132 return CK_IntegralCast; 7133 case Type::STK_Floating: 7134 return CK_IntegralToFloating; 7135 case Type::STK_IntegralComplex: 7136 Src = ImpCastExprToType(Src.get(), 7137 DestTy->castAs<ComplexType>()->getElementType(), 7138 CK_IntegralCast); 7139 return CK_IntegralRealToComplex; 7140 case Type::STK_FloatingComplex: 7141 Src = ImpCastExprToType(Src.get(), 7142 DestTy->castAs<ComplexType>()->getElementType(), 7143 CK_IntegralToFloating); 7144 return CK_FloatingRealToComplex; 7145 case Type::STK_MemberPointer: 7146 llvm_unreachable("member pointer type in C"); 7147 case Type::STK_FixedPoint: 7148 return CK_IntegralToFixedPoint; 7149 } 7150 llvm_unreachable("Should have returned before this"); 7151 7152 case Type::STK_Floating: 7153 switch (DestTy->getScalarTypeKind()) { 7154 case Type::STK_Floating: 7155 return CK_FloatingCast; 7156 case Type::STK_Bool: 7157 return CK_FloatingToBoolean; 7158 case Type::STK_Integral: 7159 return CK_FloatingToIntegral; 7160 case Type::STK_FloatingComplex: 7161 Src = ImpCastExprToType(Src.get(), 7162 DestTy->castAs<ComplexType>()->getElementType(), 7163 CK_FloatingCast); 7164 return CK_FloatingRealToComplex; 7165 case Type::STK_IntegralComplex: 7166 Src = ImpCastExprToType(Src.get(), 7167 DestTy->castAs<ComplexType>()->getElementType(), 7168 CK_FloatingToIntegral); 7169 return CK_IntegralRealToComplex; 7170 case Type::STK_CPointer: 7171 case Type::STK_ObjCObjectPointer: 7172 case Type::STK_BlockPointer: 7173 llvm_unreachable("valid float->pointer cast?"); 7174 case Type::STK_MemberPointer: 7175 llvm_unreachable("member pointer type in C"); 7176 case Type::STK_FixedPoint: 7177 return CK_FloatingToFixedPoint; 7178 } 7179 llvm_unreachable("Should have returned before this"); 7180 7181 case Type::STK_FloatingComplex: 7182 switch (DestTy->getScalarTypeKind()) { 7183 case Type::STK_FloatingComplex: 7184 return CK_FloatingComplexCast; 7185 case Type::STK_IntegralComplex: 7186 return CK_FloatingComplexToIntegralComplex; 7187 case Type::STK_Floating: { 7188 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7189 if (Context.hasSameType(ET, DestTy)) 7190 return CK_FloatingComplexToReal; 7191 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7192 return CK_FloatingCast; 7193 } 7194 case Type::STK_Bool: 7195 return CK_FloatingComplexToBoolean; 7196 case Type::STK_Integral: 7197 Src = ImpCastExprToType(Src.get(), 7198 SrcTy->castAs<ComplexType>()->getElementType(), 7199 CK_FloatingComplexToReal); 7200 return CK_FloatingToIntegral; 7201 case Type::STK_CPointer: 7202 case Type::STK_ObjCObjectPointer: 7203 case Type::STK_BlockPointer: 7204 llvm_unreachable("valid complex float->pointer cast?"); 7205 case Type::STK_MemberPointer: 7206 llvm_unreachable("member pointer type in C"); 7207 case Type::STK_FixedPoint: 7208 Diag(Src.get()->getExprLoc(), 7209 diag::err_unimplemented_conversion_with_fixed_point_type) 7210 << SrcTy; 7211 return CK_IntegralCast; 7212 } 7213 llvm_unreachable("Should have returned before this"); 7214 7215 case Type::STK_IntegralComplex: 7216 switch (DestTy->getScalarTypeKind()) { 7217 case Type::STK_FloatingComplex: 7218 return CK_IntegralComplexToFloatingComplex; 7219 case Type::STK_IntegralComplex: 7220 return CK_IntegralComplexCast; 7221 case Type::STK_Integral: { 7222 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7223 if (Context.hasSameType(ET, DestTy)) 7224 return CK_IntegralComplexToReal; 7225 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7226 return CK_IntegralCast; 7227 } 7228 case Type::STK_Bool: 7229 return CK_IntegralComplexToBoolean; 7230 case Type::STK_Floating: 7231 Src = ImpCastExprToType(Src.get(), 7232 SrcTy->castAs<ComplexType>()->getElementType(), 7233 CK_IntegralComplexToReal); 7234 return CK_IntegralToFloating; 7235 case Type::STK_CPointer: 7236 case Type::STK_ObjCObjectPointer: 7237 case Type::STK_BlockPointer: 7238 llvm_unreachable("valid complex int->pointer cast?"); 7239 case Type::STK_MemberPointer: 7240 llvm_unreachable("member pointer type in C"); 7241 case Type::STK_FixedPoint: 7242 Diag(Src.get()->getExprLoc(), 7243 diag::err_unimplemented_conversion_with_fixed_point_type) 7244 << SrcTy; 7245 return CK_IntegralCast; 7246 } 7247 llvm_unreachable("Should have returned before this"); 7248 } 7249 7250 llvm_unreachable("Unhandled scalar cast"); 7251 } 7252 7253 static bool breakDownVectorType(QualType type, uint64_t &len, 7254 QualType &eltType) { 7255 // Vectors are simple. 7256 if (const VectorType *vecType = type->getAs<VectorType>()) { 7257 len = vecType->getNumElements(); 7258 eltType = vecType->getElementType(); 7259 assert(eltType->isScalarType()); 7260 return true; 7261 } 7262 7263 // We allow lax conversion to and from non-vector types, but only if 7264 // they're real types (i.e. non-complex, non-pointer scalar types). 7265 if (!type->isRealType()) return false; 7266 7267 len = 1; 7268 eltType = type; 7269 return true; 7270 } 7271 7272 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7273 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7274 /// allowed? 7275 /// 7276 /// This will also return false if the two given types do not make sense from 7277 /// the perspective of SVE bitcasts. 7278 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7279 assert(srcTy->isVectorType() || destTy->isVectorType()); 7280 7281 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7282 if (!FirstType->isSizelessBuiltinType()) 7283 return false; 7284 7285 const auto *VecTy = SecondType->getAs<VectorType>(); 7286 return VecTy && 7287 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7288 }; 7289 7290 return ValidScalableConversion(srcTy, destTy) || 7291 ValidScalableConversion(destTy, srcTy); 7292 } 7293 7294 /// Are the two types lax-compatible vector types? That is, given 7295 /// that one of them is a vector, do they have equal storage sizes, 7296 /// where the storage size is the number of elements times the element 7297 /// size? 7298 /// 7299 /// This will also return false if either of the types is neither a 7300 /// vector nor a real type. 7301 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7302 assert(destTy->isVectorType() || srcTy->isVectorType()); 7303 7304 // Disallow lax conversions between scalars and ExtVectors (these 7305 // conversions are allowed for other vector types because common headers 7306 // depend on them). Most scalar OP ExtVector cases are handled by the 7307 // splat path anyway, which does what we want (convert, not bitcast). 7308 // What this rules out for ExtVectors is crazy things like char4*float. 7309 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7310 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7311 7312 uint64_t srcLen, destLen; 7313 QualType srcEltTy, destEltTy; 7314 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7315 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7316 7317 // ASTContext::getTypeSize will return the size rounded up to a 7318 // power of 2, so instead of using that, we need to use the raw 7319 // element size multiplied by the element count. 7320 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7321 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7322 7323 return (srcLen * srcEltSize == destLen * destEltSize); 7324 } 7325 7326 /// Is this a legal conversion between two types, one of which is 7327 /// known to be a vector type? 7328 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7329 assert(destTy->isVectorType() || srcTy->isVectorType()); 7330 7331 switch (Context.getLangOpts().getLaxVectorConversions()) { 7332 case LangOptions::LaxVectorConversionKind::None: 7333 return false; 7334 7335 case LangOptions::LaxVectorConversionKind::Integer: 7336 if (!srcTy->isIntegralOrEnumerationType()) { 7337 auto *Vec = srcTy->getAs<VectorType>(); 7338 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7339 return false; 7340 } 7341 if (!destTy->isIntegralOrEnumerationType()) { 7342 auto *Vec = destTy->getAs<VectorType>(); 7343 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7344 return false; 7345 } 7346 // OK, integer (vector) -> integer (vector) bitcast. 7347 break; 7348 7349 case LangOptions::LaxVectorConversionKind::All: 7350 break; 7351 } 7352 7353 return areLaxCompatibleVectorTypes(srcTy, destTy); 7354 } 7355 7356 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7357 CastKind &Kind) { 7358 assert(VectorTy->isVectorType() && "Not a vector type!"); 7359 7360 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7361 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7362 return Diag(R.getBegin(), 7363 Ty->isVectorType() ? 7364 diag::err_invalid_conversion_between_vectors : 7365 diag::err_invalid_conversion_between_vector_and_integer) 7366 << VectorTy << Ty << R; 7367 } else 7368 return Diag(R.getBegin(), 7369 diag::err_invalid_conversion_between_vector_and_scalar) 7370 << VectorTy << Ty << R; 7371 7372 Kind = CK_BitCast; 7373 return false; 7374 } 7375 7376 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7377 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7378 7379 if (DestElemTy == SplattedExpr->getType()) 7380 return SplattedExpr; 7381 7382 assert(DestElemTy->isFloatingType() || 7383 DestElemTy->isIntegralOrEnumerationType()); 7384 7385 CastKind CK; 7386 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7387 // OpenCL requires that we convert `true` boolean expressions to -1, but 7388 // only when splatting vectors. 7389 if (DestElemTy->isFloatingType()) { 7390 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7391 // in two steps: boolean to signed integral, then to floating. 7392 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7393 CK_BooleanToSignedIntegral); 7394 SplattedExpr = CastExprRes.get(); 7395 CK = CK_IntegralToFloating; 7396 } else { 7397 CK = CK_BooleanToSignedIntegral; 7398 } 7399 } else { 7400 ExprResult CastExprRes = SplattedExpr; 7401 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7402 if (CastExprRes.isInvalid()) 7403 return ExprError(); 7404 SplattedExpr = CastExprRes.get(); 7405 } 7406 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7407 } 7408 7409 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7410 Expr *CastExpr, CastKind &Kind) { 7411 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7412 7413 QualType SrcTy = CastExpr->getType(); 7414 7415 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7416 // an ExtVectorType. 7417 // In OpenCL, casts between vectors of different types are not allowed. 7418 // (See OpenCL 6.2). 7419 if (SrcTy->isVectorType()) { 7420 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7421 (getLangOpts().OpenCL && 7422 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7423 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7424 << DestTy << SrcTy << R; 7425 return ExprError(); 7426 } 7427 Kind = CK_BitCast; 7428 return CastExpr; 7429 } 7430 7431 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7432 // conversion will take place first from scalar to elt type, and then 7433 // splat from elt type to vector. 7434 if (SrcTy->isPointerType()) 7435 return Diag(R.getBegin(), 7436 diag::err_invalid_conversion_between_vector_and_scalar) 7437 << DestTy << SrcTy << R; 7438 7439 Kind = CK_VectorSplat; 7440 return prepareVectorSplat(DestTy, CastExpr); 7441 } 7442 7443 ExprResult 7444 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7445 Declarator &D, ParsedType &Ty, 7446 SourceLocation RParenLoc, Expr *CastExpr) { 7447 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7448 "ActOnCastExpr(): missing type or expr"); 7449 7450 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7451 if (D.isInvalidType()) 7452 return ExprError(); 7453 7454 if (getLangOpts().CPlusPlus) { 7455 // Check that there are no default arguments (C++ only). 7456 CheckExtraCXXDefaultArguments(D); 7457 } else { 7458 // Make sure any TypoExprs have been dealt with. 7459 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7460 if (!Res.isUsable()) 7461 return ExprError(); 7462 CastExpr = Res.get(); 7463 } 7464 7465 checkUnusedDeclAttributes(D); 7466 7467 QualType castType = castTInfo->getType(); 7468 Ty = CreateParsedType(castType, castTInfo); 7469 7470 bool isVectorLiteral = false; 7471 7472 // Check for an altivec or OpenCL literal, 7473 // i.e. all the elements are integer constants. 7474 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7475 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7476 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7477 && castType->isVectorType() && (PE || PLE)) { 7478 if (PLE && PLE->getNumExprs() == 0) { 7479 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7480 return ExprError(); 7481 } 7482 if (PE || PLE->getNumExprs() == 1) { 7483 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7484 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7485 isVectorLiteral = true; 7486 } 7487 else 7488 isVectorLiteral = true; 7489 } 7490 7491 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7492 // then handle it as such. 7493 if (isVectorLiteral) 7494 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7495 7496 // If the Expr being casted is a ParenListExpr, handle it specially. 7497 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7498 // sequence of BinOp comma operators. 7499 if (isa<ParenListExpr>(CastExpr)) { 7500 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7501 if (Result.isInvalid()) return ExprError(); 7502 CastExpr = Result.get(); 7503 } 7504 7505 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7506 !getSourceManager().isInSystemMacro(LParenLoc)) 7507 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7508 7509 CheckTollFreeBridgeCast(castType, CastExpr); 7510 7511 CheckObjCBridgeRelatedCast(castType, CastExpr); 7512 7513 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7514 7515 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7516 } 7517 7518 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7519 SourceLocation RParenLoc, Expr *E, 7520 TypeSourceInfo *TInfo) { 7521 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7522 "Expected paren or paren list expression"); 7523 7524 Expr **exprs; 7525 unsigned numExprs; 7526 Expr *subExpr; 7527 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7528 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7529 LiteralLParenLoc = PE->getLParenLoc(); 7530 LiteralRParenLoc = PE->getRParenLoc(); 7531 exprs = PE->getExprs(); 7532 numExprs = PE->getNumExprs(); 7533 } else { // isa<ParenExpr> by assertion at function entrance 7534 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7535 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7536 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7537 exprs = &subExpr; 7538 numExprs = 1; 7539 } 7540 7541 QualType Ty = TInfo->getType(); 7542 assert(Ty->isVectorType() && "Expected vector type"); 7543 7544 SmallVector<Expr *, 8> initExprs; 7545 const VectorType *VTy = Ty->castAs<VectorType>(); 7546 unsigned numElems = VTy->getNumElements(); 7547 7548 // '(...)' form of vector initialization in AltiVec: the number of 7549 // initializers must be one or must match the size of the vector. 7550 // If a single value is specified in the initializer then it will be 7551 // replicated to all the components of the vector 7552 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7553 // The number of initializers must be one or must match the size of the 7554 // vector. If a single value is specified in the initializer then it will 7555 // be replicated to all the components of the vector 7556 if (numExprs == 1) { 7557 QualType ElemTy = VTy->getElementType(); 7558 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7559 if (Literal.isInvalid()) 7560 return ExprError(); 7561 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7562 PrepareScalarCast(Literal, ElemTy)); 7563 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7564 } 7565 else if (numExprs < numElems) { 7566 Diag(E->getExprLoc(), 7567 diag::err_incorrect_number_of_vector_initializers); 7568 return ExprError(); 7569 } 7570 else 7571 initExprs.append(exprs, exprs + numExprs); 7572 } 7573 else { 7574 // For OpenCL, when the number of initializers is a single value, 7575 // it will be replicated to all components of the vector. 7576 if (getLangOpts().OpenCL && 7577 VTy->getVectorKind() == VectorType::GenericVector && 7578 numExprs == 1) { 7579 QualType ElemTy = VTy->getElementType(); 7580 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7581 if (Literal.isInvalid()) 7582 return ExprError(); 7583 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7584 PrepareScalarCast(Literal, ElemTy)); 7585 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7586 } 7587 7588 initExprs.append(exprs, exprs + numExprs); 7589 } 7590 // FIXME: This means that pretty-printing the final AST will produce curly 7591 // braces instead of the original commas. 7592 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7593 initExprs, LiteralRParenLoc); 7594 initE->setType(Ty); 7595 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7596 } 7597 7598 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7599 /// the ParenListExpr into a sequence of comma binary operators. 7600 ExprResult 7601 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7602 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7603 if (!E) 7604 return OrigExpr; 7605 7606 ExprResult Result(E->getExpr(0)); 7607 7608 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7609 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7610 E->getExpr(i)); 7611 7612 if (Result.isInvalid()) return ExprError(); 7613 7614 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7615 } 7616 7617 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7618 SourceLocation R, 7619 MultiExprArg Val) { 7620 return ParenListExpr::Create(Context, L, Val, R); 7621 } 7622 7623 /// Emit a specialized diagnostic when one expression is a null pointer 7624 /// constant and the other is not a pointer. Returns true if a diagnostic is 7625 /// emitted. 7626 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7627 SourceLocation QuestionLoc) { 7628 Expr *NullExpr = LHSExpr; 7629 Expr *NonPointerExpr = RHSExpr; 7630 Expr::NullPointerConstantKind NullKind = 7631 NullExpr->isNullPointerConstant(Context, 7632 Expr::NPC_ValueDependentIsNotNull); 7633 7634 if (NullKind == Expr::NPCK_NotNull) { 7635 NullExpr = RHSExpr; 7636 NonPointerExpr = LHSExpr; 7637 NullKind = 7638 NullExpr->isNullPointerConstant(Context, 7639 Expr::NPC_ValueDependentIsNotNull); 7640 } 7641 7642 if (NullKind == Expr::NPCK_NotNull) 7643 return false; 7644 7645 if (NullKind == Expr::NPCK_ZeroExpression) 7646 return false; 7647 7648 if (NullKind == Expr::NPCK_ZeroLiteral) { 7649 // In this case, check to make sure that we got here from a "NULL" 7650 // string in the source code. 7651 NullExpr = NullExpr->IgnoreParenImpCasts(); 7652 SourceLocation loc = NullExpr->getExprLoc(); 7653 if (!findMacroSpelling(loc, "NULL")) 7654 return false; 7655 } 7656 7657 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7658 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7659 << NonPointerExpr->getType() << DiagType 7660 << NonPointerExpr->getSourceRange(); 7661 return true; 7662 } 7663 7664 /// Return false if the condition expression is valid, true otherwise. 7665 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7666 QualType CondTy = Cond->getType(); 7667 7668 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7669 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7670 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7671 << CondTy << Cond->getSourceRange(); 7672 return true; 7673 } 7674 7675 // C99 6.5.15p2 7676 if (CondTy->isScalarType()) return false; 7677 7678 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7679 << CondTy << Cond->getSourceRange(); 7680 return true; 7681 } 7682 7683 /// Handle when one or both operands are void type. 7684 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7685 ExprResult &RHS) { 7686 Expr *LHSExpr = LHS.get(); 7687 Expr *RHSExpr = RHS.get(); 7688 7689 if (!LHSExpr->getType()->isVoidType()) 7690 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7691 << RHSExpr->getSourceRange(); 7692 if (!RHSExpr->getType()->isVoidType()) 7693 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7694 << LHSExpr->getSourceRange(); 7695 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7696 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7697 return S.Context.VoidTy; 7698 } 7699 7700 /// Return false if the NullExpr can be promoted to PointerTy, 7701 /// true otherwise. 7702 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7703 QualType PointerTy) { 7704 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7705 !NullExpr.get()->isNullPointerConstant(S.Context, 7706 Expr::NPC_ValueDependentIsNull)) 7707 return true; 7708 7709 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7710 return false; 7711 } 7712 7713 /// Checks compatibility between two pointers and return the resulting 7714 /// type. 7715 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7716 ExprResult &RHS, 7717 SourceLocation Loc) { 7718 QualType LHSTy = LHS.get()->getType(); 7719 QualType RHSTy = RHS.get()->getType(); 7720 7721 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7722 // Two identical pointers types are always compatible. 7723 return LHSTy; 7724 } 7725 7726 QualType lhptee, rhptee; 7727 7728 // Get the pointee types. 7729 bool IsBlockPointer = false; 7730 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7731 lhptee = LHSBTy->getPointeeType(); 7732 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7733 IsBlockPointer = true; 7734 } else { 7735 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7736 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7737 } 7738 7739 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7740 // differently qualified versions of compatible types, the result type is 7741 // a pointer to an appropriately qualified version of the composite 7742 // type. 7743 7744 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7745 // clause doesn't make sense for our extensions. E.g. address space 2 should 7746 // be incompatible with address space 3: they may live on different devices or 7747 // anything. 7748 Qualifiers lhQual = lhptee.getQualifiers(); 7749 Qualifiers rhQual = rhptee.getQualifiers(); 7750 7751 LangAS ResultAddrSpace = LangAS::Default; 7752 LangAS LAddrSpace = lhQual.getAddressSpace(); 7753 LangAS RAddrSpace = rhQual.getAddressSpace(); 7754 7755 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7756 // spaces is disallowed. 7757 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7758 ResultAddrSpace = LAddrSpace; 7759 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7760 ResultAddrSpace = RAddrSpace; 7761 else { 7762 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7763 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7764 << RHS.get()->getSourceRange(); 7765 return QualType(); 7766 } 7767 7768 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7769 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7770 lhQual.removeCVRQualifiers(); 7771 rhQual.removeCVRQualifiers(); 7772 7773 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7774 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7775 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7776 // qual types are compatible iff 7777 // * corresponded types are compatible 7778 // * CVR qualifiers are equal 7779 // * address spaces are equal 7780 // Thus for conditional operator we merge CVR and address space unqualified 7781 // pointees and if there is a composite type we return a pointer to it with 7782 // merged qualifiers. 7783 LHSCastKind = 7784 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7785 RHSCastKind = 7786 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7787 lhQual.removeAddressSpace(); 7788 rhQual.removeAddressSpace(); 7789 7790 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7791 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7792 7793 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7794 7795 if (CompositeTy.isNull()) { 7796 // In this situation, we assume void* type. No especially good 7797 // reason, but this is what gcc does, and we do have to pick 7798 // to get a consistent AST. 7799 QualType incompatTy; 7800 incompatTy = S.Context.getPointerType( 7801 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7802 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7803 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7804 7805 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7806 // for casts between types with incompatible address space qualifiers. 7807 // For the following code the compiler produces casts between global and 7808 // local address spaces of the corresponded innermost pointees: 7809 // local int *global *a; 7810 // global int *global *b; 7811 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7812 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7813 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7814 << RHS.get()->getSourceRange(); 7815 7816 return incompatTy; 7817 } 7818 7819 // The pointer types are compatible. 7820 // In case of OpenCL ResultTy should have the address space qualifier 7821 // which is a superset of address spaces of both the 2nd and the 3rd 7822 // operands of the conditional operator. 7823 QualType ResultTy = [&, ResultAddrSpace]() { 7824 if (S.getLangOpts().OpenCL) { 7825 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7826 CompositeQuals.setAddressSpace(ResultAddrSpace); 7827 return S.Context 7828 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7829 .withCVRQualifiers(MergedCVRQual); 7830 } 7831 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7832 }(); 7833 if (IsBlockPointer) 7834 ResultTy = S.Context.getBlockPointerType(ResultTy); 7835 else 7836 ResultTy = S.Context.getPointerType(ResultTy); 7837 7838 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7839 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7840 return ResultTy; 7841 } 7842 7843 /// Return the resulting type when the operands are both block pointers. 7844 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7845 ExprResult &LHS, 7846 ExprResult &RHS, 7847 SourceLocation Loc) { 7848 QualType LHSTy = LHS.get()->getType(); 7849 QualType RHSTy = RHS.get()->getType(); 7850 7851 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7852 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7853 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7854 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7855 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7856 return destType; 7857 } 7858 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7859 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7860 << RHS.get()->getSourceRange(); 7861 return QualType(); 7862 } 7863 7864 // We have 2 block pointer types. 7865 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7866 } 7867 7868 /// Return the resulting type when the operands are both pointers. 7869 static QualType 7870 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7871 ExprResult &RHS, 7872 SourceLocation Loc) { 7873 // get the pointer types 7874 QualType LHSTy = LHS.get()->getType(); 7875 QualType RHSTy = RHS.get()->getType(); 7876 7877 // get the "pointed to" types 7878 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7879 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7880 7881 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7882 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7883 // Figure out necessary qualifiers (C99 6.5.15p6) 7884 QualType destPointee 7885 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7886 QualType destType = S.Context.getPointerType(destPointee); 7887 // Add qualifiers if necessary. 7888 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7889 // Promote to void*. 7890 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7891 return destType; 7892 } 7893 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7894 QualType destPointee 7895 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7896 QualType destType = S.Context.getPointerType(destPointee); 7897 // Add qualifiers if necessary. 7898 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7899 // Promote to void*. 7900 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7901 return destType; 7902 } 7903 7904 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7905 } 7906 7907 /// Return false if the first expression is not an integer and the second 7908 /// expression is not a pointer, true otherwise. 7909 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7910 Expr* PointerExpr, SourceLocation Loc, 7911 bool IsIntFirstExpr) { 7912 if (!PointerExpr->getType()->isPointerType() || 7913 !Int.get()->getType()->isIntegerType()) 7914 return false; 7915 7916 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7917 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7918 7919 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7920 << Expr1->getType() << Expr2->getType() 7921 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7922 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7923 CK_IntegralToPointer); 7924 return true; 7925 } 7926 7927 /// Simple conversion between integer and floating point types. 7928 /// 7929 /// Used when handling the OpenCL conditional operator where the 7930 /// condition is a vector while the other operands are scalar. 7931 /// 7932 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7933 /// types are either integer or floating type. Between the two 7934 /// operands, the type with the higher rank is defined as the "result 7935 /// type". The other operand needs to be promoted to the same type. No 7936 /// other type promotion is allowed. We cannot use 7937 /// UsualArithmeticConversions() for this purpose, since it always 7938 /// promotes promotable types. 7939 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7940 ExprResult &RHS, 7941 SourceLocation QuestionLoc) { 7942 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7943 if (LHS.isInvalid()) 7944 return QualType(); 7945 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7946 if (RHS.isInvalid()) 7947 return QualType(); 7948 7949 // For conversion purposes, we ignore any qualifiers. 7950 // For example, "const float" and "float" are equivalent. 7951 QualType LHSType = 7952 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7953 QualType RHSType = 7954 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7955 7956 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7957 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7958 << LHSType << LHS.get()->getSourceRange(); 7959 return QualType(); 7960 } 7961 7962 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7963 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7964 << RHSType << RHS.get()->getSourceRange(); 7965 return QualType(); 7966 } 7967 7968 // If both types are identical, no conversion is needed. 7969 if (LHSType == RHSType) 7970 return LHSType; 7971 7972 // Now handle "real" floating types (i.e. float, double, long double). 7973 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7974 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7975 /*IsCompAssign = */ false); 7976 7977 // Finally, we have two differing integer types. 7978 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7979 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7980 } 7981 7982 /// Convert scalar operands to a vector that matches the 7983 /// condition in length. 7984 /// 7985 /// Used when handling the OpenCL conditional operator where the 7986 /// condition is a vector while the other operands are scalar. 7987 /// 7988 /// We first compute the "result type" for the scalar operands 7989 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7990 /// into a vector of that type where the length matches the condition 7991 /// vector type. s6.11.6 requires that the element types of the result 7992 /// and the condition must have the same number of bits. 7993 static QualType 7994 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7995 QualType CondTy, SourceLocation QuestionLoc) { 7996 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7997 if (ResTy.isNull()) return QualType(); 7998 7999 const VectorType *CV = CondTy->getAs<VectorType>(); 8000 assert(CV); 8001 8002 // Determine the vector result type 8003 unsigned NumElements = CV->getNumElements(); 8004 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8005 8006 // Ensure that all types have the same number of bits 8007 if (S.Context.getTypeSize(CV->getElementType()) 8008 != S.Context.getTypeSize(ResTy)) { 8009 // Since VectorTy is created internally, it does not pretty print 8010 // with an OpenCL name. Instead, we just print a description. 8011 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8012 SmallString<64> Str; 8013 llvm::raw_svector_ostream OS(Str); 8014 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8015 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8016 << CondTy << OS.str(); 8017 return QualType(); 8018 } 8019 8020 // Convert operands to the vector result type 8021 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8022 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8023 8024 return VectorTy; 8025 } 8026 8027 /// Return false if this is a valid OpenCL condition vector 8028 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8029 SourceLocation QuestionLoc) { 8030 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8031 // integral type. 8032 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8033 assert(CondTy); 8034 QualType EleTy = CondTy->getElementType(); 8035 if (EleTy->isIntegerType()) return false; 8036 8037 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8038 << Cond->getType() << Cond->getSourceRange(); 8039 return true; 8040 } 8041 8042 /// Return false if the vector condition type and the vector 8043 /// result type are compatible. 8044 /// 8045 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8046 /// number of elements, and their element types have the same number 8047 /// of bits. 8048 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8049 SourceLocation QuestionLoc) { 8050 const VectorType *CV = CondTy->getAs<VectorType>(); 8051 const VectorType *RV = VecResTy->getAs<VectorType>(); 8052 assert(CV && RV); 8053 8054 if (CV->getNumElements() != RV->getNumElements()) { 8055 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8056 << CondTy << VecResTy; 8057 return true; 8058 } 8059 8060 QualType CVE = CV->getElementType(); 8061 QualType RVE = RV->getElementType(); 8062 8063 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8064 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8065 << CondTy << VecResTy; 8066 return true; 8067 } 8068 8069 return false; 8070 } 8071 8072 /// Return the resulting type for the conditional operator in 8073 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8074 /// s6.3.i) when the condition is a vector type. 8075 static QualType 8076 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8077 ExprResult &LHS, ExprResult &RHS, 8078 SourceLocation QuestionLoc) { 8079 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8080 if (Cond.isInvalid()) 8081 return QualType(); 8082 QualType CondTy = Cond.get()->getType(); 8083 8084 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8085 return QualType(); 8086 8087 // If either operand is a vector then find the vector type of the 8088 // result as specified in OpenCL v1.1 s6.3.i. 8089 if (LHS.get()->getType()->isVectorType() || 8090 RHS.get()->getType()->isVectorType()) { 8091 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8092 /*isCompAssign*/false, 8093 /*AllowBothBool*/true, 8094 /*AllowBoolConversions*/false); 8095 if (VecResTy.isNull()) return QualType(); 8096 // The result type must match the condition type as specified in 8097 // OpenCL v1.1 s6.11.6. 8098 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8099 return QualType(); 8100 return VecResTy; 8101 } 8102 8103 // Both operands are scalar. 8104 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8105 } 8106 8107 /// Return true if the Expr is block type 8108 static bool checkBlockType(Sema &S, const Expr *E) { 8109 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8110 QualType Ty = CE->getCallee()->getType(); 8111 if (Ty->isBlockPointerType()) { 8112 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8113 return true; 8114 } 8115 } 8116 return false; 8117 } 8118 8119 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8120 /// In that case, LHS = cond. 8121 /// C99 6.5.15 8122 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8123 ExprResult &RHS, ExprValueKind &VK, 8124 ExprObjectKind &OK, 8125 SourceLocation QuestionLoc) { 8126 8127 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8128 if (!LHSResult.isUsable()) return QualType(); 8129 LHS = LHSResult; 8130 8131 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8132 if (!RHSResult.isUsable()) return QualType(); 8133 RHS = RHSResult; 8134 8135 // C++ is sufficiently different to merit its own checker. 8136 if (getLangOpts().CPlusPlus) 8137 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8138 8139 VK = VK_RValue; 8140 OK = OK_Ordinary; 8141 8142 if (Context.isDependenceAllowed() && 8143 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8144 RHS.get()->isTypeDependent())) { 8145 assert(!getLangOpts().CPlusPlus); 8146 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8147 RHS.get()->containsErrors()) && 8148 "should only occur in error-recovery path."); 8149 return Context.DependentTy; 8150 } 8151 8152 // The OpenCL operator with a vector condition is sufficiently 8153 // different to merit its own checker. 8154 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8155 Cond.get()->getType()->isExtVectorType()) 8156 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8157 8158 // First, check the condition. 8159 Cond = UsualUnaryConversions(Cond.get()); 8160 if (Cond.isInvalid()) 8161 return QualType(); 8162 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8163 return QualType(); 8164 8165 // Now check the two expressions. 8166 if (LHS.get()->getType()->isVectorType() || 8167 RHS.get()->getType()->isVectorType()) 8168 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8169 /*AllowBothBool*/true, 8170 /*AllowBoolConversions*/false); 8171 8172 QualType ResTy = 8173 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8174 if (LHS.isInvalid() || RHS.isInvalid()) 8175 return QualType(); 8176 8177 QualType LHSTy = LHS.get()->getType(); 8178 QualType RHSTy = RHS.get()->getType(); 8179 8180 // Diagnose attempts to convert between __float128 and long double where 8181 // such conversions currently can't be handled. 8182 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8183 Diag(QuestionLoc, 8184 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8185 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8186 return QualType(); 8187 } 8188 8189 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8190 // selection operator (?:). 8191 if (getLangOpts().OpenCL && 8192 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8193 return QualType(); 8194 } 8195 8196 // If both operands have arithmetic type, do the usual arithmetic conversions 8197 // to find a common type: C99 6.5.15p3,5. 8198 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8199 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8200 // different sizes, or between ExtInts and other types. 8201 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8202 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8203 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8204 << RHS.get()->getSourceRange(); 8205 return QualType(); 8206 } 8207 8208 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8209 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8210 8211 return ResTy; 8212 } 8213 8214 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8215 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8216 return LHSTy; 8217 } 8218 8219 // If both operands are the same structure or union type, the result is that 8220 // type. 8221 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8222 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8223 if (LHSRT->getDecl() == RHSRT->getDecl()) 8224 // "If both the operands have structure or union type, the result has 8225 // that type." This implies that CV qualifiers are dropped. 8226 return LHSTy.getUnqualifiedType(); 8227 // FIXME: Type of conditional expression must be complete in C mode. 8228 } 8229 8230 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8231 // The following || allows only one side to be void (a GCC-ism). 8232 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8233 return checkConditionalVoidType(*this, LHS, RHS); 8234 } 8235 8236 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8237 // the type of the other operand." 8238 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8239 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8240 8241 // All objective-c pointer type analysis is done here. 8242 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8243 QuestionLoc); 8244 if (LHS.isInvalid() || RHS.isInvalid()) 8245 return QualType(); 8246 if (!compositeType.isNull()) 8247 return compositeType; 8248 8249 8250 // Handle block pointer types. 8251 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8252 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8253 QuestionLoc); 8254 8255 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8256 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8257 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8258 QuestionLoc); 8259 8260 // GCC compatibility: soften pointer/integer mismatch. Note that 8261 // null pointers have been filtered out by this point. 8262 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8263 /*IsIntFirstExpr=*/true)) 8264 return RHSTy; 8265 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8266 /*IsIntFirstExpr=*/false)) 8267 return LHSTy; 8268 8269 // Allow ?: operations in which both operands have the same 8270 // built-in sizeless type. 8271 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8272 return LHSTy; 8273 8274 // Emit a better diagnostic if one of the expressions is a null pointer 8275 // constant and the other is not a pointer type. In this case, the user most 8276 // likely forgot to take the address of the other expression. 8277 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8278 return QualType(); 8279 8280 // Otherwise, the operands are not compatible. 8281 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8282 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8283 << RHS.get()->getSourceRange(); 8284 return QualType(); 8285 } 8286 8287 /// FindCompositeObjCPointerType - Helper method to find composite type of 8288 /// two objective-c pointer types of the two input expressions. 8289 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8290 SourceLocation QuestionLoc) { 8291 QualType LHSTy = LHS.get()->getType(); 8292 QualType RHSTy = RHS.get()->getType(); 8293 8294 // Handle things like Class and struct objc_class*. Here we case the result 8295 // to the pseudo-builtin, because that will be implicitly cast back to the 8296 // redefinition type if an attempt is made to access its fields. 8297 if (LHSTy->isObjCClassType() && 8298 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8299 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8300 return LHSTy; 8301 } 8302 if (RHSTy->isObjCClassType() && 8303 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8304 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8305 return RHSTy; 8306 } 8307 // And the same for struct objc_object* / id 8308 if (LHSTy->isObjCIdType() && 8309 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8310 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8311 return LHSTy; 8312 } 8313 if (RHSTy->isObjCIdType() && 8314 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8315 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8316 return RHSTy; 8317 } 8318 // And the same for struct objc_selector* / SEL 8319 if (Context.isObjCSelType(LHSTy) && 8320 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8321 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8322 return LHSTy; 8323 } 8324 if (Context.isObjCSelType(RHSTy) && 8325 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8326 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8327 return RHSTy; 8328 } 8329 // Check constraints for Objective-C object pointers types. 8330 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8331 8332 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8333 // Two identical object pointer types are always compatible. 8334 return LHSTy; 8335 } 8336 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8337 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8338 QualType compositeType = LHSTy; 8339 8340 // If both operands are interfaces and either operand can be 8341 // assigned to the other, use that type as the composite 8342 // type. This allows 8343 // xxx ? (A*) a : (B*) b 8344 // where B is a subclass of A. 8345 // 8346 // Additionally, as for assignment, if either type is 'id' 8347 // allow silent coercion. Finally, if the types are 8348 // incompatible then make sure to use 'id' as the composite 8349 // type so the result is acceptable for sending messages to. 8350 8351 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8352 // It could return the composite type. 8353 if (!(compositeType = 8354 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8355 // Nothing more to do. 8356 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8357 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8358 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8359 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8360 } else if ((LHSOPT->isObjCQualifiedIdType() || 8361 RHSOPT->isObjCQualifiedIdType()) && 8362 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8363 true)) { 8364 // Need to handle "id<xx>" explicitly. 8365 // GCC allows qualified id and any Objective-C type to devolve to 8366 // id. Currently localizing to here until clear this should be 8367 // part of ObjCQualifiedIdTypesAreCompatible. 8368 compositeType = Context.getObjCIdType(); 8369 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8370 compositeType = Context.getObjCIdType(); 8371 } else { 8372 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8373 << LHSTy << RHSTy 8374 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8375 QualType incompatTy = Context.getObjCIdType(); 8376 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8377 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8378 return incompatTy; 8379 } 8380 // The object pointer types are compatible. 8381 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8382 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8383 return compositeType; 8384 } 8385 // Check Objective-C object pointer types and 'void *' 8386 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8387 if (getLangOpts().ObjCAutoRefCount) { 8388 // ARC forbids the implicit conversion of object pointers to 'void *', 8389 // so these types are not compatible. 8390 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8391 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8392 LHS = RHS = true; 8393 return QualType(); 8394 } 8395 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8396 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8397 QualType destPointee 8398 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8399 QualType destType = Context.getPointerType(destPointee); 8400 // Add qualifiers if necessary. 8401 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8402 // Promote to void*. 8403 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8404 return destType; 8405 } 8406 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8407 if (getLangOpts().ObjCAutoRefCount) { 8408 // ARC forbids the implicit conversion of object pointers to 'void *', 8409 // so these types are not compatible. 8410 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8411 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8412 LHS = RHS = true; 8413 return QualType(); 8414 } 8415 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8416 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8417 QualType destPointee 8418 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8419 QualType destType = Context.getPointerType(destPointee); 8420 // Add qualifiers if necessary. 8421 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8422 // Promote to void*. 8423 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8424 return destType; 8425 } 8426 return QualType(); 8427 } 8428 8429 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8430 /// ParenRange in parentheses. 8431 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8432 const PartialDiagnostic &Note, 8433 SourceRange ParenRange) { 8434 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8435 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8436 EndLoc.isValid()) { 8437 Self.Diag(Loc, Note) 8438 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8439 << FixItHint::CreateInsertion(EndLoc, ")"); 8440 } else { 8441 // We can't display the parentheses, so just show the bare note. 8442 Self.Diag(Loc, Note) << ParenRange; 8443 } 8444 } 8445 8446 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8447 return BinaryOperator::isAdditiveOp(Opc) || 8448 BinaryOperator::isMultiplicativeOp(Opc) || 8449 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8450 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8451 // not any of the logical operators. Bitwise-xor is commonly used as a 8452 // logical-xor because there is no logical-xor operator. The logical 8453 // operators, including uses of xor, have a high false positive rate for 8454 // precedence warnings. 8455 } 8456 8457 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8458 /// expression, either using a built-in or overloaded operator, 8459 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8460 /// expression. 8461 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8462 Expr **RHSExprs) { 8463 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8464 E = E->IgnoreImpCasts(); 8465 E = E->IgnoreConversionOperatorSingleStep(); 8466 E = E->IgnoreImpCasts(); 8467 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8468 E = MTE->getSubExpr(); 8469 E = E->IgnoreImpCasts(); 8470 } 8471 8472 // Built-in binary operator. 8473 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8474 if (IsArithmeticOp(OP->getOpcode())) { 8475 *Opcode = OP->getOpcode(); 8476 *RHSExprs = OP->getRHS(); 8477 return true; 8478 } 8479 } 8480 8481 // Overloaded operator. 8482 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8483 if (Call->getNumArgs() != 2) 8484 return false; 8485 8486 // Make sure this is really a binary operator that is safe to pass into 8487 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8488 OverloadedOperatorKind OO = Call->getOperator(); 8489 if (OO < OO_Plus || OO > OO_Arrow || 8490 OO == OO_PlusPlus || OO == OO_MinusMinus) 8491 return false; 8492 8493 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8494 if (IsArithmeticOp(OpKind)) { 8495 *Opcode = OpKind; 8496 *RHSExprs = Call->getArg(1); 8497 return true; 8498 } 8499 } 8500 8501 return false; 8502 } 8503 8504 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8505 /// or is a logical expression such as (x==y) which has int type, but is 8506 /// commonly interpreted as boolean. 8507 static bool ExprLooksBoolean(Expr *E) { 8508 E = E->IgnoreParenImpCasts(); 8509 8510 if (E->getType()->isBooleanType()) 8511 return true; 8512 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8513 return OP->isComparisonOp() || OP->isLogicalOp(); 8514 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8515 return OP->getOpcode() == UO_LNot; 8516 if (E->getType()->isPointerType()) 8517 return true; 8518 // FIXME: What about overloaded operator calls returning "unspecified boolean 8519 // type"s (commonly pointer-to-members)? 8520 8521 return false; 8522 } 8523 8524 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8525 /// and binary operator are mixed in a way that suggests the programmer assumed 8526 /// the conditional operator has higher precedence, for example: 8527 /// "int x = a + someBinaryCondition ? 1 : 2". 8528 static void DiagnoseConditionalPrecedence(Sema &Self, 8529 SourceLocation OpLoc, 8530 Expr *Condition, 8531 Expr *LHSExpr, 8532 Expr *RHSExpr) { 8533 BinaryOperatorKind CondOpcode; 8534 Expr *CondRHS; 8535 8536 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8537 return; 8538 if (!ExprLooksBoolean(CondRHS)) 8539 return; 8540 8541 // The condition is an arithmetic binary expression, with a right- 8542 // hand side that looks boolean, so warn. 8543 8544 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8545 ? diag::warn_precedence_bitwise_conditional 8546 : diag::warn_precedence_conditional; 8547 8548 Self.Diag(OpLoc, DiagID) 8549 << Condition->getSourceRange() 8550 << BinaryOperator::getOpcodeStr(CondOpcode); 8551 8552 SuggestParentheses( 8553 Self, OpLoc, 8554 Self.PDiag(diag::note_precedence_silence) 8555 << BinaryOperator::getOpcodeStr(CondOpcode), 8556 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8557 8558 SuggestParentheses(Self, OpLoc, 8559 Self.PDiag(diag::note_precedence_conditional_first), 8560 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8561 } 8562 8563 /// Compute the nullability of a conditional expression. 8564 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8565 QualType LHSTy, QualType RHSTy, 8566 ASTContext &Ctx) { 8567 if (!ResTy->isAnyPointerType()) 8568 return ResTy; 8569 8570 auto GetNullability = [&Ctx](QualType Ty) { 8571 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8572 if (Kind) { 8573 // For our purposes, treat _Nullable_result as _Nullable. 8574 if (*Kind == NullabilityKind::NullableResult) 8575 return NullabilityKind::Nullable; 8576 return *Kind; 8577 } 8578 return NullabilityKind::Unspecified; 8579 }; 8580 8581 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8582 NullabilityKind MergedKind; 8583 8584 // Compute nullability of a binary conditional expression. 8585 if (IsBin) { 8586 if (LHSKind == NullabilityKind::NonNull) 8587 MergedKind = NullabilityKind::NonNull; 8588 else 8589 MergedKind = RHSKind; 8590 // Compute nullability of a normal conditional expression. 8591 } else { 8592 if (LHSKind == NullabilityKind::Nullable || 8593 RHSKind == NullabilityKind::Nullable) 8594 MergedKind = NullabilityKind::Nullable; 8595 else if (LHSKind == NullabilityKind::NonNull) 8596 MergedKind = RHSKind; 8597 else if (RHSKind == NullabilityKind::NonNull) 8598 MergedKind = LHSKind; 8599 else 8600 MergedKind = NullabilityKind::Unspecified; 8601 } 8602 8603 // Return if ResTy already has the correct nullability. 8604 if (GetNullability(ResTy) == MergedKind) 8605 return ResTy; 8606 8607 // Strip all nullability from ResTy. 8608 while (ResTy->getNullability(Ctx)) 8609 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8610 8611 // Create a new AttributedType with the new nullability kind. 8612 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8613 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8614 } 8615 8616 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8617 /// in the case of a the GNU conditional expr extension. 8618 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8619 SourceLocation ColonLoc, 8620 Expr *CondExpr, Expr *LHSExpr, 8621 Expr *RHSExpr) { 8622 if (!Context.isDependenceAllowed()) { 8623 // C cannot handle TypoExpr nodes in the condition because it 8624 // doesn't handle dependent types properly, so make sure any TypoExprs have 8625 // been dealt with before checking the operands. 8626 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8627 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8628 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8629 8630 if (!CondResult.isUsable()) 8631 return ExprError(); 8632 8633 if (LHSExpr) { 8634 if (!LHSResult.isUsable()) 8635 return ExprError(); 8636 } 8637 8638 if (!RHSResult.isUsable()) 8639 return ExprError(); 8640 8641 CondExpr = CondResult.get(); 8642 LHSExpr = LHSResult.get(); 8643 RHSExpr = RHSResult.get(); 8644 } 8645 8646 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8647 // was the condition. 8648 OpaqueValueExpr *opaqueValue = nullptr; 8649 Expr *commonExpr = nullptr; 8650 if (!LHSExpr) { 8651 commonExpr = CondExpr; 8652 // Lower out placeholder types first. This is important so that we don't 8653 // try to capture a placeholder. This happens in few cases in C++; such 8654 // as Objective-C++'s dictionary subscripting syntax. 8655 if (commonExpr->hasPlaceholderType()) { 8656 ExprResult result = CheckPlaceholderExpr(commonExpr); 8657 if (!result.isUsable()) return ExprError(); 8658 commonExpr = result.get(); 8659 } 8660 // We usually want to apply unary conversions *before* saving, except 8661 // in the special case of a C++ l-value conditional. 8662 if (!(getLangOpts().CPlusPlus 8663 && !commonExpr->isTypeDependent() 8664 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8665 && commonExpr->isGLValue() 8666 && commonExpr->isOrdinaryOrBitFieldObject() 8667 && RHSExpr->isOrdinaryOrBitFieldObject() 8668 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8669 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8670 if (commonRes.isInvalid()) 8671 return ExprError(); 8672 commonExpr = commonRes.get(); 8673 } 8674 8675 // If the common expression is a class or array prvalue, materialize it 8676 // so that we can safely refer to it multiple times. 8677 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8678 commonExpr->getType()->isArrayType())) { 8679 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8680 if (MatExpr.isInvalid()) 8681 return ExprError(); 8682 commonExpr = MatExpr.get(); 8683 } 8684 8685 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8686 commonExpr->getType(), 8687 commonExpr->getValueKind(), 8688 commonExpr->getObjectKind(), 8689 commonExpr); 8690 LHSExpr = CondExpr = opaqueValue; 8691 } 8692 8693 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8694 ExprValueKind VK = VK_RValue; 8695 ExprObjectKind OK = OK_Ordinary; 8696 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8697 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8698 VK, OK, QuestionLoc); 8699 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8700 RHS.isInvalid()) 8701 return ExprError(); 8702 8703 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8704 RHS.get()); 8705 8706 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8707 8708 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8709 Context); 8710 8711 if (!commonExpr) 8712 return new (Context) 8713 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8714 RHS.get(), result, VK, OK); 8715 8716 return new (Context) BinaryConditionalOperator( 8717 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8718 ColonLoc, result, VK, OK); 8719 } 8720 8721 // Check if we have a conversion between incompatible cmse function pointer 8722 // types, that is, a conversion between a function pointer with the 8723 // cmse_nonsecure_call attribute and one without. 8724 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8725 QualType ToType) { 8726 if (const auto *ToFn = 8727 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8728 if (const auto *FromFn = 8729 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8730 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8731 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8732 8733 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8734 } 8735 } 8736 return false; 8737 } 8738 8739 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8740 // being closely modeled after the C99 spec:-). The odd characteristic of this 8741 // routine is it effectively iqnores the qualifiers on the top level pointee. 8742 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8743 // FIXME: add a couple examples in this comment. 8744 static Sema::AssignConvertType 8745 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8746 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8747 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8748 8749 // get the "pointed to" type (ignoring qualifiers at the top level) 8750 const Type *lhptee, *rhptee; 8751 Qualifiers lhq, rhq; 8752 std::tie(lhptee, lhq) = 8753 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8754 std::tie(rhptee, rhq) = 8755 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8756 8757 Sema::AssignConvertType ConvTy = Sema::Compatible; 8758 8759 // C99 6.5.16.1p1: This following citation is common to constraints 8760 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8761 // qualifiers of the type *pointed to* by the right; 8762 8763 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8764 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8765 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8766 // Ignore lifetime for further calculation. 8767 lhq.removeObjCLifetime(); 8768 rhq.removeObjCLifetime(); 8769 } 8770 8771 if (!lhq.compatiblyIncludes(rhq)) { 8772 // Treat address-space mismatches as fatal. 8773 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8774 return Sema::IncompatiblePointerDiscardsQualifiers; 8775 8776 // It's okay to add or remove GC or lifetime qualifiers when converting to 8777 // and from void*. 8778 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8779 .compatiblyIncludes( 8780 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8781 && (lhptee->isVoidType() || rhptee->isVoidType())) 8782 ; // keep old 8783 8784 // Treat lifetime mismatches as fatal. 8785 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8786 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8787 8788 // For GCC/MS compatibility, other qualifier mismatches are treated 8789 // as still compatible in C. 8790 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8791 } 8792 8793 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8794 // incomplete type and the other is a pointer to a qualified or unqualified 8795 // version of void... 8796 if (lhptee->isVoidType()) { 8797 if (rhptee->isIncompleteOrObjectType()) 8798 return ConvTy; 8799 8800 // As an extension, we allow cast to/from void* to function pointer. 8801 assert(rhptee->isFunctionType()); 8802 return Sema::FunctionVoidPointer; 8803 } 8804 8805 if (rhptee->isVoidType()) { 8806 if (lhptee->isIncompleteOrObjectType()) 8807 return ConvTy; 8808 8809 // As an extension, we allow cast to/from void* to function pointer. 8810 assert(lhptee->isFunctionType()); 8811 return Sema::FunctionVoidPointer; 8812 } 8813 8814 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8815 // unqualified versions of compatible types, ... 8816 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8817 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8818 // Check if the pointee types are compatible ignoring the sign. 8819 // We explicitly check for char so that we catch "char" vs 8820 // "unsigned char" on systems where "char" is unsigned. 8821 if (lhptee->isCharType()) 8822 ltrans = S.Context.UnsignedCharTy; 8823 else if (lhptee->hasSignedIntegerRepresentation()) 8824 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8825 8826 if (rhptee->isCharType()) 8827 rtrans = S.Context.UnsignedCharTy; 8828 else if (rhptee->hasSignedIntegerRepresentation()) 8829 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8830 8831 if (ltrans == rtrans) { 8832 // Types are compatible ignoring the sign. Qualifier incompatibility 8833 // takes priority over sign incompatibility because the sign 8834 // warning can be disabled. 8835 if (ConvTy != Sema::Compatible) 8836 return ConvTy; 8837 8838 return Sema::IncompatiblePointerSign; 8839 } 8840 8841 // If we are a multi-level pointer, it's possible that our issue is simply 8842 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8843 // the eventual target type is the same and the pointers have the same 8844 // level of indirection, this must be the issue. 8845 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8846 do { 8847 std::tie(lhptee, lhq) = 8848 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8849 std::tie(rhptee, rhq) = 8850 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8851 8852 // Inconsistent address spaces at this point is invalid, even if the 8853 // address spaces would be compatible. 8854 // FIXME: This doesn't catch address space mismatches for pointers of 8855 // different nesting levels, like: 8856 // __local int *** a; 8857 // int ** b = a; 8858 // It's not clear how to actually determine when such pointers are 8859 // invalidly incompatible. 8860 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8861 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8862 8863 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8864 8865 if (lhptee == rhptee) 8866 return Sema::IncompatibleNestedPointerQualifiers; 8867 } 8868 8869 // General pointer incompatibility takes priority over qualifiers. 8870 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8871 return Sema::IncompatibleFunctionPointer; 8872 return Sema::IncompatiblePointer; 8873 } 8874 if (!S.getLangOpts().CPlusPlus && 8875 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8876 return Sema::IncompatibleFunctionPointer; 8877 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8878 return Sema::IncompatibleFunctionPointer; 8879 return ConvTy; 8880 } 8881 8882 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8883 /// block pointer types are compatible or whether a block and normal pointer 8884 /// are compatible. It is more restrict than comparing two function pointer 8885 // types. 8886 static Sema::AssignConvertType 8887 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8888 QualType RHSType) { 8889 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8890 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8891 8892 QualType lhptee, rhptee; 8893 8894 // get the "pointed to" type (ignoring qualifiers at the top level) 8895 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8896 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8897 8898 // In C++, the types have to match exactly. 8899 if (S.getLangOpts().CPlusPlus) 8900 return Sema::IncompatibleBlockPointer; 8901 8902 Sema::AssignConvertType ConvTy = Sema::Compatible; 8903 8904 // For blocks we enforce that qualifiers are identical. 8905 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8906 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8907 if (S.getLangOpts().OpenCL) { 8908 LQuals.removeAddressSpace(); 8909 RQuals.removeAddressSpace(); 8910 } 8911 if (LQuals != RQuals) 8912 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8913 8914 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8915 // assignment. 8916 // The current behavior is similar to C++ lambdas. A block might be 8917 // assigned to a variable iff its return type and parameters are compatible 8918 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8919 // an assignment. Presumably it should behave in way that a function pointer 8920 // assignment does in C, so for each parameter and return type: 8921 // * CVR and address space of LHS should be a superset of CVR and address 8922 // space of RHS. 8923 // * unqualified types should be compatible. 8924 if (S.getLangOpts().OpenCL) { 8925 if (!S.Context.typesAreBlockPointerCompatible( 8926 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8927 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8928 return Sema::IncompatibleBlockPointer; 8929 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8930 return Sema::IncompatibleBlockPointer; 8931 8932 return ConvTy; 8933 } 8934 8935 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8936 /// for assignment compatibility. 8937 static Sema::AssignConvertType 8938 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8939 QualType RHSType) { 8940 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8941 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8942 8943 if (LHSType->isObjCBuiltinType()) { 8944 // Class is not compatible with ObjC object pointers. 8945 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8946 !RHSType->isObjCQualifiedClassType()) 8947 return Sema::IncompatiblePointer; 8948 return Sema::Compatible; 8949 } 8950 if (RHSType->isObjCBuiltinType()) { 8951 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8952 !LHSType->isObjCQualifiedClassType()) 8953 return Sema::IncompatiblePointer; 8954 return Sema::Compatible; 8955 } 8956 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8957 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8958 8959 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8960 // make an exception for id<P> 8961 !LHSType->isObjCQualifiedIdType()) 8962 return Sema::CompatiblePointerDiscardsQualifiers; 8963 8964 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8965 return Sema::Compatible; 8966 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8967 return Sema::IncompatibleObjCQualifiedId; 8968 return Sema::IncompatiblePointer; 8969 } 8970 8971 Sema::AssignConvertType 8972 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8973 QualType LHSType, QualType RHSType) { 8974 // Fake up an opaque expression. We don't actually care about what 8975 // cast operations are required, so if CheckAssignmentConstraints 8976 // adds casts to this they'll be wasted, but fortunately that doesn't 8977 // usually happen on valid code. 8978 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8979 ExprResult RHSPtr = &RHSExpr; 8980 CastKind K; 8981 8982 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8983 } 8984 8985 /// This helper function returns true if QT is a vector type that has element 8986 /// type ElementType. 8987 static bool isVector(QualType QT, QualType ElementType) { 8988 if (const VectorType *VT = QT->getAs<VectorType>()) 8989 return VT->getElementType().getCanonicalType() == ElementType; 8990 return false; 8991 } 8992 8993 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8994 /// has code to accommodate several GCC extensions when type checking 8995 /// pointers. Here are some objectionable examples that GCC considers warnings: 8996 /// 8997 /// int a, *pint; 8998 /// short *pshort; 8999 /// struct foo *pfoo; 9000 /// 9001 /// pint = pshort; // warning: assignment from incompatible pointer type 9002 /// a = pint; // warning: assignment makes integer from pointer without a cast 9003 /// pint = a; // warning: assignment makes pointer from integer without a cast 9004 /// pint = pfoo; // warning: assignment from incompatible pointer type 9005 /// 9006 /// As a result, the code for dealing with pointers is more complex than the 9007 /// C99 spec dictates. 9008 /// 9009 /// Sets 'Kind' for any result kind except Incompatible. 9010 Sema::AssignConvertType 9011 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9012 CastKind &Kind, bool ConvertRHS) { 9013 QualType RHSType = RHS.get()->getType(); 9014 QualType OrigLHSType = LHSType; 9015 9016 // Get canonical types. We're not formatting these types, just comparing 9017 // them. 9018 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9019 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9020 9021 // Common case: no conversion required. 9022 if (LHSType == RHSType) { 9023 Kind = CK_NoOp; 9024 return Compatible; 9025 } 9026 9027 // If we have an atomic type, try a non-atomic assignment, then just add an 9028 // atomic qualification step. 9029 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9030 Sema::AssignConvertType result = 9031 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9032 if (result != Compatible) 9033 return result; 9034 if (Kind != CK_NoOp && ConvertRHS) 9035 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9036 Kind = CK_NonAtomicToAtomic; 9037 return Compatible; 9038 } 9039 9040 // If the left-hand side is a reference type, then we are in a 9041 // (rare!) case where we've allowed the use of references in C, 9042 // e.g., as a parameter type in a built-in function. In this case, 9043 // just make sure that the type referenced is compatible with the 9044 // right-hand side type. The caller is responsible for adjusting 9045 // LHSType so that the resulting expression does not have reference 9046 // type. 9047 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9048 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9049 Kind = CK_LValueBitCast; 9050 return Compatible; 9051 } 9052 return Incompatible; 9053 } 9054 9055 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9056 // to the same ExtVector type. 9057 if (LHSType->isExtVectorType()) { 9058 if (RHSType->isExtVectorType()) 9059 return Incompatible; 9060 if (RHSType->isArithmeticType()) { 9061 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9062 if (ConvertRHS) 9063 RHS = prepareVectorSplat(LHSType, RHS.get()); 9064 Kind = CK_VectorSplat; 9065 return Compatible; 9066 } 9067 } 9068 9069 // Conversions to or from vector type. 9070 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9071 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9072 // Allow assignments of an AltiVec vector type to an equivalent GCC 9073 // vector type and vice versa 9074 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9075 Kind = CK_BitCast; 9076 return Compatible; 9077 } 9078 9079 // If we are allowing lax vector conversions, and LHS and RHS are both 9080 // vectors, the total size only needs to be the same. This is a bitcast; 9081 // no bits are changed but the result type is different. 9082 if (isLaxVectorConversion(RHSType, LHSType)) { 9083 Kind = CK_BitCast; 9084 return IncompatibleVectors; 9085 } 9086 } 9087 9088 // When the RHS comes from another lax conversion (e.g. binops between 9089 // scalars and vectors) the result is canonicalized as a vector. When the 9090 // LHS is also a vector, the lax is allowed by the condition above. Handle 9091 // the case where LHS is a scalar. 9092 if (LHSType->isScalarType()) { 9093 const VectorType *VecType = RHSType->getAs<VectorType>(); 9094 if (VecType && VecType->getNumElements() == 1 && 9095 isLaxVectorConversion(RHSType, LHSType)) { 9096 ExprResult *VecExpr = &RHS; 9097 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9098 Kind = CK_BitCast; 9099 return Compatible; 9100 } 9101 } 9102 9103 // Allow assignments between fixed-length and sizeless SVE vectors. 9104 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9105 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9106 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9107 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9108 Kind = CK_BitCast; 9109 return Compatible; 9110 } 9111 9112 return Incompatible; 9113 } 9114 9115 // Diagnose attempts to convert between __float128 and long double where 9116 // such conversions currently can't be handled. 9117 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9118 return Incompatible; 9119 9120 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9121 // discards the imaginary part. 9122 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9123 !LHSType->getAs<ComplexType>()) 9124 return Incompatible; 9125 9126 // Arithmetic conversions. 9127 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9128 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9129 if (ConvertRHS) 9130 Kind = PrepareScalarCast(RHS, LHSType); 9131 return Compatible; 9132 } 9133 9134 // Conversions to normal pointers. 9135 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9136 // U* -> T* 9137 if (isa<PointerType>(RHSType)) { 9138 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9139 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9140 if (AddrSpaceL != AddrSpaceR) 9141 Kind = CK_AddressSpaceConversion; 9142 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9143 Kind = CK_NoOp; 9144 else 9145 Kind = CK_BitCast; 9146 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9147 } 9148 9149 // int -> T* 9150 if (RHSType->isIntegerType()) { 9151 Kind = CK_IntegralToPointer; // FIXME: null? 9152 return IntToPointer; 9153 } 9154 9155 // C pointers are not compatible with ObjC object pointers, 9156 // with two exceptions: 9157 if (isa<ObjCObjectPointerType>(RHSType)) { 9158 // - conversions to void* 9159 if (LHSPointer->getPointeeType()->isVoidType()) { 9160 Kind = CK_BitCast; 9161 return Compatible; 9162 } 9163 9164 // - conversions from 'Class' to the redefinition type 9165 if (RHSType->isObjCClassType() && 9166 Context.hasSameType(LHSType, 9167 Context.getObjCClassRedefinitionType())) { 9168 Kind = CK_BitCast; 9169 return Compatible; 9170 } 9171 9172 Kind = CK_BitCast; 9173 return IncompatiblePointer; 9174 } 9175 9176 // U^ -> void* 9177 if (RHSType->getAs<BlockPointerType>()) { 9178 if (LHSPointer->getPointeeType()->isVoidType()) { 9179 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9180 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9181 ->getPointeeType() 9182 .getAddressSpace(); 9183 Kind = 9184 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9185 return Compatible; 9186 } 9187 } 9188 9189 return Incompatible; 9190 } 9191 9192 // Conversions to block pointers. 9193 if (isa<BlockPointerType>(LHSType)) { 9194 // U^ -> T^ 9195 if (RHSType->isBlockPointerType()) { 9196 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9197 ->getPointeeType() 9198 .getAddressSpace(); 9199 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9200 ->getPointeeType() 9201 .getAddressSpace(); 9202 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9203 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9204 } 9205 9206 // int or null -> T^ 9207 if (RHSType->isIntegerType()) { 9208 Kind = CK_IntegralToPointer; // FIXME: null 9209 return IntToBlockPointer; 9210 } 9211 9212 // id -> T^ 9213 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9214 Kind = CK_AnyPointerToBlockPointerCast; 9215 return Compatible; 9216 } 9217 9218 // void* -> T^ 9219 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9220 if (RHSPT->getPointeeType()->isVoidType()) { 9221 Kind = CK_AnyPointerToBlockPointerCast; 9222 return Compatible; 9223 } 9224 9225 return Incompatible; 9226 } 9227 9228 // Conversions to Objective-C pointers. 9229 if (isa<ObjCObjectPointerType>(LHSType)) { 9230 // A* -> B* 9231 if (RHSType->isObjCObjectPointerType()) { 9232 Kind = CK_BitCast; 9233 Sema::AssignConvertType result = 9234 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9235 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9236 result == Compatible && 9237 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9238 result = IncompatibleObjCWeakRef; 9239 return result; 9240 } 9241 9242 // int or null -> A* 9243 if (RHSType->isIntegerType()) { 9244 Kind = CK_IntegralToPointer; // FIXME: null 9245 return IntToPointer; 9246 } 9247 9248 // In general, C pointers are not compatible with ObjC object pointers, 9249 // with two exceptions: 9250 if (isa<PointerType>(RHSType)) { 9251 Kind = CK_CPointerToObjCPointerCast; 9252 9253 // - conversions from 'void*' 9254 if (RHSType->isVoidPointerType()) { 9255 return Compatible; 9256 } 9257 9258 // - conversions to 'Class' from its redefinition type 9259 if (LHSType->isObjCClassType() && 9260 Context.hasSameType(RHSType, 9261 Context.getObjCClassRedefinitionType())) { 9262 return Compatible; 9263 } 9264 9265 return IncompatiblePointer; 9266 } 9267 9268 // Only under strict condition T^ is compatible with an Objective-C pointer. 9269 if (RHSType->isBlockPointerType() && 9270 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9271 if (ConvertRHS) 9272 maybeExtendBlockObject(RHS); 9273 Kind = CK_BlockPointerToObjCPointerCast; 9274 return Compatible; 9275 } 9276 9277 return Incompatible; 9278 } 9279 9280 // Conversions from pointers that are not covered by the above. 9281 if (isa<PointerType>(RHSType)) { 9282 // T* -> _Bool 9283 if (LHSType == Context.BoolTy) { 9284 Kind = CK_PointerToBoolean; 9285 return Compatible; 9286 } 9287 9288 // T* -> int 9289 if (LHSType->isIntegerType()) { 9290 Kind = CK_PointerToIntegral; 9291 return PointerToInt; 9292 } 9293 9294 return Incompatible; 9295 } 9296 9297 // Conversions from Objective-C pointers that are not covered by the above. 9298 if (isa<ObjCObjectPointerType>(RHSType)) { 9299 // T* -> _Bool 9300 if (LHSType == Context.BoolTy) { 9301 Kind = CK_PointerToBoolean; 9302 return Compatible; 9303 } 9304 9305 // T* -> int 9306 if (LHSType->isIntegerType()) { 9307 Kind = CK_PointerToIntegral; 9308 return PointerToInt; 9309 } 9310 9311 return Incompatible; 9312 } 9313 9314 // struct A -> struct B 9315 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9316 if (Context.typesAreCompatible(LHSType, RHSType)) { 9317 Kind = CK_NoOp; 9318 return Compatible; 9319 } 9320 } 9321 9322 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9323 Kind = CK_IntToOCLSampler; 9324 return Compatible; 9325 } 9326 9327 return Incompatible; 9328 } 9329 9330 /// Constructs a transparent union from an expression that is 9331 /// used to initialize the transparent union. 9332 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9333 ExprResult &EResult, QualType UnionType, 9334 FieldDecl *Field) { 9335 // Build an initializer list that designates the appropriate member 9336 // of the transparent union. 9337 Expr *E = EResult.get(); 9338 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9339 E, SourceLocation()); 9340 Initializer->setType(UnionType); 9341 Initializer->setInitializedFieldInUnion(Field); 9342 9343 // Build a compound literal constructing a value of the transparent 9344 // union type from this initializer list. 9345 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9346 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9347 VK_RValue, Initializer, false); 9348 } 9349 9350 Sema::AssignConvertType 9351 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9352 ExprResult &RHS) { 9353 QualType RHSType = RHS.get()->getType(); 9354 9355 // If the ArgType is a Union type, we want to handle a potential 9356 // transparent_union GCC extension. 9357 const RecordType *UT = ArgType->getAsUnionType(); 9358 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9359 return Incompatible; 9360 9361 // The field to initialize within the transparent union. 9362 RecordDecl *UD = UT->getDecl(); 9363 FieldDecl *InitField = nullptr; 9364 // It's compatible if the expression matches any of the fields. 9365 for (auto *it : UD->fields()) { 9366 if (it->getType()->isPointerType()) { 9367 // If the transparent union contains a pointer type, we allow: 9368 // 1) void pointer 9369 // 2) null pointer constant 9370 if (RHSType->isPointerType()) 9371 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9372 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9373 InitField = it; 9374 break; 9375 } 9376 9377 if (RHS.get()->isNullPointerConstant(Context, 9378 Expr::NPC_ValueDependentIsNull)) { 9379 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9380 CK_NullToPointer); 9381 InitField = it; 9382 break; 9383 } 9384 } 9385 9386 CastKind Kind; 9387 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9388 == Compatible) { 9389 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9390 InitField = it; 9391 break; 9392 } 9393 } 9394 9395 if (!InitField) 9396 return Incompatible; 9397 9398 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9399 return Compatible; 9400 } 9401 9402 Sema::AssignConvertType 9403 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9404 bool Diagnose, 9405 bool DiagnoseCFAudited, 9406 bool ConvertRHS) { 9407 // We need to be able to tell the caller whether we diagnosed a problem, if 9408 // they ask us to issue diagnostics. 9409 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9410 9411 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9412 // we can't avoid *all* modifications at the moment, so we need some somewhere 9413 // to put the updated value. 9414 ExprResult LocalRHS = CallerRHS; 9415 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9416 9417 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9418 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9419 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9420 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9421 Diag(RHS.get()->getExprLoc(), 9422 diag::warn_noderef_to_dereferenceable_pointer) 9423 << RHS.get()->getSourceRange(); 9424 } 9425 } 9426 } 9427 9428 if (getLangOpts().CPlusPlus) { 9429 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9430 // C++ 5.17p3: If the left operand is not of class type, the 9431 // expression is implicitly converted (C++ 4) to the 9432 // cv-unqualified type of the left operand. 9433 QualType RHSType = RHS.get()->getType(); 9434 if (Diagnose) { 9435 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9436 AA_Assigning); 9437 } else { 9438 ImplicitConversionSequence ICS = 9439 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9440 /*SuppressUserConversions=*/false, 9441 AllowedExplicit::None, 9442 /*InOverloadResolution=*/false, 9443 /*CStyle=*/false, 9444 /*AllowObjCWritebackConversion=*/false); 9445 if (ICS.isFailure()) 9446 return Incompatible; 9447 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9448 ICS, AA_Assigning); 9449 } 9450 if (RHS.isInvalid()) 9451 return Incompatible; 9452 Sema::AssignConvertType result = Compatible; 9453 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9454 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9455 result = IncompatibleObjCWeakRef; 9456 return result; 9457 } 9458 9459 // FIXME: Currently, we fall through and treat C++ classes like C 9460 // structures. 9461 // FIXME: We also fall through for atomics; not sure what should 9462 // happen there, though. 9463 } else if (RHS.get()->getType() == Context.OverloadTy) { 9464 // As a set of extensions to C, we support overloading on functions. These 9465 // functions need to be resolved here. 9466 DeclAccessPair DAP; 9467 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9468 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9469 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9470 else 9471 return Incompatible; 9472 } 9473 9474 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9475 // a null pointer constant. 9476 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9477 LHSType->isBlockPointerType()) && 9478 RHS.get()->isNullPointerConstant(Context, 9479 Expr::NPC_ValueDependentIsNull)) { 9480 if (Diagnose || ConvertRHS) { 9481 CastKind Kind; 9482 CXXCastPath Path; 9483 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9484 /*IgnoreBaseAccess=*/false, Diagnose); 9485 if (ConvertRHS) 9486 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9487 } 9488 return Compatible; 9489 } 9490 9491 // OpenCL queue_t type assignment. 9492 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9493 Context, Expr::NPC_ValueDependentIsNull)) { 9494 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9495 return Compatible; 9496 } 9497 9498 // This check seems unnatural, however it is necessary to ensure the proper 9499 // conversion of functions/arrays. If the conversion were done for all 9500 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9501 // expressions that suppress this implicit conversion (&, sizeof). 9502 // 9503 // Suppress this for references: C++ 8.5.3p5. 9504 if (!LHSType->isReferenceType()) { 9505 // FIXME: We potentially allocate here even if ConvertRHS is false. 9506 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9507 if (RHS.isInvalid()) 9508 return Incompatible; 9509 } 9510 CastKind Kind; 9511 Sema::AssignConvertType result = 9512 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9513 9514 // C99 6.5.16.1p2: The value of the right operand is converted to the 9515 // type of the assignment expression. 9516 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9517 // so that we can use references in built-in functions even in C. 9518 // The getNonReferenceType() call makes sure that the resulting expression 9519 // does not have reference type. 9520 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9521 QualType Ty = LHSType.getNonLValueExprType(Context); 9522 Expr *E = RHS.get(); 9523 9524 // Check for various Objective-C errors. If we are not reporting 9525 // diagnostics and just checking for errors, e.g., during overload 9526 // resolution, return Incompatible to indicate the failure. 9527 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9528 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9529 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9530 if (!Diagnose) 9531 return Incompatible; 9532 } 9533 if (getLangOpts().ObjC && 9534 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9535 E->getType(), E, Diagnose) || 9536 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9537 if (!Diagnose) 9538 return Incompatible; 9539 // Replace the expression with a corrected version and continue so we 9540 // can find further errors. 9541 RHS = E; 9542 return Compatible; 9543 } 9544 9545 if (ConvertRHS) 9546 RHS = ImpCastExprToType(E, Ty, Kind); 9547 } 9548 9549 return result; 9550 } 9551 9552 namespace { 9553 /// The original operand to an operator, prior to the application of the usual 9554 /// arithmetic conversions and converting the arguments of a builtin operator 9555 /// candidate. 9556 struct OriginalOperand { 9557 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9558 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9559 Op = MTE->getSubExpr(); 9560 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9561 Op = BTE->getSubExpr(); 9562 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9563 Orig = ICE->getSubExprAsWritten(); 9564 Conversion = ICE->getConversionFunction(); 9565 } 9566 } 9567 9568 QualType getType() const { return Orig->getType(); } 9569 9570 Expr *Orig; 9571 NamedDecl *Conversion; 9572 }; 9573 } 9574 9575 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9576 ExprResult &RHS) { 9577 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9578 9579 Diag(Loc, diag::err_typecheck_invalid_operands) 9580 << OrigLHS.getType() << OrigRHS.getType() 9581 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9582 9583 // If a user-defined conversion was applied to either of the operands prior 9584 // to applying the built-in operator rules, tell the user about it. 9585 if (OrigLHS.Conversion) { 9586 Diag(OrigLHS.Conversion->getLocation(), 9587 diag::note_typecheck_invalid_operands_converted) 9588 << 0 << LHS.get()->getType(); 9589 } 9590 if (OrigRHS.Conversion) { 9591 Diag(OrigRHS.Conversion->getLocation(), 9592 diag::note_typecheck_invalid_operands_converted) 9593 << 1 << RHS.get()->getType(); 9594 } 9595 9596 return QualType(); 9597 } 9598 9599 // Diagnose cases where a scalar was implicitly converted to a vector and 9600 // diagnose the underlying types. Otherwise, diagnose the error 9601 // as invalid vector logical operands for non-C++ cases. 9602 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9603 ExprResult &RHS) { 9604 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9605 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9606 9607 bool LHSNatVec = LHSType->isVectorType(); 9608 bool RHSNatVec = RHSType->isVectorType(); 9609 9610 if (!(LHSNatVec && RHSNatVec)) { 9611 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9612 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9613 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9614 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9615 << Vector->getSourceRange(); 9616 return QualType(); 9617 } 9618 9619 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9620 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9621 << RHS.get()->getSourceRange(); 9622 9623 return QualType(); 9624 } 9625 9626 /// Try to convert a value of non-vector type to a vector type by converting 9627 /// the type to the element type of the vector and then performing a splat. 9628 /// If the language is OpenCL, we only use conversions that promote scalar 9629 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9630 /// for float->int. 9631 /// 9632 /// OpenCL V2.0 6.2.6.p2: 9633 /// An error shall occur if any scalar operand type has greater rank 9634 /// than the type of the vector element. 9635 /// 9636 /// \param scalar - if non-null, actually perform the conversions 9637 /// \return true if the operation fails (but without diagnosing the failure) 9638 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9639 QualType scalarTy, 9640 QualType vectorEltTy, 9641 QualType vectorTy, 9642 unsigned &DiagID) { 9643 // The conversion to apply to the scalar before splatting it, 9644 // if necessary. 9645 CastKind scalarCast = CK_NoOp; 9646 9647 if (vectorEltTy->isIntegralType(S.Context)) { 9648 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9649 (scalarTy->isIntegerType() && 9650 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9651 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9652 return true; 9653 } 9654 if (!scalarTy->isIntegralType(S.Context)) 9655 return true; 9656 scalarCast = CK_IntegralCast; 9657 } else if (vectorEltTy->isRealFloatingType()) { 9658 if (scalarTy->isRealFloatingType()) { 9659 if (S.getLangOpts().OpenCL && 9660 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9661 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9662 return true; 9663 } 9664 scalarCast = CK_FloatingCast; 9665 } 9666 else if (scalarTy->isIntegralType(S.Context)) 9667 scalarCast = CK_IntegralToFloating; 9668 else 9669 return true; 9670 } else { 9671 return true; 9672 } 9673 9674 // Adjust scalar if desired. 9675 if (scalar) { 9676 if (scalarCast != CK_NoOp) 9677 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9678 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9679 } 9680 return false; 9681 } 9682 9683 /// Convert vector E to a vector with the same number of elements but different 9684 /// element type. 9685 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9686 const auto *VecTy = E->getType()->getAs<VectorType>(); 9687 assert(VecTy && "Expression E must be a vector"); 9688 QualType NewVecTy = S.Context.getVectorType(ElementType, 9689 VecTy->getNumElements(), 9690 VecTy->getVectorKind()); 9691 9692 // Look through the implicit cast. Return the subexpression if its type is 9693 // NewVecTy. 9694 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9695 if (ICE->getSubExpr()->getType() == NewVecTy) 9696 return ICE->getSubExpr(); 9697 9698 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9699 return S.ImpCastExprToType(E, NewVecTy, Cast); 9700 } 9701 9702 /// Test if a (constant) integer Int can be casted to another integer type 9703 /// IntTy without losing precision. 9704 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9705 QualType OtherIntTy) { 9706 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9707 9708 // Reject cases where the value of the Int is unknown as that would 9709 // possibly cause truncation, but accept cases where the scalar can be 9710 // demoted without loss of precision. 9711 Expr::EvalResult EVResult; 9712 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9713 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9714 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9715 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9716 9717 if (CstInt) { 9718 // If the scalar is constant and is of a higher order and has more active 9719 // bits that the vector element type, reject it. 9720 llvm::APSInt Result = EVResult.Val.getInt(); 9721 unsigned NumBits = IntSigned 9722 ? (Result.isNegative() ? Result.getMinSignedBits() 9723 : Result.getActiveBits()) 9724 : Result.getActiveBits(); 9725 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9726 return true; 9727 9728 // If the signedness of the scalar type and the vector element type 9729 // differs and the number of bits is greater than that of the vector 9730 // element reject it. 9731 return (IntSigned != OtherIntSigned && 9732 NumBits > S.Context.getIntWidth(OtherIntTy)); 9733 } 9734 9735 // Reject cases where the value of the scalar is not constant and it's 9736 // order is greater than that of the vector element type. 9737 return (Order < 0); 9738 } 9739 9740 /// Test if a (constant) integer Int can be casted to floating point type 9741 /// FloatTy without losing precision. 9742 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9743 QualType FloatTy) { 9744 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9745 9746 // Determine if the integer constant can be expressed as a floating point 9747 // number of the appropriate type. 9748 Expr::EvalResult EVResult; 9749 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9750 9751 uint64_t Bits = 0; 9752 if (CstInt) { 9753 // Reject constants that would be truncated if they were converted to 9754 // the floating point type. Test by simple to/from conversion. 9755 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9756 // could be avoided if there was a convertFromAPInt method 9757 // which could signal back if implicit truncation occurred. 9758 llvm::APSInt Result = EVResult.Val.getInt(); 9759 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9760 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9761 llvm::APFloat::rmTowardZero); 9762 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9763 !IntTy->hasSignedIntegerRepresentation()); 9764 bool Ignored = false; 9765 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9766 &Ignored); 9767 if (Result != ConvertBack) 9768 return true; 9769 } else { 9770 // Reject types that cannot be fully encoded into the mantissa of 9771 // the float. 9772 Bits = S.Context.getTypeSize(IntTy); 9773 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9774 S.Context.getFloatTypeSemantics(FloatTy)); 9775 if (Bits > FloatPrec) 9776 return true; 9777 } 9778 9779 return false; 9780 } 9781 9782 /// Attempt to convert and splat Scalar into a vector whose types matches 9783 /// Vector following GCC conversion rules. The rule is that implicit 9784 /// conversion can occur when Scalar can be casted to match Vector's element 9785 /// type without causing truncation of Scalar. 9786 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9787 ExprResult *Vector) { 9788 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9789 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9790 const VectorType *VT = VectorTy->getAs<VectorType>(); 9791 9792 assert(!isa<ExtVectorType>(VT) && 9793 "ExtVectorTypes should not be handled here!"); 9794 9795 QualType VectorEltTy = VT->getElementType(); 9796 9797 // Reject cases where the vector element type or the scalar element type are 9798 // not integral or floating point types. 9799 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9800 return true; 9801 9802 // The conversion to apply to the scalar before splatting it, 9803 // if necessary. 9804 CastKind ScalarCast = CK_NoOp; 9805 9806 // Accept cases where the vector elements are integers and the scalar is 9807 // an integer. 9808 // FIXME: Notionally if the scalar was a floating point value with a precise 9809 // integral representation, we could cast it to an appropriate integer 9810 // type and then perform the rest of the checks here. GCC will perform 9811 // this conversion in some cases as determined by the input language. 9812 // We should accept it on a language independent basis. 9813 if (VectorEltTy->isIntegralType(S.Context) && 9814 ScalarTy->isIntegralType(S.Context) && 9815 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9816 9817 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9818 return true; 9819 9820 ScalarCast = CK_IntegralCast; 9821 } else if (VectorEltTy->isIntegralType(S.Context) && 9822 ScalarTy->isRealFloatingType()) { 9823 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9824 ScalarCast = CK_FloatingToIntegral; 9825 else 9826 return true; 9827 } else if (VectorEltTy->isRealFloatingType()) { 9828 if (ScalarTy->isRealFloatingType()) { 9829 9830 // Reject cases where the scalar type is not a constant and has a higher 9831 // Order than the vector element type. 9832 llvm::APFloat Result(0.0); 9833 9834 // Determine whether this is a constant scalar. In the event that the 9835 // value is dependent (and thus cannot be evaluated by the constant 9836 // evaluator), skip the evaluation. This will then diagnose once the 9837 // expression is instantiated. 9838 bool CstScalar = Scalar->get()->isValueDependent() || 9839 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9840 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9841 if (!CstScalar && Order < 0) 9842 return true; 9843 9844 // If the scalar cannot be safely casted to the vector element type, 9845 // reject it. 9846 if (CstScalar) { 9847 bool Truncated = false; 9848 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9849 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9850 if (Truncated) 9851 return true; 9852 } 9853 9854 ScalarCast = CK_FloatingCast; 9855 } else if (ScalarTy->isIntegralType(S.Context)) { 9856 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9857 return true; 9858 9859 ScalarCast = CK_IntegralToFloating; 9860 } else 9861 return true; 9862 } else if (ScalarTy->isEnumeralType()) 9863 return true; 9864 9865 // Adjust scalar if desired. 9866 if (Scalar) { 9867 if (ScalarCast != CK_NoOp) 9868 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9869 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9870 } 9871 return false; 9872 } 9873 9874 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9875 SourceLocation Loc, bool IsCompAssign, 9876 bool AllowBothBool, 9877 bool AllowBoolConversions) { 9878 if (!IsCompAssign) { 9879 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9880 if (LHS.isInvalid()) 9881 return QualType(); 9882 } 9883 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9884 if (RHS.isInvalid()) 9885 return QualType(); 9886 9887 // For conversion purposes, we ignore any qualifiers. 9888 // For example, "const float" and "float" are equivalent. 9889 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9890 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9891 9892 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9893 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9894 assert(LHSVecType || RHSVecType); 9895 9896 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9897 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9898 return InvalidOperands(Loc, LHS, RHS); 9899 9900 // AltiVec-style "vector bool op vector bool" combinations are allowed 9901 // for some operators but not others. 9902 if (!AllowBothBool && 9903 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9904 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9905 return InvalidOperands(Loc, LHS, RHS); 9906 9907 // If the vector types are identical, return. 9908 if (Context.hasSameType(LHSType, RHSType)) 9909 return LHSType; 9910 9911 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9912 if (LHSVecType && RHSVecType && 9913 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9914 if (isa<ExtVectorType>(LHSVecType)) { 9915 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9916 return LHSType; 9917 } 9918 9919 if (!IsCompAssign) 9920 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9921 return RHSType; 9922 } 9923 9924 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9925 // can be mixed, with the result being the non-bool type. The non-bool 9926 // operand must have integer element type. 9927 if (AllowBoolConversions && LHSVecType && RHSVecType && 9928 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9929 (Context.getTypeSize(LHSVecType->getElementType()) == 9930 Context.getTypeSize(RHSVecType->getElementType()))) { 9931 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9932 LHSVecType->getElementType()->isIntegerType() && 9933 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9934 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9935 return LHSType; 9936 } 9937 if (!IsCompAssign && 9938 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9939 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9940 RHSVecType->getElementType()->isIntegerType()) { 9941 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9942 return RHSType; 9943 } 9944 } 9945 9946 // Expressions containing fixed-length and sizeless SVE vectors are invalid 9947 // since the ambiguity can affect the ABI. 9948 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9949 const VectorType *VecType = SecondType->getAs<VectorType>(); 9950 return FirstType->isSizelessBuiltinType() && VecType && 9951 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9952 VecType->getVectorKind() == 9953 VectorType::SveFixedLengthPredicateVector); 9954 }; 9955 9956 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9957 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 9958 return QualType(); 9959 } 9960 9961 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 9962 // since the ambiguity can affect the ABI. 9963 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 9964 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 9965 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 9966 9967 if (FirstVecType && SecondVecType) 9968 return FirstVecType->getVectorKind() == VectorType::GenericVector && 9969 (SecondVecType->getVectorKind() == 9970 VectorType::SveFixedLengthDataVector || 9971 SecondVecType->getVectorKind() == 9972 VectorType::SveFixedLengthPredicateVector); 9973 9974 return FirstType->isSizelessBuiltinType() && SecondVecType && 9975 SecondVecType->getVectorKind() == VectorType::GenericVector; 9976 }; 9977 9978 if (IsSveGnuConversion(LHSType, RHSType) || 9979 IsSveGnuConversion(RHSType, LHSType)) { 9980 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 9981 return QualType(); 9982 } 9983 9984 // If there's a vector type and a scalar, try to convert the scalar to 9985 // the vector element type and splat. 9986 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9987 if (!RHSVecType) { 9988 if (isa<ExtVectorType>(LHSVecType)) { 9989 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9990 LHSVecType->getElementType(), LHSType, 9991 DiagID)) 9992 return LHSType; 9993 } else { 9994 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9995 return LHSType; 9996 } 9997 } 9998 if (!LHSVecType) { 9999 if (isa<ExtVectorType>(RHSVecType)) { 10000 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10001 LHSType, RHSVecType->getElementType(), 10002 RHSType, DiagID)) 10003 return RHSType; 10004 } else { 10005 if (LHS.get()->getValueKind() == VK_LValue || 10006 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10007 return RHSType; 10008 } 10009 } 10010 10011 // FIXME: The code below also handles conversion between vectors and 10012 // non-scalars, we should break this down into fine grained specific checks 10013 // and emit proper diagnostics. 10014 QualType VecType = LHSVecType ? LHSType : RHSType; 10015 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10016 QualType OtherType = LHSVecType ? RHSType : LHSType; 10017 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10018 if (isLaxVectorConversion(OtherType, VecType)) { 10019 // If we're allowing lax vector conversions, only the total (data) size 10020 // needs to be the same. For non compound assignment, if one of the types is 10021 // scalar, the result is always the vector type. 10022 if (!IsCompAssign) { 10023 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10024 return VecType; 10025 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10026 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10027 // type. Note that this is already done by non-compound assignments in 10028 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10029 // <1 x T> -> T. The result is also a vector type. 10030 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10031 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10032 ExprResult *RHSExpr = &RHS; 10033 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10034 return VecType; 10035 } 10036 } 10037 10038 // Okay, the expression is invalid. 10039 10040 // If there's a non-vector, non-real operand, diagnose that. 10041 if ((!RHSVecType && !RHSType->isRealType()) || 10042 (!LHSVecType && !LHSType->isRealType())) { 10043 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10044 << LHSType << RHSType 10045 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10046 return QualType(); 10047 } 10048 10049 // OpenCL V1.1 6.2.6.p1: 10050 // If the operands are of more than one vector type, then an error shall 10051 // occur. Implicit conversions between vector types are not permitted, per 10052 // section 6.2.1. 10053 if (getLangOpts().OpenCL && 10054 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10055 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10056 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10057 << RHSType; 10058 return QualType(); 10059 } 10060 10061 10062 // If there is a vector type that is not a ExtVector and a scalar, we reach 10063 // this point if scalar could not be converted to the vector's element type 10064 // without truncation. 10065 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10066 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10067 QualType Scalar = LHSVecType ? RHSType : LHSType; 10068 QualType Vector = LHSVecType ? LHSType : RHSType; 10069 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10070 Diag(Loc, 10071 diag::err_typecheck_vector_not_convertable_implict_truncation) 10072 << ScalarOrVector << Scalar << Vector; 10073 10074 return QualType(); 10075 } 10076 10077 // Otherwise, use the generic diagnostic. 10078 Diag(Loc, DiagID) 10079 << LHSType << RHSType 10080 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10081 return QualType(); 10082 } 10083 10084 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10085 // expression. These are mainly cases where the null pointer is used as an 10086 // integer instead of a pointer. 10087 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10088 SourceLocation Loc, bool IsCompare) { 10089 // The canonical way to check for a GNU null is with isNullPointerConstant, 10090 // but we use a bit of a hack here for speed; this is a relatively 10091 // hot path, and isNullPointerConstant is slow. 10092 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10093 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10094 10095 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10096 10097 // Avoid analyzing cases where the result will either be invalid (and 10098 // diagnosed as such) or entirely valid and not something to warn about. 10099 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10100 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10101 return; 10102 10103 // Comparison operations would not make sense with a null pointer no matter 10104 // what the other expression is. 10105 if (!IsCompare) { 10106 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10107 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10108 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10109 return; 10110 } 10111 10112 // The rest of the operations only make sense with a null pointer 10113 // if the other expression is a pointer. 10114 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10115 NonNullType->canDecayToPointerType()) 10116 return; 10117 10118 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10119 << LHSNull /* LHS is NULL */ << NonNullType 10120 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10121 } 10122 10123 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10124 SourceLocation Loc) { 10125 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10126 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10127 if (!LUE || !RUE) 10128 return; 10129 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10130 RUE->getKind() != UETT_SizeOf) 10131 return; 10132 10133 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10134 QualType LHSTy = LHSArg->getType(); 10135 QualType RHSTy; 10136 10137 if (RUE->isArgumentType()) 10138 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10139 else 10140 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10141 10142 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10143 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10144 return; 10145 10146 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10147 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10148 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10149 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10150 << LHSArgDecl; 10151 } 10152 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10153 QualType ArrayElemTy = ArrayTy->getElementType(); 10154 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10155 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10156 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10157 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10158 return; 10159 S.Diag(Loc, diag::warn_division_sizeof_array) 10160 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10161 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10162 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10163 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10164 << LHSArgDecl; 10165 } 10166 10167 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10168 } 10169 } 10170 10171 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10172 ExprResult &RHS, 10173 SourceLocation Loc, bool IsDiv) { 10174 // Check for division/remainder by zero. 10175 Expr::EvalResult RHSValue; 10176 if (!RHS.get()->isValueDependent() && 10177 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10178 RHSValue.Val.getInt() == 0) 10179 S.DiagRuntimeBehavior(Loc, RHS.get(), 10180 S.PDiag(diag::warn_remainder_division_by_zero) 10181 << IsDiv << RHS.get()->getSourceRange()); 10182 } 10183 10184 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10185 SourceLocation Loc, 10186 bool IsCompAssign, bool IsDiv) { 10187 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10188 10189 if (LHS.get()->getType()->isVectorType() || 10190 RHS.get()->getType()->isVectorType()) 10191 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10192 /*AllowBothBool*/getLangOpts().AltiVec, 10193 /*AllowBoolConversions*/false); 10194 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10195 RHS.get()->getType()->isConstantMatrixType())) 10196 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10197 10198 QualType compType = UsualArithmeticConversions( 10199 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10200 if (LHS.isInvalid() || RHS.isInvalid()) 10201 return QualType(); 10202 10203 10204 if (compType.isNull() || !compType->isArithmeticType()) 10205 return InvalidOperands(Loc, LHS, RHS); 10206 if (IsDiv) { 10207 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10208 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10209 } 10210 return compType; 10211 } 10212 10213 QualType Sema::CheckRemainderOperands( 10214 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10215 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10216 10217 if (LHS.get()->getType()->isVectorType() || 10218 RHS.get()->getType()->isVectorType()) { 10219 if (LHS.get()->getType()->hasIntegerRepresentation() && 10220 RHS.get()->getType()->hasIntegerRepresentation()) 10221 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10222 /*AllowBothBool*/getLangOpts().AltiVec, 10223 /*AllowBoolConversions*/false); 10224 return InvalidOperands(Loc, LHS, RHS); 10225 } 10226 10227 QualType compType = UsualArithmeticConversions( 10228 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10229 if (LHS.isInvalid() || RHS.isInvalid()) 10230 return QualType(); 10231 10232 if (compType.isNull() || !compType->isIntegerType()) 10233 return InvalidOperands(Loc, LHS, RHS); 10234 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10235 return compType; 10236 } 10237 10238 /// Diagnose invalid arithmetic on two void pointers. 10239 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10240 Expr *LHSExpr, Expr *RHSExpr) { 10241 S.Diag(Loc, S.getLangOpts().CPlusPlus 10242 ? diag::err_typecheck_pointer_arith_void_type 10243 : diag::ext_gnu_void_ptr) 10244 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10245 << RHSExpr->getSourceRange(); 10246 } 10247 10248 /// Diagnose invalid arithmetic on a void pointer. 10249 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10250 Expr *Pointer) { 10251 S.Diag(Loc, S.getLangOpts().CPlusPlus 10252 ? diag::err_typecheck_pointer_arith_void_type 10253 : diag::ext_gnu_void_ptr) 10254 << 0 /* one pointer */ << Pointer->getSourceRange(); 10255 } 10256 10257 /// Diagnose invalid arithmetic on a null pointer. 10258 /// 10259 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10260 /// idiom, which we recognize as a GNU extension. 10261 /// 10262 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10263 Expr *Pointer, bool IsGNUIdiom) { 10264 if (IsGNUIdiom) 10265 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10266 << Pointer->getSourceRange(); 10267 else 10268 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10269 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10270 } 10271 10272 /// Diagnose invalid arithmetic on two function pointers. 10273 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10274 Expr *LHS, Expr *RHS) { 10275 assert(LHS->getType()->isAnyPointerType()); 10276 assert(RHS->getType()->isAnyPointerType()); 10277 S.Diag(Loc, S.getLangOpts().CPlusPlus 10278 ? diag::err_typecheck_pointer_arith_function_type 10279 : diag::ext_gnu_ptr_func_arith) 10280 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10281 // We only show the second type if it differs from the first. 10282 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10283 RHS->getType()) 10284 << RHS->getType()->getPointeeType() 10285 << LHS->getSourceRange() << RHS->getSourceRange(); 10286 } 10287 10288 /// Diagnose invalid arithmetic on a function pointer. 10289 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10290 Expr *Pointer) { 10291 assert(Pointer->getType()->isAnyPointerType()); 10292 S.Diag(Loc, S.getLangOpts().CPlusPlus 10293 ? diag::err_typecheck_pointer_arith_function_type 10294 : diag::ext_gnu_ptr_func_arith) 10295 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10296 << 0 /* one pointer, so only one type */ 10297 << Pointer->getSourceRange(); 10298 } 10299 10300 /// Emit error if Operand is incomplete pointer type 10301 /// 10302 /// \returns True if pointer has incomplete type 10303 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10304 Expr *Operand) { 10305 QualType ResType = Operand->getType(); 10306 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10307 ResType = ResAtomicType->getValueType(); 10308 10309 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10310 QualType PointeeTy = ResType->getPointeeType(); 10311 return S.RequireCompleteSizedType( 10312 Loc, PointeeTy, 10313 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10314 Operand->getSourceRange()); 10315 } 10316 10317 /// Check the validity of an arithmetic pointer operand. 10318 /// 10319 /// If the operand has pointer type, this code will check for pointer types 10320 /// which are invalid in arithmetic operations. These will be diagnosed 10321 /// appropriately, including whether or not the use is supported as an 10322 /// extension. 10323 /// 10324 /// \returns True when the operand is valid to use (even if as an extension). 10325 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10326 Expr *Operand) { 10327 QualType ResType = Operand->getType(); 10328 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10329 ResType = ResAtomicType->getValueType(); 10330 10331 if (!ResType->isAnyPointerType()) return true; 10332 10333 QualType PointeeTy = ResType->getPointeeType(); 10334 if (PointeeTy->isVoidType()) { 10335 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10336 return !S.getLangOpts().CPlusPlus; 10337 } 10338 if (PointeeTy->isFunctionType()) { 10339 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10340 return !S.getLangOpts().CPlusPlus; 10341 } 10342 10343 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10344 10345 return true; 10346 } 10347 10348 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10349 /// operands. 10350 /// 10351 /// This routine will diagnose any invalid arithmetic on pointer operands much 10352 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10353 /// for emitting a single diagnostic even for operations where both LHS and RHS 10354 /// are (potentially problematic) pointers. 10355 /// 10356 /// \returns True when the operand is valid to use (even if as an extension). 10357 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10358 Expr *LHSExpr, Expr *RHSExpr) { 10359 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10360 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10361 if (!isLHSPointer && !isRHSPointer) return true; 10362 10363 QualType LHSPointeeTy, RHSPointeeTy; 10364 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10365 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10366 10367 // if both are pointers check if operation is valid wrt address spaces 10368 if (isLHSPointer && isRHSPointer) { 10369 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10370 S.Diag(Loc, 10371 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10372 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10373 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10374 return false; 10375 } 10376 } 10377 10378 // Check for arithmetic on pointers to incomplete types. 10379 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10380 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10381 if (isLHSVoidPtr || isRHSVoidPtr) { 10382 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10383 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10384 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10385 10386 return !S.getLangOpts().CPlusPlus; 10387 } 10388 10389 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10390 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10391 if (isLHSFuncPtr || isRHSFuncPtr) { 10392 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10393 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10394 RHSExpr); 10395 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10396 10397 return !S.getLangOpts().CPlusPlus; 10398 } 10399 10400 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10401 return false; 10402 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10403 return false; 10404 10405 return true; 10406 } 10407 10408 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10409 /// literal. 10410 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10411 Expr *LHSExpr, Expr *RHSExpr) { 10412 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10413 Expr* IndexExpr = RHSExpr; 10414 if (!StrExpr) { 10415 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10416 IndexExpr = LHSExpr; 10417 } 10418 10419 bool IsStringPlusInt = StrExpr && 10420 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10421 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10422 return; 10423 10424 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10425 Self.Diag(OpLoc, diag::warn_string_plus_int) 10426 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10427 10428 // Only print a fixit for "str" + int, not for int + "str". 10429 if (IndexExpr == RHSExpr) { 10430 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10431 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10432 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10433 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10434 << FixItHint::CreateInsertion(EndLoc, "]"); 10435 } else 10436 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10437 } 10438 10439 /// Emit a warning when adding a char literal to a string. 10440 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10441 Expr *LHSExpr, Expr *RHSExpr) { 10442 const Expr *StringRefExpr = LHSExpr; 10443 const CharacterLiteral *CharExpr = 10444 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10445 10446 if (!CharExpr) { 10447 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10448 StringRefExpr = RHSExpr; 10449 } 10450 10451 if (!CharExpr || !StringRefExpr) 10452 return; 10453 10454 const QualType StringType = StringRefExpr->getType(); 10455 10456 // Return if not a PointerType. 10457 if (!StringType->isAnyPointerType()) 10458 return; 10459 10460 // Return if not a CharacterType. 10461 if (!StringType->getPointeeType()->isAnyCharacterType()) 10462 return; 10463 10464 ASTContext &Ctx = Self.getASTContext(); 10465 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10466 10467 const QualType CharType = CharExpr->getType(); 10468 if (!CharType->isAnyCharacterType() && 10469 CharType->isIntegerType() && 10470 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10471 Self.Diag(OpLoc, diag::warn_string_plus_char) 10472 << DiagRange << Ctx.CharTy; 10473 } else { 10474 Self.Diag(OpLoc, diag::warn_string_plus_char) 10475 << DiagRange << CharExpr->getType(); 10476 } 10477 10478 // Only print a fixit for str + char, not for char + str. 10479 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10480 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10481 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10482 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10483 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10484 << FixItHint::CreateInsertion(EndLoc, "]"); 10485 } else { 10486 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10487 } 10488 } 10489 10490 /// Emit error when two pointers are incompatible. 10491 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10492 Expr *LHSExpr, Expr *RHSExpr) { 10493 assert(LHSExpr->getType()->isAnyPointerType()); 10494 assert(RHSExpr->getType()->isAnyPointerType()); 10495 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10496 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10497 << RHSExpr->getSourceRange(); 10498 } 10499 10500 // C99 6.5.6 10501 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10502 SourceLocation Loc, BinaryOperatorKind Opc, 10503 QualType* CompLHSTy) { 10504 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10505 10506 if (LHS.get()->getType()->isVectorType() || 10507 RHS.get()->getType()->isVectorType()) { 10508 QualType compType = CheckVectorOperands( 10509 LHS, RHS, Loc, CompLHSTy, 10510 /*AllowBothBool*/getLangOpts().AltiVec, 10511 /*AllowBoolConversions*/getLangOpts().ZVector); 10512 if (CompLHSTy) *CompLHSTy = compType; 10513 return compType; 10514 } 10515 10516 if (LHS.get()->getType()->isConstantMatrixType() || 10517 RHS.get()->getType()->isConstantMatrixType()) { 10518 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10519 } 10520 10521 QualType compType = UsualArithmeticConversions( 10522 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10523 if (LHS.isInvalid() || RHS.isInvalid()) 10524 return QualType(); 10525 10526 // Diagnose "string literal" '+' int and string '+' "char literal". 10527 if (Opc == BO_Add) { 10528 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10529 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10530 } 10531 10532 // handle the common case first (both operands are arithmetic). 10533 if (!compType.isNull() && compType->isArithmeticType()) { 10534 if (CompLHSTy) *CompLHSTy = compType; 10535 return compType; 10536 } 10537 10538 // Type-checking. Ultimately the pointer's going to be in PExp; 10539 // note that we bias towards the LHS being the pointer. 10540 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10541 10542 bool isObjCPointer; 10543 if (PExp->getType()->isPointerType()) { 10544 isObjCPointer = false; 10545 } else if (PExp->getType()->isObjCObjectPointerType()) { 10546 isObjCPointer = true; 10547 } else { 10548 std::swap(PExp, IExp); 10549 if (PExp->getType()->isPointerType()) { 10550 isObjCPointer = false; 10551 } else if (PExp->getType()->isObjCObjectPointerType()) { 10552 isObjCPointer = true; 10553 } else { 10554 return InvalidOperands(Loc, LHS, RHS); 10555 } 10556 } 10557 assert(PExp->getType()->isAnyPointerType()); 10558 10559 if (!IExp->getType()->isIntegerType()) 10560 return InvalidOperands(Loc, LHS, RHS); 10561 10562 // Adding to a null pointer results in undefined behavior. 10563 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10564 Context, Expr::NPC_ValueDependentIsNotNull)) { 10565 // In C++ adding zero to a null pointer is defined. 10566 Expr::EvalResult KnownVal; 10567 if (!getLangOpts().CPlusPlus || 10568 (!IExp->isValueDependent() && 10569 (!IExp->EvaluateAsInt(KnownVal, Context) || 10570 KnownVal.Val.getInt() != 0))) { 10571 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10572 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10573 Context, BO_Add, PExp, IExp); 10574 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10575 } 10576 } 10577 10578 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10579 return QualType(); 10580 10581 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10582 return QualType(); 10583 10584 // Check array bounds for pointer arithemtic 10585 CheckArrayAccess(PExp, IExp); 10586 10587 if (CompLHSTy) { 10588 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10589 if (LHSTy.isNull()) { 10590 LHSTy = LHS.get()->getType(); 10591 if (LHSTy->isPromotableIntegerType()) 10592 LHSTy = Context.getPromotedIntegerType(LHSTy); 10593 } 10594 *CompLHSTy = LHSTy; 10595 } 10596 10597 return PExp->getType(); 10598 } 10599 10600 // C99 6.5.6 10601 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10602 SourceLocation Loc, 10603 QualType* CompLHSTy) { 10604 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10605 10606 if (LHS.get()->getType()->isVectorType() || 10607 RHS.get()->getType()->isVectorType()) { 10608 QualType compType = CheckVectorOperands( 10609 LHS, RHS, Loc, CompLHSTy, 10610 /*AllowBothBool*/getLangOpts().AltiVec, 10611 /*AllowBoolConversions*/getLangOpts().ZVector); 10612 if (CompLHSTy) *CompLHSTy = compType; 10613 return compType; 10614 } 10615 10616 if (LHS.get()->getType()->isConstantMatrixType() || 10617 RHS.get()->getType()->isConstantMatrixType()) { 10618 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10619 } 10620 10621 QualType compType = UsualArithmeticConversions( 10622 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10623 if (LHS.isInvalid() || RHS.isInvalid()) 10624 return QualType(); 10625 10626 // Enforce type constraints: C99 6.5.6p3. 10627 10628 // Handle the common case first (both operands are arithmetic). 10629 if (!compType.isNull() && compType->isArithmeticType()) { 10630 if (CompLHSTy) *CompLHSTy = compType; 10631 return compType; 10632 } 10633 10634 // Either ptr - int or ptr - ptr. 10635 if (LHS.get()->getType()->isAnyPointerType()) { 10636 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10637 10638 // Diagnose bad cases where we step over interface counts. 10639 if (LHS.get()->getType()->isObjCObjectPointerType() && 10640 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10641 return QualType(); 10642 10643 // The result type of a pointer-int computation is the pointer type. 10644 if (RHS.get()->getType()->isIntegerType()) { 10645 // Subtracting from a null pointer should produce a warning. 10646 // The last argument to the diagnose call says this doesn't match the 10647 // GNU int-to-pointer idiom. 10648 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10649 Expr::NPC_ValueDependentIsNotNull)) { 10650 // In C++ adding zero to a null pointer is defined. 10651 Expr::EvalResult KnownVal; 10652 if (!getLangOpts().CPlusPlus || 10653 (!RHS.get()->isValueDependent() && 10654 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10655 KnownVal.Val.getInt() != 0))) { 10656 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10657 } 10658 } 10659 10660 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10661 return QualType(); 10662 10663 // Check array bounds for pointer arithemtic 10664 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10665 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10666 10667 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10668 return LHS.get()->getType(); 10669 } 10670 10671 // Handle pointer-pointer subtractions. 10672 if (const PointerType *RHSPTy 10673 = RHS.get()->getType()->getAs<PointerType>()) { 10674 QualType rpointee = RHSPTy->getPointeeType(); 10675 10676 if (getLangOpts().CPlusPlus) { 10677 // Pointee types must be the same: C++ [expr.add] 10678 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10679 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10680 } 10681 } else { 10682 // Pointee types must be compatible C99 6.5.6p3 10683 if (!Context.typesAreCompatible( 10684 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10685 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10686 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10687 return QualType(); 10688 } 10689 } 10690 10691 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10692 LHS.get(), RHS.get())) 10693 return QualType(); 10694 10695 // FIXME: Add warnings for nullptr - ptr. 10696 10697 // The pointee type may have zero size. As an extension, a structure or 10698 // union may have zero size or an array may have zero length. In this 10699 // case subtraction does not make sense. 10700 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10701 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10702 if (ElementSize.isZero()) { 10703 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10704 << rpointee.getUnqualifiedType() 10705 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10706 } 10707 } 10708 10709 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10710 return Context.getPointerDiffType(); 10711 } 10712 } 10713 10714 return InvalidOperands(Loc, LHS, RHS); 10715 } 10716 10717 static bool isScopedEnumerationType(QualType T) { 10718 if (const EnumType *ET = T->getAs<EnumType>()) 10719 return ET->getDecl()->isScoped(); 10720 return false; 10721 } 10722 10723 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10724 SourceLocation Loc, BinaryOperatorKind Opc, 10725 QualType LHSType) { 10726 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10727 // so skip remaining warnings as we don't want to modify values within Sema. 10728 if (S.getLangOpts().OpenCL) 10729 return; 10730 10731 // Check right/shifter operand 10732 Expr::EvalResult RHSResult; 10733 if (RHS.get()->isValueDependent() || 10734 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10735 return; 10736 llvm::APSInt Right = RHSResult.Val.getInt(); 10737 10738 if (Right.isNegative()) { 10739 S.DiagRuntimeBehavior(Loc, RHS.get(), 10740 S.PDiag(diag::warn_shift_negative) 10741 << RHS.get()->getSourceRange()); 10742 return; 10743 } 10744 10745 QualType LHSExprType = LHS.get()->getType(); 10746 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10747 if (LHSExprType->isExtIntType()) 10748 LeftSize = S.Context.getIntWidth(LHSExprType); 10749 else if (LHSExprType->isFixedPointType()) { 10750 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10751 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10752 } 10753 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10754 if (Right.uge(LeftBits)) { 10755 S.DiagRuntimeBehavior(Loc, RHS.get(), 10756 S.PDiag(diag::warn_shift_gt_typewidth) 10757 << RHS.get()->getSourceRange()); 10758 return; 10759 } 10760 10761 // FIXME: We probably need to handle fixed point types specially here. 10762 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10763 return; 10764 10765 // When left shifting an ICE which is signed, we can check for overflow which 10766 // according to C++ standards prior to C++2a has undefined behavior 10767 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10768 // more than the maximum value representable in the result type, so never 10769 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10770 // expression is still probably a bug.) 10771 Expr::EvalResult LHSResult; 10772 if (LHS.get()->isValueDependent() || 10773 LHSType->hasUnsignedIntegerRepresentation() || 10774 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10775 return; 10776 llvm::APSInt Left = LHSResult.Val.getInt(); 10777 10778 // If LHS does not have a signed type and non-negative value 10779 // then, the behavior is undefined before C++2a. Warn about it. 10780 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10781 !S.getLangOpts().CPlusPlus20) { 10782 S.DiagRuntimeBehavior(Loc, LHS.get(), 10783 S.PDiag(diag::warn_shift_lhs_negative) 10784 << LHS.get()->getSourceRange()); 10785 return; 10786 } 10787 10788 llvm::APInt ResultBits = 10789 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10790 if (LeftBits.uge(ResultBits)) 10791 return; 10792 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10793 Result = Result.shl(Right); 10794 10795 // Print the bit representation of the signed integer as an unsigned 10796 // hexadecimal number. 10797 SmallString<40> HexResult; 10798 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10799 10800 // If we are only missing a sign bit, this is less likely to result in actual 10801 // bugs -- if the result is cast back to an unsigned type, it will have the 10802 // expected value. Thus we place this behind a different warning that can be 10803 // turned off separately if needed. 10804 if (LeftBits == ResultBits - 1) { 10805 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10806 << HexResult << LHSType 10807 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10808 return; 10809 } 10810 10811 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10812 << HexResult.str() << Result.getMinSignedBits() << LHSType 10813 << Left.getBitWidth() << LHS.get()->getSourceRange() 10814 << RHS.get()->getSourceRange(); 10815 } 10816 10817 /// Return the resulting type when a vector is shifted 10818 /// by a scalar or vector shift amount. 10819 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10820 SourceLocation Loc, bool IsCompAssign) { 10821 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10822 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10823 !LHS.get()->getType()->isVectorType()) { 10824 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10825 << RHS.get()->getType() << LHS.get()->getType() 10826 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10827 return QualType(); 10828 } 10829 10830 if (!IsCompAssign) { 10831 LHS = S.UsualUnaryConversions(LHS.get()); 10832 if (LHS.isInvalid()) return QualType(); 10833 } 10834 10835 RHS = S.UsualUnaryConversions(RHS.get()); 10836 if (RHS.isInvalid()) return QualType(); 10837 10838 QualType LHSType = LHS.get()->getType(); 10839 // Note that LHS might be a scalar because the routine calls not only in 10840 // OpenCL case. 10841 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10842 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10843 10844 // Note that RHS might not be a vector. 10845 QualType RHSType = RHS.get()->getType(); 10846 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10847 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10848 10849 // The operands need to be integers. 10850 if (!LHSEleType->isIntegerType()) { 10851 S.Diag(Loc, diag::err_typecheck_expect_int) 10852 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10853 return QualType(); 10854 } 10855 10856 if (!RHSEleType->isIntegerType()) { 10857 S.Diag(Loc, diag::err_typecheck_expect_int) 10858 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10859 return QualType(); 10860 } 10861 10862 if (!LHSVecTy) { 10863 assert(RHSVecTy); 10864 if (IsCompAssign) 10865 return RHSType; 10866 if (LHSEleType != RHSEleType) { 10867 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10868 LHSEleType = RHSEleType; 10869 } 10870 QualType VecTy = 10871 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10872 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10873 LHSType = VecTy; 10874 } else if (RHSVecTy) { 10875 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10876 // are applied component-wise. So if RHS is a vector, then ensure 10877 // that the number of elements is the same as LHS... 10878 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10879 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10880 << LHS.get()->getType() << RHS.get()->getType() 10881 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10882 return QualType(); 10883 } 10884 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10885 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10886 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10887 if (LHSBT != RHSBT && 10888 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10889 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10890 << LHS.get()->getType() << RHS.get()->getType() 10891 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10892 } 10893 } 10894 } else { 10895 // ...else expand RHS to match the number of elements in LHS. 10896 QualType VecTy = 10897 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10898 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10899 } 10900 10901 return LHSType; 10902 } 10903 10904 // C99 6.5.7 10905 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10906 SourceLocation Loc, BinaryOperatorKind Opc, 10907 bool IsCompAssign) { 10908 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10909 10910 // Vector shifts promote their scalar inputs to vector type. 10911 if (LHS.get()->getType()->isVectorType() || 10912 RHS.get()->getType()->isVectorType()) { 10913 if (LangOpts.ZVector) { 10914 // The shift operators for the z vector extensions work basically 10915 // like general shifts, except that neither the LHS nor the RHS is 10916 // allowed to be a "vector bool". 10917 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10918 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10919 return InvalidOperands(Loc, LHS, RHS); 10920 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10921 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10922 return InvalidOperands(Loc, LHS, RHS); 10923 } 10924 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10925 } 10926 10927 // Shifts don't perform usual arithmetic conversions, they just do integer 10928 // promotions on each operand. C99 6.5.7p3 10929 10930 // For the LHS, do usual unary conversions, but then reset them away 10931 // if this is a compound assignment. 10932 ExprResult OldLHS = LHS; 10933 LHS = UsualUnaryConversions(LHS.get()); 10934 if (LHS.isInvalid()) 10935 return QualType(); 10936 QualType LHSType = LHS.get()->getType(); 10937 if (IsCompAssign) LHS = OldLHS; 10938 10939 // The RHS is simpler. 10940 RHS = UsualUnaryConversions(RHS.get()); 10941 if (RHS.isInvalid()) 10942 return QualType(); 10943 QualType RHSType = RHS.get()->getType(); 10944 10945 // C99 6.5.7p2: Each of the operands shall have integer type. 10946 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10947 if ((!LHSType->isFixedPointOrIntegerType() && 10948 !LHSType->hasIntegerRepresentation()) || 10949 !RHSType->hasIntegerRepresentation()) 10950 return InvalidOperands(Loc, LHS, RHS); 10951 10952 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10953 // hasIntegerRepresentation() above instead of this. 10954 if (isScopedEnumerationType(LHSType) || 10955 isScopedEnumerationType(RHSType)) { 10956 return InvalidOperands(Loc, LHS, RHS); 10957 } 10958 // Sanity-check shift operands 10959 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10960 10961 // "The type of the result is that of the promoted left operand." 10962 return LHSType; 10963 } 10964 10965 /// Diagnose bad pointer comparisons. 10966 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10967 ExprResult &LHS, ExprResult &RHS, 10968 bool IsError) { 10969 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10970 : diag::ext_typecheck_comparison_of_distinct_pointers) 10971 << LHS.get()->getType() << RHS.get()->getType() 10972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10973 } 10974 10975 /// Returns false if the pointers are converted to a composite type, 10976 /// true otherwise. 10977 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10978 ExprResult &LHS, ExprResult &RHS) { 10979 // C++ [expr.rel]p2: 10980 // [...] Pointer conversions (4.10) and qualification 10981 // conversions (4.4) are performed on pointer operands (or on 10982 // a pointer operand and a null pointer constant) to bring 10983 // them to their composite pointer type. [...] 10984 // 10985 // C++ [expr.eq]p1 uses the same notion for (in)equality 10986 // comparisons of pointers. 10987 10988 QualType LHSType = LHS.get()->getType(); 10989 QualType RHSType = RHS.get()->getType(); 10990 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10991 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10992 10993 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10994 if (T.isNull()) { 10995 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10996 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10997 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10998 else 10999 S.InvalidOperands(Loc, LHS, RHS); 11000 return true; 11001 } 11002 11003 return false; 11004 } 11005 11006 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11007 ExprResult &LHS, 11008 ExprResult &RHS, 11009 bool IsError) { 11010 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11011 : diag::ext_typecheck_comparison_of_fptr_to_void) 11012 << LHS.get()->getType() << RHS.get()->getType() 11013 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11014 } 11015 11016 static bool isObjCObjectLiteral(ExprResult &E) { 11017 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11018 case Stmt::ObjCArrayLiteralClass: 11019 case Stmt::ObjCDictionaryLiteralClass: 11020 case Stmt::ObjCStringLiteralClass: 11021 case Stmt::ObjCBoxedExprClass: 11022 return true; 11023 default: 11024 // Note that ObjCBoolLiteral is NOT an object literal! 11025 return false; 11026 } 11027 } 11028 11029 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11030 const ObjCObjectPointerType *Type = 11031 LHS->getType()->getAs<ObjCObjectPointerType>(); 11032 11033 // If this is not actually an Objective-C object, bail out. 11034 if (!Type) 11035 return false; 11036 11037 // Get the LHS object's interface type. 11038 QualType InterfaceType = Type->getPointeeType(); 11039 11040 // If the RHS isn't an Objective-C object, bail out. 11041 if (!RHS->getType()->isObjCObjectPointerType()) 11042 return false; 11043 11044 // Try to find the -isEqual: method. 11045 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11046 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11047 InterfaceType, 11048 /*IsInstance=*/true); 11049 if (!Method) { 11050 if (Type->isObjCIdType()) { 11051 // For 'id', just check the global pool. 11052 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11053 /*receiverId=*/true); 11054 } else { 11055 // Check protocols. 11056 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11057 /*IsInstance=*/true); 11058 } 11059 } 11060 11061 if (!Method) 11062 return false; 11063 11064 QualType T = Method->parameters()[0]->getType(); 11065 if (!T->isObjCObjectPointerType()) 11066 return false; 11067 11068 QualType R = Method->getReturnType(); 11069 if (!R->isScalarType()) 11070 return false; 11071 11072 return true; 11073 } 11074 11075 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11076 FromE = FromE->IgnoreParenImpCasts(); 11077 switch (FromE->getStmtClass()) { 11078 default: 11079 break; 11080 case Stmt::ObjCStringLiteralClass: 11081 // "string literal" 11082 return LK_String; 11083 case Stmt::ObjCArrayLiteralClass: 11084 // "array literal" 11085 return LK_Array; 11086 case Stmt::ObjCDictionaryLiteralClass: 11087 // "dictionary literal" 11088 return LK_Dictionary; 11089 case Stmt::BlockExprClass: 11090 return LK_Block; 11091 case Stmt::ObjCBoxedExprClass: { 11092 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11093 switch (Inner->getStmtClass()) { 11094 case Stmt::IntegerLiteralClass: 11095 case Stmt::FloatingLiteralClass: 11096 case Stmt::CharacterLiteralClass: 11097 case Stmt::ObjCBoolLiteralExprClass: 11098 case Stmt::CXXBoolLiteralExprClass: 11099 // "numeric literal" 11100 return LK_Numeric; 11101 case Stmt::ImplicitCastExprClass: { 11102 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11103 // Boolean literals can be represented by implicit casts. 11104 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11105 return LK_Numeric; 11106 break; 11107 } 11108 default: 11109 break; 11110 } 11111 return LK_Boxed; 11112 } 11113 } 11114 return LK_None; 11115 } 11116 11117 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11118 ExprResult &LHS, ExprResult &RHS, 11119 BinaryOperator::Opcode Opc){ 11120 Expr *Literal; 11121 Expr *Other; 11122 if (isObjCObjectLiteral(LHS)) { 11123 Literal = LHS.get(); 11124 Other = RHS.get(); 11125 } else { 11126 Literal = RHS.get(); 11127 Other = LHS.get(); 11128 } 11129 11130 // Don't warn on comparisons against nil. 11131 Other = Other->IgnoreParenCasts(); 11132 if (Other->isNullPointerConstant(S.getASTContext(), 11133 Expr::NPC_ValueDependentIsNotNull)) 11134 return; 11135 11136 // This should be kept in sync with warn_objc_literal_comparison. 11137 // LK_String should always be after the other literals, since it has its own 11138 // warning flag. 11139 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11140 assert(LiteralKind != Sema::LK_Block); 11141 if (LiteralKind == Sema::LK_None) { 11142 llvm_unreachable("Unknown Objective-C object literal kind"); 11143 } 11144 11145 if (LiteralKind == Sema::LK_String) 11146 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11147 << Literal->getSourceRange(); 11148 else 11149 S.Diag(Loc, diag::warn_objc_literal_comparison) 11150 << LiteralKind << Literal->getSourceRange(); 11151 11152 if (BinaryOperator::isEqualityOp(Opc) && 11153 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11154 SourceLocation Start = LHS.get()->getBeginLoc(); 11155 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11156 CharSourceRange OpRange = 11157 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11158 11159 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11160 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11161 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11162 << FixItHint::CreateInsertion(End, "]"); 11163 } 11164 } 11165 11166 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11167 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11168 ExprResult &RHS, SourceLocation Loc, 11169 BinaryOperatorKind Opc) { 11170 // Check that left hand side is !something. 11171 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11172 if (!UO || UO->getOpcode() != UO_LNot) return; 11173 11174 // Only check if the right hand side is non-bool arithmetic type. 11175 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11176 11177 // Make sure that the something in !something is not bool. 11178 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11179 if (SubExpr->isKnownToHaveBooleanValue()) return; 11180 11181 // Emit warning. 11182 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11183 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11184 << Loc << IsBitwiseOp; 11185 11186 // First note suggest !(x < y) 11187 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11188 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11189 FirstClose = S.getLocForEndOfToken(FirstClose); 11190 if (FirstClose.isInvalid()) 11191 FirstOpen = SourceLocation(); 11192 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11193 << IsBitwiseOp 11194 << FixItHint::CreateInsertion(FirstOpen, "(") 11195 << FixItHint::CreateInsertion(FirstClose, ")"); 11196 11197 // Second note suggests (!x) < y 11198 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11199 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11200 SecondClose = S.getLocForEndOfToken(SecondClose); 11201 if (SecondClose.isInvalid()) 11202 SecondOpen = SourceLocation(); 11203 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11204 << FixItHint::CreateInsertion(SecondOpen, "(") 11205 << FixItHint::CreateInsertion(SecondClose, ")"); 11206 } 11207 11208 // Returns true if E refers to a non-weak array. 11209 static bool checkForArray(const Expr *E) { 11210 const ValueDecl *D = nullptr; 11211 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11212 D = DR->getDecl(); 11213 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11214 if (Mem->isImplicitAccess()) 11215 D = Mem->getMemberDecl(); 11216 } 11217 if (!D) 11218 return false; 11219 return D->getType()->isArrayType() && !D->isWeak(); 11220 } 11221 11222 /// Diagnose some forms of syntactically-obvious tautological comparison. 11223 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11224 Expr *LHS, Expr *RHS, 11225 BinaryOperatorKind Opc) { 11226 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11227 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11228 11229 QualType LHSType = LHS->getType(); 11230 QualType RHSType = RHS->getType(); 11231 if (LHSType->hasFloatingRepresentation() || 11232 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11233 S.inTemplateInstantiation()) 11234 return; 11235 11236 // Comparisons between two array types are ill-formed for operator<=>, so 11237 // we shouldn't emit any additional warnings about it. 11238 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11239 return; 11240 11241 // For non-floating point types, check for self-comparisons of the form 11242 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11243 // often indicate logic errors in the program. 11244 // 11245 // NOTE: Don't warn about comparison expressions resulting from macro 11246 // expansion. Also don't warn about comparisons which are only self 11247 // comparisons within a template instantiation. The warnings should catch 11248 // obvious cases in the definition of the template anyways. The idea is to 11249 // warn when the typed comparison operator will always evaluate to the same 11250 // result. 11251 11252 // Used for indexing into %select in warn_comparison_always 11253 enum { 11254 AlwaysConstant, 11255 AlwaysTrue, 11256 AlwaysFalse, 11257 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11258 }; 11259 11260 // C++2a [depr.array.comp]: 11261 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11262 // operands of array type are deprecated. 11263 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11264 RHSStripped->getType()->isArrayType()) { 11265 S.Diag(Loc, diag::warn_depr_array_comparison) 11266 << LHS->getSourceRange() << RHS->getSourceRange() 11267 << LHSStripped->getType() << RHSStripped->getType(); 11268 // Carry on to produce the tautological comparison warning, if this 11269 // expression is potentially-evaluated, we can resolve the array to a 11270 // non-weak declaration, and so on. 11271 } 11272 11273 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11274 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11275 unsigned Result; 11276 switch (Opc) { 11277 case BO_EQ: 11278 case BO_LE: 11279 case BO_GE: 11280 Result = AlwaysTrue; 11281 break; 11282 case BO_NE: 11283 case BO_LT: 11284 case BO_GT: 11285 Result = AlwaysFalse; 11286 break; 11287 case BO_Cmp: 11288 Result = AlwaysEqual; 11289 break; 11290 default: 11291 Result = AlwaysConstant; 11292 break; 11293 } 11294 S.DiagRuntimeBehavior(Loc, nullptr, 11295 S.PDiag(diag::warn_comparison_always) 11296 << 0 /*self-comparison*/ 11297 << Result); 11298 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11299 // What is it always going to evaluate to? 11300 unsigned Result; 11301 switch (Opc) { 11302 case BO_EQ: // e.g. array1 == array2 11303 Result = AlwaysFalse; 11304 break; 11305 case BO_NE: // e.g. array1 != array2 11306 Result = AlwaysTrue; 11307 break; 11308 default: // e.g. array1 <= array2 11309 // The best we can say is 'a constant' 11310 Result = AlwaysConstant; 11311 break; 11312 } 11313 S.DiagRuntimeBehavior(Loc, nullptr, 11314 S.PDiag(diag::warn_comparison_always) 11315 << 1 /*array comparison*/ 11316 << Result); 11317 } 11318 } 11319 11320 if (isa<CastExpr>(LHSStripped)) 11321 LHSStripped = LHSStripped->IgnoreParenCasts(); 11322 if (isa<CastExpr>(RHSStripped)) 11323 RHSStripped = RHSStripped->IgnoreParenCasts(); 11324 11325 // Warn about comparisons against a string constant (unless the other 11326 // operand is null); the user probably wants string comparison function. 11327 Expr *LiteralString = nullptr; 11328 Expr *LiteralStringStripped = nullptr; 11329 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11330 !RHSStripped->isNullPointerConstant(S.Context, 11331 Expr::NPC_ValueDependentIsNull)) { 11332 LiteralString = LHS; 11333 LiteralStringStripped = LHSStripped; 11334 } else if ((isa<StringLiteral>(RHSStripped) || 11335 isa<ObjCEncodeExpr>(RHSStripped)) && 11336 !LHSStripped->isNullPointerConstant(S.Context, 11337 Expr::NPC_ValueDependentIsNull)) { 11338 LiteralString = RHS; 11339 LiteralStringStripped = RHSStripped; 11340 } 11341 11342 if (LiteralString) { 11343 S.DiagRuntimeBehavior(Loc, nullptr, 11344 S.PDiag(diag::warn_stringcompare) 11345 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11346 << LiteralString->getSourceRange()); 11347 } 11348 } 11349 11350 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11351 switch (CK) { 11352 default: { 11353 #ifndef NDEBUG 11354 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11355 << "\n"; 11356 #endif 11357 llvm_unreachable("unhandled cast kind"); 11358 } 11359 case CK_UserDefinedConversion: 11360 return ICK_Identity; 11361 case CK_LValueToRValue: 11362 return ICK_Lvalue_To_Rvalue; 11363 case CK_ArrayToPointerDecay: 11364 return ICK_Array_To_Pointer; 11365 case CK_FunctionToPointerDecay: 11366 return ICK_Function_To_Pointer; 11367 case CK_IntegralCast: 11368 return ICK_Integral_Conversion; 11369 case CK_FloatingCast: 11370 return ICK_Floating_Conversion; 11371 case CK_IntegralToFloating: 11372 case CK_FloatingToIntegral: 11373 return ICK_Floating_Integral; 11374 case CK_IntegralComplexCast: 11375 case CK_FloatingComplexCast: 11376 case CK_FloatingComplexToIntegralComplex: 11377 case CK_IntegralComplexToFloatingComplex: 11378 return ICK_Complex_Conversion; 11379 case CK_FloatingComplexToReal: 11380 case CK_FloatingRealToComplex: 11381 case CK_IntegralComplexToReal: 11382 case CK_IntegralRealToComplex: 11383 return ICK_Complex_Real; 11384 } 11385 } 11386 11387 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11388 QualType FromType, 11389 SourceLocation Loc) { 11390 // Check for a narrowing implicit conversion. 11391 StandardConversionSequence SCS; 11392 SCS.setAsIdentityConversion(); 11393 SCS.setToType(0, FromType); 11394 SCS.setToType(1, ToType); 11395 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11396 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11397 11398 APValue PreNarrowingValue; 11399 QualType PreNarrowingType; 11400 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11401 PreNarrowingType, 11402 /*IgnoreFloatToIntegralConversion*/ true)) { 11403 case NK_Dependent_Narrowing: 11404 // Implicit conversion to a narrower type, but the expression is 11405 // value-dependent so we can't tell whether it's actually narrowing. 11406 case NK_Not_Narrowing: 11407 return false; 11408 11409 case NK_Constant_Narrowing: 11410 // Implicit conversion to a narrower type, and the value is not a constant 11411 // expression. 11412 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11413 << /*Constant*/ 1 11414 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11415 return true; 11416 11417 case NK_Variable_Narrowing: 11418 // Implicit conversion to a narrower type, and the value is not a constant 11419 // expression. 11420 case NK_Type_Narrowing: 11421 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11422 << /*Constant*/ 0 << FromType << ToType; 11423 // TODO: It's not a constant expression, but what if the user intended it 11424 // to be? Can we produce notes to help them figure out why it isn't? 11425 return true; 11426 } 11427 llvm_unreachable("unhandled case in switch"); 11428 } 11429 11430 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11431 ExprResult &LHS, 11432 ExprResult &RHS, 11433 SourceLocation Loc) { 11434 QualType LHSType = LHS.get()->getType(); 11435 QualType RHSType = RHS.get()->getType(); 11436 // Dig out the original argument type and expression before implicit casts 11437 // were applied. These are the types/expressions we need to check the 11438 // [expr.spaceship] requirements against. 11439 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11440 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11441 QualType LHSStrippedType = LHSStripped.get()->getType(); 11442 QualType RHSStrippedType = RHSStripped.get()->getType(); 11443 11444 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11445 // other is not, the program is ill-formed. 11446 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11447 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11448 return QualType(); 11449 } 11450 11451 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11452 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11453 RHSStrippedType->isEnumeralType(); 11454 if (NumEnumArgs == 1) { 11455 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11456 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11457 if (OtherTy->hasFloatingRepresentation()) { 11458 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11459 return QualType(); 11460 } 11461 } 11462 if (NumEnumArgs == 2) { 11463 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11464 // type E, the operator yields the result of converting the operands 11465 // to the underlying type of E and applying <=> to the converted operands. 11466 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11467 S.InvalidOperands(Loc, LHS, RHS); 11468 return QualType(); 11469 } 11470 QualType IntType = 11471 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11472 assert(IntType->isArithmeticType()); 11473 11474 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11475 // promote the boolean type, and all other promotable integer types, to 11476 // avoid this. 11477 if (IntType->isPromotableIntegerType()) 11478 IntType = S.Context.getPromotedIntegerType(IntType); 11479 11480 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11481 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11482 LHSType = RHSType = IntType; 11483 } 11484 11485 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11486 // usual arithmetic conversions are applied to the operands. 11487 QualType Type = 11488 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11489 if (LHS.isInvalid() || RHS.isInvalid()) 11490 return QualType(); 11491 if (Type.isNull()) 11492 return S.InvalidOperands(Loc, LHS, RHS); 11493 11494 Optional<ComparisonCategoryType> CCT = 11495 getComparisonCategoryForBuiltinCmp(Type); 11496 if (!CCT) 11497 return S.InvalidOperands(Loc, LHS, RHS); 11498 11499 bool HasNarrowing = checkThreeWayNarrowingConversion( 11500 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11501 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11502 RHS.get()->getBeginLoc()); 11503 if (HasNarrowing) 11504 return QualType(); 11505 11506 assert(!Type.isNull() && "composite type for <=> has not been set"); 11507 11508 return S.CheckComparisonCategoryType( 11509 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11510 } 11511 11512 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11513 ExprResult &RHS, 11514 SourceLocation Loc, 11515 BinaryOperatorKind Opc) { 11516 if (Opc == BO_Cmp) 11517 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11518 11519 // C99 6.5.8p3 / C99 6.5.9p4 11520 QualType Type = 11521 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11522 if (LHS.isInvalid() || RHS.isInvalid()) 11523 return QualType(); 11524 if (Type.isNull()) 11525 return S.InvalidOperands(Loc, LHS, RHS); 11526 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11527 11528 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11529 return S.InvalidOperands(Loc, LHS, RHS); 11530 11531 // Check for comparisons of floating point operands using != and ==. 11532 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11533 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11534 11535 // The result of comparisons is 'bool' in C++, 'int' in C. 11536 return S.Context.getLogicalOperationType(); 11537 } 11538 11539 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11540 if (!NullE.get()->getType()->isAnyPointerType()) 11541 return; 11542 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11543 if (!E.get()->getType()->isAnyPointerType() && 11544 E.get()->isNullPointerConstant(Context, 11545 Expr::NPC_ValueDependentIsNotNull) == 11546 Expr::NPCK_ZeroExpression) { 11547 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11548 if (CL->getValue() == 0) 11549 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11550 << NullValue 11551 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11552 NullValue ? "NULL" : "(void *)0"); 11553 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11554 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11555 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11556 if (T == Context.CharTy) 11557 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11558 << NullValue 11559 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11560 NullValue ? "NULL" : "(void *)0"); 11561 } 11562 } 11563 } 11564 11565 // C99 6.5.8, C++ [expr.rel] 11566 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11567 SourceLocation Loc, 11568 BinaryOperatorKind Opc) { 11569 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11570 bool IsThreeWay = Opc == BO_Cmp; 11571 bool IsOrdered = IsRelational || IsThreeWay; 11572 auto IsAnyPointerType = [](ExprResult E) { 11573 QualType Ty = E.get()->getType(); 11574 return Ty->isPointerType() || Ty->isMemberPointerType(); 11575 }; 11576 11577 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11578 // type, array-to-pointer, ..., conversions are performed on both operands to 11579 // bring them to their composite type. 11580 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11581 // any type-related checks. 11582 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11583 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11584 if (LHS.isInvalid()) 11585 return QualType(); 11586 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11587 if (RHS.isInvalid()) 11588 return QualType(); 11589 } else { 11590 LHS = DefaultLvalueConversion(LHS.get()); 11591 if (LHS.isInvalid()) 11592 return QualType(); 11593 RHS = DefaultLvalueConversion(RHS.get()); 11594 if (RHS.isInvalid()) 11595 return QualType(); 11596 } 11597 11598 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11599 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11600 CheckPtrComparisonWithNullChar(LHS, RHS); 11601 CheckPtrComparisonWithNullChar(RHS, LHS); 11602 } 11603 11604 // Handle vector comparisons separately. 11605 if (LHS.get()->getType()->isVectorType() || 11606 RHS.get()->getType()->isVectorType()) 11607 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11608 11609 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11610 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11611 11612 QualType LHSType = LHS.get()->getType(); 11613 QualType RHSType = RHS.get()->getType(); 11614 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11615 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11616 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11617 11618 const Expr::NullPointerConstantKind LHSNullKind = 11619 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11620 const Expr::NullPointerConstantKind RHSNullKind = 11621 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11622 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11623 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11624 11625 auto computeResultTy = [&]() { 11626 if (Opc != BO_Cmp) 11627 return Context.getLogicalOperationType(); 11628 assert(getLangOpts().CPlusPlus); 11629 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11630 11631 QualType CompositeTy = LHS.get()->getType(); 11632 assert(!CompositeTy->isReferenceType()); 11633 11634 Optional<ComparisonCategoryType> CCT = 11635 getComparisonCategoryForBuiltinCmp(CompositeTy); 11636 if (!CCT) 11637 return InvalidOperands(Loc, LHS, RHS); 11638 11639 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11640 // P0946R0: Comparisons between a null pointer constant and an object 11641 // pointer result in std::strong_equality, which is ill-formed under 11642 // P1959R0. 11643 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11644 << (LHSIsNull ? LHS.get()->getSourceRange() 11645 : RHS.get()->getSourceRange()); 11646 return QualType(); 11647 } 11648 11649 return CheckComparisonCategoryType( 11650 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11651 }; 11652 11653 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11654 bool IsEquality = Opc == BO_EQ; 11655 if (RHSIsNull) 11656 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11657 RHS.get()->getSourceRange()); 11658 else 11659 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11660 LHS.get()->getSourceRange()); 11661 } 11662 11663 if ((LHSType->isIntegerType() && !LHSIsNull) || 11664 (RHSType->isIntegerType() && !RHSIsNull)) { 11665 // Skip normal pointer conversion checks in this case; we have better 11666 // diagnostics for this below. 11667 } else if (getLangOpts().CPlusPlus) { 11668 // Equality comparison of a function pointer to a void pointer is invalid, 11669 // but we allow it as an extension. 11670 // FIXME: If we really want to allow this, should it be part of composite 11671 // pointer type computation so it works in conditionals too? 11672 if (!IsOrdered && 11673 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11674 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11675 // This is a gcc extension compatibility comparison. 11676 // In a SFINAE context, we treat this as a hard error to maintain 11677 // conformance with the C++ standard. 11678 diagnoseFunctionPointerToVoidComparison( 11679 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11680 11681 if (isSFINAEContext()) 11682 return QualType(); 11683 11684 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11685 return computeResultTy(); 11686 } 11687 11688 // C++ [expr.eq]p2: 11689 // If at least one operand is a pointer [...] bring them to their 11690 // composite pointer type. 11691 // C++ [expr.spaceship]p6 11692 // If at least one of the operands is of pointer type, [...] bring them 11693 // to their composite pointer type. 11694 // C++ [expr.rel]p2: 11695 // If both operands are pointers, [...] bring them to their composite 11696 // pointer type. 11697 // For <=>, the only valid non-pointer types are arrays and functions, and 11698 // we already decayed those, so this is really the same as the relational 11699 // comparison rule. 11700 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11701 (IsOrdered ? 2 : 1) && 11702 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11703 RHSType->isObjCObjectPointerType()))) { 11704 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11705 return QualType(); 11706 return computeResultTy(); 11707 } 11708 } else if (LHSType->isPointerType() && 11709 RHSType->isPointerType()) { // C99 6.5.8p2 11710 // All of the following pointer-related warnings are GCC extensions, except 11711 // when handling null pointer constants. 11712 QualType LCanPointeeTy = 11713 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11714 QualType RCanPointeeTy = 11715 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11716 11717 // C99 6.5.9p2 and C99 6.5.8p2 11718 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11719 RCanPointeeTy.getUnqualifiedType())) { 11720 if (IsRelational) { 11721 // Pointers both need to point to complete or incomplete types 11722 if ((LCanPointeeTy->isIncompleteType() != 11723 RCanPointeeTy->isIncompleteType()) && 11724 !getLangOpts().C11) { 11725 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11727 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11728 << RCanPointeeTy->isIncompleteType(); 11729 } 11730 if (LCanPointeeTy->isFunctionType()) { 11731 // Valid unless a relational comparison of function pointers 11732 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11733 << LHSType << RHSType << LHS.get()->getSourceRange() 11734 << RHS.get()->getSourceRange(); 11735 } 11736 } 11737 } else if (!IsRelational && 11738 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11739 // Valid unless comparison between non-null pointer and function pointer 11740 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11741 && !LHSIsNull && !RHSIsNull) 11742 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11743 /*isError*/false); 11744 } else { 11745 // Invalid 11746 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11747 } 11748 if (LCanPointeeTy != RCanPointeeTy) { 11749 // Treat NULL constant as a special case in OpenCL. 11750 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11751 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11752 Diag(Loc, 11753 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11754 << LHSType << RHSType << 0 /* comparison */ 11755 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11756 } 11757 } 11758 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11759 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11760 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11761 : CK_BitCast; 11762 if (LHSIsNull && !RHSIsNull) 11763 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11764 else 11765 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11766 } 11767 return computeResultTy(); 11768 } 11769 11770 if (getLangOpts().CPlusPlus) { 11771 // C++ [expr.eq]p4: 11772 // Two operands of type std::nullptr_t or one operand of type 11773 // std::nullptr_t and the other a null pointer constant compare equal. 11774 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11775 if (LHSType->isNullPtrType()) { 11776 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11777 return computeResultTy(); 11778 } 11779 if (RHSType->isNullPtrType()) { 11780 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11781 return computeResultTy(); 11782 } 11783 } 11784 11785 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11786 // These aren't covered by the composite pointer type rules. 11787 if (!IsOrdered && RHSType->isNullPtrType() && 11788 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11789 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11790 return computeResultTy(); 11791 } 11792 if (!IsOrdered && LHSType->isNullPtrType() && 11793 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11794 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11795 return computeResultTy(); 11796 } 11797 11798 if (IsRelational && 11799 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11800 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11801 // HACK: Relational comparison of nullptr_t against a pointer type is 11802 // invalid per DR583, but we allow it within std::less<> and friends, 11803 // since otherwise common uses of it break. 11804 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11805 // friends to have std::nullptr_t overload candidates. 11806 DeclContext *DC = CurContext; 11807 if (isa<FunctionDecl>(DC)) 11808 DC = DC->getParent(); 11809 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11810 if (CTSD->isInStdNamespace() && 11811 llvm::StringSwitch<bool>(CTSD->getName()) 11812 .Cases("less", "less_equal", "greater", "greater_equal", true) 11813 .Default(false)) { 11814 if (RHSType->isNullPtrType()) 11815 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11816 else 11817 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11818 return computeResultTy(); 11819 } 11820 } 11821 } 11822 11823 // C++ [expr.eq]p2: 11824 // If at least one operand is a pointer to member, [...] bring them to 11825 // their composite pointer type. 11826 if (!IsOrdered && 11827 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11828 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11829 return QualType(); 11830 else 11831 return computeResultTy(); 11832 } 11833 } 11834 11835 // Handle block pointer types. 11836 if (!IsOrdered && LHSType->isBlockPointerType() && 11837 RHSType->isBlockPointerType()) { 11838 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11839 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11840 11841 if (!LHSIsNull && !RHSIsNull && 11842 !Context.typesAreCompatible(lpointee, rpointee)) { 11843 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11844 << LHSType << RHSType << LHS.get()->getSourceRange() 11845 << RHS.get()->getSourceRange(); 11846 } 11847 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11848 return computeResultTy(); 11849 } 11850 11851 // Allow block pointers to be compared with null pointer constants. 11852 if (!IsOrdered 11853 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11854 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11855 if (!LHSIsNull && !RHSIsNull) { 11856 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11857 ->getPointeeType()->isVoidType()) 11858 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11859 ->getPointeeType()->isVoidType()))) 11860 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11861 << LHSType << RHSType << LHS.get()->getSourceRange() 11862 << RHS.get()->getSourceRange(); 11863 } 11864 if (LHSIsNull && !RHSIsNull) 11865 LHS = ImpCastExprToType(LHS.get(), RHSType, 11866 RHSType->isPointerType() ? CK_BitCast 11867 : CK_AnyPointerToBlockPointerCast); 11868 else 11869 RHS = ImpCastExprToType(RHS.get(), LHSType, 11870 LHSType->isPointerType() ? CK_BitCast 11871 : CK_AnyPointerToBlockPointerCast); 11872 return computeResultTy(); 11873 } 11874 11875 if (LHSType->isObjCObjectPointerType() || 11876 RHSType->isObjCObjectPointerType()) { 11877 const PointerType *LPT = LHSType->getAs<PointerType>(); 11878 const PointerType *RPT = RHSType->getAs<PointerType>(); 11879 if (LPT || RPT) { 11880 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11881 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11882 11883 if (!LPtrToVoid && !RPtrToVoid && 11884 !Context.typesAreCompatible(LHSType, RHSType)) { 11885 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11886 /*isError*/false); 11887 } 11888 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11889 // the RHS, but we have test coverage for this behavior. 11890 // FIXME: Consider using convertPointersToCompositeType in C++. 11891 if (LHSIsNull && !RHSIsNull) { 11892 Expr *E = LHS.get(); 11893 if (getLangOpts().ObjCAutoRefCount) 11894 CheckObjCConversion(SourceRange(), RHSType, E, 11895 CCK_ImplicitConversion); 11896 LHS = ImpCastExprToType(E, RHSType, 11897 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11898 } 11899 else { 11900 Expr *E = RHS.get(); 11901 if (getLangOpts().ObjCAutoRefCount) 11902 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11903 /*Diagnose=*/true, 11904 /*DiagnoseCFAudited=*/false, Opc); 11905 RHS = ImpCastExprToType(E, LHSType, 11906 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11907 } 11908 return computeResultTy(); 11909 } 11910 if (LHSType->isObjCObjectPointerType() && 11911 RHSType->isObjCObjectPointerType()) { 11912 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11913 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11914 /*isError*/false); 11915 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11916 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11917 11918 if (LHSIsNull && !RHSIsNull) 11919 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11920 else 11921 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11922 return computeResultTy(); 11923 } 11924 11925 if (!IsOrdered && LHSType->isBlockPointerType() && 11926 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11927 LHS = ImpCastExprToType(LHS.get(), RHSType, 11928 CK_BlockPointerToObjCPointerCast); 11929 return computeResultTy(); 11930 } else if (!IsOrdered && 11931 LHSType->isBlockCompatibleObjCPointerType(Context) && 11932 RHSType->isBlockPointerType()) { 11933 RHS = ImpCastExprToType(RHS.get(), LHSType, 11934 CK_BlockPointerToObjCPointerCast); 11935 return computeResultTy(); 11936 } 11937 } 11938 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11939 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11940 unsigned DiagID = 0; 11941 bool isError = false; 11942 if (LangOpts.DebuggerSupport) { 11943 // Under a debugger, allow the comparison of pointers to integers, 11944 // since users tend to want to compare addresses. 11945 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11946 (RHSIsNull && RHSType->isIntegerType())) { 11947 if (IsOrdered) { 11948 isError = getLangOpts().CPlusPlus; 11949 DiagID = 11950 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11951 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11952 } 11953 } else if (getLangOpts().CPlusPlus) { 11954 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11955 isError = true; 11956 } else if (IsOrdered) 11957 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11958 else 11959 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11960 11961 if (DiagID) { 11962 Diag(Loc, DiagID) 11963 << LHSType << RHSType << LHS.get()->getSourceRange() 11964 << RHS.get()->getSourceRange(); 11965 if (isError) 11966 return QualType(); 11967 } 11968 11969 if (LHSType->isIntegerType()) 11970 LHS = ImpCastExprToType(LHS.get(), RHSType, 11971 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11972 else 11973 RHS = ImpCastExprToType(RHS.get(), LHSType, 11974 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11975 return computeResultTy(); 11976 } 11977 11978 // Handle block pointers. 11979 if (!IsOrdered && RHSIsNull 11980 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11981 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11982 return computeResultTy(); 11983 } 11984 if (!IsOrdered && LHSIsNull 11985 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11986 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11987 return computeResultTy(); 11988 } 11989 11990 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11991 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11992 return computeResultTy(); 11993 } 11994 11995 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11996 return computeResultTy(); 11997 } 11998 11999 if (LHSIsNull && RHSType->isQueueT()) { 12000 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12001 return computeResultTy(); 12002 } 12003 12004 if (LHSType->isQueueT() && RHSIsNull) { 12005 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12006 return computeResultTy(); 12007 } 12008 } 12009 12010 return InvalidOperands(Loc, LHS, RHS); 12011 } 12012 12013 // Return a signed ext_vector_type that is of identical size and number of 12014 // elements. For floating point vectors, return an integer type of identical 12015 // size and number of elements. In the non ext_vector_type case, search from 12016 // the largest type to the smallest type to avoid cases where long long == long, 12017 // where long gets picked over long long. 12018 QualType Sema::GetSignedVectorType(QualType V) { 12019 const VectorType *VTy = V->castAs<VectorType>(); 12020 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12021 12022 if (isa<ExtVectorType>(VTy)) { 12023 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12024 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12025 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12026 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12027 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12028 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12029 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12030 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12031 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12032 "Unhandled vector element size in vector compare"); 12033 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12034 } 12035 12036 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12037 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12038 VectorType::GenericVector); 12039 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12040 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12041 VectorType::GenericVector); 12042 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12043 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12044 VectorType::GenericVector); 12045 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12046 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12047 VectorType::GenericVector); 12048 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12049 "Unhandled vector element size in vector compare"); 12050 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12051 VectorType::GenericVector); 12052 } 12053 12054 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12055 /// operates on extended vector types. Instead of producing an IntTy result, 12056 /// like a scalar comparison, a vector comparison produces a vector of integer 12057 /// types. 12058 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12059 SourceLocation Loc, 12060 BinaryOperatorKind Opc) { 12061 if (Opc == BO_Cmp) { 12062 Diag(Loc, diag::err_three_way_vector_comparison); 12063 return QualType(); 12064 } 12065 12066 // Check to make sure we're operating on vectors of the same type and width, 12067 // Allowing one side to be a scalar of element type. 12068 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12069 /*AllowBothBool*/true, 12070 /*AllowBoolConversions*/getLangOpts().ZVector); 12071 if (vType.isNull()) 12072 return vType; 12073 12074 QualType LHSType = LHS.get()->getType(); 12075 12076 // If AltiVec, the comparison results in a numeric type, i.e. 12077 // bool for C++, int for C 12078 if (getLangOpts().AltiVec && 12079 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12080 return Context.getLogicalOperationType(); 12081 12082 // For non-floating point types, check for self-comparisons of the form 12083 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12084 // often indicate logic errors in the program. 12085 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12086 12087 // Check for comparisons of floating point operands using != and ==. 12088 if (BinaryOperator::isEqualityOp(Opc) && 12089 LHSType->hasFloatingRepresentation()) { 12090 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12091 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12092 } 12093 12094 // Return a signed type for the vector. 12095 return GetSignedVectorType(vType); 12096 } 12097 12098 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12099 const ExprResult &XorRHS, 12100 const SourceLocation Loc) { 12101 // Do not diagnose macros. 12102 if (Loc.isMacroID()) 12103 return; 12104 12105 bool Negative = false; 12106 bool ExplicitPlus = false; 12107 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12108 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12109 12110 if (!LHSInt) 12111 return; 12112 if (!RHSInt) { 12113 // Check negative literals. 12114 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12115 UnaryOperatorKind Opc = UO->getOpcode(); 12116 if (Opc != UO_Minus && Opc != UO_Plus) 12117 return; 12118 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12119 if (!RHSInt) 12120 return; 12121 Negative = (Opc == UO_Minus); 12122 ExplicitPlus = !Negative; 12123 } else { 12124 return; 12125 } 12126 } 12127 12128 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12129 llvm::APInt RightSideValue = RHSInt->getValue(); 12130 if (LeftSideValue != 2 && LeftSideValue != 10) 12131 return; 12132 12133 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12134 return; 12135 12136 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12137 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12138 llvm::StringRef ExprStr = 12139 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12140 12141 CharSourceRange XorRange = 12142 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12143 llvm::StringRef XorStr = 12144 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12145 // Do not diagnose if xor keyword/macro is used. 12146 if (XorStr == "xor") 12147 return; 12148 12149 std::string LHSStr = std::string(Lexer::getSourceText( 12150 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12151 S.getSourceManager(), S.getLangOpts())); 12152 std::string RHSStr = std::string(Lexer::getSourceText( 12153 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12154 S.getSourceManager(), S.getLangOpts())); 12155 12156 if (Negative) { 12157 RightSideValue = -RightSideValue; 12158 RHSStr = "-" + RHSStr; 12159 } else if (ExplicitPlus) { 12160 RHSStr = "+" + RHSStr; 12161 } 12162 12163 StringRef LHSStrRef = LHSStr; 12164 StringRef RHSStrRef = RHSStr; 12165 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12166 // literals. 12167 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12168 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12169 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12170 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12171 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12172 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12173 LHSStrRef.find('\'') != StringRef::npos || 12174 RHSStrRef.find('\'') != StringRef::npos) 12175 return; 12176 12177 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12178 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12179 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12180 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12181 std::string SuggestedExpr = "1 << " + RHSStr; 12182 bool Overflow = false; 12183 llvm::APInt One = (LeftSideValue - 1); 12184 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12185 if (Overflow) { 12186 if (RightSideIntValue < 64) 12187 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12188 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12189 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12190 else if (RightSideIntValue == 64) 12191 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12192 else 12193 return; 12194 } else { 12195 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12196 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12197 << PowValue.toString(10, true) 12198 << FixItHint::CreateReplacement( 12199 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12200 } 12201 12202 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12203 } else if (LeftSideValue == 10) { 12204 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12205 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12206 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12207 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12208 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12209 } 12210 } 12211 12212 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12213 SourceLocation Loc) { 12214 // Ensure that either both operands are of the same vector type, or 12215 // one operand is of a vector type and the other is of its element type. 12216 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12217 /*AllowBothBool*/true, 12218 /*AllowBoolConversions*/false); 12219 if (vType.isNull()) 12220 return InvalidOperands(Loc, LHS, RHS); 12221 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12222 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12223 return InvalidOperands(Loc, LHS, RHS); 12224 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12225 // usage of the logical operators && and || with vectors in C. This 12226 // check could be notionally dropped. 12227 if (!getLangOpts().CPlusPlus && 12228 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12229 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12230 12231 return GetSignedVectorType(LHS.get()->getType()); 12232 } 12233 12234 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12235 SourceLocation Loc, 12236 bool IsCompAssign) { 12237 if (!IsCompAssign) { 12238 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12239 if (LHS.isInvalid()) 12240 return QualType(); 12241 } 12242 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12243 if (RHS.isInvalid()) 12244 return QualType(); 12245 12246 // For conversion purposes, we ignore any qualifiers. 12247 // For example, "const float" and "float" are equivalent. 12248 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12249 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12250 12251 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12252 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12253 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12254 12255 if (Context.hasSameType(LHSType, RHSType)) 12256 return LHSType; 12257 12258 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12259 // case we have to return InvalidOperands. 12260 ExprResult OriginalLHS = LHS; 12261 ExprResult OriginalRHS = RHS; 12262 if (LHSMatType && !RHSMatType) { 12263 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12264 if (!RHS.isInvalid()) 12265 return LHSType; 12266 12267 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12268 } 12269 12270 if (!LHSMatType && RHSMatType) { 12271 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12272 if (!LHS.isInvalid()) 12273 return RHSType; 12274 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12275 } 12276 12277 return InvalidOperands(Loc, LHS, RHS); 12278 } 12279 12280 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12281 SourceLocation Loc, 12282 bool IsCompAssign) { 12283 if (!IsCompAssign) { 12284 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12285 if (LHS.isInvalid()) 12286 return QualType(); 12287 } 12288 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12289 if (RHS.isInvalid()) 12290 return QualType(); 12291 12292 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12293 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12294 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12295 12296 if (LHSMatType && RHSMatType) { 12297 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12298 return InvalidOperands(Loc, LHS, RHS); 12299 12300 if (!Context.hasSameType(LHSMatType->getElementType(), 12301 RHSMatType->getElementType())) 12302 return InvalidOperands(Loc, LHS, RHS); 12303 12304 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12305 LHSMatType->getNumRows(), 12306 RHSMatType->getNumColumns()); 12307 } 12308 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12309 } 12310 12311 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12312 SourceLocation Loc, 12313 BinaryOperatorKind Opc) { 12314 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12315 12316 bool IsCompAssign = 12317 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12318 12319 if (LHS.get()->getType()->isVectorType() || 12320 RHS.get()->getType()->isVectorType()) { 12321 if (LHS.get()->getType()->hasIntegerRepresentation() && 12322 RHS.get()->getType()->hasIntegerRepresentation()) 12323 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12324 /*AllowBothBool*/true, 12325 /*AllowBoolConversions*/getLangOpts().ZVector); 12326 return InvalidOperands(Loc, LHS, RHS); 12327 } 12328 12329 if (Opc == BO_And) 12330 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12331 12332 if (LHS.get()->getType()->hasFloatingRepresentation() || 12333 RHS.get()->getType()->hasFloatingRepresentation()) 12334 return InvalidOperands(Loc, LHS, RHS); 12335 12336 ExprResult LHSResult = LHS, RHSResult = RHS; 12337 QualType compType = UsualArithmeticConversions( 12338 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12339 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12340 return QualType(); 12341 LHS = LHSResult.get(); 12342 RHS = RHSResult.get(); 12343 12344 if (Opc == BO_Xor) 12345 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12346 12347 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12348 return compType; 12349 return InvalidOperands(Loc, LHS, RHS); 12350 } 12351 12352 // C99 6.5.[13,14] 12353 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12354 SourceLocation Loc, 12355 BinaryOperatorKind Opc) { 12356 // Check vector operands differently. 12357 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12358 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12359 12360 bool EnumConstantInBoolContext = false; 12361 for (const ExprResult &HS : {LHS, RHS}) { 12362 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12363 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12364 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12365 EnumConstantInBoolContext = true; 12366 } 12367 } 12368 12369 if (EnumConstantInBoolContext) 12370 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12371 12372 // Diagnose cases where the user write a logical and/or but probably meant a 12373 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12374 // is a constant. 12375 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12376 !LHS.get()->getType()->isBooleanType() && 12377 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12378 // Don't warn in macros or template instantiations. 12379 !Loc.isMacroID() && !inTemplateInstantiation()) { 12380 // If the RHS can be constant folded, and if it constant folds to something 12381 // that isn't 0 or 1 (which indicate a potential logical operation that 12382 // happened to fold to true/false) then warn. 12383 // Parens on the RHS are ignored. 12384 Expr::EvalResult EVResult; 12385 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12386 llvm::APSInt Result = EVResult.Val.getInt(); 12387 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12388 !RHS.get()->getExprLoc().isMacroID()) || 12389 (Result != 0 && Result != 1)) { 12390 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12391 << RHS.get()->getSourceRange() 12392 << (Opc == BO_LAnd ? "&&" : "||"); 12393 // Suggest replacing the logical operator with the bitwise version 12394 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12395 << (Opc == BO_LAnd ? "&" : "|") 12396 << FixItHint::CreateReplacement(SourceRange( 12397 Loc, getLocForEndOfToken(Loc)), 12398 Opc == BO_LAnd ? "&" : "|"); 12399 if (Opc == BO_LAnd) 12400 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12401 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12402 << FixItHint::CreateRemoval( 12403 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12404 RHS.get()->getEndLoc())); 12405 } 12406 } 12407 } 12408 12409 if (!Context.getLangOpts().CPlusPlus) { 12410 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12411 // not operate on the built-in scalar and vector float types. 12412 if (Context.getLangOpts().OpenCL && 12413 Context.getLangOpts().OpenCLVersion < 120) { 12414 if (LHS.get()->getType()->isFloatingType() || 12415 RHS.get()->getType()->isFloatingType()) 12416 return InvalidOperands(Loc, LHS, RHS); 12417 } 12418 12419 LHS = UsualUnaryConversions(LHS.get()); 12420 if (LHS.isInvalid()) 12421 return QualType(); 12422 12423 RHS = UsualUnaryConversions(RHS.get()); 12424 if (RHS.isInvalid()) 12425 return QualType(); 12426 12427 if (!LHS.get()->getType()->isScalarType() || 12428 !RHS.get()->getType()->isScalarType()) 12429 return InvalidOperands(Loc, LHS, RHS); 12430 12431 return Context.IntTy; 12432 } 12433 12434 // The following is safe because we only use this method for 12435 // non-overloadable operands. 12436 12437 // C++ [expr.log.and]p1 12438 // C++ [expr.log.or]p1 12439 // The operands are both contextually converted to type bool. 12440 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12441 if (LHSRes.isInvalid()) 12442 return InvalidOperands(Loc, LHS, RHS); 12443 LHS = LHSRes; 12444 12445 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12446 if (RHSRes.isInvalid()) 12447 return InvalidOperands(Loc, LHS, RHS); 12448 RHS = RHSRes; 12449 12450 // C++ [expr.log.and]p2 12451 // C++ [expr.log.or]p2 12452 // The result is a bool. 12453 return Context.BoolTy; 12454 } 12455 12456 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12457 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12458 if (!ME) return false; 12459 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12460 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12461 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12462 if (!Base) return false; 12463 return Base->getMethodDecl() != nullptr; 12464 } 12465 12466 /// Is the given expression (which must be 'const') a reference to a 12467 /// variable which was originally non-const, but which has become 12468 /// 'const' due to being captured within a block? 12469 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12470 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12471 assert(E->isLValue() && E->getType().isConstQualified()); 12472 E = E->IgnoreParens(); 12473 12474 // Must be a reference to a declaration from an enclosing scope. 12475 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12476 if (!DRE) return NCCK_None; 12477 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12478 12479 // The declaration must be a variable which is not declared 'const'. 12480 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12481 if (!var) return NCCK_None; 12482 if (var->getType().isConstQualified()) return NCCK_None; 12483 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12484 12485 // Decide whether the first capture was for a block or a lambda. 12486 DeclContext *DC = S.CurContext, *Prev = nullptr; 12487 // Decide whether the first capture was for a block or a lambda. 12488 while (DC) { 12489 // For init-capture, it is possible that the variable belongs to the 12490 // template pattern of the current context. 12491 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12492 if (var->isInitCapture() && 12493 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12494 break; 12495 if (DC == var->getDeclContext()) 12496 break; 12497 Prev = DC; 12498 DC = DC->getParent(); 12499 } 12500 // Unless we have an init-capture, we've gone one step too far. 12501 if (!var->isInitCapture()) 12502 DC = Prev; 12503 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12504 } 12505 12506 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12507 Ty = Ty.getNonReferenceType(); 12508 if (IsDereference && Ty->isPointerType()) 12509 Ty = Ty->getPointeeType(); 12510 return !Ty.isConstQualified(); 12511 } 12512 12513 // Update err_typecheck_assign_const and note_typecheck_assign_const 12514 // when this enum is changed. 12515 enum { 12516 ConstFunction, 12517 ConstVariable, 12518 ConstMember, 12519 ConstMethod, 12520 NestedConstMember, 12521 ConstUnknown, // Keep as last element 12522 }; 12523 12524 /// Emit the "read-only variable not assignable" error and print notes to give 12525 /// more information about why the variable is not assignable, such as pointing 12526 /// to the declaration of a const variable, showing that a method is const, or 12527 /// that the function is returning a const reference. 12528 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12529 SourceLocation Loc) { 12530 SourceRange ExprRange = E->getSourceRange(); 12531 12532 // Only emit one error on the first const found. All other consts will emit 12533 // a note to the error. 12534 bool DiagnosticEmitted = false; 12535 12536 // Track if the current expression is the result of a dereference, and if the 12537 // next checked expression is the result of a dereference. 12538 bool IsDereference = false; 12539 bool NextIsDereference = false; 12540 12541 // Loop to process MemberExpr chains. 12542 while (true) { 12543 IsDereference = NextIsDereference; 12544 12545 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12546 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12547 NextIsDereference = ME->isArrow(); 12548 const ValueDecl *VD = ME->getMemberDecl(); 12549 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12550 // Mutable fields can be modified even if the class is const. 12551 if (Field->isMutable()) { 12552 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12553 break; 12554 } 12555 12556 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12557 if (!DiagnosticEmitted) { 12558 S.Diag(Loc, diag::err_typecheck_assign_const) 12559 << ExprRange << ConstMember << false /*static*/ << Field 12560 << Field->getType(); 12561 DiagnosticEmitted = true; 12562 } 12563 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12564 << ConstMember << false /*static*/ << Field << Field->getType() 12565 << Field->getSourceRange(); 12566 } 12567 E = ME->getBase(); 12568 continue; 12569 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12570 if (VDecl->getType().isConstQualified()) { 12571 if (!DiagnosticEmitted) { 12572 S.Diag(Loc, diag::err_typecheck_assign_const) 12573 << ExprRange << ConstMember << true /*static*/ << VDecl 12574 << VDecl->getType(); 12575 DiagnosticEmitted = true; 12576 } 12577 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12578 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12579 << VDecl->getSourceRange(); 12580 } 12581 // Static fields do not inherit constness from parents. 12582 break; 12583 } 12584 break; // End MemberExpr 12585 } else if (const ArraySubscriptExpr *ASE = 12586 dyn_cast<ArraySubscriptExpr>(E)) { 12587 E = ASE->getBase()->IgnoreParenImpCasts(); 12588 continue; 12589 } else if (const ExtVectorElementExpr *EVE = 12590 dyn_cast<ExtVectorElementExpr>(E)) { 12591 E = EVE->getBase()->IgnoreParenImpCasts(); 12592 continue; 12593 } 12594 break; 12595 } 12596 12597 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12598 // Function calls 12599 const FunctionDecl *FD = CE->getDirectCallee(); 12600 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12601 if (!DiagnosticEmitted) { 12602 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12603 << ConstFunction << FD; 12604 DiagnosticEmitted = true; 12605 } 12606 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12607 diag::note_typecheck_assign_const) 12608 << ConstFunction << FD << FD->getReturnType() 12609 << FD->getReturnTypeSourceRange(); 12610 } 12611 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12612 // Point to variable declaration. 12613 if (const ValueDecl *VD = DRE->getDecl()) { 12614 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12615 if (!DiagnosticEmitted) { 12616 S.Diag(Loc, diag::err_typecheck_assign_const) 12617 << ExprRange << ConstVariable << VD << VD->getType(); 12618 DiagnosticEmitted = true; 12619 } 12620 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12621 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12622 } 12623 } 12624 } else if (isa<CXXThisExpr>(E)) { 12625 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12626 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12627 if (MD->isConst()) { 12628 if (!DiagnosticEmitted) { 12629 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12630 << ConstMethod << MD; 12631 DiagnosticEmitted = true; 12632 } 12633 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12634 << ConstMethod << MD << MD->getSourceRange(); 12635 } 12636 } 12637 } 12638 } 12639 12640 if (DiagnosticEmitted) 12641 return; 12642 12643 // Can't determine a more specific message, so display the generic error. 12644 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12645 } 12646 12647 enum OriginalExprKind { 12648 OEK_Variable, 12649 OEK_Member, 12650 OEK_LValue 12651 }; 12652 12653 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12654 const RecordType *Ty, 12655 SourceLocation Loc, SourceRange Range, 12656 OriginalExprKind OEK, 12657 bool &DiagnosticEmitted) { 12658 std::vector<const RecordType *> RecordTypeList; 12659 RecordTypeList.push_back(Ty); 12660 unsigned NextToCheckIndex = 0; 12661 // We walk the record hierarchy breadth-first to ensure that we print 12662 // diagnostics in field nesting order. 12663 while (RecordTypeList.size() > NextToCheckIndex) { 12664 bool IsNested = NextToCheckIndex > 0; 12665 for (const FieldDecl *Field : 12666 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12667 // First, check every field for constness. 12668 QualType FieldTy = Field->getType(); 12669 if (FieldTy.isConstQualified()) { 12670 if (!DiagnosticEmitted) { 12671 S.Diag(Loc, diag::err_typecheck_assign_const) 12672 << Range << NestedConstMember << OEK << VD 12673 << IsNested << Field; 12674 DiagnosticEmitted = true; 12675 } 12676 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12677 << NestedConstMember << IsNested << Field 12678 << FieldTy << Field->getSourceRange(); 12679 } 12680 12681 // Then we append it to the list to check next in order. 12682 FieldTy = FieldTy.getCanonicalType(); 12683 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12684 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12685 RecordTypeList.push_back(FieldRecTy); 12686 } 12687 } 12688 ++NextToCheckIndex; 12689 } 12690 } 12691 12692 /// Emit an error for the case where a record we are trying to assign to has a 12693 /// const-qualified field somewhere in its hierarchy. 12694 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12695 SourceLocation Loc) { 12696 QualType Ty = E->getType(); 12697 assert(Ty->isRecordType() && "lvalue was not record?"); 12698 SourceRange Range = E->getSourceRange(); 12699 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12700 bool DiagEmitted = false; 12701 12702 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12703 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12704 Range, OEK_Member, DiagEmitted); 12705 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12706 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12707 Range, OEK_Variable, DiagEmitted); 12708 else 12709 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12710 Range, OEK_LValue, DiagEmitted); 12711 if (!DiagEmitted) 12712 DiagnoseConstAssignment(S, E, Loc); 12713 } 12714 12715 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12716 /// emit an error and return true. If so, return false. 12717 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12718 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12719 12720 S.CheckShadowingDeclModification(E, Loc); 12721 12722 SourceLocation OrigLoc = Loc; 12723 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12724 &Loc); 12725 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12726 IsLV = Expr::MLV_InvalidMessageExpression; 12727 if (IsLV == Expr::MLV_Valid) 12728 return false; 12729 12730 unsigned DiagID = 0; 12731 bool NeedType = false; 12732 switch (IsLV) { // C99 6.5.16p2 12733 case Expr::MLV_ConstQualified: 12734 // Use a specialized diagnostic when we're assigning to an object 12735 // from an enclosing function or block. 12736 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12737 if (NCCK == NCCK_Block) 12738 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12739 else 12740 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12741 break; 12742 } 12743 12744 // In ARC, use some specialized diagnostics for occasions where we 12745 // infer 'const'. These are always pseudo-strong variables. 12746 if (S.getLangOpts().ObjCAutoRefCount) { 12747 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12748 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12749 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12750 12751 // Use the normal diagnostic if it's pseudo-__strong but the 12752 // user actually wrote 'const'. 12753 if (var->isARCPseudoStrong() && 12754 (!var->getTypeSourceInfo() || 12755 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12756 // There are three pseudo-strong cases: 12757 // - self 12758 ObjCMethodDecl *method = S.getCurMethodDecl(); 12759 if (method && var == method->getSelfDecl()) { 12760 DiagID = method->isClassMethod() 12761 ? diag::err_typecheck_arc_assign_self_class_method 12762 : diag::err_typecheck_arc_assign_self; 12763 12764 // - Objective-C externally_retained attribute. 12765 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12766 isa<ParmVarDecl>(var)) { 12767 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12768 12769 // - fast enumeration variables 12770 } else { 12771 DiagID = diag::err_typecheck_arr_assign_enumeration; 12772 } 12773 12774 SourceRange Assign; 12775 if (Loc != OrigLoc) 12776 Assign = SourceRange(OrigLoc, OrigLoc); 12777 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12778 // We need to preserve the AST regardless, so migration tool 12779 // can do its job. 12780 return false; 12781 } 12782 } 12783 } 12784 12785 // If none of the special cases above are triggered, then this is a 12786 // simple const assignment. 12787 if (DiagID == 0) { 12788 DiagnoseConstAssignment(S, E, Loc); 12789 return true; 12790 } 12791 12792 break; 12793 case Expr::MLV_ConstAddrSpace: 12794 DiagnoseConstAssignment(S, E, Loc); 12795 return true; 12796 case Expr::MLV_ConstQualifiedField: 12797 DiagnoseRecursiveConstFields(S, E, Loc); 12798 return true; 12799 case Expr::MLV_ArrayType: 12800 case Expr::MLV_ArrayTemporary: 12801 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12802 NeedType = true; 12803 break; 12804 case Expr::MLV_NotObjectType: 12805 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12806 NeedType = true; 12807 break; 12808 case Expr::MLV_LValueCast: 12809 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12810 break; 12811 case Expr::MLV_Valid: 12812 llvm_unreachable("did not take early return for MLV_Valid"); 12813 case Expr::MLV_InvalidExpression: 12814 case Expr::MLV_MemberFunction: 12815 case Expr::MLV_ClassTemporary: 12816 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12817 break; 12818 case Expr::MLV_IncompleteType: 12819 case Expr::MLV_IncompleteVoidType: 12820 return S.RequireCompleteType(Loc, E->getType(), 12821 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12822 case Expr::MLV_DuplicateVectorComponents: 12823 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12824 break; 12825 case Expr::MLV_NoSetterProperty: 12826 llvm_unreachable("readonly properties should be processed differently"); 12827 case Expr::MLV_InvalidMessageExpression: 12828 DiagID = diag::err_readonly_message_assignment; 12829 break; 12830 case Expr::MLV_SubObjCPropertySetting: 12831 DiagID = diag::err_no_subobject_property_setting; 12832 break; 12833 } 12834 12835 SourceRange Assign; 12836 if (Loc != OrigLoc) 12837 Assign = SourceRange(OrigLoc, OrigLoc); 12838 if (NeedType) 12839 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12840 else 12841 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12842 return true; 12843 } 12844 12845 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12846 SourceLocation Loc, 12847 Sema &Sema) { 12848 if (Sema.inTemplateInstantiation()) 12849 return; 12850 if (Sema.isUnevaluatedContext()) 12851 return; 12852 if (Loc.isInvalid() || Loc.isMacroID()) 12853 return; 12854 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12855 return; 12856 12857 // C / C++ fields 12858 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12859 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12860 if (ML && MR) { 12861 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12862 return; 12863 const ValueDecl *LHSDecl = 12864 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12865 const ValueDecl *RHSDecl = 12866 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12867 if (LHSDecl != RHSDecl) 12868 return; 12869 if (LHSDecl->getType().isVolatileQualified()) 12870 return; 12871 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12872 if (RefTy->getPointeeType().isVolatileQualified()) 12873 return; 12874 12875 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12876 } 12877 12878 // Objective-C instance variables 12879 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12880 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12881 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12882 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12883 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12884 if (RL && RR && RL->getDecl() == RR->getDecl()) 12885 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12886 } 12887 } 12888 12889 // C99 6.5.16.1 12890 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12891 SourceLocation Loc, 12892 QualType CompoundType) { 12893 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12894 12895 // Verify that LHS is a modifiable lvalue, and emit error if not. 12896 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12897 return QualType(); 12898 12899 QualType LHSType = LHSExpr->getType(); 12900 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12901 CompoundType; 12902 // OpenCL v1.2 s6.1.1.1 p2: 12903 // The half data type can only be used to declare a pointer to a buffer that 12904 // contains half values 12905 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12906 LHSType->isHalfType()) { 12907 Diag(Loc, diag::err_opencl_half_load_store) << 1 12908 << LHSType.getUnqualifiedType(); 12909 return QualType(); 12910 } 12911 12912 AssignConvertType ConvTy; 12913 if (CompoundType.isNull()) { 12914 Expr *RHSCheck = RHS.get(); 12915 12916 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12917 12918 QualType LHSTy(LHSType); 12919 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12920 if (RHS.isInvalid()) 12921 return QualType(); 12922 // Special case of NSObject attributes on c-style pointer types. 12923 if (ConvTy == IncompatiblePointer && 12924 ((Context.isObjCNSObjectType(LHSType) && 12925 RHSType->isObjCObjectPointerType()) || 12926 (Context.isObjCNSObjectType(RHSType) && 12927 LHSType->isObjCObjectPointerType()))) 12928 ConvTy = Compatible; 12929 12930 if (ConvTy == Compatible && 12931 LHSType->isObjCObjectType()) 12932 Diag(Loc, diag::err_objc_object_assignment) 12933 << LHSType; 12934 12935 // If the RHS is a unary plus or minus, check to see if they = and + are 12936 // right next to each other. If so, the user may have typo'd "x =+ 4" 12937 // instead of "x += 4". 12938 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12939 RHSCheck = ICE->getSubExpr(); 12940 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12941 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12942 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12943 // Only if the two operators are exactly adjacent. 12944 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12945 // And there is a space or other character before the subexpr of the 12946 // unary +/-. We don't want to warn on "x=-1". 12947 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12948 UO->getSubExpr()->getBeginLoc().isFileID()) { 12949 Diag(Loc, diag::warn_not_compound_assign) 12950 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12951 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12952 } 12953 } 12954 12955 if (ConvTy == Compatible) { 12956 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12957 // Warn about retain cycles where a block captures the LHS, but 12958 // not if the LHS is a simple variable into which the block is 12959 // being stored...unless that variable can be captured by reference! 12960 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12961 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12962 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12963 checkRetainCycles(LHSExpr, RHS.get()); 12964 } 12965 12966 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12967 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12968 // It is safe to assign a weak reference into a strong variable. 12969 // Although this code can still have problems: 12970 // id x = self.weakProp; 12971 // id y = self.weakProp; 12972 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12973 // paths through the function. This should be revisited if 12974 // -Wrepeated-use-of-weak is made flow-sensitive. 12975 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12976 // variable, which will be valid for the current autorelease scope. 12977 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12978 RHS.get()->getBeginLoc())) 12979 getCurFunction()->markSafeWeakUse(RHS.get()); 12980 12981 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12982 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12983 } 12984 } 12985 } else { 12986 // Compound assignment "x += y" 12987 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12988 } 12989 12990 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12991 RHS.get(), AA_Assigning)) 12992 return QualType(); 12993 12994 CheckForNullPointerDereference(*this, LHSExpr); 12995 12996 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12997 if (CompoundType.isNull()) { 12998 // C++2a [expr.ass]p5: 12999 // A simple-assignment whose left operand is of a volatile-qualified 13000 // type is deprecated unless the assignment is either a discarded-value 13001 // expression or an unevaluated operand 13002 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13003 } else { 13004 // C++2a [expr.ass]p6: 13005 // [Compound-assignment] expressions are deprecated if E1 has 13006 // volatile-qualified type 13007 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13008 } 13009 } 13010 13011 // C99 6.5.16p3: The type of an assignment expression is the type of the 13012 // left operand unless the left operand has qualified type, in which case 13013 // it is the unqualified version of the type of the left operand. 13014 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13015 // is converted to the type of the assignment expression (above). 13016 // C++ 5.17p1: the type of the assignment expression is that of its left 13017 // operand. 13018 return (getLangOpts().CPlusPlus 13019 ? LHSType : LHSType.getUnqualifiedType()); 13020 } 13021 13022 // Only ignore explicit casts to void. 13023 static bool IgnoreCommaOperand(const Expr *E) { 13024 E = E->IgnoreParens(); 13025 13026 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13027 if (CE->getCastKind() == CK_ToVoid) { 13028 return true; 13029 } 13030 13031 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13032 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13033 CE->getSubExpr()->getType()->isDependentType()) { 13034 return true; 13035 } 13036 } 13037 13038 return false; 13039 } 13040 13041 // Look for instances where it is likely the comma operator is confused with 13042 // another operator. There is an explicit list of acceptable expressions for 13043 // the left hand side of the comma operator, otherwise emit a warning. 13044 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13045 // No warnings in macros 13046 if (Loc.isMacroID()) 13047 return; 13048 13049 // Don't warn in template instantiations. 13050 if (inTemplateInstantiation()) 13051 return; 13052 13053 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13054 // instead, skip more than needed, then call back into here with the 13055 // CommaVisitor in SemaStmt.cpp. 13056 // The listed locations are the initialization and increment portions 13057 // of a for loop. The additional checks are on the condition of 13058 // if statements, do/while loops, and for loops. 13059 // Differences in scope flags for C89 mode requires the extra logic. 13060 const unsigned ForIncrementFlags = 13061 getLangOpts().C99 || getLangOpts().CPlusPlus 13062 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13063 : Scope::ContinueScope | Scope::BreakScope; 13064 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13065 const unsigned ScopeFlags = getCurScope()->getFlags(); 13066 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13067 (ScopeFlags & ForInitFlags) == ForInitFlags) 13068 return; 13069 13070 // If there are multiple comma operators used together, get the RHS of the 13071 // of the comma operator as the LHS. 13072 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13073 if (BO->getOpcode() != BO_Comma) 13074 break; 13075 LHS = BO->getRHS(); 13076 } 13077 13078 // Only allow some expressions on LHS to not warn. 13079 if (IgnoreCommaOperand(LHS)) 13080 return; 13081 13082 Diag(Loc, diag::warn_comma_operator); 13083 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13084 << LHS->getSourceRange() 13085 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13086 LangOpts.CPlusPlus ? "static_cast<void>(" 13087 : "(void)(") 13088 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13089 ")"); 13090 } 13091 13092 // C99 6.5.17 13093 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13094 SourceLocation Loc) { 13095 LHS = S.CheckPlaceholderExpr(LHS.get()); 13096 RHS = S.CheckPlaceholderExpr(RHS.get()); 13097 if (LHS.isInvalid() || RHS.isInvalid()) 13098 return QualType(); 13099 13100 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13101 // operands, but not unary promotions. 13102 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13103 13104 // So we treat the LHS as a ignored value, and in C++ we allow the 13105 // containing site to determine what should be done with the RHS. 13106 LHS = S.IgnoredValueConversions(LHS.get()); 13107 if (LHS.isInvalid()) 13108 return QualType(); 13109 13110 S.DiagnoseUnusedExprResult(LHS.get()); 13111 13112 if (!S.getLangOpts().CPlusPlus) { 13113 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13114 if (RHS.isInvalid()) 13115 return QualType(); 13116 if (!RHS.get()->getType()->isVoidType()) 13117 S.RequireCompleteType(Loc, RHS.get()->getType(), 13118 diag::err_incomplete_type); 13119 } 13120 13121 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13122 S.DiagnoseCommaOperator(LHS.get(), Loc); 13123 13124 return RHS.get()->getType(); 13125 } 13126 13127 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13128 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13129 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13130 ExprValueKind &VK, 13131 ExprObjectKind &OK, 13132 SourceLocation OpLoc, 13133 bool IsInc, bool IsPrefix) { 13134 if (Op->isTypeDependent()) 13135 return S.Context.DependentTy; 13136 13137 QualType ResType = Op->getType(); 13138 // Atomic types can be used for increment / decrement where the non-atomic 13139 // versions can, so ignore the _Atomic() specifier for the purpose of 13140 // checking. 13141 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13142 ResType = ResAtomicType->getValueType(); 13143 13144 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13145 13146 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13147 // Decrement of bool is not allowed. 13148 if (!IsInc) { 13149 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13150 return QualType(); 13151 } 13152 // Increment of bool sets it to true, but is deprecated. 13153 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13154 : diag::warn_increment_bool) 13155 << Op->getSourceRange(); 13156 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13157 // Error on enum increments and decrements in C++ mode 13158 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13159 return QualType(); 13160 } else if (ResType->isRealType()) { 13161 // OK! 13162 } else if (ResType->isPointerType()) { 13163 // C99 6.5.2.4p2, 6.5.6p2 13164 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13165 return QualType(); 13166 } else if (ResType->isObjCObjectPointerType()) { 13167 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13168 // Otherwise, we just need a complete type. 13169 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13170 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13171 return QualType(); 13172 } else if (ResType->isAnyComplexType()) { 13173 // C99 does not support ++/-- on complex types, we allow as an extension. 13174 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13175 << ResType << Op->getSourceRange(); 13176 } else if (ResType->isPlaceholderType()) { 13177 ExprResult PR = S.CheckPlaceholderExpr(Op); 13178 if (PR.isInvalid()) return QualType(); 13179 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13180 IsInc, IsPrefix); 13181 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13182 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13183 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13184 (ResType->castAs<VectorType>()->getVectorKind() != 13185 VectorType::AltiVecBool)) { 13186 // The z vector extensions allow ++ and -- for non-bool vectors. 13187 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13188 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13189 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13190 } else { 13191 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13192 << ResType << int(IsInc) << Op->getSourceRange(); 13193 return QualType(); 13194 } 13195 // At this point, we know we have a real, complex or pointer type. 13196 // Now make sure the operand is a modifiable lvalue. 13197 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13198 return QualType(); 13199 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13200 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13201 // An operand with volatile-qualified type is deprecated 13202 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13203 << IsInc << ResType; 13204 } 13205 // In C++, a prefix increment is the same type as the operand. Otherwise 13206 // (in C or with postfix), the increment is the unqualified type of the 13207 // operand. 13208 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13209 VK = VK_LValue; 13210 OK = Op->getObjectKind(); 13211 return ResType; 13212 } else { 13213 VK = VK_RValue; 13214 return ResType.getUnqualifiedType(); 13215 } 13216 } 13217 13218 13219 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13220 /// This routine allows us to typecheck complex/recursive expressions 13221 /// where the declaration is needed for type checking. We only need to 13222 /// handle cases when the expression references a function designator 13223 /// or is an lvalue. Here are some examples: 13224 /// - &(x) => x 13225 /// - &*****f => f for f a function designator. 13226 /// - &s.xx => s 13227 /// - &s.zz[1].yy -> s, if zz is an array 13228 /// - *(x + 1) -> x, if x is an array 13229 /// - &"123"[2] -> 0 13230 /// - & __real__ x -> x 13231 /// 13232 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13233 /// members. 13234 static ValueDecl *getPrimaryDecl(Expr *E) { 13235 switch (E->getStmtClass()) { 13236 case Stmt::DeclRefExprClass: 13237 return cast<DeclRefExpr>(E)->getDecl(); 13238 case Stmt::MemberExprClass: 13239 // If this is an arrow operator, the address is an offset from 13240 // the base's value, so the object the base refers to is 13241 // irrelevant. 13242 if (cast<MemberExpr>(E)->isArrow()) 13243 return nullptr; 13244 // Otherwise, the expression refers to a part of the base 13245 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13246 case Stmt::ArraySubscriptExprClass: { 13247 // FIXME: This code shouldn't be necessary! We should catch the implicit 13248 // promotion of register arrays earlier. 13249 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13250 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13251 if (ICE->getSubExpr()->getType()->isArrayType()) 13252 return getPrimaryDecl(ICE->getSubExpr()); 13253 } 13254 return nullptr; 13255 } 13256 case Stmt::UnaryOperatorClass: { 13257 UnaryOperator *UO = cast<UnaryOperator>(E); 13258 13259 switch(UO->getOpcode()) { 13260 case UO_Real: 13261 case UO_Imag: 13262 case UO_Extension: 13263 return getPrimaryDecl(UO->getSubExpr()); 13264 default: 13265 return nullptr; 13266 } 13267 } 13268 case Stmt::ParenExprClass: 13269 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13270 case Stmt::ImplicitCastExprClass: 13271 // If the result of an implicit cast is an l-value, we care about 13272 // the sub-expression; otherwise, the result here doesn't matter. 13273 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13274 case Stmt::CXXUuidofExprClass: 13275 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13276 default: 13277 return nullptr; 13278 } 13279 } 13280 13281 namespace { 13282 enum { 13283 AO_Bit_Field = 0, 13284 AO_Vector_Element = 1, 13285 AO_Property_Expansion = 2, 13286 AO_Register_Variable = 3, 13287 AO_Matrix_Element = 4, 13288 AO_No_Error = 5 13289 }; 13290 } 13291 /// Diagnose invalid operand for address of operations. 13292 /// 13293 /// \param Type The type of operand which cannot have its address taken. 13294 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13295 Expr *E, unsigned Type) { 13296 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13297 } 13298 13299 /// CheckAddressOfOperand - The operand of & must be either a function 13300 /// designator or an lvalue designating an object. If it is an lvalue, the 13301 /// object cannot be declared with storage class register or be a bit field. 13302 /// Note: The usual conversions are *not* applied to the operand of the & 13303 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13304 /// In C++, the operand might be an overloaded function name, in which case 13305 /// we allow the '&' but retain the overloaded-function type. 13306 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13307 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13308 if (PTy->getKind() == BuiltinType::Overload) { 13309 Expr *E = OrigOp.get()->IgnoreParens(); 13310 if (!isa<OverloadExpr>(E)) { 13311 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13312 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13313 << OrigOp.get()->getSourceRange(); 13314 return QualType(); 13315 } 13316 13317 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13318 if (isa<UnresolvedMemberExpr>(Ovl)) 13319 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13320 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13321 << OrigOp.get()->getSourceRange(); 13322 return QualType(); 13323 } 13324 13325 return Context.OverloadTy; 13326 } 13327 13328 if (PTy->getKind() == BuiltinType::UnknownAny) 13329 return Context.UnknownAnyTy; 13330 13331 if (PTy->getKind() == BuiltinType::BoundMember) { 13332 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13333 << OrigOp.get()->getSourceRange(); 13334 return QualType(); 13335 } 13336 13337 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13338 if (OrigOp.isInvalid()) return QualType(); 13339 } 13340 13341 if (OrigOp.get()->isTypeDependent()) 13342 return Context.DependentTy; 13343 13344 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13345 13346 // Make sure to ignore parentheses in subsequent checks 13347 Expr *op = OrigOp.get()->IgnoreParens(); 13348 13349 // In OpenCL captures for blocks called as lambda functions 13350 // are located in the private address space. Blocks used in 13351 // enqueue_kernel can be located in a different address space 13352 // depending on a vendor implementation. Thus preventing 13353 // taking an address of the capture to avoid invalid AS casts. 13354 if (LangOpts.OpenCL) { 13355 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13356 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13357 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13358 return QualType(); 13359 } 13360 } 13361 13362 if (getLangOpts().C99) { 13363 // Implement C99-only parts of addressof rules. 13364 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13365 if (uOp->getOpcode() == UO_Deref) 13366 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13367 // (assuming the deref expression is valid). 13368 return uOp->getSubExpr()->getType(); 13369 } 13370 // Technically, there should be a check for array subscript 13371 // expressions here, but the result of one is always an lvalue anyway. 13372 } 13373 ValueDecl *dcl = getPrimaryDecl(op); 13374 13375 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13376 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13377 op->getBeginLoc())) 13378 return QualType(); 13379 13380 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13381 unsigned AddressOfError = AO_No_Error; 13382 13383 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13384 bool sfinae = (bool)isSFINAEContext(); 13385 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13386 : diag::ext_typecheck_addrof_temporary) 13387 << op->getType() << op->getSourceRange(); 13388 if (sfinae) 13389 return QualType(); 13390 // Materialize the temporary as an lvalue so that we can take its address. 13391 OrigOp = op = 13392 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13393 } else if (isa<ObjCSelectorExpr>(op)) { 13394 return Context.getPointerType(op->getType()); 13395 } else if (lval == Expr::LV_MemberFunction) { 13396 // If it's an instance method, make a member pointer. 13397 // The expression must have exactly the form &A::foo. 13398 13399 // If the underlying expression isn't a decl ref, give up. 13400 if (!isa<DeclRefExpr>(op)) { 13401 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13402 << OrigOp.get()->getSourceRange(); 13403 return QualType(); 13404 } 13405 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13406 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13407 13408 // The id-expression was parenthesized. 13409 if (OrigOp.get() != DRE) { 13410 Diag(OpLoc, diag::err_parens_pointer_member_function) 13411 << OrigOp.get()->getSourceRange(); 13412 13413 // The method was named without a qualifier. 13414 } else if (!DRE->getQualifier()) { 13415 if (MD->getParent()->getName().empty()) 13416 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13417 << op->getSourceRange(); 13418 else { 13419 SmallString<32> Str; 13420 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13421 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13422 << op->getSourceRange() 13423 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13424 } 13425 } 13426 13427 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13428 if (isa<CXXDestructorDecl>(MD)) 13429 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13430 13431 QualType MPTy = Context.getMemberPointerType( 13432 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13433 // Under the MS ABI, lock down the inheritance model now. 13434 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13435 (void)isCompleteType(OpLoc, MPTy); 13436 return MPTy; 13437 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13438 // C99 6.5.3.2p1 13439 // The operand must be either an l-value or a function designator 13440 if (!op->getType()->isFunctionType()) { 13441 // Use a special diagnostic for loads from property references. 13442 if (isa<PseudoObjectExpr>(op)) { 13443 AddressOfError = AO_Property_Expansion; 13444 } else { 13445 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13446 << op->getType() << op->getSourceRange(); 13447 return QualType(); 13448 } 13449 } 13450 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13451 // The operand cannot be a bit-field 13452 AddressOfError = AO_Bit_Field; 13453 } else if (op->getObjectKind() == OK_VectorComponent) { 13454 // The operand cannot be an element of a vector 13455 AddressOfError = AO_Vector_Element; 13456 } else if (op->getObjectKind() == OK_MatrixComponent) { 13457 // The operand cannot be an element of a matrix. 13458 AddressOfError = AO_Matrix_Element; 13459 } else if (dcl) { // C99 6.5.3.2p1 13460 // We have an lvalue with a decl. Make sure the decl is not declared 13461 // with the register storage-class specifier. 13462 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13463 // in C++ it is not error to take address of a register 13464 // variable (c++03 7.1.1P3) 13465 if (vd->getStorageClass() == SC_Register && 13466 !getLangOpts().CPlusPlus) { 13467 AddressOfError = AO_Register_Variable; 13468 } 13469 } else if (isa<MSPropertyDecl>(dcl)) { 13470 AddressOfError = AO_Property_Expansion; 13471 } else if (isa<FunctionTemplateDecl>(dcl)) { 13472 return Context.OverloadTy; 13473 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13474 // Okay: we can take the address of a field. 13475 // Could be a pointer to member, though, if there is an explicit 13476 // scope qualifier for the class. 13477 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13478 DeclContext *Ctx = dcl->getDeclContext(); 13479 if (Ctx && Ctx->isRecord()) { 13480 if (dcl->getType()->isReferenceType()) { 13481 Diag(OpLoc, 13482 diag::err_cannot_form_pointer_to_member_of_reference_type) 13483 << dcl->getDeclName() << dcl->getType(); 13484 return QualType(); 13485 } 13486 13487 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13488 Ctx = Ctx->getParent(); 13489 13490 QualType MPTy = Context.getMemberPointerType( 13491 op->getType(), 13492 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13493 // Under the MS ABI, lock down the inheritance model now. 13494 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13495 (void)isCompleteType(OpLoc, MPTy); 13496 return MPTy; 13497 } 13498 } 13499 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13500 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13501 llvm_unreachable("Unknown/unexpected decl type"); 13502 } 13503 13504 if (AddressOfError != AO_No_Error) { 13505 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13506 return QualType(); 13507 } 13508 13509 if (lval == Expr::LV_IncompleteVoidType) { 13510 // Taking the address of a void variable is technically illegal, but we 13511 // allow it in cases which are otherwise valid. 13512 // Example: "extern void x; void* y = &x;". 13513 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13514 } 13515 13516 // If the operand has type "type", the result has type "pointer to type". 13517 if (op->getType()->isObjCObjectType()) 13518 return Context.getObjCObjectPointerType(op->getType()); 13519 13520 CheckAddressOfPackedMember(op); 13521 13522 return Context.getPointerType(op->getType()); 13523 } 13524 13525 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13526 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13527 if (!DRE) 13528 return; 13529 const Decl *D = DRE->getDecl(); 13530 if (!D) 13531 return; 13532 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13533 if (!Param) 13534 return; 13535 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13536 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13537 return; 13538 if (FunctionScopeInfo *FD = S.getCurFunction()) 13539 if (!FD->ModifiedNonNullParams.count(Param)) 13540 FD->ModifiedNonNullParams.insert(Param); 13541 } 13542 13543 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13544 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13545 SourceLocation OpLoc) { 13546 if (Op->isTypeDependent()) 13547 return S.Context.DependentTy; 13548 13549 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13550 if (ConvResult.isInvalid()) 13551 return QualType(); 13552 Op = ConvResult.get(); 13553 QualType OpTy = Op->getType(); 13554 QualType Result; 13555 13556 if (isa<CXXReinterpretCastExpr>(Op)) { 13557 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13558 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13559 Op->getSourceRange()); 13560 } 13561 13562 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13563 { 13564 Result = PT->getPointeeType(); 13565 } 13566 else if (const ObjCObjectPointerType *OPT = 13567 OpTy->getAs<ObjCObjectPointerType>()) 13568 Result = OPT->getPointeeType(); 13569 else { 13570 ExprResult PR = S.CheckPlaceholderExpr(Op); 13571 if (PR.isInvalid()) return QualType(); 13572 if (PR.get() != Op) 13573 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13574 } 13575 13576 if (Result.isNull()) { 13577 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13578 << OpTy << Op->getSourceRange(); 13579 return QualType(); 13580 } 13581 13582 // Note that per both C89 and C99, indirection is always legal, even if Result 13583 // is an incomplete type or void. It would be possible to warn about 13584 // dereferencing a void pointer, but it's completely well-defined, and such a 13585 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13586 // for pointers to 'void' but is fine for any other pointer type: 13587 // 13588 // C++ [expr.unary.op]p1: 13589 // [...] the expression to which [the unary * operator] is applied shall 13590 // be a pointer to an object type, or a pointer to a function type 13591 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13592 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13593 << OpTy << Op->getSourceRange(); 13594 13595 // Dereferences are usually l-values... 13596 VK = VK_LValue; 13597 13598 // ...except that certain expressions are never l-values in C. 13599 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13600 VK = VK_RValue; 13601 13602 return Result; 13603 } 13604 13605 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13606 BinaryOperatorKind Opc; 13607 switch (Kind) { 13608 default: llvm_unreachable("Unknown binop!"); 13609 case tok::periodstar: Opc = BO_PtrMemD; break; 13610 case tok::arrowstar: Opc = BO_PtrMemI; break; 13611 case tok::star: Opc = BO_Mul; break; 13612 case tok::slash: Opc = BO_Div; break; 13613 case tok::percent: Opc = BO_Rem; break; 13614 case tok::plus: Opc = BO_Add; break; 13615 case tok::minus: Opc = BO_Sub; break; 13616 case tok::lessless: Opc = BO_Shl; break; 13617 case tok::greatergreater: Opc = BO_Shr; break; 13618 case tok::lessequal: Opc = BO_LE; break; 13619 case tok::less: Opc = BO_LT; break; 13620 case tok::greaterequal: Opc = BO_GE; break; 13621 case tok::greater: Opc = BO_GT; break; 13622 case tok::exclaimequal: Opc = BO_NE; break; 13623 case tok::equalequal: Opc = BO_EQ; break; 13624 case tok::spaceship: Opc = BO_Cmp; break; 13625 case tok::amp: Opc = BO_And; break; 13626 case tok::caret: Opc = BO_Xor; break; 13627 case tok::pipe: Opc = BO_Or; break; 13628 case tok::ampamp: Opc = BO_LAnd; break; 13629 case tok::pipepipe: Opc = BO_LOr; break; 13630 case tok::equal: Opc = BO_Assign; break; 13631 case tok::starequal: Opc = BO_MulAssign; break; 13632 case tok::slashequal: Opc = BO_DivAssign; break; 13633 case tok::percentequal: Opc = BO_RemAssign; break; 13634 case tok::plusequal: Opc = BO_AddAssign; break; 13635 case tok::minusequal: Opc = BO_SubAssign; break; 13636 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13637 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13638 case tok::ampequal: Opc = BO_AndAssign; break; 13639 case tok::caretequal: Opc = BO_XorAssign; break; 13640 case tok::pipeequal: Opc = BO_OrAssign; break; 13641 case tok::comma: Opc = BO_Comma; break; 13642 } 13643 return Opc; 13644 } 13645 13646 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13647 tok::TokenKind Kind) { 13648 UnaryOperatorKind Opc; 13649 switch (Kind) { 13650 default: llvm_unreachable("Unknown unary op!"); 13651 case tok::plusplus: Opc = UO_PreInc; break; 13652 case tok::minusminus: Opc = UO_PreDec; break; 13653 case tok::amp: Opc = UO_AddrOf; break; 13654 case tok::star: Opc = UO_Deref; break; 13655 case tok::plus: Opc = UO_Plus; break; 13656 case tok::minus: Opc = UO_Minus; break; 13657 case tok::tilde: Opc = UO_Not; break; 13658 case tok::exclaim: Opc = UO_LNot; break; 13659 case tok::kw___real: Opc = UO_Real; break; 13660 case tok::kw___imag: Opc = UO_Imag; break; 13661 case tok::kw___extension__: Opc = UO_Extension; break; 13662 } 13663 return Opc; 13664 } 13665 13666 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13667 /// This warning suppressed in the event of macro expansions. 13668 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13669 SourceLocation OpLoc, bool IsBuiltin) { 13670 if (S.inTemplateInstantiation()) 13671 return; 13672 if (S.isUnevaluatedContext()) 13673 return; 13674 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13675 return; 13676 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13677 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13678 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13679 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13680 if (!LHSDeclRef || !RHSDeclRef || 13681 LHSDeclRef->getLocation().isMacroID() || 13682 RHSDeclRef->getLocation().isMacroID()) 13683 return; 13684 const ValueDecl *LHSDecl = 13685 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13686 const ValueDecl *RHSDecl = 13687 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13688 if (LHSDecl != RHSDecl) 13689 return; 13690 if (LHSDecl->getType().isVolatileQualified()) 13691 return; 13692 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13693 if (RefTy->getPointeeType().isVolatileQualified()) 13694 return; 13695 13696 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13697 : diag::warn_self_assignment_overloaded) 13698 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13699 << RHSExpr->getSourceRange(); 13700 } 13701 13702 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13703 /// is usually indicative of introspection within the Objective-C pointer. 13704 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13705 SourceLocation OpLoc) { 13706 if (!S.getLangOpts().ObjC) 13707 return; 13708 13709 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13710 const Expr *LHS = L.get(); 13711 const Expr *RHS = R.get(); 13712 13713 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13714 ObjCPointerExpr = LHS; 13715 OtherExpr = RHS; 13716 } 13717 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13718 ObjCPointerExpr = RHS; 13719 OtherExpr = LHS; 13720 } 13721 13722 // This warning is deliberately made very specific to reduce false 13723 // positives with logic that uses '&' for hashing. This logic mainly 13724 // looks for code trying to introspect into tagged pointers, which 13725 // code should generally never do. 13726 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13727 unsigned Diag = diag::warn_objc_pointer_masking; 13728 // Determine if we are introspecting the result of performSelectorXXX. 13729 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13730 // Special case messages to -performSelector and friends, which 13731 // can return non-pointer values boxed in a pointer value. 13732 // Some clients may wish to silence warnings in this subcase. 13733 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13734 Selector S = ME->getSelector(); 13735 StringRef SelArg0 = S.getNameForSlot(0); 13736 if (SelArg0.startswith("performSelector")) 13737 Diag = diag::warn_objc_pointer_masking_performSelector; 13738 } 13739 13740 S.Diag(OpLoc, Diag) 13741 << ObjCPointerExpr->getSourceRange(); 13742 } 13743 } 13744 13745 static NamedDecl *getDeclFromExpr(Expr *E) { 13746 if (!E) 13747 return nullptr; 13748 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13749 return DRE->getDecl(); 13750 if (auto *ME = dyn_cast<MemberExpr>(E)) 13751 return ME->getMemberDecl(); 13752 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13753 return IRE->getDecl(); 13754 return nullptr; 13755 } 13756 13757 // This helper function promotes a binary operator's operands (which are of a 13758 // half vector type) to a vector of floats and then truncates the result to 13759 // a vector of either half or short. 13760 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13761 BinaryOperatorKind Opc, QualType ResultTy, 13762 ExprValueKind VK, ExprObjectKind OK, 13763 bool IsCompAssign, SourceLocation OpLoc, 13764 FPOptionsOverride FPFeatures) { 13765 auto &Context = S.getASTContext(); 13766 assert((isVector(ResultTy, Context.HalfTy) || 13767 isVector(ResultTy, Context.ShortTy)) && 13768 "Result must be a vector of half or short"); 13769 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13770 isVector(RHS.get()->getType(), Context.HalfTy) && 13771 "both operands expected to be a half vector"); 13772 13773 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13774 QualType BinOpResTy = RHS.get()->getType(); 13775 13776 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13777 // change BinOpResTy to a vector of ints. 13778 if (isVector(ResultTy, Context.ShortTy)) 13779 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13780 13781 if (IsCompAssign) 13782 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13783 ResultTy, VK, OK, OpLoc, FPFeatures, 13784 BinOpResTy, BinOpResTy); 13785 13786 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13787 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13788 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13789 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13790 } 13791 13792 static std::pair<ExprResult, ExprResult> 13793 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13794 Expr *RHSExpr) { 13795 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13796 if (!S.Context.isDependenceAllowed()) { 13797 // C cannot handle TypoExpr nodes on either side of a binop because it 13798 // doesn't handle dependent types properly, so make sure any TypoExprs have 13799 // been dealt with before checking the operands. 13800 LHS = S.CorrectDelayedTyposInExpr(LHS); 13801 RHS = S.CorrectDelayedTyposInExpr( 13802 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13803 [Opc, LHS](Expr *E) { 13804 if (Opc != BO_Assign) 13805 return ExprResult(E); 13806 // Avoid correcting the RHS to the same Expr as the LHS. 13807 Decl *D = getDeclFromExpr(E); 13808 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13809 }); 13810 } 13811 return std::make_pair(LHS, RHS); 13812 } 13813 13814 /// Returns true if conversion between vectors of halfs and vectors of floats 13815 /// is needed. 13816 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13817 Expr *E0, Expr *E1 = nullptr) { 13818 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13819 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13820 return false; 13821 13822 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13823 QualType Ty = E->IgnoreImplicit()->getType(); 13824 13825 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13826 // to vectors of floats. Although the element type of the vectors is __fp16, 13827 // the vectors shouldn't be treated as storage-only types. See the 13828 // discussion here: https://reviews.llvm.org/rG825235c140e7 13829 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13830 if (VT->getVectorKind() == VectorType::NeonVector) 13831 return false; 13832 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13833 } 13834 return false; 13835 }; 13836 13837 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13838 } 13839 13840 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13841 /// operator @p Opc at location @c TokLoc. This routine only supports 13842 /// built-in operations; ActOnBinOp handles overloaded operators. 13843 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13844 BinaryOperatorKind Opc, 13845 Expr *LHSExpr, Expr *RHSExpr) { 13846 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13847 // The syntax only allows initializer lists on the RHS of assignment, 13848 // so we don't need to worry about accepting invalid code for 13849 // non-assignment operators. 13850 // C++11 5.17p9: 13851 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13852 // of x = {} is x = T(). 13853 InitializationKind Kind = InitializationKind::CreateDirectList( 13854 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13855 InitializedEntity Entity = 13856 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13857 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13858 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13859 if (Init.isInvalid()) 13860 return Init; 13861 RHSExpr = Init.get(); 13862 } 13863 13864 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13865 QualType ResultTy; // Result type of the binary operator. 13866 // The following two variables are used for compound assignment operators 13867 QualType CompLHSTy; // Type of LHS after promotions for computation 13868 QualType CompResultTy; // Type of computation result 13869 ExprValueKind VK = VK_RValue; 13870 ExprObjectKind OK = OK_Ordinary; 13871 bool ConvertHalfVec = false; 13872 13873 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13874 if (!LHS.isUsable() || !RHS.isUsable()) 13875 return ExprError(); 13876 13877 if (getLangOpts().OpenCL) { 13878 QualType LHSTy = LHSExpr->getType(); 13879 QualType RHSTy = RHSExpr->getType(); 13880 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13881 // the ATOMIC_VAR_INIT macro. 13882 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13883 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13884 if (BO_Assign == Opc) 13885 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13886 else 13887 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13888 return ExprError(); 13889 } 13890 13891 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13892 // only with a builtin functions and therefore should be disallowed here. 13893 if (LHSTy->isImageType() || RHSTy->isImageType() || 13894 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13895 LHSTy->isPipeType() || RHSTy->isPipeType() || 13896 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13897 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13898 return ExprError(); 13899 } 13900 } 13901 13902 switch (Opc) { 13903 case BO_Assign: 13904 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13905 if (getLangOpts().CPlusPlus && 13906 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13907 VK = LHS.get()->getValueKind(); 13908 OK = LHS.get()->getObjectKind(); 13909 } 13910 if (!ResultTy.isNull()) { 13911 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13912 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13913 13914 // Avoid copying a block to the heap if the block is assigned to a local 13915 // auto variable that is declared in the same scope as the block. This 13916 // optimization is unsafe if the local variable is declared in an outer 13917 // scope. For example: 13918 // 13919 // BlockTy b; 13920 // { 13921 // b = ^{...}; 13922 // } 13923 // // It is unsafe to invoke the block here if it wasn't copied to the 13924 // // heap. 13925 // b(); 13926 13927 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13928 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13929 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13930 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13931 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13932 13933 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13934 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13935 NTCUC_Assignment, NTCUK_Copy); 13936 } 13937 RecordModifiableNonNullParam(*this, LHS.get()); 13938 break; 13939 case BO_PtrMemD: 13940 case BO_PtrMemI: 13941 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13942 Opc == BO_PtrMemI); 13943 break; 13944 case BO_Mul: 13945 case BO_Div: 13946 ConvertHalfVec = true; 13947 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13948 Opc == BO_Div); 13949 break; 13950 case BO_Rem: 13951 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13952 break; 13953 case BO_Add: 13954 ConvertHalfVec = true; 13955 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13956 break; 13957 case BO_Sub: 13958 ConvertHalfVec = true; 13959 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13960 break; 13961 case BO_Shl: 13962 case BO_Shr: 13963 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13964 break; 13965 case BO_LE: 13966 case BO_LT: 13967 case BO_GE: 13968 case BO_GT: 13969 ConvertHalfVec = true; 13970 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13971 break; 13972 case BO_EQ: 13973 case BO_NE: 13974 ConvertHalfVec = true; 13975 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13976 break; 13977 case BO_Cmp: 13978 ConvertHalfVec = true; 13979 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13980 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13981 break; 13982 case BO_And: 13983 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13984 LLVM_FALLTHROUGH; 13985 case BO_Xor: 13986 case BO_Or: 13987 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13988 break; 13989 case BO_LAnd: 13990 case BO_LOr: 13991 ConvertHalfVec = true; 13992 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13993 break; 13994 case BO_MulAssign: 13995 case BO_DivAssign: 13996 ConvertHalfVec = true; 13997 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13998 Opc == BO_DivAssign); 13999 CompLHSTy = CompResultTy; 14000 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14001 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14002 break; 14003 case BO_RemAssign: 14004 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14005 CompLHSTy = CompResultTy; 14006 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14007 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14008 break; 14009 case BO_AddAssign: 14010 ConvertHalfVec = true; 14011 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14012 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14013 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14014 break; 14015 case BO_SubAssign: 14016 ConvertHalfVec = true; 14017 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14018 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14019 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14020 break; 14021 case BO_ShlAssign: 14022 case BO_ShrAssign: 14023 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14024 CompLHSTy = CompResultTy; 14025 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14026 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14027 break; 14028 case BO_AndAssign: 14029 case BO_OrAssign: // fallthrough 14030 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14031 LLVM_FALLTHROUGH; 14032 case BO_XorAssign: 14033 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14034 CompLHSTy = CompResultTy; 14035 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14036 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14037 break; 14038 case BO_Comma: 14039 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14040 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14041 VK = RHS.get()->getValueKind(); 14042 OK = RHS.get()->getObjectKind(); 14043 } 14044 break; 14045 } 14046 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14047 return ExprError(); 14048 14049 // Some of the binary operations require promoting operands of half vector to 14050 // float vectors and truncating the result back to half vector. For now, we do 14051 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14052 // arm64). 14053 assert( 14054 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14055 isVector(LHS.get()->getType(), Context.HalfTy)) && 14056 "both sides are half vectors or neither sides are"); 14057 ConvertHalfVec = 14058 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14059 14060 // Check for array bounds violations for both sides of the BinaryOperator 14061 CheckArrayAccess(LHS.get()); 14062 CheckArrayAccess(RHS.get()); 14063 14064 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14065 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14066 &Context.Idents.get("object_setClass"), 14067 SourceLocation(), LookupOrdinaryName); 14068 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14069 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14070 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14071 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14072 "object_setClass(") 14073 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14074 ",") 14075 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14076 } 14077 else 14078 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14079 } 14080 else if (const ObjCIvarRefExpr *OIRE = 14081 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14082 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14083 14084 // Opc is not a compound assignment if CompResultTy is null. 14085 if (CompResultTy.isNull()) { 14086 if (ConvertHalfVec) 14087 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14088 OpLoc, CurFPFeatureOverrides()); 14089 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14090 VK, OK, OpLoc, CurFPFeatureOverrides()); 14091 } 14092 14093 // Handle compound assignments. 14094 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14095 OK_ObjCProperty) { 14096 VK = VK_LValue; 14097 OK = LHS.get()->getObjectKind(); 14098 } 14099 14100 // The LHS is not converted to the result type for fixed-point compound 14101 // assignment as the common type is computed on demand. Reset the CompLHSTy 14102 // to the LHS type we would have gotten after unary conversions. 14103 if (CompResultTy->isFixedPointType()) 14104 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14105 14106 if (ConvertHalfVec) 14107 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14108 OpLoc, CurFPFeatureOverrides()); 14109 14110 return CompoundAssignOperator::Create( 14111 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14112 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14113 } 14114 14115 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14116 /// operators are mixed in a way that suggests that the programmer forgot that 14117 /// comparison operators have higher precedence. The most typical example of 14118 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14119 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14120 SourceLocation OpLoc, Expr *LHSExpr, 14121 Expr *RHSExpr) { 14122 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14123 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14124 14125 // Check that one of the sides is a comparison operator and the other isn't. 14126 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14127 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14128 if (isLeftComp == isRightComp) 14129 return; 14130 14131 // Bitwise operations are sometimes used as eager logical ops. 14132 // Don't diagnose this. 14133 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14134 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14135 if (isLeftBitwise || isRightBitwise) 14136 return; 14137 14138 SourceRange DiagRange = isLeftComp 14139 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14140 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14141 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14142 SourceRange ParensRange = 14143 isLeftComp 14144 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14145 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14146 14147 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14148 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14149 SuggestParentheses(Self, OpLoc, 14150 Self.PDiag(diag::note_precedence_silence) << OpStr, 14151 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14152 SuggestParentheses(Self, OpLoc, 14153 Self.PDiag(diag::note_precedence_bitwise_first) 14154 << BinaryOperator::getOpcodeStr(Opc), 14155 ParensRange); 14156 } 14157 14158 /// It accepts a '&&' expr that is inside a '||' one. 14159 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14160 /// in parentheses. 14161 static void 14162 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14163 BinaryOperator *Bop) { 14164 assert(Bop->getOpcode() == BO_LAnd); 14165 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14166 << Bop->getSourceRange() << OpLoc; 14167 SuggestParentheses(Self, Bop->getOperatorLoc(), 14168 Self.PDiag(diag::note_precedence_silence) 14169 << Bop->getOpcodeStr(), 14170 Bop->getSourceRange()); 14171 } 14172 14173 /// Returns true if the given expression can be evaluated as a constant 14174 /// 'true'. 14175 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14176 bool Res; 14177 return !E->isValueDependent() && 14178 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14179 } 14180 14181 /// Returns true if the given expression can be evaluated as a constant 14182 /// 'false'. 14183 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14184 bool Res; 14185 return !E->isValueDependent() && 14186 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14187 } 14188 14189 /// Look for '&&' in the left hand of a '||' expr. 14190 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14191 Expr *LHSExpr, Expr *RHSExpr) { 14192 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14193 if (Bop->getOpcode() == BO_LAnd) { 14194 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14195 if (EvaluatesAsFalse(S, RHSExpr)) 14196 return; 14197 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14198 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14199 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14200 } else if (Bop->getOpcode() == BO_LOr) { 14201 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14202 // If it's "a || b && 1 || c" we didn't warn earlier for 14203 // "a || b && 1", but warn now. 14204 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14205 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14206 } 14207 } 14208 } 14209 } 14210 14211 /// Look for '&&' in the right hand of a '||' expr. 14212 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14213 Expr *LHSExpr, Expr *RHSExpr) { 14214 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14215 if (Bop->getOpcode() == BO_LAnd) { 14216 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14217 if (EvaluatesAsFalse(S, LHSExpr)) 14218 return; 14219 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14220 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14221 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14222 } 14223 } 14224 } 14225 14226 /// Look for bitwise op in the left or right hand of a bitwise op with 14227 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14228 /// the '&' expression in parentheses. 14229 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14230 SourceLocation OpLoc, Expr *SubExpr) { 14231 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14232 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14233 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14234 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14235 << Bop->getSourceRange() << OpLoc; 14236 SuggestParentheses(S, Bop->getOperatorLoc(), 14237 S.PDiag(diag::note_precedence_silence) 14238 << Bop->getOpcodeStr(), 14239 Bop->getSourceRange()); 14240 } 14241 } 14242 } 14243 14244 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14245 Expr *SubExpr, StringRef Shift) { 14246 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14247 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14248 StringRef Op = Bop->getOpcodeStr(); 14249 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14250 << Bop->getSourceRange() << OpLoc << Shift << Op; 14251 SuggestParentheses(S, Bop->getOperatorLoc(), 14252 S.PDiag(diag::note_precedence_silence) << Op, 14253 Bop->getSourceRange()); 14254 } 14255 } 14256 } 14257 14258 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14259 Expr *LHSExpr, Expr *RHSExpr) { 14260 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14261 if (!OCE) 14262 return; 14263 14264 FunctionDecl *FD = OCE->getDirectCallee(); 14265 if (!FD || !FD->isOverloadedOperator()) 14266 return; 14267 14268 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14269 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14270 return; 14271 14272 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14273 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14274 << (Kind == OO_LessLess); 14275 SuggestParentheses(S, OCE->getOperatorLoc(), 14276 S.PDiag(diag::note_precedence_silence) 14277 << (Kind == OO_LessLess ? "<<" : ">>"), 14278 OCE->getSourceRange()); 14279 SuggestParentheses( 14280 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14281 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14282 } 14283 14284 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14285 /// precedence. 14286 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14287 SourceLocation OpLoc, Expr *LHSExpr, 14288 Expr *RHSExpr){ 14289 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14290 if (BinaryOperator::isBitwiseOp(Opc)) 14291 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14292 14293 // Diagnose "arg1 & arg2 | arg3" 14294 if ((Opc == BO_Or || Opc == BO_Xor) && 14295 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14296 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14297 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14298 } 14299 14300 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14301 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14302 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14303 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14304 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14305 } 14306 14307 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14308 || Opc == BO_Shr) { 14309 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14310 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14311 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14312 } 14313 14314 // Warn on overloaded shift operators and comparisons, such as: 14315 // cout << 5 == 4; 14316 if (BinaryOperator::isComparisonOp(Opc)) 14317 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14318 } 14319 14320 // Binary Operators. 'Tok' is the token for the operator. 14321 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14322 tok::TokenKind Kind, 14323 Expr *LHSExpr, Expr *RHSExpr) { 14324 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14325 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14326 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14327 14328 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14329 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14330 14331 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14332 } 14333 14334 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14335 UnresolvedSetImpl &Functions) { 14336 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14337 if (OverOp != OO_None && OverOp != OO_Equal) 14338 LookupOverloadedOperatorName(OverOp, S, Functions); 14339 14340 // In C++20 onwards, we may have a second operator to look up. 14341 if (getLangOpts().CPlusPlus20) { 14342 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14343 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14344 } 14345 } 14346 14347 /// Build an overloaded binary operator expression in the given scope. 14348 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14349 BinaryOperatorKind Opc, 14350 Expr *LHS, Expr *RHS) { 14351 switch (Opc) { 14352 case BO_Assign: 14353 case BO_DivAssign: 14354 case BO_RemAssign: 14355 case BO_SubAssign: 14356 case BO_AndAssign: 14357 case BO_OrAssign: 14358 case BO_XorAssign: 14359 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14360 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14361 break; 14362 default: 14363 break; 14364 } 14365 14366 // Find all of the overloaded operators visible from this point. 14367 UnresolvedSet<16> Functions; 14368 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14369 14370 // Build the (potentially-overloaded, potentially-dependent) 14371 // binary operation. 14372 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14373 } 14374 14375 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14376 BinaryOperatorKind Opc, 14377 Expr *LHSExpr, Expr *RHSExpr) { 14378 ExprResult LHS, RHS; 14379 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14380 if (!LHS.isUsable() || !RHS.isUsable()) 14381 return ExprError(); 14382 LHSExpr = LHS.get(); 14383 RHSExpr = RHS.get(); 14384 14385 // We want to end up calling one of checkPseudoObjectAssignment 14386 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14387 // both expressions are overloadable or either is type-dependent), 14388 // or CreateBuiltinBinOp (in any other case). We also want to get 14389 // any placeholder types out of the way. 14390 14391 // Handle pseudo-objects in the LHS. 14392 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14393 // Assignments with a pseudo-object l-value need special analysis. 14394 if (pty->getKind() == BuiltinType::PseudoObject && 14395 BinaryOperator::isAssignmentOp(Opc)) 14396 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14397 14398 // Don't resolve overloads if the other type is overloadable. 14399 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14400 // We can't actually test that if we still have a placeholder, 14401 // though. Fortunately, none of the exceptions we see in that 14402 // code below are valid when the LHS is an overload set. Note 14403 // that an overload set can be dependently-typed, but it never 14404 // instantiates to having an overloadable type. 14405 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14406 if (resolvedRHS.isInvalid()) return ExprError(); 14407 RHSExpr = resolvedRHS.get(); 14408 14409 if (RHSExpr->isTypeDependent() || 14410 RHSExpr->getType()->isOverloadableType()) 14411 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14412 } 14413 14414 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14415 // template, diagnose the missing 'template' keyword instead of diagnosing 14416 // an invalid use of a bound member function. 14417 // 14418 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14419 // to C++1z [over.over]/1.4, but we already checked for that case above. 14420 if (Opc == BO_LT && inTemplateInstantiation() && 14421 (pty->getKind() == BuiltinType::BoundMember || 14422 pty->getKind() == BuiltinType::Overload)) { 14423 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14424 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14425 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14426 return isa<FunctionTemplateDecl>(ND); 14427 })) { 14428 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14429 : OE->getNameLoc(), 14430 diag::err_template_kw_missing) 14431 << OE->getName().getAsString() << ""; 14432 return ExprError(); 14433 } 14434 } 14435 14436 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14437 if (LHS.isInvalid()) return ExprError(); 14438 LHSExpr = LHS.get(); 14439 } 14440 14441 // Handle pseudo-objects in the RHS. 14442 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14443 // An overload in the RHS can potentially be resolved by the type 14444 // being assigned to. 14445 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14446 if (getLangOpts().CPlusPlus && 14447 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14448 LHSExpr->getType()->isOverloadableType())) 14449 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14450 14451 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14452 } 14453 14454 // Don't resolve overloads if the other type is overloadable. 14455 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14456 LHSExpr->getType()->isOverloadableType()) 14457 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14458 14459 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14460 if (!resolvedRHS.isUsable()) return ExprError(); 14461 RHSExpr = resolvedRHS.get(); 14462 } 14463 14464 if (getLangOpts().CPlusPlus) { 14465 // If either expression is type-dependent, always build an 14466 // overloaded op. 14467 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14468 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14469 14470 // Otherwise, build an overloaded op if either expression has an 14471 // overloadable type. 14472 if (LHSExpr->getType()->isOverloadableType() || 14473 RHSExpr->getType()->isOverloadableType()) 14474 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14475 } 14476 14477 if (getLangOpts().RecoveryAST && 14478 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14479 assert(!getLangOpts().CPlusPlus); 14480 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14481 "Should only occur in error-recovery path."); 14482 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14483 // C [6.15.16] p3: 14484 // An assignment expression has the value of the left operand after the 14485 // assignment, but is not an lvalue. 14486 return CompoundAssignOperator::Create( 14487 Context, LHSExpr, RHSExpr, Opc, 14488 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14489 OpLoc, CurFPFeatureOverrides()); 14490 QualType ResultType; 14491 switch (Opc) { 14492 case BO_Assign: 14493 ResultType = LHSExpr->getType().getUnqualifiedType(); 14494 break; 14495 case BO_LT: 14496 case BO_GT: 14497 case BO_LE: 14498 case BO_GE: 14499 case BO_EQ: 14500 case BO_NE: 14501 case BO_LAnd: 14502 case BO_LOr: 14503 // These operators have a fixed result type regardless of operands. 14504 ResultType = Context.IntTy; 14505 break; 14506 case BO_Comma: 14507 ResultType = RHSExpr->getType(); 14508 break; 14509 default: 14510 ResultType = Context.DependentTy; 14511 break; 14512 } 14513 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14514 VK_RValue, OK_Ordinary, OpLoc, 14515 CurFPFeatureOverrides()); 14516 } 14517 14518 // Build a built-in binary operation. 14519 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14520 } 14521 14522 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14523 if (T.isNull() || T->isDependentType()) 14524 return false; 14525 14526 if (!T->isPromotableIntegerType()) 14527 return true; 14528 14529 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14530 } 14531 14532 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14533 UnaryOperatorKind Opc, 14534 Expr *InputExpr) { 14535 ExprResult Input = InputExpr; 14536 ExprValueKind VK = VK_RValue; 14537 ExprObjectKind OK = OK_Ordinary; 14538 QualType resultType; 14539 bool CanOverflow = false; 14540 14541 bool ConvertHalfVec = false; 14542 if (getLangOpts().OpenCL) { 14543 QualType Ty = InputExpr->getType(); 14544 // The only legal unary operation for atomics is '&'. 14545 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14546 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14547 // only with a builtin functions and therefore should be disallowed here. 14548 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14549 || Ty->isBlockPointerType())) { 14550 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14551 << InputExpr->getType() 14552 << Input.get()->getSourceRange()); 14553 } 14554 } 14555 14556 switch (Opc) { 14557 case UO_PreInc: 14558 case UO_PreDec: 14559 case UO_PostInc: 14560 case UO_PostDec: 14561 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14562 OpLoc, 14563 Opc == UO_PreInc || 14564 Opc == UO_PostInc, 14565 Opc == UO_PreInc || 14566 Opc == UO_PreDec); 14567 CanOverflow = isOverflowingIntegerType(Context, resultType); 14568 break; 14569 case UO_AddrOf: 14570 resultType = CheckAddressOfOperand(Input, OpLoc); 14571 CheckAddressOfNoDeref(InputExpr); 14572 RecordModifiableNonNullParam(*this, InputExpr); 14573 break; 14574 case UO_Deref: { 14575 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14576 if (Input.isInvalid()) return ExprError(); 14577 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14578 break; 14579 } 14580 case UO_Plus: 14581 case UO_Minus: 14582 CanOverflow = Opc == UO_Minus && 14583 isOverflowingIntegerType(Context, Input.get()->getType()); 14584 Input = UsualUnaryConversions(Input.get()); 14585 if (Input.isInvalid()) return ExprError(); 14586 // Unary plus and minus require promoting an operand of half vector to a 14587 // float vector and truncating the result back to a half vector. For now, we 14588 // do this only when HalfArgsAndReturns is set (that is, when the target is 14589 // arm or arm64). 14590 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14591 14592 // If the operand is a half vector, promote it to a float vector. 14593 if (ConvertHalfVec) 14594 Input = convertVector(Input.get(), Context.FloatTy, *this); 14595 resultType = Input.get()->getType(); 14596 if (resultType->isDependentType()) 14597 break; 14598 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14599 break; 14600 else if (resultType->isVectorType() && 14601 // The z vector extensions don't allow + or - with bool vectors. 14602 (!Context.getLangOpts().ZVector || 14603 resultType->castAs<VectorType>()->getVectorKind() != 14604 VectorType::AltiVecBool)) 14605 break; 14606 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14607 Opc == UO_Plus && 14608 resultType->isPointerType()) 14609 break; 14610 14611 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14612 << resultType << Input.get()->getSourceRange()); 14613 14614 case UO_Not: // bitwise complement 14615 Input = UsualUnaryConversions(Input.get()); 14616 if (Input.isInvalid()) 14617 return ExprError(); 14618 resultType = Input.get()->getType(); 14619 if (resultType->isDependentType()) 14620 break; 14621 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14622 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14623 // C99 does not support '~' for complex conjugation. 14624 Diag(OpLoc, diag::ext_integer_complement_complex) 14625 << resultType << Input.get()->getSourceRange(); 14626 else if (resultType->hasIntegerRepresentation()) 14627 break; 14628 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14629 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14630 // on vector float types. 14631 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14632 if (!T->isIntegerType()) 14633 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14634 << resultType << Input.get()->getSourceRange()); 14635 } else { 14636 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14637 << resultType << Input.get()->getSourceRange()); 14638 } 14639 break; 14640 14641 case UO_LNot: // logical negation 14642 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14643 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14644 if (Input.isInvalid()) return ExprError(); 14645 resultType = Input.get()->getType(); 14646 14647 // Though we still have to promote half FP to float... 14648 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14649 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14650 resultType = Context.FloatTy; 14651 } 14652 14653 if (resultType->isDependentType()) 14654 break; 14655 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14656 // C99 6.5.3.3p1: ok, fallthrough; 14657 if (Context.getLangOpts().CPlusPlus) { 14658 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14659 // operand contextually converted to bool. 14660 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14661 ScalarTypeToBooleanCastKind(resultType)); 14662 } else if (Context.getLangOpts().OpenCL && 14663 Context.getLangOpts().OpenCLVersion < 120) { 14664 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14665 // operate on scalar float types. 14666 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14667 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14668 << resultType << Input.get()->getSourceRange()); 14669 } 14670 } else if (resultType->isExtVectorType()) { 14671 if (Context.getLangOpts().OpenCL && 14672 Context.getLangOpts().OpenCLVersion < 120 && 14673 !Context.getLangOpts().OpenCLCPlusPlus) { 14674 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14675 // operate on vector float types. 14676 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14677 if (!T->isIntegerType()) 14678 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14679 << resultType << Input.get()->getSourceRange()); 14680 } 14681 // Vector logical not returns the signed variant of the operand type. 14682 resultType = GetSignedVectorType(resultType); 14683 break; 14684 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14685 const VectorType *VTy = resultType->castAs<VectorType>(); 14686 if (VTy->getVectorKind() != VectorType::GenericVector) 14687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14688 << resultType << Input.get()->getSourceRange()); 14689 14690 // Vector logical not returns the signed variant of the operand type. 14691 resultType = GetSignedVectorType(resultType); 14692 break; 14693 } else { 14694 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14695 << resultType << Input.get()->getSourceRange()); 14696 } 14697 14698 // LNot always has type int. C99 6.5.3.3p5. 14699 // In C++, it's bool. C++ 5.3.1p8 14700 resultType = Context.getLogicalOperationType(); 14701 break; 14702 case UO_Real: 14703 case UO_Imag: 14704 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14705 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14706 // complex l-values to ordinary l-values and all other values to r-values. 14707 if (Input.isInvalid()) return ExprError(); 14708 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14709 if (Input.get()->getValueKind() != VK_RValue && 14710 Input.get()->getObjectKind() == OK_Ordinary) 14711 VK = Input.get()->getValueKind(); 14712 } else if (!getLangOpts().CPlusPlus) { 14713 // In C, a volatile scalar is read by __imag. In C++, it is not. 14714 Input = DefaultLvalueConversion(Input.get()); 14715 } 14716 break; 14717 case UO_Extension: 14718 resultType = Input.get()->getType(); 14719 VK = Input.get()->getValueKind(); 14720 OK = Input.get()->getObjectKind(); 14721 break; 14722 case UO_Coawait: 14723 // It's unnecessary to represent the pass-through operator co_await in the 14724 // AST; just return the input expression instead. 14725 assert(!Input.get()->getType()->isDependentType() && 14726 "the co_await expression must be non-dependant before " 14727 "building operator co_await"); 14728 return Input; 14729 } 14730 if (resultType.isNull() || Input.isInvalid()) 14731 return ExprError(); 14732 14733 // Check for array bounds violations in the operand of the UnaryOperator, 14734 // except for the '*' and '&' operators that have to be handled specially 14735 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14736 // that are explicitly defined as valid by the standard). 14737 if (Opc != UO_AddrOf && Opc != UO_Deref) 14738 CheckArrayAccess(Input.get()); 14739 14740 auto *UO = 14741 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14742 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14743 14744 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14745 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14746 !isUnevaluatedContext()) 14747 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14748 14749 // Convert the result back to a half vector. 14750 if (ConvertHalfVec) 14751 return convertVector(UO, Context.HalfTy, *this); 14752 return UO; 14753 } 14754 14755 /// Determine whether the given expression is a qualified member 14756 /// access expression, of a form that could be turned into a pointer to member 14757 /// with the address-of operator. 14758 bool Sema::isQualifiedMemberAccess(Expr *E) { 14759 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14760 if (!DRE->getQualifier()) 14761 return false; 14762 14763 ValueDecl *VD = DRE->getDecl(); 14764 if (!VD->isCXXClassMember()) 14765 return false; 14766 14767 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14768 return true; 14769 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14770 return Method->isInstance(); 14771 14772 return false; 14773 } 14774 14775 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14776 if (!ULE->getQualifier()) 14777 return false; 14778 14779 for (NamedDecl *D : ULE->decls()) { 14780 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14781 if (Method->isInstance()) 14782 return true; 14783 } else { 14784 // Overload set does not contain methods. 14785 break; 14786 } 14787 } 14788 14789 return false; 14790 } 14791 14792 return false; 14793 } 14794 14795 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14796 UnaryOperatorKind Opc, Expr *Input) { 14797 // First things first: handle placeholders so that the 14798 // overloaded-operator check considers the right type. 14799 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14800 // Increment and decrement of pseudo-object references. 14801 if (pty->getKind() == BuiltinType::PseudoObject && 14802 UnaryOperator::isIncrementDecrementOp(Opc)) 14803 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14804 14805 // extension is always a builtin operator. 14806 if (Opc == UO_Extension) 14807 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14808 14809 // & gets special logic for several kinds of placeholder. 14810 // The builtin code knows what to do. 14811 if (Opc == UO_AddrOf && 14812 (pty->getKind() == BuiltinType::Overload || 14813 pty->getKind() == BuiltinType::UnknownAny || 14814 pty->getKind() == BuiltinType::BoundMember)) 14815 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14816 14817 // Anything else needs to be handled now. 14818 ExprResult Result = CheckPlaceholderExpr(Input); 14819 if (Result.isInvalid()) return ExprError(); 14820 Input = Result.get(); 14821 } 14822 14823 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14824 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14825 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14826 // Find all of the overloaded operators visible from this point. 14827 UnresolvedSet<16> Functions; 14828 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14829 if (S && OverOp != OO_None) 14830 LookupOverloadedOperatorName(OverOp, S, Functions); 14831 14832 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14833 } 14834 14835 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14836 } 14837 14838 // Unary Operators. 'Tok' is the token for the operator. 14839 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14840 tok::TokenKind Op, Expr *Input) { 14841 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14842 } 14843 14844 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14845 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14846 LabelDecl *TheDecl) { 14847 TheDecl->markUsed(Context); 14848 // Create the AST node. The address of a label always has type 'void*'. 14849 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14850 Context.getPointerType(Context.VoidTy)); 14851 } 14852 14853 void Sema::ActOnStartStmtExpr() { 14854 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14855 } 14856 14857 void Sema::ActOnStmtExprError() { 14858 // Note that function is also called by TreeTransform when leaving a 14859 // StmtExpr scope without rebuilding anything. 14860 14861 DiscardCleanupsInEvaluationContext(); 14862 PopExpressionEvaluationContext(); 14863 } 14864 14865 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14866 SourceLocation RPLoc) { 14867 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14868 } 14869 14870 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14871 SourceLocation RPLoc, unsigned TemplateDepth) { 14872 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14873 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14874 14875 if (hasAnyUnrecoverableErrorsInThisFunction()) 14876 DiscardCleanupsInEvaluationContext(); 14877 assert(!Cleanup.exprNeedsCleanups() && 14878 "cleanups within StmtExpr not correctly bound!"); 14879 PopExpressionEvaluationContext(); 14880 14881 // FIXME: there are a variety of strange constraints to enforce here, for 14882 // example, it is not possible to goto into a stmt expression apparently. 14883 // More semantic analysis is needed. 14884 14885 // If there are sub-stmts in the compound stmt, take the type of the last one 14886 // as the type of the stmtexpr. 14887 QualType Ty = Context.VoidTy; 14888 bool StmtExprMayBindToTemp = false; 14889 if (!Compound->body_empty()) { 14890 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14891 if (const auto *LastStmt = 14892 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14893 if (const Expr *Value = LastStmt->getExprStmt()) { 14894 StmtExprMayBindToTemp = true; 14895 Ty = Value->getType(); 14896 } 14897 } 14898 } 14899 14900 // FIXME: Check that expression type is complete/non-abstract; statement 14901 // expressions are not lvalues. 14902 Expr *ResStmtExpr = 14903 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14904 if (StmtExprMayBindToTemp) 14905 return MaybeBindToTemporary(ResStmtExpr); 14906 return ResStmtExpr; 14907 } 14908 14909 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14910 if (ER.isInvalid()) 14911 return ExprError(); 14912 14913 // Do function/array conversion on the last expression, but not 14914 // lvalue-to-rvalue. However, initialize an unqualified type. 14915 ER = DefaultFunctionArrayConversion(ER.get()); 14916 if (ER.isInvalid()) 14917 return ExprError(); 14918 Expr *E = ER.get(); 14919 14920 if (E->isTypeDependent()) 14921 return E; 14922 14923 // In ARC, if the final expression ends in a consume, splice 14924 // the consume out and bind it later. In the alternate case 14925 // (when dealing with a retainable type), the result 14926 // initialization will create a produce. In both cases the 14927 // result will be +1, and we'll need to balance that out with 14928 // a bind. 14929 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14930 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14931 return Cast->getSubExpr(); 14932 14933 // FIXME: Provide a better location for the initialization. 14934 return PerformCopyInitialization( 14935 InitializedEntity::InitializeStmtExprResult( 14936 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14937 SourceLocation(), E); 14938 } 14939 14940 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14941 TypeSourceInfo *TInfo, 14942 ArrayRef<OffsetOfComponent> Components, 14943 SourceLocation RParenLoc) { 14944 QualType ArgTy = TInfo->getType(); 14945 bool Dependent = ArgTy->isDependentType(); 14946 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14947 14948 // We must have at least one component that refers to the type, and the first 14949 // one is known to be a field designator. Verify that the ArgTy represents 14950 // a struct/union/class. 14951 if (!Dependent && !ArgTy->isRecordType()) 14952 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14953 << ArgTy << TypeRange); 14954 14955 // Type must be complete per C99 7.17p3 because a declaring a variable 14956 // with an incomplete type would be ill-formed. 14957 if (!Dependent 14958 && RequireCompleteType(BuiltinLoc, ArgTy, 14959 diag::err_offsetof_incomplete_type, TypeRange)) 14960 return ExprError(); 14961 14962 bool DidWarnAboutNonPOD = false; 14963 QualType CurrentType = ArgTy; 14964 SmallVector<OffsetOfNode, 4> Comps; 14965 SmallVector<Expr*, 4> Exprs; 14966 for (const OffsetOfComponent &OC : Components) { 14967 if (OC.isBrackets) { 14968 // Offset of an array sub-field. TODO: Should we allow vector elements? 14969 if (!CurrentType->isDependentType()) { 14970 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14971 if(!AT) 14972 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14973 << CurrentType); 14974 CurrentType = AT->getElementType(); 14975 } else 14976 CurrentType = Context.DependentTy; 14977 14978 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14979 if (IdxRval.isInvalid()) 14980 return ExprError(); 14981 Expr *Idx = IdxRval.get(); 14982 14983 // The expression must be an integral expression. 14984 // FIXME: An integral constant expression? 14985 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14986 !Idx->getType()->isIntegerType()) 14987 return ExprError( 14988 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14989 << Idx->getSourceRange()); 14990 14991 // Record this array index. 14992 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14993 Exprs.push_back(Idx); 14994 continue; 14995 } 14996 14997 // Offset of a field. 14998 if (CurrentType->isDependentType()) { 14999 // We have the offset of a field, but we can't look into the dependent 15000 // type. Just record the identifier of the field. 15001 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15002 CurrentType = Context.DependentTy; 15003 continue; 15004 } 15005 15006 // We need to have a complete type to look into. 15007 if (RequireCompleteType(OC.LocStart, CurrentType, 15008 diag::err_offsetof_incomplete_type)) 15009 return ExprError(); 15010 15011 // Look for the designated field. 15012 const RecordType *RC = CurrentType->getAs<RecordType>(); 15013 if (!RC) 15014 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15015 << CurrentType); 15016 RecordDecl *RD = RC->getDecl(); 15017 15018 // C++ [lib.support.types]p5: 15019 // The macro offsetof accepts a restricted set of type arguments in this 15020 // International Standard. type shall be a POD structure or a POD union 15021 // (clause 9). 15022 // C++11 [support.types]p4: 15023 // If type is not a standard-layout class (Clause 9), the results are 15024 // undefined. 15025 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15026 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15027 unsigned DiagID = 15028 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15029 : diag::ext_offsetof_non_pod_type; 15030 15031 if (!IsSafe && !DidWarnAboutNonPOD && 15032 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15033 PDiag(DiagID) 15034 << SourceRange(Components[0].LocStart, OC.LocEnd) 15035 << CurrentType)) 15036 DidWarnAboutNonPOD = true; 15037 } 15038 15039 // Look for the field. 15040 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15041 LookupQualifiedName(R, RD); 15042 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15043 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15044 if (!MemberDecl) { 15045 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15046 MemberDecl = IndirectMemberDecl->getAnonField(); 15047 } 15048 15049 if (!MemberDecl) 15050 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15051 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15052 OC.LocEnd)); 15053 15054 // C99 7.17p3: 15055 // (If the specified member is a bit-field, the behavior is undefined.) 15056 // 15057 // We diagnose this as an error. 15058 if (MemberDecl->isBitField()) { 15059 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15060 << MemberDecl->getDeclName() 15061 << SourceRange(BuiltinLoc, RParenLoc); 15062 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15063 return ExprError(); 15064 } 15065 15066 RecordDecl *Parent = MemberDecl->getParent(); 15067 if (IndirectMemberDecl) 15068 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15069 15070 // If the member was found in a base class, introduce OffsetOfNodes for 15071 // the base class indirections. 15072 CXXBasePaths Paths; 15073 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15074 Paths)) { 15075 if (Paths.getDetectedVirtual()) { 15076 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15077 << MemberDecl->getDeclName() 15078 << SourceRange(BuiltinLoc, RParenLoc); 15079 return ExprError(); 15080 } 15081 15082 CXXBasePath &Path = Paths.front(); 15083 for (const CXXBasePathElement &B : Path) 15084 Comps.push_back(OffsetOfNode(B.Base)); 15085 } 15086 15087 if (IndirectMemberDecl) { 15088 for (auto *FI : IndirectMemberDecl->chain()) { 15089 assert(isa<FieldDecl>(FI)); 15090 Comps.push_back(OffsetOfNode(OC.LocStart, 15091 cast<FieldDecl>(FI), OC.LocEnd)); 15092 } 15093 } else 15094 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15095 15096 CurrentType = MemberDecl->getType().getNonReferenceType(); 15097 } 15098 15099 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15100 Comps, Exprs, RParenLoc); 15101 } 15102 15103 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15104 SourceLocation BuiltinLoc, 15105 SourceLocation TypeLoc, 15106 ParsedType ParsedArgTy, 15107 ArrayRef<OffsetOfComponent> Components, 15108 SourceLocation RParenLoc) { 15109 15110 TypeSourceInfo *ArgTInfo; 15111 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15112 if (ArgTy.isNull()) 15113 return ExprError(); 15114 15115 if (!ArgTInfo) 15116 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15117 15118 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15119 } 15120 15121 15122 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15123 Expr *CondExpr, 15124 Expr *LHSExpr, Expr *RHSExpr, 15125 SourceLocation RPLoc) { 15126 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15127 15128 ExprValueKind VK = VK_RValue; 15129 ExprObjectKind OK = OK_Ordinary; 15130 QualType resType; 15131 bool CondIsTrue = false; 15132 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15133 resType = Context.DependentTy; 15134 } else { 15135 // The conditional expression is required to be a constant expression. 15136 llvm::APSInt condEval(32); 15137 ExprResult CondICE = VerifyIntegerConstantExpression( 15138 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15139 if (CondICE.isInvalid()) 15140 return ExprError(); 15141 CondExpr = CondICE.get(); 15142 CondIsTrue = condEval.getZExtValue(); 15143 15144 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15145 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15146 15147 resType = ActiveExpr->getType(); 15148 VK = ActiveExpr->getValueKind(); 15149 OK = ActiveExpr->getObjectKind(); 15150 } 15151 15152 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15153 resType, VK, OK, RPLoc, CondIsTrue); 15154 } 15155 15156 //===----------------------------------------------------------------------===// 15157 // Clang Extensions. 15158 //===----------------------------------------------------------------------===// 15159 15160 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15161 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15162 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15163 15164 if (LangOpts.CPlusPlus) { 15165 MangleNumberingContext *MCtx; 15166 Decl *ManglingContextDecl; 15167 std::tie(MCtx, ManglingContextDecl) = 15168 getCurrentMangleNumberContext(Block->getDeclContext()); 15169 if (MCtx) { 15170 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15171 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15172 } 15173 } 15174 15175 PushBlockScope(CurScope, Block); 15176 CurContext->addDecl(Block); 15177 if (CurScope) 15178 PushDeclContext(CurScope, Block); 15179 else 15180 CurContext = Block; 15181 15182 getCurBlock()->HasImplicitReturnType = true; 15183 15184 // Enter a new evaluation context to insulate the block from any 15185 // cleanups from the enclosing full-expression. 15186 PushExpressionEvaluationContext( 15187 ExpressionEvaluationContext::PotentiallyEvaluated); 15188 } 15189 15190 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15191 Scope *CurScope) { 15192 assert(ParamInfo.getIdentifier() == nullptr && 15193 "block-id should have no identifier!"); 15194 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15195 BlockScopeInfo *CurBlock = getCurBlock(); 15196 15197 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15198 QualType T = Sig->getType(); 15199 15200 // FIXME: We should allow unexpanded parameter packs here, but that would, 15201 // in turn, make the block expression contain unexpanded parameter packs. 15202 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15203 // Drop the parameters. 15204 FunctionProtoType::ExtProtoInfo EPI; 15205 EPI.HasTrailingReturn = false; 15206 EPI.TypeQuals.addConst(); 15207 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15208 Sig = Context.getTrivialTypeSourceInfo(T); 15209 } 15210 15211 // GetTypeForDeclarator always produces a function type for a block 15212 // literal signature. Furthermore, it is always a FunctionProtoType 15213 // unless the function was written with a typedef. 15214 assert(T->isFunctionType() && 15215 "GetTypeForDeclarator made a non-function block signature"); 15216 15217 // Look for an explicit signature in that function type. 15218 FunctionProtoTypeLoc ExplicitSignature; 15219 15220 if ((ExplicitSignature = Sig->getTypeLoc() 15221 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15222 15223 // Check whether that explicit signature was synthesized by 15224 // GetTypeForDeclarator. If so, don't save that as part of the 15225 // written signature. 15226 if (ExplicitSignature.getLocalRangeBegin() == 15227 ExplicitSignature.getLocalRangeEnd()) { 15228 // This would be much cheaper if we stored TypeLocs instead of 15229 // TypeSourceInfos. 15230 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15231 unsigned Size = Result.getFullDataSize(); 15232 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15233 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15234 15235 ExplicitSignature = FunctionProtoTypeLoc(); 15236 } 15237 } 15238 15239 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15240 CurBlock->FunctionType = T; 15241 15242 const auto *Fn = T->castAs<FunctionType>(); 15243 QualType RetTy = Fn->getReturnType(); 15244 bool isVariadic = 15245 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15246 15247 CurBlock->TheDecl->setIsVariadic(isVariadic); 15248 15249 // Context.DependentTy is used as a placeholder for a missing block 15250 // return type. TODO: what should we do with declarators like: 15251 // ^ * { ... } 15252 // If the answer is "apply template argument deduction".... 15253 if (RetTy != Context.DependentTy) { 15254 CurBlock->ReturnType = RetTy; 15255 CurBlock->TheDecl->setBlockMissingReturnType(false); 15256 CurBlock->HasImplicitReturnType = false; 15257 } 15258 15259 // Push block parameters from the declarator if we had them. 15260 SmallVector<ParmVarDecl*, 8> Params; 15261 if (ExplicitSignature) { 15262 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15263 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15264 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15265 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15266 // Diagnose this as an extension in C17 and earlier. 15267 if (!getLangOpts().C2x) 15268 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15269 } 15270 Params.push_back(Param); 15271 } 15272 15273 // Fake up parameter variables if we have a typedef, like 15274 // ^ fntype { ... } 15275 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15276 for (const auto &I : Fn->param_types()) { 15277 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15278 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15279 Params.push_back(Param); 15280 } 15281 } 15282 15283 // Set the parameters on the block decl. 15284 if (!Params.empty()) { 15285 CurBlock->TheDecl->setParams(Params); 15286 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15287 /*CheckParameterNames=*/false); 15288 } 15289 15290 // Finally we can process decl attributes. 15291 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15292 15293 // Put the parameter variables in scope. 15294 for (auto AI : CurBlock->TheDecl->parameters()) { 15295 AI->setOwningFunction(CurBlock->TheDecl); 15296 15297 // If this has an identifier, add it to the scope stack. 15298 if (AI->getIdentifier()) { 15299 CheckShadow(CurBlock->TheScope, AI); 15300 15301 PushOnScopeChains(AI, CurBlock->TheScope); 15302 } 15303 } 15304 } 15305 15306 /// ActOnBlockError - If there is an error parsing a block, this callback 15307 /// is invoked to pop the information about the block from the action impl. 15308 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15309 // Leave the expression-evaluation context. 15310 DiscardCleanupsInEvaluationContext(); 15311 PopExpressionEvaluationContext(); 15312 15313 // Pop off CurBlock, handle nested blocks. 15314 PopDeclContext(); 15315 PopFunctionScopeInfo(); 15316 } 15317 15318 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15319 /// literal was successfully completed. ^(int x){...} 15320 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15321 Stmt *Body, Scope *CurScope) { 15322 // If blocks are disabled, emit an error. 15323 if (!LangOpts.Blocks) 15324 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15325 15326 // Leave the expression-evaluation context. 15327 if (hasAnyUnrecoverableErrorsInThisFunction()) 15328 DiscardCleanupsInEvaluationContext(); 15329 assert(!Cleanup.exprNeedsCleanups() && 15330 "cleanups within block not correctly bound!"); 15331 PopExpressionEvaluationContext(); 15332 15333 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15334 BlockDecl *BD = BSI->TheDecl; 15335 15336 if (BSI->HasImplicitReturnType) 15337 deduceClosureReturnType(*BSI); 15338 15339 QualType RetTy = Context.VoidTy; 15340 if (!BSI->ReturnType.isNull()) 15341 RetTy = BSI->ReturnType; 15342 15343 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15344 QualType BlockTy; 15345 15346 // If the user wrote a function type in some form, try to use that. 15347 if (!BSI->FunctionType.isNull()) { 15348 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15349 15350 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15351 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15352 15353 // Turn protoless block types into nullary block types. 15354 if (isa<FunctionNoProtoType>(FTy)) { 15355 FunctionProtoType::ExtProtoInfo EPI; 15356 EPI.ExtInfo = Ext; 15357 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15358 15359 // Otherwise, if we don't need to change anything about the function type, 15360 // preserve its sugar structure. 15361 } else if (FTy->getReturnType() == RetTy && 15362 (!NoReturn || FTy->getNoReturnAttr())) { 15363 BlockTy = BSI->FunctionType; 15364 15365 // Otherwise, make the minimal modifications to the function type. 15366 } else { 15367 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15368 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15369 EPI.TypeQuals = Qualifiers(); 15370 EPI.ExtInfo = Ext; 15371 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15372 } 15373 15374 // If we don't have a function type, just build one from nothing. 15375 } else { 15376 FunctionProtoType::ExtProtoInfo EPI; 15377 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15378 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15379 } 15380 15381 DiagnoseUnusedParameters(BD->parameters()); 15382 BlockTy = Context.getBlockPointerType(BlockTy); 15383 15384 // If needed, diagnose invalid gotos and switches in the block. 15385 if (getCurFunction()->NeedsScopeChecking() && 15386 !PP.isCodeCompletionEnabled()) 15387 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15388 15389 BD->setBody(cast<CompoundStmt>(Body)); 15390 15391 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15392 DiagnoseUnguardedAvailabilityViolations(BD); 15393 15394 // Try to apply the named return value optimization. We have to check again 15395 // if we can do this, though, because blocks keep return statements around 15396 // to deduce an implicit return type. 15397 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15398 !BD->isDependentContext()) 15399 computeNRVO(Body, BSI); 15400 15401 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15402 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15403 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15404 NTCUK_Destruct|NTCUK_Copy); 15405 15406 PopDeclContext(); 15407 15408 // Set the captured variables on the block. 15409 SmallVector<BlockDecl::Capture, 4> Captures; 15410 for (Capture &Cap : BSI->Captures) { 15411 if (Cap.isInvalid() || Cap.isThisCapture()) 15412 continue; 15413 15414 VarDecl *Var = Cap.getVariable(); 15415 Expr *CopyExpr = nullptr; 15416 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15417 if (const RecordType *Record = 15418 Cap.getCaptureType()->getAs<RecordType>()) { 15419 // The capture logic needs the destructor, so make sure we mark it. 15420 // Usually this is unnecessary because most local variables have 15421 // their destructors marked at declaration time, but parameters are 15422 // an exception because it's technically only the call site that 15423 // actually requires the destructor. 15424 if (isa<ParmVarDecl>(Var)) 15425 FinalizeVarWithDestructor(Var, Record); 15426 15427 // Enter a separate potentially-evaluated context while building block 15428 // initializers to isolate their cleanups from those of the block 15429 // itself. 15430 // FIXME: Is this appropriate even when the block itself occurs in an 15431 // unevaluated operand? 15432 EnterExpressionEvaluationContext EvalContext( 15433 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15434 15435 SourceLocation Loc = Cap.getLocation(); 15436 15437 ExprResult Result = BuildDeclarationNameExpr( 15438 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15439 15440 // According to the blocks spec, the capture of a variable from 15441 // the stack requires a const copy constructor. This is not true 15442 // of the copy/move done to move a __block variable to the heap. 15443 if (!Result.isInvalid() && 15444 !Result.get()->getType().isConstQualified()) { 15445 Result = ImpCastExprToType(Result.get(), 15446 Result.get()->getType().withConst(), 15447 CK_NoOp, VK_LValue); 15448 } 15449 15450 if (!Result.isInvalid()) { 15451 Result = PerformCopyInitialization( 15452 InitializedEntity::InitializeBlock(Var->getLocation(), 15453 Cap.getCaptureType(), false), 15454 Loc, Result.get()); 15455 } 15456 15457 // Build a full-expression copy expression if initialization 15458 // succeeded and used a non-trivial constructor. Recover from 15459 // errors by pretending that the copy isn't necessary. 15460 if (!Result.isInvalid() && 15461 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15462 ->isTrivial()) { 15463 Result = MaybeCreateExprWithCleanups(Result); 15464 CopyExpr = Result.get(); 15465 } 15466 } 15467 } 15468 15469 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15470 CopyExpr); 15471 Captures.push_back(NewCap); 15472 } 15473 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15474 15475 // Pop the block scope now but keep it alive to the end of this function. 15476 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15477 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15478 15479 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15480 15481 // If the block isn't obviously global, i.e. it captures anything at 15482 // all, then we need to do a few things in the surrounding context: 15483 if (Result->getBlockDecl()->hasCaptures()) { 15484 // First, this expression has a new cleanup object. 15485 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15486 Cleanup.setExprNeedsCleanups(true); 15487 15488 // It also gets a branch-protected scope if any of the captured 15489 // variables needs destruction. 15490 for (const auto &CI : Result->getBlockDecl()->captures()) { 15491 const VarDecl *var = CI.getVariable(); 15492 if (var->getType().isDestructedType() != QualType::DK_none) { 15493 setFunctionHasBranchProtectedScope(); 15494 break; 15495 } 15496 } 15497 } 15498 15499 if (getCurFunction()) 15500 getCurFunction()->addBlock(BD); 15501 15502 return Result; 15503 } 15504 15505 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15506 SourceLocation RPLoc) { 15507 TypeSourceInfo *TInfo; 15508 GetTypeFromParser(Ty, &TInfo); 15509 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15510 } 15511 15512 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15513 Expr *E, TypeSourceInfo *TInfo, 15514 SourceLocation RPLoc) { 15515 Expr *OrigExpr = E; 15516 bool IsMS = false; 15517 15518 // CUDA device code does not support varargs. 15519 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15520 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15521 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15522 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15523 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15524 } 15525 } 15526 15527 // NVPTX does not support va_arg expression. 15528 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15529 Context.getTargetInfo().getTriple().isNVPTX()) 15530 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15531 15532 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15533 // as Microsoft ABI on an actual Microsoft platform, where 15534 // __builtin_ms_va_list and __builtin_va_list are the same.) 15535 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15536 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15537 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15538 if (Context.hasSameType(MSVaListType, E->getType())) { 15539 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15540 return ExprError(); 15541 IsMS = true; 15542 } 15543 } 15544 15545 // Get the va_list type 15546 QualType VaListType = Context.getBuiltinVaListType(); 15547 if (!IsMS) { 15548 if (VaListType->isArrayType()) { 15549 // Deal with implicit array decay; for example, on x86-64, 15550 // va_list is an array, but it's supposed to decay to 15551 // a pointer for va_arg. 15552 VaListType = Context.getArrayDecayedType(VaListType); 15553 // Make sure the input expression also decays appropriately. 15554 ExprResult Result = UsualUnaryConversions(E); 15555 if (Result.isInvalid()) 15556 return ExprError(); 15557 E = Result.get(); 15558 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15559 // If va_list is a record type and we are compiling in C++ mode, 15560 // check the argument using reference binding. 15561 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15562 Context, Context.getLValueReferenceType(VaListType), false); 15563 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15564 if (Init.isInvalid()) 15565 return ExprError(); 15566 E = Init.getAs<Expr>(); 15567 } else { 15568 // Otherwise, the va_list argument must be an l-value because 15569 // it is modified by va_arg. 15570 if (!E->isTypeDependent() && 15571 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15572 return ExprError(); 15573 } 15574 } 15575 15576 if (!IsMS && !E->isTypeDependent() && 15577 !Context.hasSameType(VaListType, E->getType())) 15578 return ExprError( 15579 Diag(E->getBeginLoc(), 15580 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15581 << OrigExpr->getType() << E->getSourceRange()); 15582 15583 if (!TInfo->getType()->isDependentType()) { 15584 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15585 diag::err_second_parameter_to_va_arg_incomplete, 15586 TInfo->getTypeLoc())) 15587 return ExprError(); 15588 15589 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15590 TInfo->getType(), 15591 diag::err_second_parameter_to_va_arg_abstract, 15592 TInfo->getTypeLoc())) 15593 return ExprError(); 15594 15595 if (!TInfo->getType().isPODType(Context)) { 15596 Diag(TInfo->getTypeLoc().getBeginLoc(), 15597 TInfo->getType()->isObjCLifetimeType() 15598 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15599 : diag::warn_second_parameter_to_va_arg_not_pod) 15600 << TInfo->getType() 15601 << TInfo->getTypeLoc().getSourceRange(); 15602 } 15603 15604 // Check for va_arg where arguments of the given type will be promoted 15605 // (i.e. this va_arg is guaranteed to have undefined behavior). 15606 QualType PromoteType; 15607 if (TInfo->getType()->isPromotableIntegerType()) { 15608 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15609 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15610 PromoteType = QualType(); 15611 } 15612 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15613 PromoteType = Context.DoubleTy; 15614 if (!PromoteType.isNull()) 15615 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15616 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15617 << TInfo->getType() 15618 << PromoteType 15619 << TInfo->getTypeLoc().getSourceRange()); 15620 } 15621 15622 QualType T = TInfo->getType().getNonLValueExprType(Context); 15623 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15624 } 15625 15626 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15627 // The type of __null will be int or long, depending on the size of 15628 // pointers on the target. 15629 QualType Ty; 15630 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15631 if (pw == Context.getTargetInfo().getIntWidth()) 15632 Ty = Context.IntTy; 15633 else if (pw == Context.getTargetInfo().getLongWidth()) 15634 Ty = Context.LongTy; 15635 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15636 Ty = Context.LongLongTy; 15637 else { 15638 llvm_unreachable("I don't know size of pointer!"); 15639 } 15640 15641 return new (Context) GNUNullExpr(Ty, TokenLoc); 15642 } 15643 15644 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15645 SourceLocation BuiltinLoc, 15646 SourceLocation RPLoc) { 15647 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15648 } 15649 15650 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15651 SourceLocation BuiltinLoc, 15652 SourceLocation RPLoc, 15653 DeclContext *ParentContext) { 15654 return new (Context) 15655 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15656 } 15657 15658 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15659 bool Diagnose) { 15660 if (!getLangOpts().ObjC) 15661 return false; 15662 15663 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15664 if (!PT) 15665 return false; 15666 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15667 15668 // Ignore any parens, implicit casts (should only be 15669 // array-to-pointer decays), and not-so-opaque values. The last is 15670 // important for making this trigger for property assignments. 15671 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15672 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15673 if (OV->getSourceExpr()) 15674 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15675 15676 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15677 if (!PT->isObjCIdType() && 15678 !(ID && ID->getIdentifier()->isStr("NSString"))) 15679 return false; 15680 if (!SL->isAscii()) 15681 return false; 15682 15683 if (Diagnose) { 15684 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15685 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15686 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15687 } 15688 return true; 15689 } 15690 15691 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15692 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15693 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15694 !SrcExpr->isNullPointerConstant( 15695 getASTContext(), Expr::NPC_NeverValueDependent)) { 15696 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15697 return false; 15698 if (Diagnose) { 15699 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15700 << /*number*/1 15701 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15702 Expr *NumLit = 15703 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15704 if (NumLit) 15705 Exp = NumLit; 15706 } 15707 return true; 15708 } 15709 15710 return false; 15711 } 15712 15713 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15714 const Expr *SrcExpr) { 15715 if (!DstType->isFunctionPointerType() || 15716 !SrcExpr->getType()->isFunctionType()) 15717 return false; 15718 15719 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15720 if (!DRE) 15721 return false; 15722 15723 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15724 if (!FD) 15725 return false; 15726 15727 return !S.checkAddressOfFunctionIsAvailable(FD, 15728 /*Complain=*/true, 15729 SrcExpr->getBeginLoc()); 15730 } 15731 15732 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15733 SourceLocation Loc, 15734 QualType DstType, QualType SrcType, 15735 Expr *SrcExpr, AssignmentAction Action, 15736 bool *Complained) { 15737 if (Complained) 15738 *Complained = false; 15739 15740 // Decode the result (notice that AST's are still created for extensions). 15741 bool CheckInferredResultType = false; 15742 bool isInvalid = false; 15743 unsigned DiagKind = 0; 15744 ConversionFixItGenerator ConvHints; 15745 bool MayHaveConvFixit = false; 15746 bool MayHaveFunctionDiff = false; 15747 const ObjCInterfaceDecl *IFace = nullptr; 15748 const ObjCProtocolDecl *PDecl = nullptr; 15749 15750 switch (ConvTy) { 15751 case Compatible: 15752 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15753 return false; 15754 15755 case PointerToInt: 15756 if (getLangOpts().CPlusPlus) { 15757 DiagKind = diag::err_typecheck_convert_pointer_int; 15758 isInvalid = true; 15759 } else { 15760 DiagKind = diag::ext_typecheck_convert_pointer_int; 15761 } 15762 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15763 MayHaveConvFixit = true; 15764 break; 15765 case IntToPointer: 15766 if (getLangOpts().CPlusPlus) { 15767 DiagKind = diag::err_typecheck_convert_int_pointer; 15768 isInvalid = true; 15769 } else { 15770 DiagKind = diag::ext_typecheck_convert_int_pointer; 15771 } 15772 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15773 MayHaveConvFixit = true; 15774 break; 15775 case IncompatibleFunctionPointer: 15776 if (getLangOpts().CPlusPlus) { 15777 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15778 isInvalid = true; 15779 } else { 15780 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15781 } 15782 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15783 MayHaveConvFixit = true; 15784 break; 15785 case IncompatiblePointer: 15786 if (Action == AA_Passing_CFAudited) { 15787 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15788 } else if (getLangOpts().CPlusPlus) { 15789 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15790 isInvalid = true; 15791 } else { 15792 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15793 } 15794 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15795 SrcType->isObjCObjectPointerType(); 15796 if (!CheckInferredResultType) { 15797 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15798 } else if (CheckInferredResultType) { 15799 SrcType = SrcType.getUnqualifiedType(); 15800 DstType = DstType.getUnqualifiedType(); 15801 } 15802 MayHaveConvFixit = true; 15803 break; 15804 case IncompatiblePointerSign: 15805 if (getLangOpts().CPlusPlus) { 15806 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15807 isInvalid = true; 15808 } else { 15809 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15810 } 15811 break; 15812 case FunctionVoidPointer: 15813 if (getLangOpts().CPlusPlus) { 15814 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15815 isInvalid = true; 15816 } else { 15817 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15818 } 15819 break; 15820 case IncompatiblePointerDiscardsQualifiers: { 15821 // Perform array-to-pointer decay if necessary. 15822 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15823 15824 isInvalid = true; 15825 15826 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15827 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15828 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15829 DiagKind = diag::err_typecheck_incompatible_address_space; 15830 break; 15831 15832 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15833 DiagKind = diag::err_typecheck_incompatible_ownership; 15834 break; 15835 } 15836 15837 llvm_unreachable("unknown error case for discarding qualifiers!"); 15838 // fallthrough 15839 } 15840 case CompatiblePointerDiscardsQualifiers: 15841 // If the qualifiers lost were because we were applying the 15842 // (deprecated) C++ conversion from a string literal to a char* 15843 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15844 // Ideally, this check would be performed in 15845 // checkPointerTypesForAssignment. However, that would require a 15846 // bit of refactoring (so that the second argument is an 15847 // expression, rather than a type), which should be done as part 15848 // of a larger effort to fix checkPointerTypesForAssignment for 15849 // C++ semantics. 15850 if (getLangOpts().CPlusPlus && 15851 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15852 return false; 15853 if (getLangOpts().CPlusPlus) { 15854 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15855 isInvalid = true; 15856 } else { 15857 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15858 } 15859 15860 break; 15861 case IncompatibleNestedPointerQualifiers: 15862 if (getLangOpts().CPlusPlus) { 15863 isInvalid = true; 15864 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15865 } else { 15866 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15867 } 15868 break; 15869 case IncompatibleNestedPointerAddressSpaceMismatch: 15870 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15871 isInvalid = true; 15872 break; 15873 case IntToBlockPointer: 15874 DiagKind = diag::err_int_to_block_pointer; 15875 isInvalid = true; 15876 break; 15877 case IncompatibleBlockPointer: 15878 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15879 isInvalid = true; 15880 break; 15881 case IncompatibleObjCQualifiedId: { 15882 if (SrcType->isObjCQualifiedIdType()) { 15883 const ObjCObjectPointerType *srcOPT = 15884 SrcType->castAs<ObjCObjectPointerType>(); 15885 for (auto *srcProto : srcOPT->quals()) { 15886 PDecl = srcProto; 15887 break; 15888 } 15889 if (const ObjCInterfaceType *IFaceT = 15890 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15891 IFace = IFaceT->getDecl(); 15892 } 15893 else if (DstType->isObjCQualifiedIdType()) { 15894 const ObjCObjectPointerType *dstOPT = 15895 DstType->castAs<ObjCObjectPointerType>(); 15896 for (auto *dstProto : dstOPT->quals()) { 15897 PDecl = dstProto; 15898 break; 15899 } 15900 if (const ObjCInterfaceType *IFaceT = 15901 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15902 IFace = IFaceT->getDecl(); 15903 } 15904 if (getLangOpts().CPlusPlus) { 15905 DiagKind = diag::err_incompatible_qualified_id; 15906 isInvalid = true; 15907 } else { 15908 DiagKind = diag::warn_incompatible_qualified_id; 15909 } 15910 break; 15911 } 15912 case IncompatibleVectors: 15913 if (getLangOpts().CPlusPlus) { 15914 DiagKind = diag::err_incompatible_vectors; 15915 isInvalid = true; 15916 } else { 15917 DiagKind = diag::warn_incompatible_vectors; 15918 } 15919 break; 15920 case IncompatibleObjCWeakRef: 15921 DiagKind = diag::err_arc_weak_unavailable_assign; 15922 isInvalid = true; 15923 break; 15924 case Incompatible: 15925 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15926 if (Complained) 15927 *Complained = true; 15928 return true; 15929 } 15930 15931 DiagKind = diag::err_typecheck_convert_incompatible; 15932 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15933 MayHaveConvFixit = true; 15934 isInvalid = true; 15935 MayHaveFunctionDiff = true; 15936 break; 15937 } 15938 15939 QualType FirstType, SecondType; 15940 switch (Action) { 15941 case AA_Assigning: 15942 case AA_Initializing: 15943 // The destination type comes first. 15944 FirstType = DstType; 15945 SecondType = SrcType; 15946 break; 15947 15948 case AA_Returning: 15949 case AA_Passing: 15950 case AA_Passing_CFAudited: 15951 case AA_Converting: 15952 case AA_Sending: 15953 case AA_Casting: 15954 // The source type comes first. 15955 FirstType = SrcType; 15956 SecondType = DstType; 15957 break; 15958 } 15959 15960 PartialDiagnostic FDiag = PDiag(DiagKind); 15961 if (Action == AA_Passing_CFAudited) 15962 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15963 else 15964 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15965 15966 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 15967 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 15968 auto isPlainChar = [](const clang::Type *Type) { 15969 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 15970 Type->isSpecificBuiltinType(BuiltinType::Char_U); 15971 }; 15972 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 15973 isPlainChar(SecondType->getPointeeOrArrayElementType())); 15974 } 15975 15976 // If we can fix the conversion, suggest the FixIts. 15977 if (!ConvHints.isNull()) { 15978 for (FixItHint &H : ConvHints.Hints) 15979 FDiag << H; 15980 } 15981 15982 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15983 15984 if (MayHaveFunctionDiff) 15985 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15986 15987 Diag(Loc, FDiag); 15988 if ((DiagKind == diag::warn_incompatible_qualified_id || 15989 DiagKind == diag::err_incompatible_qualified_id) && 15990 PDecl && IFace && !IFace->hasDefinition()) 15991 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15992 << IFace << PDecl; 15993 15994 if (SecondType == Context.OverloadTy) 15995 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15996 FirstType, /*TakingAddress=*/true); 15997 15998 if (CheckInferredResultType) 15999 EmitRelatedResultTypeNote(SrcExpr); 16000 16001 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16002 EmitRelatedResultTypeNoteForReturn(DstType); 16003 16004 if (Complained) 16005 *Complained = true; 16006 return isInvalid; 16007 } 16008 16009 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16010 llvm::APSInt *Result, 16011 AllowFoldKind CanFold) { 16012 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16013 public: 16014 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16015 QualType T) override { 16016 return S.Diag(Loc, diag::err_ice_not_integral) 16017 << T << S.LangOpts.CPlusPlus; 16018 } 16019 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16020 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16021 } 16022 } Diagnoser; 16023 16024 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16025 } 16026 16027 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16028 llvm::APSInt *Result, 16029 unsigned DiagID, 16030 AllowFoldKind CanFold) { 16031 class IDDiagnoser : public VerifyICEDiagnoser { 16032 unsigned DiagID; 16033 16034 public: 16035 IDDiagnoser(unsigned DiagID) 16036 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16037 16038 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16039 return S.Diag(Loc, DiagID); 16040 } 16041 } Diagnoser(DiagID); 16042 16043 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16044 } 16045 16046 Sema::SemaDiagnosticBuilder 16047 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16048 QualType T) { 16049 return diagnoseNotICE(S, Loc); 16050 } 16051 16052 Sema::SemaDiagnosticBuilder 16053 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16054 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16055 } 16056 16057 ExprResult 16058 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16059 VerifyICEDiagnoser &Diagnoser, 16060 AllowFoldKind CanFold) { 16061 SourceLocation DiagLoc = E->getBeginLoc(); 16062 16063 if (getLangOpts().CPlusPlus11) { 16064 // C++11 [expr.const]p5: 16065 // If an expression of literal class type is used in a context where an 16066 // integral constant expression is required, then that class type shall 16067 // have a single non-explicit conversion function to an integral or 16068 // unscoped enumeration type 16069 ExprResult Converted; 16070 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16071 VerifyICEDiagnoser &BaseDiagnoser; 16072 public: 16073 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16074 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16075 BaseDiagnoser.Suppress, true), 16076 BaseDiagnoser(BaseDiagnoser) {} 16077 16078 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16079 QualType T) override { 16080 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16081 } 16082 16083 SemaDiagnosticBuilder diagnoseIncomplete( 16084 Sema &S, SourceLocation Loc, QualType T) override { 16085 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16086 } 16087 16088 SemaDiagnosticBuilder diagnoseExplicitConv( 16089 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16090 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16091 } 16092 16093 SemaDiagnosticBuilder noteExplicitConv( 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 diagnoseAmbiguous( 16100 Sema &S, SourceLocation Loc, QualType T) override { 16101 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16102 } 16103 16104 SemaDiagnosticBuilder noteAmbiguous( 16105 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16106 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16107 << ConvTy->isEnumeralType() << ConvTy; 16108 } 16109 16110 SemaDiagnosticBuilder diagnoseConversion( 16111 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16112 llvm_unreachable("conversion functions are permitted"); 16113 } 16114 } ConvertDiagnoser(Diagnoser); 16115 16116 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16117 ConvertDiagnoser); 16118 if (Converted.isInvalid()) 16119 return Converted; 16120 E = Converted.get(); 16121 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16122 return ExprError(); 16123 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16124 // An ICE must be of integral or unscoped enumeration type. 16125 if (!Diagnoser.Suppress) 16126 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16127 << E->getSourceRange(); 16128 return ExprError(); 16129 } 16130 16131 ExprResult RValueExpr = DefaultLvalueConversion(E); 16132 if (RValueExpr.isInvalid()) 16133 return ExprError(); 16134 16135 E = RValueExpr.get(); 16136 16137 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16138 // in the non-ICE case. 16139 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16140 if (Result) 16141 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16142 if (!isa<ConstantExpr>(E)) 16143 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16144 : ConstantExpr::Create(Context, E); 16145 return E; 16146 } 16147 16148 Expr::EvalResult EvalResult; 16149 SmallVector<PartialDiagnosticAt, 8> Notes; 16150 EvalResult.Diag = &Notes; 16151 16152 // Try to evaluate the expression, and produce diagnostics explaining why it's 16153 // not a constant expression as a side-effect. 16154 bool Folded = 16155 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16156 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16157 16158 if (!isa<ConstantExpr>(E)) 16159 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16160 16161 // In C++11, we can rely on diagnostics being produced for any expression 16162 // which is not a constant expression. If no diagnostics were produced, then 16163 // this is a constant expression. 16164 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16165 if (Result) 16166 *Result = EvalResult.Val.getInt(); 16167 return E; 16168 } 16169 16170 // If our only note is the usual "invalid subexpression" note, just point 16171 // the caret at its location rather than producing an essentially 16172 // redundant note. 16173 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16174 diag::note_invalid_subexpr_in_const_expr) { 16175 DiagLoc = Notes[0].first; 16176 Notes.clear(); 16177 } 16178 16179 if (!Folded || !CanFold) { 16180 if (!Diagnoser.Suppress) { 16181 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16182 for (const PartialDiagnosticAt &Note : Notes) 16183 Diag(Note.first, Note.second); 16184 } 16185 16186 return ExprError(); 16187 } 16188 16189 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16190 for (const PartialDiagnosticAt &Note : Notes) 16191 Diag(Note.first, Note.second); 16192 16193 if (Result) 16194 *Result = EvalResult.Val.getInt(); 16195 return E; 16196 } 16197 16198 namespace { 16199 // Handle the case where we conclude a expression which we speculatively 16200 // considered to be unevaluated is actually evaluated. 16201 class TransformToPE : public TreeTransform<TransformToPE> { 16202 typedef TreeTransform<TransformToPE> BaseTransform; 16203 16204 public: 16205 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16206 16207 // Make sure we redo semantic analysis 16208 bool AlwaysRebuild() { return true; } 16209 bool ReplacingOriginal() { return true; } 16210 16211 // We need to special-case DeclRefExprs referring to FieldDecls which 16212 // are not part of a member pointer formation; normal TreeTransforming 16213 // doesn't catch this case because of the way we represent them in the AST. 16214 // FIXME: This is a bit ugly; is it really the best way to handle this 16215 // case? 16216 // 16217 // Error on DeclRefExprs referring to FieldDecls. 16218 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16219 if (isa<FieldDecl>(E->getDecl()) && 16220 !SemaRef.isUnevaluatedContext()) 16221 return SemaRef.Diag(E->getLocation(), 16222 diag::err_invalid_non_static_member_use) 16223 << E->getDecl() << E->getSourceRange(); 16224 16225 return BaseTransform::TransformDeclRefExpr(E); 16226 } 16227 16228 // Exception: filter out member pointer formation 16229 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16230 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16231 return E; 16232 16233 return BaseTransform::TransformUnaryOperator(E); 16234 } 16235 16236 // The body of a lambda-expression is in a separate expression evaluation 16237 // context so never needs to be transformed. 16238 // FIXME: Ideally we wouldn't transform the closure type either, and would 16239 // just recreate the capture expressions and lambda expression. 16240 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16241 return SkipLambdaBody(E, Body); 16242 } 16243 }; 16244 } 16245 16246 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16247 assert(isUnevaluatedContext() && 16248 "Should only transform unevaluated expressions"); 16249 ExprEvalContexts.back().Context = 16250 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16251 if (isUnevaluatedContext()) 16252 return E; 16253 return TransformToPE(*this).TransformExpr(E); 16254 } 16255 16256 void 16257 Sema::PushExpressionEvaluationContext( 16258 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16259 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16260 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16261 LambdaContextDecl, ExprContext); 16262 Cleanup.reset(); 16263 if (!MaybeODRUseExprs.empty()) 16264 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16265 } 16266 16267 void 16268 Sema::PushExpressionEvaluationContext( 16269 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16270 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16271 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16272 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16273 } 16274 16275 namespace { 16276 16277 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16278 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16279 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16280 if (E->getOpcode() == UO_Deref) 16281 return CheckPossibleDeref(S, E->getSubExpr()); 16282 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16283 return CheckPossibleDeref(S, E->getBase()); 16284 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16285 return CheckPossibleDeref(S, E->getBase()); 16286 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16287 QualType Inner; 16288 QualType Ty = E->getType(); 16289 if (const auto *Ptr = Ty->getAs<PointerType>()) 16290 Inner = Ptr->getPointeeType(); 16291 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16292 Inner = Arr->getElementType(); 16293 else 16294 return nullptr; 16295 16296 if (Inner->hasAttr(attr::NoDeref)) 16297 return E; 16298 } 16299 return nullptr; 16300 } 16301 16302 } // namespace 16303 16304 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16305 for (const Expr *E : Rec.PossibleDerefs) { 16306 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16307 if (DeclRef) { 16308 const ValueDecl *Decl = DeclRef->getDecl(); 16309 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16310 << Decl->getName() << E->getSourceRange(); 16311 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16312 } else { 16313 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16314 << E->getSourceRange(); 16315 } 16316 } 16317 Rec.PossibleDerefs.clear(); 16318 } 16319 16320 /// Check whether E, which is either a discarded-value expression or an 16321 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16322 /// and if so, remove it from the list of volatile-qualified assignments that 16323 /// we are going to warn are deprecated. 16324 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16325 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16326 return; 16327 16328 // Note: ignoring parens here is not justified by the standard rules, but 16329 // ignoring parentheses seems like a more reasonable approach, and this only 16330 // drives a deprecation warning so doesn't affect conformance. 16331 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16332 if (BO->getOpcode() == BO_Assign) { 16333 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16334 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16335 LHSs.end()); 16336 } 16337 } 16338 } 16339 16340 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16341 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16342 RebuildingImmediateInvocation) 16343 return E; 16344 16345 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16346 /// It's OK if this fails; we'll also remove this in 16347 /// HandleImmediateInvocations, but catching it here allows us to avoid 16348 /// walking the AST looking for it in simple cases. 16349 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16350 if (auto *DeclRef = 16351 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16352 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16353 16354 E = MaybeCreateExprWithCleanups(E); 16355 16356 ConstantExpr *Res = ConstantExpr::Create( 16357 getASTContext(), E.get(), 16358 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16359 getASTContext()), 16360 /*IsImmediateInvocation*/ true); 16361 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16362 return Res; 16363 } 16364 16365 static void EvaluateAndDiagnoseImmediateInvocation( 16366 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16367 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16368 Expr::EvalResult Eval; 16369 Eval.Diag = &Notes; 16370 ConstantExpr *CE = Candidate.getPointer(); 16371 bool Result = CE->EvaluateAsConstantExpr( 16372 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16373 if (!Result || !Notes.empty()) { 16374 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16375 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16376 InnerExpr = FunctionalCast->getSubExpr(); 16377 FunctionDecl *FD = nullptr; 16378 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16379 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16380 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16381 FD = Call->getConstructor(); 16382 else 16383 llvm_unreachable("unhandled decl kind"); 16384 assert(FD->isConsteval()); 16385 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16386 for (auto &Note : Notes) 16387 SemaRef.Diag(Note.first, Note.second); 16388 return; 16389 } 16390 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16391 } 16392 16393 static void RemoveNestedImmediateInvocation( 16394 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16395 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16396 struct ComplexRemove : TreeTransform<ComplexRemove> { 16397 using Base = TreeTransform<ComplexRemove>; 16398 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16399 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16400 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16401 CurrentII; 16402 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16403 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16404 SmallVector<Sema::ImmediateInvocationCandidate, 16405 4>::reverse_iterator Current) 16406 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16407 void RemoveImmediateInvocation(ConstantExpr* E) { 16408 auto It = std::find_if(CurrentII, IISet.rend(), 16409 [E](Sema::ImmediateInvocationCandidate Elem) { 16410 return Elem.getPointer() == E; 16411 }); 16412 assert(It != IISet.rend() && 16413 "ConstantExpr marked IsImmediateInvocation should " 16414 "be present"); 16415 It->setInt(1); // Mark as deleted 16416 } 16417 ExprResult TransformConstantExpr(ConstantExpr *E) { 16418 if (!E->isImmediateInvocation()) 16419 return Base::TransformConstantExpr(E); 16420 RemoveImmediateInvocation(E); 16421 return Base::TransformExpr(E->getSubExpr()); 16422 } 16423 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16424 /// we need to remove its DeclRefExpr from the DRSet. 16425 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16426 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16427 return Base::TransformCXXOperatorCallExpr(E); 16428 } 16429 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16430 /// here. 16431 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16432 if (!Init) 16433 return Init; 16434 /// ConstantExpr are the first layer of implicit node to be removed so if 16435 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16436 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16437 if (CE->isImmediateInvocation()) 16438 RemoveImmediateInvocation(CE); 16439 return Base::TransformInitializer(Init, NotCopyInit); 16440 } 16441 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16442 DRSet.erase(E); 16443 return E; 16444 } 16445 bool AlwaysRebuild() { return false; } 16446 bool ReplacingOriginal() { return true; } 16447 bool AllowSkippingCXXConstructExpr() { 16448 bool Res = AllowSkippingFirstCXXConstructExpr; 16449 AllowSkippingFirstCXXConstructExpr = true; 16450 return Res; 16451 } 16452 bool AllowSkippingFirstCXXConstructExpr = true; 16453 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16454 Rec.ImmediateInvocationCandidates, It); 16455 16456 /// CXXConstructExpr with a single argument are getting skipped by 16457 /// TreeTransform in some situtation because they could be implicit. This 16458 /// can only occur for the top-level CXXConstructExpr because it is used 16459 /// nowhere in the expression being transformed therefore will not be rebuilt. 16460 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16461 /// skipping the first CXXConstructExpr. 16462 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16463 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16464 16465 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16466 assert(Res.isUsable()); 16467 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16468 It->getPointer()->setSubExpr(Res.get()); 16469 } 16470 16471 static void 16472 HandleImmediateInvocations(Sema &SemaRef, 16473 Sema::ExpressionEvaluationContextRecord &Rec) { 16474 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16475 Rec.ReferenceToConsteval.size() == 0) || 16476 SemaRef.RebuildingImmediateInvocation) 16477 return; 16478 16479 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16480 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16481 /// need to remove ReferenceToConsteval in the immediate invocation. 16482 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16483 16484 /// Prevent sema calls during the tree transform from adding pointers that 16485 /// are already in the sets. 16486 llvm::SaveAndRestore<bool> DisableIITracking( 16487 SemaRef.RebuildingImmediateInvocation, true); 16488 16489 /// Prevent diagnostic during tree transfrom as they are duplicates 16490 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16491 16492 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16493 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16494 if (!It->getInt()) 16495 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16496 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16497 Rec.ReferenceToConsteval.size()) { 16498 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16499 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16500 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16501 bool VisitDeclRefExpr(DeclRefExpr *E) { 16502 DRSet.erase(E); 16503 return DRSet.size(); 16504 } 16505 } Visitor(Rec.ReferenceToConsteval); 16506 Visitor.TraverseStmt( 16507 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16508 } 16509 for (auto CE : Rec.ImmediateInvocationCandidates) 16510 if (!CE.getInt()) 16511 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16512 for (auto DR : Rec.ReferenceToConsteval) { 16513 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16514 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16515 << FD; 16516 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16517 } 16518 } 16519 16520 void Sema::PopExpressionEvaluationContext() { 16521 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16522 unsigned NumTypos = Rec.NumTypos; 16523 16524 if (!Rec.Lambdas.empty()) { 16525 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16526 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16527 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16528 unsigned D; 16529 if (Rec.isUnevaluated()) { 16530 // C++11 [expr.prim.lambda]p2: 16531 // A lambda-expression shall not appear in an unevaluated operand 16532 // (Clause 5). 16533 D = diag::err_lambda_unevaluated_operand; 16534 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16535 // C++1y [expr.const]p2: 16536 // A conditional-expression e is a core constant expression unless the 16537 // evaluation of e, following the rules of the abstract machine, would 16538 // evaluate [...] a lambda-expression. 16539 D = diag::err_lambda_in_constant_expression; 16540 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16541 // C++17 [expr.prim.lamda]p2: 16542 // A lambda-expression shall not appear [...] in a template-argument. 16543 D = diag::err_lambda_in_invalid_context; 16544 } else 16545 llvm_unreachable("Couldn't infer lambda error message."); 16546 16547 for (const auto *L : Rec.Lambdas) 16548 Diag(L->getBeginLoc(), D); 16549 } 16550 } 16551 16552 WarnOnPendingNoDerefs(Rec); 16553 HandleImmediateInvocations(*this, Rec); 16554 16555 // Warn on any volatile-qualified simple-assignments that are not discarded- 16556 // value expressions nor unevaluated operands (those cases get removed from 16557 // this list by CheckUnusedVolatileAssignment). 16558 for (auto *BO : Rec.VolatileAssignmentLHSs) 16559 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16560 << BO->getType(); 16561 16562 // When are coming out of an unevaluated context, clear out any 16563 // temporaries that we may have created as part of the evaluation of 16564 // the expression in that context: they aren't relevant because they 16565 // will never be constructed. 16566 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16567 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16568 ExprCleanupObjects.end()); 16569 Cleanup = Rec.ParentCleanup; 16570 CleanupVarDeclMarking(); 16571 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16572 // Otherwise, merge the contexts together. 16573 } else { 16574 Cleanup.mergeFrom(Rec.ParentCleanup); 16575 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16576 Rec.SavedMaybeODRUseExprs.end()); 16577 } 16578 16579 // Pop the current expression evaluation context off the stack. 16580 ExprEvalContexts.pop_back(); 16581 16582 // The global expression evaluation context record is never popped. 16583 ExprEvalContexts.back().NumTypos += NumTypos; 16584 } 16585 16586 void Sema::DiscardCleanupsInEvaluationContext() { 16587 ExprCleanupObjects.erase( 16588 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16589 ExprCleanupObjects.end()); 16590 Cleanup.reset(); 16591 MaybeODRUseExprs.clear(); 16592 } 16593 16594 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16595 ExprResult Result = CheckPlaceholderExpr(E); 16596 if (Result.isInvalid()) 16597 return ExprError(); 16598 E = Result.get(); 16599 if (!E->getType()->isVariablyModifiedType()) 16600 return E; 16601 return TransformToPotentiallyEvaluated(E); 16602 } 16603 16604 /// Are we in a context that is potentially constant evaluated per C++20 16605 /// [expr.const]p12? 16606 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16607 /// C++2a [expr.const]p12: 16608 // An expression or conversion is potentially constant evaluated if it is 16609 switch (SemaRef.ExprEvalContexts.back().Context) { 16610 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16611 // -- a manifestly constant-evaluated expression, 16612 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16613 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16614 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16615 // -- a potentially-evaluated expression, 16616 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16617 // -- an immediate subexpression of a braced-init-list, 16618 16619 // -- [FIXME] an expression of the form & cast-expression that occurs 16620 // within a templated entity 16621 // -- a subexpression of one of the above that is not a subexpression of 16622 // a nested unevaluated operand. 16623 return true; 16624 16625 case Sema::ExpressionEvaluationContext::Unevaluated: 16626 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16627 // Expressions in this context are never evaluated. 16628 return false; 16629 } 16630 llvm_unreachable("Invalid context"); 16631 } 16632 16633 /// Return true if this function has a calling convention that requires mangling 16634 /// in the size of the parameter pack. 16635 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16636 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16637 // we don't need parameter type sizes. 16638 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16639 if (!TT.isOSWindows() || !TT.isX86()) 16640 return false; 16641 16642 // If this is C++ and this isn't an extern "C" function, parameters do not 16643 // need to be complete. In this case, C++ mangling will apply, which doesn't 16644 // use the size of the parameters. 16645 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16646 return false; 16647 16648 // Stdcall, fastcall, and vectorcall need this special treatment. 16649 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16650 switch (CC) { 16651 case CC_X86StdCall: 16652 case CC_X86FastCall: 16653 case CC_X86VectorCall: 16654 return true; 16655 default: 16656 break; 16657 } 16658 return false; 16659 } 16660 16661 /// Require that all of the parameter types of function be complete. Normally, 16662 /// parameter types are only required to be complete when a function is called 16663 /// or defined, but to mangle functions with certain calling conventions, the 16664 /// mangler needs to know the size of the parameter list. In this situation, 16665 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16666 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16667 /// result in a linker error. Clang doesn't implement this behavior, and instead 16668 /// attempts to error at compile time. 16669 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16670 SourceLocation Loc) { 16671 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16672 FunctionDecl *FD; 16673 ParmVarDecl *Param; 16674 16675 public: 16676 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16677 : FD(FD), Param(Param) {} 16678 16679 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16680 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16681 StringRef CCName; 16682 switch (CC) { 16683 case CC_X86StdCall: 16684 CCName = "stdcall"; 16685 break; 16686 case CC_X86FastCall: 16687 CCName = "fastcall"; 16688 break; 16689 case CC_X86VectorCall: 16690 CCName = "vectorcall"; 16691 break; 16692 default: 16693 llvm_unreachable("CC does not need mangling"); 16694 } 16695 16696 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16697 << Param->getDeclName() << FD->getDeclName() << CCName; 16698 } 16699 }; 16700 16701 for (ParmVarDecl *Param : FD->parameters()) { 16702 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16703 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16704 } 16705 } 16706 16707 namespace { 16708 enum class OdrUseContext { 16709 /// Declarations in this context are not odr-used. 16710 None, 16711 /// Declarations in this context are formally odr-used, but this is a 16712 /// dependent context. 16713 Dependent, 16714 /// Declarations in this context are odr-used but not actually used (yet). 16715 FormallyOdrUsed, 16716 /// Declarations in this context are used. 16717 Used 16718 }; 16719 } 16720 16721 /// Are we within a context in which references to resolved functions or to 16722 /// variables result in odr-use? 16723 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16724 OdrUseContext Result; 16725 16726 switch (SemaRef.ExprEvalContexts.back().Context) { 16727 case Sema::ExpressionEvaluationContext::Unevaluated: 16728 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16729 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16730 return OdrUseContext::None; 16731 16732 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16733 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16734 Result = OdrUseContext::Used; 16735 break; 16736 16737 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16738 Result = OdrUseContext::FormallyOdrUsed; 16739 break; 16740 16741 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16742 // A default argument formally results in odr-use, but doesn't actually 16743 // result in a use in any real sense until it itself is used. 16744 Result = OdrUseContext::FormallyOdrUsed; 16745 break; 16746 } 16747 16748 if (SemaRef.CurContext->isDependentContext()) 16749 return OdrUseContext::Dependent; 16750 16751 return Result; 16752 } 16753 16754 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16755 if (!Func->isConstexpr()) 16756 return false; 16757 16758 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16759 return true; 16760 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16761 return CCD && CCD->getInheritedConstructor(); 16762 } 16763 16764 /// Mark a function referenced, and check whether it is odr-used 16765 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16766 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16767 bool MightBeOdrUse) { 16768 assert(Func && "No function?"); 16769 16770 Func->setReferenced(); 16771 16772 // Recursive functions aren't really used until they're used from some other 16773 // context. 16774 bool IsRecursiveCall = CurContext == Func; 16775 16776 // C++11 [basic.def.odr]p3: 16777 // A function whose name appears as a potentially-evaluated expression is 16778 // odr-used if it is the unique lookup result or the selected member of a 16779 // set of overloaded functions [...]. 16780 // 16781 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16782 // can just check that here. 16783 OdrUseContext OdrUse = 16784 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16785 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16786 OdrUse = OdrUseContext::FormallyOdrUsed; 16787 16788 // Trivial default constructors and destructors are never actually used. 16789 // FIXME: What about other special members? 16790 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16791 OdrUse == OdrUseContext::Used) { 16792 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16793 if (Constructor->isDefaultConstructor()) 16794 OdrUse = OdrUseContext::FormallyOdrUsed; 16795 if (isa<CXXDestructorDecl>(Func)) 16796 OdrUse = OdrUseContext::FormallyOdrUsed; 16797 } 16798 16799 // C++20 [expr.const]p12: 16800 // A function [...] is needed for constant evaluation if it is [...] a 16801 // constexpr function that is named by an expression that is potentially 16802 // constant evaluated 16803 bool NeededForConstantEvaluation = 16804 isPotentiallyConstantEvaluatedContext(*this) && 16805 isImplicitlyDefinableConstexprFunction(Func); 16806 16807 // Determine whether we require a function definition to exist, per 16808 // C++11 [temp.inst]p3: 16809 // Unless a function template specialization has been explicitly 16810 // instantiated or explicitly specialized, the function template 16811 // specialization is implicitly instantiated when the specialization is 16812 // referenced in a context that requires a function definition to exist. 16813 // C++20 [temp.inst]p7: 16814 // The existence of a definition of a [...] function is considered to 16815 // affect the semantics of the program if the [...] function is needed for 16816 // constant evaluation by an expression 16817 // C++20 [basic.def.odr]p10: 16818 // Every program shall contain exactly one definition of every non-inline 16819 // function or variable that is odr-used in that program outside of a 16820 // discarded statement 16821 // C++20 [special]p1: 16822 // The implementation will implicitly define [defaulted special members] 16823 // if they are odr-used or needed for constant evaluation. 16824 // 16825 // Note that we skip the implicit instantiation of templates that are only 16826 // used in unused default arguments or by recursive calls to themselves. 16827 // This is formally non-conforming, but seems reasonable in practice. 16828 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16829 NeededForConstantEvaluation); 16830 16831 // C++14 [temp.expl.spec]p6: 16832 // If a template [...] is explicitly specialized then that specialization 16833 // shall be declared before the first use of that specialization that would 16834 // cause an implicit instantiation to take place, in every translation unit 16835 // in which such a use occurs 16836 if (NeedDefinition && 16837 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16838 Func->getMemberSpecializationInfo())) 16839 checkSpecializationVisibility(Loc, Func); 16840 16841 if (getLangOpts().CUDA) 16842 CheckCUDACall(Loc, Func); 16843 16844 if (getLangOpts().SYCLIsDevice) 16845 checkSYCLDeviceFunction(Loc, Func); 16846 16847 // If we need a definition, try to create one. 16848 if (NeedDefinition && !Func->getBody()) { 16849 runWithSufficientStackSpace(Loc, [&] { 16850 if (CXXConstructorDecl *Constructor = 16851 dyn_cast<CXXConstructorDecl>(Func)) { 16852 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16853 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16854 if (Constructor->isDefaultConstructor()) { 16855 if (Constructor->isTrivial() && 16856 !Constructor->hasAttr<DLLExportAttr>()) 16857 return; 16858 DefineImplicitDefaultConstructor(Loc, Constructor); 16859 } else if (Constructor->isCopyConstructor()) { 16860 DefineImplicitCopyConstructor(Loc, Constructor); 16861 } else if (Constructor->isMoveConstructor()) { 16862 DefineImplicitMoveConstructor(Loc, Constructor); 16863 } 16864 } else if (Constructor->getInheritedConstructor()) { 16865 DefineInheritingConstructor(Loc, Constructor); 16866 } 16867 } else if (CXXDestructorDecl *Destructor = 16868 dyn_cast<CXXDestructorDecl>(Func)) { 16869 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16870 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16871 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16872 return; 16873 DefineImplicitDestructor(Loc, Destructor); 16874 } 16875 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16876 MarkVTableUsed(Loc, Destructor->getParent()); 16877 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16878 if (MethodDecl->isOverloadedOperator() && 16879 MethodDecl->getOverloadedOperator() == OO_Equal) { 16880 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16881 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16882 if (MethodDecl->isCopyAssignmentOperator()) 16883 DefineImplicitCopyAssignment(Loc, MethodDecl); 16884 else if (MethodDecl->isMoveAssignmentOperator()) 16885 DefineImplicitMoveAssignment(Loc, MethodDecl); 16886 } 16887 } else if (isa<CXXConversionDecl>(MethodDecl) && 16888 MethodDecl->getParent()->isLambda()) { 16889 CXXConversionDecl *Conversion = 16890 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16891 if (Conversion->isLambdaToBlockPointerConversion()) 16892 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16893 else 16894 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16895 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16896 MarkVTableUsed(Loc, MethodDecl->getParent()); 16897 } 16898 16899 if (Func->isDefaulted() && !Func->isDeleted()) { 16900 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16901 if (DCK != DefaultedComparisonKind::None) 16902 DefineDefaultedComparison(Loc, Func, DCK); 16903 } 16904 16905 // Implicit instantiation of function templates and member functions of 16906 // class templates. 16907 if (Func->isImplicitlyInstantiable()) { 16908 TemplateSpecializationKind TSK = 16909 Func->getTemplateSpecializationKindForInstantiation(); 16910 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16911 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16912 if (FirstInstantiation) { 16913 PointOfInstantiation = Loc; 16914 if (auto *MSI = Func->getMemberSpecializationInfo()) 16915 MSI->setPointOfInstantiation(Loc); 16916 // FIXME: Notify listener. 16917 else 16918 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16919 } else if (TSK != TSK_ImplicitInstantiation) { 16920 // Use the point of use as the point of instantiation, instead of the 16921 // point of explicit instantiation (which we track as the actual point 16922 // of instantiation). This gives better backtraces in diagnostics. 16923 PointOfInstantiation = Loc; 16924 } 16925 16926 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16927 Func->isConstexpr()) { 16928 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16929 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16930 CodeSynthesisContexts.size()) 16931 PendingLocalImplicitInstantiations.push_back( 16932 std::make_pair(Func, PointOfInstantiation)); 16933 else if (Func->isConstexpr()) 16934 // Do not defer instantiations of constexpr functions, to avoid the 16935 // expression evaluator needing to call back into Sema if it sees a 16936 // call to such a function. 16937 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16938 else { 16939 Func->setInstantiationIsPending(true); 16940 PendingInstantiations.push_back( 16941 std::make_pair(Func, PointOfInstantiation)); 16942 // Notify the consumer that a function was implicitly instantiated. 16943 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16944 } 16945 } 16946 } else { 16947 // Walk redefinitions, as some of them may be instantiable. 16948 for (auto i : Func->redecls()) { 16949 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16950 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16951 } 16952 } 16953 }); 16954 } 16955 16956 // C++14 [except.spec]p17: 16957 // An exception-specification is considered to be needed when: 16958 // - the function is odr-used or, if it appears in an unevaluated operand, 16959 // would be odr-used if the expression were potentially-evaluated; 16960 // 16961 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16962 // function is a pure virtual function we're calling, and in that case the 16963 // function was selected by overload resolution and we need to resolve its 16964 // exception specification for a different reason. 16965 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16966 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16967 ResolveExceptionSpec(Loc, FPT); 16968 16969 // If this is the first "real" use, act on that. 16970 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16971 // Keep track of used but undefined functions. 16972 if (!Func->isDefined()) { 16973 if (mightHaveNonExternalLinkage(Func)) 16974 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16975 else if (Func->getMostRecentDecl()->isInlined() && 16976 !LangOpts.GNUInline && 16977 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16978 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16979 else if (isExternalWithNoLinkageType(Func)) 16980 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16981 } 16982 16983 // Some x86 Windows calling conventions mangle the size of the parameter 16984 // pack into the name. Computing the size of the parameters requires the 16985 // parameter types to be complete. Check that now. 16986 if (funcHasParameterSizeMangling(*this, Func)) 16987 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16988 16989 // In the MS C++ ABI, the compiler emits destructor variants where they are 16990 // used. If the destructor is used here but defined elsewhere, mark the 16991 // virtual base destructors referenced. If those virtual base destructors 16992 // are inline, this will ensure they are defined when emitting the complete 16993 // destructor variant. This checking may be redundant if the destructor is 16994 // provided later in this TU. 16995 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16996 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16997 CXXRecordDecl *Parent = Dtor->getParent(); 16998 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16999 CheckCompleteDestructorVariant(Loc, Dtor); 17000 } 17001 } 17002 17003 Func->markUsed(Context); 17004 } 17005 } 17006 17007 /// Directly mark a variable odr-used. Given a choice, prefer to use 17008 /// MarkVariableReferenced since it does additional checks and then 17009 /// calls MarkVarDeclODRUsed. 17010 /// If the variable must be captured: 17011 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17012 /// - else capture it in the DeclContext that maps to the 17013 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17014 static void 17015 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17016 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17017 // Keep track of used but undefined variables. 17018 // FIXME: We shouldn't suppress this warning for static data members. 17019 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17020 (!Var->isExternallyVisible() || Var->isInline() || 17021 SemaRef.isExternalWithNoLinkageType(Var)) && 17022 !(Var->isStaticDataMember() && Var->hasInit())) { 17023 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17024 if (old.isInvalid()) 17025 old = Loc; 17026 } 17027 QualType CaptureType, DeclRefType; 17028 if (SemaRef.LangOpts.OpenMP) 17029 SemaRef.tryCaptureOpenMPLambdas(Var); 17030 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17031 /*EllipsisLoc*/ SourceLocation(), 17032 /*BuildAndDiagnose*/ true, 17033 CaptureType, DeclRefType, 17034 FunctionScopeIndexToStopAt); 17035 17036 Var->markUsed(SemaRef.Context); 17037 } 17038 17039 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17040 SourceLocation Loc, 17041 unsigned CapturingScopeIndex) { 17042 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17043 } 17044 17045 static void 17046 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17047 ValueDecl *var, DeclContext *DC) { 17048 DeclContext *VarDC = var->getDeclContext(); 17049 17050 // If the parameter still belongs to the translation unit, then 17051 // we're actually just using one parameter in the declaration of 17052 // the next. 17053 if (isa<ParmVarDecl>(var) && 17054 isa<TranslationUnitDecl>(VarDC)) 17055 return; 17056 17057 // For C code, don't diagnose about capture if we're not actually in code 17058 // right now; it's impossible to write a non-constant expression outside of 17059 // function context, so we'll get other (more useful) diagnostics later. 17060 // 17061 // For C++, things get a bit more nasty... it would be nice to suppress this 17062 // diagnostic for certain cases like using a local variable in an array bound 17063 // for a member of a local class, but the correct predicate is not obvious. 17064 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17065 return; 17066 17067 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17068 unsigned ContextKind = 3; // unknown 17069 if (isa<CXXMethodDecl>(VarDC) && 17070 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17071 ContextKind = 2; 17072 } else if (isa<FunctionDecl>(VarDC)) { 17073 ContextKind = 0; 17074 } else if (isa<BlockDecl>(VarDC)) { 17075 ContextKind = 1; 17076 } 17077 17078 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17079 << var << ValueKind << ContextKind << VarDC; 17080 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17081 << var; 17082 17083 // FIXME: Add additional diagnostic info about class etc. which prevents 17084 // capture. 17085 } 17086 17087 17088 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17089 bool &SubCapturesAreNested, 17090 QualType &CaptureType, 17091 QualType &DeclRefType) { 17092 // Check whether we've already captured it. 17093 if (CSI->CaptureMap.count(Var)) { 17094 // If we found a capture, any subcaptures are nested. 17095 SubCapturesAreNested = true; 17096 17097 // Retrieve the capture type for this variable. 17098 CaptureType = CSI->getCapture(Var).getCaptureType(); 17099 17100 // Compute the type of an expression that refers to this variable. 17101 DeclRefType = CaptureType.getNonReferenceType(); 17102 17103 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17104 // are mutable in the sense that user can change their value - they are 17105 // private instances of the captured declarations. 17106 const Capture &Cap = CSI->getCapture(Var); 17107 if (Cap.isCopyCapture() && 17108 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17109 !(isa<CapturedRegionScopeInfo>(CSI) && 17110 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17111 DeclRefType.addConst(); 17112 return true; 17113 } 17114 return false; 17115 } 17116 17117 // Only block literals, captured statements, and lambda expressions can 17118 // capture; other scopes don't work. 17119 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17120 SourceLocation Loc, 17121 const bool Diagnose, Sema &S) { 17122 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17123 return getLambdaAwareParentOfDeclContext(DC); 17124 else if (Var->hasLocalStorage()) { 17125 if (Diagnose) 17126 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17127 } 17128 return nullptr; 17129 } 17130 17131 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17132 // certain types of variables (unnamed, variably modified types etc.) 17133 // so check for eligibility. 17134 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17135 SourceLocation Loc, 17136 const bool Diagnose, Sema &S) { 17137 17138 bool IsBlock = isa<BlockScopeInfo>(CSI); 17139 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17140 17141 // Lambdas are not allowed to capture unnamed variables 17142 // (e.g. anonymous unions). 17143 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17144 // assuming that's the intent. 17145 if (IsLambda && !Var->getDeclName()) { 17146 if (Diagnose) { 17147 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17148 S.Diag(Var->getLocation(), diag::note_declared_at); 17149 } 17150 return false; 17151 } 17152 17153 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17154 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17155 if (Diagnose) { 17156 S.Diag(Loc, diag::err_ref_vm_type); 17157 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17158 } 17159 return false; 17160 } 17161 // Prohibit structs with flexible array members too. 17162 // We cannot capture what is in the tail end of the struct. 17163 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17164 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17165 if (Diagnose) { 17166 if (IsBlock) 17167 S.Diag(Loc, diag::err_ref_flexarray_type); 17168 else 17169 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17170 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17171 } 17172 return false; 17173 } 17174 } 17175 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17176 // Lambdas and captured statements are not allowed to capture __block 17177 // variables; they don't support the expected semantics. 17178 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17179 if (Diagnose) { 17180 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17181 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17182 } 17183 return false; 17184 } 17185 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17186 if (S.getLangOpts().OpenCL && IsBlock && 17187 Var->getType()->isBlockPointerType()) { 17188 if (Diagnose) 17189 S.Diag(Loc, diag::err_opencl_block_ref_block); 17190 return false; 17191 } 17192 17193 return true; 17194 } 17195 17196 // Returns true if the capture by block was successful. 17197 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17198 SourceLocation Loc, 17199 const bool BuildAndDiagnose, 17200 QualType &CaptureType, 17201 QualType &DeclRefType, 17202 const bool Nested, 17203 Sema &S, bool Invalid) { 17204 bool ByRef = false; 17205 17206 // Blocks are not allowed to capture arrays, excepting OpenCL. 17207 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17208 // (decayed to pointers). 17209 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17210 if (BuildAndDiagnose) { 17211 S.Diag(Loc, diag::err_ref_array_type); 17212 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17213 Invalid = true; 17214 } else { 17215 return false; 17216 } 17217 } 17218 17219 // Forbid the block-capture of autoreleasing variables. 17220 if (!Invalid && 17221 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17222 if (BuildAndDiagnose) { 17223 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17224 << /*block*/ 0; 17225 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17226 Invalid = true; 17227 } else { 17228 return false; 17229 } 17230 } 17231 17232 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17233 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17234 QualType PointeeTy = PT->getPointeeType(); 17235 17236 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17237 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17238 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17239 if (BuildAndDiagnose) { 17240 SourceLocation VarLoc = Var->getLocation(); 17241 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17242 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17243 } 17244 } 17245 } 17246 17247 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17248 if (HasBlocksAttr || CaptureType->isReferenceType() || 17249 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17250 // Block capture by reference does not change the capture or 17251 // declaration reference types. 17252 ByRef = true; 17253 } else { 17254 // Block capture by copy introduces 'const'. 17255 CaptureType = CaptureType.getNonReferenceType().withConst(); 17256 DeclRefType = CaptureType; 17257 } 17258 17259 // Actually capture the variable. 17260 if (BuildAndDiagnose) 17261 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17262 CaptureType, Invalid); 17263 17264 return !Invalid; 17265 } 17266 17267 17268 /// Capture the given variable in the captured region. 17269 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17270 VarDecl *Var, 17271 SourceLocation Loc, 17272 const bool BuildAndDiagnose, 17273 QualType &CaptureType, 17274 QualType &DeclRefType, 17275 const bool RefersToCapturedVariable, 17276 Sema &S, bool Invalid) { 17277 // By default, capture variables by reference. 17278 bool ByRef = true; 17279 // Using an LValue reference type is consistent with Lambdas (see below). 17280 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17281 if (S.isOpenMPCapturedDecl(Var)) { 17282 bool HasConst = DeclRefType.isConstQualified(); 17283 DeclRefType = DeclRefType.getUnqualifiedType(); 17284 // Don't lose diagnostics about assignments to const. 17285 if (HasConst) 17286 DeclRefType.addConst(); 17287 } 17288 // Do not capture firstprivates in tasks. 17289 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17290 OMPC_unknown) 17291 return true; 17292 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17293 RSI->OpenMPCaptureLevel); 17294 } 17295 17296 if (ByRef) 17297 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17298 else 17299 CaptureType = DeclRefType; 17300 17301 // Actually capture the variable. 17302 if (BuildAndDiagnose) 17303 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17304 Loc, SourceLocation(), CaptureType, Invalid); 17305 17306 return !Invalid; 17307 } 17308 17309 /// Capture the given variable in the lambda. 17310 static bool captureInLambda(LambdaScopeInfo *LSI, 17311 VarDecl *Var, 17312 SourceLocation Loc, 17313 const bool BuildAndDiagnose, 17314 QualType &CaptureType, 17315 QualType &DeclRefType, 17316 const bool RefersToCapturedVariable, 17317 const Sema::TryCaptureKind Kind, 17318 SourceLocation EllipsisLoc, 17319 const bool IsTopScope, 17320 Sema &S, bool Invalid) { 17321 // Determine whether we are capturing by reference or by value. 17322 bool ByRef = false; 17323 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17324 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17325 } else { 17326 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17327 } 17328 17329 // Compute the type of the field that will capture this variable. 17330 if (ByRef) { 17331 // C++11 [expr.prim.lambda]p15: 17332 // An entity is captured by reference if it is implicitly or 17333 // explicitly captured but not captured by copy. It is 17334 // unspecified whether additional unnamed non-static data 17335 // members are declared in the closure type for entities 17336 // captured by reference. 17337 // 17338 // FIXME: It is not clear whether we want to build an lvalue reference 17339 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17340 // to do the former, while EDG does the latter. Core issue 1249 will 17341 // clarify, but for now we follow GCC because it's a more permissive and 17342 // easily defensible position. 17343 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17344 } else { 17345 // C++11 [expr.prim.lambda]p14: 17346 // For each entity captured by copy, an unnamed non-static 17347 // data member is declared in the closure type. The 17348 // declaration order of these members is unspecified. The type 17349 // of such a data member is the type of the corresponding 17350 // captured entity if the entity is not a reference to an 17351 // object, or the referenced type otherwise. [Note: If the 17352 // captured entity is a reference to a function, the 17353 // corresponding data member is also a reference to a 17354 // function. - end note ] 17355 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17356 if (!RefType->getPointeeType()->isFunctionType()) 17357 CaptureType = RefType->getPointeeType(); 17358 } 17359 17360 // Forbid the lambda copy-capture of autoreleasing variables. 17361 if (!Invalid && 17362 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17363 if (BuildAndDiagnose) { 17364 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17365 S.Diag(Var->getLocation(), diag::note_previous_decl) 17366 << Var->getDeclName(); 17367 Invalid = true; 17368 } else { 17369 return false; 17370 } 17371 } 17372 17373 // Make sure that by-copy captures are of a complete and non-abstract type. 17374 if (!Invalid && BuildAndDiagnose) { 17375 if (!CaptureType->isDependentType() && 17376 S.RequireCompleteSizedType( 17377 Loc, CaptureType, 17378 diag::err_capture_of_incomplete_or_sizeless_type, 17379 Var->getDeclName())) 17380 Invalid = true; 17381 else if (S.RequireNonAbstractType(Loc, CaptureType, 17382 diag::err_capture_of_abstract_type)) 17383 Invalid = true; 17384 } 17385 } 17386 17387 // Compute the type of a reference to this captured variable. 17388 if (ByRef) 17389 DeclRefType = CaptureType.getNonReferenceType(); 17390 else { 17391 // C++ [expr.prim.lambda]p5: 17392 // The closure type for a lambda-expression has a public inline 17393 // function call operator [...]. This function call operator is 17394 // declared const (9.3.1) if and only if the lambda-expression's 17395 // parameter-declaration-clause is not followed by mutable. 17396 DeclRefType = CaptureType.getNonReferenceType(); 17397 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17398 DeclRefType.addConst(); 17399 } 17400 17401 // Add the capture. 17402 if (BuildAndDiagnose) 17403 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17404 Loc, EllipsisLoc, CaptureType, Invalid); 17405 17406 return !Invalid; 17407 } 17408 17409 bool Sema::tryCaptureVariable( 17410 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17411 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17412 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17413 // An init-capture is notionally from the context surrounding its 17414 // declaration, but its parent DC is the lambda class. 17415 DeclContext *VarDC = Var->getDeclContext(); 17416 if (Var->isInitCapture()) 17417 VarDC = VarDC->getParent(); 17418 17419 DeclContext *DC = CurContext; 17420 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17421 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17422 // We need to sync up the Declaration Context with the 17423 // FunctionScopeIndexToStopAt 17424 if (FunctionScopeIndexToStopAt) { 17425 unsigned FSIndex = FunctionScopes.size() - 1; 17426 while (FSIndex != MaxFunctionScopesIndex) { 17427 DC = getLambdaAwareParentOfDeclContext(DC); 17428 --FSIndex; 17429 } 17430 } 17431 17432 17433 // If the variable is declared in the current context, there is no need to 17434 // capture it. 17435 if (VarDC == DC) return true; 17436 17437 // Capture global variables if it is required to use private copy of this 17438 // variable. 17439 bool IsGlobal = !Var->hasLocalStorage(); 17440 if (IsGlobal && 17441 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17442 MaxFunctionScopesIndex))) 17443 return true; 17444 Var = Var->getCanonicalDecl(); 17445 17446 // Walk up the stack to determine whether we can capture the variable, 17447 // performing the "simple" checks that don't depend on type. We stop when 17448 // we've either hit the declared scope of the variable or find an existing 17449 // capture of that variable. We start from the innermost capturing-entity 17450 // (the DC) and ensure that all intervening capturing-entities 17451 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17452 // declcontext can either capture the variable or have already captured 17453 // the variable. 17454 CaptureType = Var->getType(); 17455 DeclRefType = CaptureType.getNonReferenceType(); 17456 bool Nested = false; 17457 bool Explicit = (Kind != TryCapture_Implicit); 17458 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17459 do { 17460 // Only block literals, captured statements, and lambda expressions can 17461 // capture; other scopes don't work. 17462 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17463 ExprLoc, 17464 BuildAndDiagnose, 17465 *this); 17466 // We need to check for the parent *first* because, if we *have* 17467 // private-captured a global variable, we need to recursively capture it in 17468 // intermediate blocks, lambdas, etc. 17469 if (!ParentDC) { 17470 if (IsGlobal) { 17471 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17472 break; 17473 } 17474 return true; 17475 } 17476 17477 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17478 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17479 17480 17481 // Check whether we've already captured it. 17482 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17483 DeclRefType)) { 17484 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17485 break; 17486 } 17487 // If we are instantiating a generic lambda call operator body, 17488 // we do not want to capture new variables. What was captured 17489 // during either a lambdas transformation or initial parsing 17490 // should be used. 17491 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17492 if (BuildAndDiagnose) { 17493 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17494 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17495 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17496 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17497 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17498 } else 17499 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17500 } 17501 return true; 17502 } 17503 17504 // Try to capture variable-length arrays types. 17505 if (Var->getType()->isVariablyModifiedType()) { 17506 // We're going to walk down into the type and look for VLA 17507 // expressions. 17508 QualType QTy = Var->getType(); 17509 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17510 QTy = PVD->getOriginalType(); 17511 captureVariablyModifiedType(Context, QTy, CSI); 17512 } 17513 17514 if (getLangOpts().OpenMP) { 17515 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17516 // OpenMP private variables should not be captured in outer scope, so 17517 // just break here. Similarly, global variables that are captured in a 17518 // target region should not be captured outside the scope of the region. 17519 if (RSI->CapRegionKind == CR_OpenMP) { 17520 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17521 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17522 // If the variable is private (i.e. not captured) and has variably 17523 // modified type, we still need to capture the type for correct 17524 // codegen in all regions, associated with the construct. Currently, 17525 // it is captured in the innermost captured region only. 17526 if (IsOpenMPPrivateDecl != OMPC_unknown && 17527 Var->getType()->isVariablyModifiedType()) { 17528 QualType QTy = Var->getType(); 17529 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17530 QTy = PVD->getOriginalType(); 17531 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17532 I < E; ++I) { 17533 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17534 FunctionScopes[FunctionScopesIndex - I]); 17535 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17536 "Wrong number of captured regions associated with the " 17537 "OpenMP construct."); 17538 captureVariablyModifiedType(Context, QTy, OuterRSI); 17539 } 17540 } 17541 bool IsTargetCap = 17542 IsOpenMPPrivateDecl != OMPC_private && 17543 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17544 RSI->OpenMPCaptureLevel); 17545 // Do not capture global if it is not privatized in outer regions. 17546 bool IsGlobalCap = 17547 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17548 RSI->OpenMPCaptureLevel); 17549 17550 // When we detect target captures we are looking from inside the 17551 // target region, therefore we need to propagate the capture from the 17552 // enclosing region. Therefore, the capture is not initially nested. 17553 if (IsTargetCap) 17554 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17555 17556 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17557 (IsGlobal && !IsGlobalCap)) { 17558 Nested = !IsTargetCap; 17559 bool HasConst = DeclRefType.isConstQualified(); 17560 DeclRefType = DeclRefType.getUnqualifiedType(); 17561 // Don't lose diagnostics about assignments to const. 17562 if (HasConst) 17563 DeclRefType.addConst(); 17564 CaptureType = Context.getLValueReferenceType(DeclRefType); 17565 break; 17566 } 17567 } 17568 } 17569 } 17570 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17571 // No capture-default, and this is not an explicit capture 17572 // so cannot capture this variable. 17573 if (BuildAndDiagnose) { 17574 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17575 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17576 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17577 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17578 diag::note_lambda_decl); 17579 // FIXME: If we error out because an outer lambda can not implicitly 17580 // capture a variable that an inner lambda explicitly captures, we 17581 // should have the inner lambda do the explicit capture - because 17582 // it makes for cleaner diagnostics later. This would purely be done 17583 // so that the diagnostic does not misleadingly claim that a variable 17584 // can not be captured by a lambda implicitly even though it is captured 17585 // explicitly. Suggestion: 17586 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17587 // at the function head 17588 // - cache the StartingDeclContext - this must be a lambda 17589 // - captureInLambda in the innermost lambda the variable. 17590 } 17591 return true; 17592 } 17593 17594 FunctionScopesIndex--; 17595 DC = ParentDC; 17596 Explicit = false; 17597 } while (!VarDC->Equals(DC)); 17598 17599 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17600 // computing the type of the capture at each step, checking type-specific 17601 // requirements, and adding captures if requested. 17602 // If the variable had already been captured previously, we start capturing 17603 // at the lambda nested within that one. 17604 bool Invalid = false; 17605 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17606 ++I) { 17607 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17608 17609 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17610 // certain types of variables (unnamed, variably modified types etc.) 17611 // so check for eligibility. 17612 if (!Invalid) 17613 Invalid = 17614 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17615 17616 // After encountering an error, if we're actually supposed to capture, keep 17617 // capturing in nested contexts to suppress any follow-on diagnostics. 17618 if (Invalid && !BuildAndDiagnose) 17619 return true; 17620 17621 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17622 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17623 DeclRefType, Nested, *this, Invalid); 17624 Nested = true; 17625 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17626 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17627 CaptureType, DeclRefType, Nested, 17628 *this, Invalid); 17629 Nested = true; 17630 } else { 17631 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17632 Invalid = 17633 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17634 DeclRefType, Nested, Kind, EllipsisLoc, 17635 /*IsTopScope*/ I == N - 1, *this, Invalid); 17636 Nested = true; 17637 } 17638 17639 if (Invalid && !BuildAndDiagnose) 17640 return true; 17641 } 17642 return Invalid; 17643 } 17644 17645 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17646 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17647 QualType CaptureType; 17648 QualType DeclRefType; 17649 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17650 /*BuildAndDiagnose=*/true, CaptureType, 17651 DeclRefType, nullptr); 17652 } 17653 17654 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17655 QualType CaptureType; 17656 QualType DeclRefType; 17657 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17658 /*BuildAndDiagnose=*/false, CaptureType, 17659 DeclRefType, nullptr); 17660 } 17661 17662 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17663 QualType CaptureType; 17664 QualType DeclRefType; 17665 17666 // Determine whether we can capture this variable. 17667 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17668 /*BuildAndDiagnose=*/false, CaptureType, 17669 DeclRefType, nullptr)) 17670 return QualType(); 17671 17672 return DeclRefType; 17673 } 17674 17675 namespace { 17676 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17677 // The produced TemplateArgumentListInfo* points to data stored within this 17678 // object, so should only be used in contexts where the pointer will not be 17679 // used after the CopiedTemplateArgs object is destroyed. 17680 class CopiedTemplateArgs { 17681 bool HasArgs; 17682 TemplateArgumentListInfo TemplateArgStorage; 17683 public: 17684 template<typename RefExpr> 17685 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17686 if (HasArgs) 17687 E->copyTemplateArgumentsInto(TemplateArgStorage); 17688 } 17689 operator TemplateArgumentListInfo*() 17690 #ifdef __has_cpp_attribute 17691 #if __has_cpp_attribute(clang::lifetimebound) 17692 [[clang::lifetimebound]] 17693 #endif 17694 #endif 17695 { 17696 return HasArgs ? &TemplateArgStorage : nullptr; 17697 } 17698 }; 17699 } 17700 17701 /// Walk the set of potential results of an expression and mark them all as 17702 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17703 /// 17704 /// \return A new expression if we found any potential results, ExprEmpty() if 17705 /// not, and ExprError() if we diagnosed an error. 17706 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17707 NonOdrUseReason NOUR) { 17708 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17709 // an object that satisfies the requirements for appearing in a 17710 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17711 // is immediately applied." This function handles the lvalue-to-rvalue 17712 // conversion part. 17713 // 17714 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17715 // transform it into the relevant kind of non-odr-use node and rebuild the 17716 // tree of nodes leading to it. 17717 // 17718 // This is a mini-TreeTransform that only transforms a restricted subset of 17719 // nodes (and only certain operands of them). 17720 17721 // Rebuild a subexpression. 17722 auto Rebuild = [&](Expr *Sub) { 17723 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17724 }; 17725 17726 // Check whether a potential result satisfies the requirements of NOUR. 17727 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17728 // Any entity other than a VarDecl is always odr-used whenever it's named 17729 // in a potentially-evaluated expression. 17730 auto *VD = dyn_cast<VarDecl>(D); 17731 if (!VD) 17732 return true; 17733 17734 // C++2a [basic.def.odr]p4: 17735 // A variable x whose name appears as a potentially-evalauted expression 17736 // e is odr-used by e unless 17737 // -- x is a reference that is usable in constant expressions, or 17738 // -- x is a variable of non-reference type that is usable in constant 17739 // expressions and has no mutable subobjects, and e is an element of 17740 // the set of potential results of an expression of 17741 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17742 // conversion is applied, or 17743 // -- x is a variable of non-reference type, and e is an element of the 17744 // set of potential results of a discarded-value expression to which 17745 // the lvalue-to-rvalue conversion is not applied 17746 // 17747 // We check the first bullet and the "potentially-evaluated" condition in 17748 // BuildDeclRefExpr. We check the type requirements in the second bullet 17749 // in CheckLValueToRValueConversionOperand below. 17750 switch (NOUR) { 17751 case NOUR_None: 17752 case NOUR_Unevaluated: 17753 llvm_unreachable("unexpected non-odr-use-reason"); 17754 17755 case NOUR_Constant: 17756 // Constant references were handled when they were built. 17757 if (VD->getType()->isReferenceType()) 17758 return true; 17759 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17760 if (RD->hasMutableFields()) 17761 return true; 17762 if (!VD->isUsableInConstantExpressions(S.Context)) 17763 return true; 17764 break; 17765 17766 case NOUR_Discarded: 17767 if (VD->getType()->isReferenceType()) 17768 return true; 17769 break; 17770 } 17771 return false; 17772 }; 17773 17774 // Mark that this expression does not constitute an odr-use. 17775 auto MarkNotOdrUsed = [&] { 17776 S.MaybeODRUseExprs.remove(E); 17777 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17778 LSI->markVariableExprAsNonODRUsed(E); 17779 }; 17780 17781 // C++2a [basic.def.odr]p2: 17782 // The set of potential results of an expression e is defined as follows: 17783 switch (E->getStmtClass()) { 17784 // -- If e is an id-expression, ... 17785 case Expr::DeclRefExprClass: { 17786 auto *DRE = cast<DeclRefExpr>(E); 17787 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17788 break; 17789 17790 // Rebuild as a non-odr-use DeclRefExpr. 17791 MarkNotOdrUsed(); 17792 return DeclRefExpr::Create( 17793 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17794 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17795 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17796 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17797 } 17798 17799 case Expr::FunctionParmPackExprClass: { 17800 auto *FPPE = cast<FunctionParmPackExpr>(E); 17801 // If any of the declarations in the pack is odr-used, then the expression 17802 // as a whole constitutes an odr-use. 17803 for (VarDecl *D : *FPPE) 17804 if (IsPotentialResultOdrUsed(D)) 17805 return ExprEmpty(); 17806 17807 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17808 // nothing cares about whether we marked this as an odr-use, but it might 17809 // be useful for non-compiler tools. 17810 MarkNotOdrUsed(); 17811 break; 17812 } 17813 17814 // -- If e is a subscripting operation with an array operand... 17815 case Expr::ArraySubscriptExprClass: { 17816 auto *ASE = cast<ArraySubscriptExpr>(E); 17817 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17818 if (!OldBase->getType()->isArrayType()) 17819 break; 17820 ExprResult Base = Rebuild(OldBase); 17821 if (!Base.isUsable()) 17822 return Base; 17823 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17824 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17825 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17826 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17827 ASE->getRBracketLoc()); 17828 } 17829 17830 case Expr::MemberExprClass: { 17831 auto *ME = cast<MemberExpr>(E); 17832 // -- If e is a class member access expression [...] naming a non-static 17833 // data member... 17834 if (isa<FieldDecl>(ME->getMemberDecl())) { 17835 ExprResult Base = Rebuild(ME->getBase()); 17836 if (!Base.isUsable()) 17837 return Base; 17838 return MemberExpr::Create( 17839 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17840 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17841 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17842 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17843 ME->getObjectKind(), ME->isNonOdrUse()); 17844 } 17845 17846 if (ME->getMemberDecl()->isCXXInstanceMember()) 17847 break; 17848 17849 // -- If e is a class member access expression naming a static data member, 17850 // ... 17851 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17852 break; 17853 17854 // Rebuild as a non-odr-use MemberExpr. 17855 MarkNotOdrUsed(); 17856 return MemberExpr::Create( 17857 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17858 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17859 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17860 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17861 return ExprEmpty(); 17862 } 17863 17864 case Expr::BinaryOperatorClass: { 17865 auto *BO = cast<BinaryOperator>(E); 17866 Expr *LHS = BO->getLHS(); 17867 Expr *RHS = BO->getRHS(); 17868 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17869 if (BO->getOpcode() == BO_PtrMemD) { 17870 ExprResult Sub = Rebuild(LHS); 17871 if (!Sub.isUsable()) 17872 return Sub; 17873 LHS = Sub.get(); 17874 // -- If e is a comma expression, ... 17875 } else if (BO->getOpcode() == BO_Comma) { 17876 ExprResult Sub = Rebuild(RHS); 17877 if (!Sub.isUsable()) 17878 return Sub; 17879 RHS = Sub.get(); 17880 } else { 17881 break; 17882 } 17883 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17884 LHS, RHS); 17885 } 17886 17887 // -- If e has the form (e1)... 17888 case Expr::ParenExprClass: { 17889 auto *PE = cast<ParenExpr>(E); 17890 ExprResult Sub = Rebuild(PE->getSubExpr()); 17891 if (!Sub.isUsable()) 17892 return Sub; 17893 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17894 } 17895 17896 // -- If e is a glvalue conditional expression, ... 17897 // We don't apply this to a binary conditional operator. FIXME: Should we? 17898 case Expr::ConditionalOperatorClass: { 17899 auto *CO = cast<ConditionalOperator>(E); 17900 ExprResult LHS = Rebuild(CO->getLHS()); 17901 if (LHS.isInvalid()) 17902 return ExprError(); 17903 ExprResult RHS = Rebuild(CO->getRHS()); 17904 if (RHS.isInvalid()) 17905 return ExprError(); 17906 if (!LHS.isUsable() && !RHS.isUsable()) 17907 return ExprEmpty(); 17908 if (!LHS.isUsable()) 17909 LHS = CO->getLHS(); 17910 if (!RHS.isUsable()) 17911 RHS = CO->getRHS(); 17912 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17913 CO->getCond(), LHS.get(), RHS.get()); 17914 } 17915 17916 // [Clang extension] 17917 // -- If e has the form __extension__ e1... 17918 case Expr::UnaryOperatorClass: { 17919 auto *UO = cast<UnaryOperator>(E); 17920 if (UO->getOpcode() != UO_Extension) 17921 break; 17922 ExprResult Sub = Rebuild(UO->getSubExpr()); 17923 if (!Sub.isUsable()) 17924 return Sub; 17925 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17926 Sub.get()); 17927 } 17928 17929 // [Clang extension] 17930 // -- If e has the form _Generic(...), the set of potential results is the 17931 // union of the sets of potential results of the associated expressions. 17932 case Expr::GenericSelectionExprClass: { 17933 auto *GSE = cast<GenericSelectionExpr>(E); 17934 17935 SmallVector<Expr *, 4> AssocExprs; 17936 bool AnyChanged = false; 17937 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17938 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17939 if (AssocExpr.isInvalid()) 17940 return ExprError(); 17941 if (AssocExpr.isUsable()) { 17942 AssocExprs.push_back(AssocExpr.get()); 17943 AnyChanged = true; 17944 } else { 17945 AssocExprs.push_back(OrigAssocExpr); 17946 } 17947 } 17948 17949 return AnyChanged ? S.CreateGenericSelectionExpr( 17950 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17951 GSE->getRParenLoc(), GSE->getControllingExpr(), 17952 GSE->getAssocTypeSourceInfos(), AssocExprs) 17953 : ExprEmpty(); 17954 } 17955 17956 // [Clang extension] 17957 // -- If e has the form __builtin_choose_expr(...), the set of potential 17958 // results is the union of the sets of potential results of the 17959 // second and third subexpressions. 17960 case Expr::ChooseExprClass: { 17961 auto *CE = cast<ChooseExpr>(E); 17962 17963 ExprResult LHS = Rebuild(CE->getLHS()); 17964 if (LHS.isInvalid()) 17965 return ExprError(); 17966 17967 ExprResult RHS = Rebuild(CE->getLHS()); 17968 if (RHS.isInvalid()) 17969 return ExprError(); 17970 17971 if (!LHS.get() && !RHS.get()) 17972 return ExprEmpty(); 17973 if (!LHS.isUsable()) 17974 LHS = CE->getLHS(); 17975 if (!RHS.isUsable()) 17976 RHS = CE->getRHS(); 17977 17978 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17979 RHS.get(), CE->getRParenLoc()); 17980 } 17981 17982 // Step through non-syntactic nodes. 17983 case Expr::ConstantExprClass: { 17984 auto *CE = cast<ConstantExpr>(E); 17985 ExprResult Sub = Rebuild(CE->getSubExpr()); 17986 if (!Sub.isUsable()) 17987 return Sub; 17988 return ConstantExpr::Create(S.Context, Sub.get()); 17989 } 17990 17991 // We could mostly rely on the recursive rebuilding to rebuild implicit 17992 // casts, but not at the top level, so rebuild them here. 17993 case Expr::ImplicitCastExprClass: { 17994 auto *ICE = cast<ImplicitCastExpr>(E); 17995 // Only step through the narrow set of cast kinds we expect to encounter. 17996 // Anything else suggests we've left the region in which potential results 17997 // can be found. 17998 switch (ICE->getCastKind()) { 17999 case CK_NoOp: 18000 case CK_DerivedToBase: 18001 case CK_UncheckedDerivedToBase: { 18002 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18003 if (!Sub.isUsable()) 18004 return Sub; 18005 CXXCastPath Path(ICE->path()); 18006 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18007 ICE->getValueKind(), &Path); 18008 } 18009 18010 default: 18011 break; 18012 } 18013 break; 18014 } 18015 18016 default: 18017 break; 18018 } 18019 18020 // Can't traverse through this node. Nothing to do. 18021 return ExprEmpty(); 18022 } 18023 18024 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18025 // Check whether the operand is or contains an object of non-trivial C union 18026 // type. 18027 if (E->getType().isVolatileQualified() && 18028 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18029 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18030 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18031 Sema::NTCUC_LValueToRValueVolatile, 18032 NTCUK_Destruct|NTCUK_Copy); 18033 18034 // C++2a [basic.def.odr]p4: 18035 // [...] an expression of non-volatile-qualified non-class type to which 18036 // the lvalue-to-rvalue conversion is applied [...] 18037 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18038 return E; 18039 18040 ExprResult Result = 18041 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18042 if (Result.isInvalid()) 18043 return ExprError(); 18044 return Result.get() ? Result : E; 18045 } 18046 18047 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18048 Res = CorrectDelayedTyposInExpr(Res); 18049 18050 if (!Res.isUsable()) 18051 return Res; 18052 18053 // If a constant-expression is a reference to a variable where we delay 18054 // deciding whether it is an odr-use, just assume we will apply the 18055 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18056 // (a non-type template argument), we have special handling anyway. 18057 return CheckLValueToRValueConversionOperand(Res.get()); 18058 } 18059 18060 void Sema::CleanupVarDeclMarking() { 18061 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18062 // call. 18063 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18064 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18065 18066 for (Expr *E : LocalMaybeODRUseExprs) { 18067 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18068 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18069 DRE->getLocation(), *this); 18070 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18071 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18072 *this); 18073 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18074 for (VarDecl *VD : *FP) 18075 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18076 } else { 18077 llvm_unreachable("Unexpected expression"); 18078 } 18079 } 18080 18081 assert(MaybeODRUseExprs.empty() && 18082 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18083 } 18084 18085 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18086 VarDecl *Var, Expr *E) { 18087 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18088 isa<FunctionParmPackExpr>(E)) && 18089 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18090 Var->setReferenced(); 18091 18092 if (Var->isInvalidDecl()) 18093 return; 18094 18095 // Record a CUDA/HIP static device/constant variable if it is referenced 18096 // by host code. This is done conservatively, when the variable is referenced 18097 // in any of the following contexts: 18098 // - a non-function context 18099 // - a host function 18100 // - a host device function 18101 // This also requires the reference of the static device/constant variable by 18102 // host code to be visible in the device compilation for the compiler to be 18103 // able to externalize the static device/constant variable. 18104 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18105 auto *CurContext = SemaRef.CurContext; 18106 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18107 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18108 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18109 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18110 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18111 } 18112 18113 auto *MSI = Var->getMemberSpecializationInfo(); 18114 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18115 : Var->getTemplateSpecializationKind(); 18116 18117 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18118 bool UsableInConstantExpr = 18119 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18120 18121 // C++20 [expr.const]p12: 18122 // A variable [...] is needed for constant evaluation if it is [...] a 18123 // variable whose name appears as a potentially constant evaluated 18124 // expression that is either a contexpr variable or is of non-volatile 18125 // const-qualified integral type or of reference type 18126 bool NeededForConstantEvaluation = 18127 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18128 18129 bool NeedDefinition = 18130 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18131 18132 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18133 "Can't instantiate a partial template specialization."); 18134 18135 // If this might be a member specialization of a static data member, check 18136 // the specialization is visible. We already did the checks for variable 18137 // template specializations when we created them. 18138 if (NeedDefinition && TSK != TSK_Undeclared && 18139 !isa<VarTemplateSpecializationDecl>(Var)) 18140 SemaRef.checkSpecializationVisibility(Loc, Var); 18141 18142 // Perform implicit instantiation of static data members, static data member 18143 // templates of class templates, and variable template specializations. Delay 18144 // instantiations of variable templates, except for those that could be used 18145 // in a constant expression. 18146 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18147 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18148 // instantiation declaration if a variable is usable in a constant 18149 // expression (among other cases). 18150 bool TryInstantiating = 18151 TSK == TSK_ImplicitInstantiation || 18152 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18153 18154 if (TryInstantiating) { 18155 SourceLocation PointOfInstantiation = 18156 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18157 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18158 if (FirstInstantiation) { 18159 PointOfInstantiation = Loc; 18160 if (MSI) 18161 MSI->setPointOfInstantiation(PointOfInstantiation); 18162 // FIXME: Notify listener. 18163 else 18164 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18165 } 18166 18167 if (UsableInConstantExpr) { 18168 // Do not defer instantiations of variables that could be used in a 18169 // constant expression. 18170 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18171 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18172 }); 18173 18174 // Re-set the member to trigger a recomputation of the dependence bits 18175 // for the expression. 18176 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18177 DRE->setDecl(DRE->getDecl()); 18178 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18179 ME->setMemberDecl(ME->getMemberDecl()); 18180 } else if (FirstInstantiation || 18181 isa<VarTemplateSpecializationDecl>(Var)) { 18182 // FIXME: For a specialization of a variable template, we don't 18183 // distinguish between "declaration and type implicitly instantiated" 18184 // and "implicit instantiation of definition requested", so we have 18185 // no direct way to avoid enqueueing the pending instantiation 18186 // multiple times. 18187 SemaRef.PendingInstantiations 18188 .push_back(std::make_pair(Var, PointOfInstantiation)); 18189 } 18190 } 18191 } 18192 18193 // C++2a [basic.def.odr]p4: 18194 // A variable x whose name appears as a potentially-evaluated expression e 18195 // is odr-used by e unless 18196 // -- x is a reference that is usable in constant expressions 18197 // -- x is a variable of non-reference type that is usable in constant 18198 // expressions and has no mutable subobjects [FIXME], and e is an 18199 // element of the set of potential results of an expression of 18200 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18201 // conversion is applied 18202 // -- x is a variable of non-reference type, and e is an element of the set 18203 // of potential results of a discarded-value expression to which the 18204 // lvalue-to-rvalue conversion is not applied [FIXME] 18205 // 18206 // We check the first part of the second bullet here, and 18207 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18208 // FIXME: To get the third bullet right, we need to delay this even for 18209 // variables that are not usable in constant expressions. 18210 18211 // If we already know this isn't an odr-use, there's nothing more to do. 18212 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18213 if (DRE->isNonOdrUse()) 18214 return; 18215 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18216 if (ME->isNonOdrUse()) 18217 return; 18218 18219 switch (OdrUse) { 18220 case OdrUseContext::None: 18221 assert((!E || isa<FunctionParmPackExpr>(E)) && 18222 "missing non-odr-use marking for unevaluated decl ref"); 18223 break; 18224 18225 case OdrUseContext::FormallyOdrUsed: 18226 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18227 // behavior. 18228 break; 18229 18230 case OdrUseContext::Used: 18231 // If we might later find that this expression isn't actually an odr-use, 18232 // delay the marking. 18233 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18234 SemaRef.MaybeODRUseExprs.insert(E); 18235 else 18236 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18237 break; 18238 18239 case OdrUseContext::Dependent: 18240 // If this is a dependent context, we don't need to mark variables as 18241 // odr-used, but we may still need to track them for lambda capture. 18242 // FIXME: Do we also need to do this inside dependent typeid expressions 18243 // (which are modeled as unevaluated at this point)? 18244 const bool RefersToEnclosingScope = 18245 (SemaRef.CurContext != Var->getDeclContext() && 18246 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18247 if (RefersToEnclosingScope) { 18248 LambdaScopeInfo *const LSI = 18249 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18250 if (LSI && (!LSI->CallOperator || 18251 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18252 // If a variable could potentially be odr-used, defer marking it so 18253 // until we finish analyzing the full expression for any 18254 // lvalue-to-rvalue 18255 // or discarded value conversions that would obviate odr-use. 18256 // Add it to the list of potential captures that will be analyzed 18257 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18258 // unless the variable is a reference that was initialized by a constant 18259 // expression (this will never need to be captured or odr-used). 18260 // 18261 // FIXME: We can simplify this a lot after implementing P0588R1. 18262 assert(E && "Capture variable should be used in an expression."); 18263 if (!Var->getType()->isReferenceType() || 18264 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18265 LSI->addPotentialCapture(E->IgnoreParens()); 18266 } 18267 } 18268 break; 18269 } 18270 } 18271 18272 /// Mark a variable referenced, and check whether it is odr-used 18273 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18274 /// used directly for normal expressions referring to VarDecl. 18275 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18276 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18277 } 18278 18279 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18280 Decl *D, Expr *E, bool MightBeOdrUse) { 18281 if (SemaRef.isInOpenMPDeclareTargetContext()) 18282 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18283 18284 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18285 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18286 return; 18287 } 18288 18289 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18290 18291 // If this is a call to a method via a cast, also mark the method in the 18292 // derived class used in case codegen can devirtualize the call. 18293 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18294 if (!ME) 18295 return; 18296 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18297 if (!MD) 18298 return; 18299 // Only attempt to devirtualize if this is truly a virtual call. 18300 bool IsVirtualCall = MD->isVirtual() && 18301 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18302 if (!IsVirtualCall) 18303 return; 18304 18305 // If it's possible to devirtualize the call, mark the called function 18306 // referenced. 18307 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18308 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18309 if (DM) 18310 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18311 } 18312 18313 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18314 /// 18315 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18316 /// handled with care if the DeclRefExpr is not newly-created. 18317 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18318 // TODO: update this with DR# once a defect report is filed. 18319 // C++11 defect. The address of a pure member should not be an ODR use, even 18320 // if it's a qualified reference. 18321 bool OdrUse = true; 18322 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18323 if (Method->isVirtual() && 18324 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18325 OdrUse = false; 18326 18327 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18328 if (!isConstantEvaluated() && FD->isConsteval() && 18329 !RebuildingImmediateInvocation) 18330 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18331 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18332 } 18333 18334 /// Perform reference-marking and odr-use handling for a MemberExpr. 18335 void Sema::MarkMemberReferenced(MemberExpr *E) { 18336 // C++11 [basic.def.odr]p2: 18337 // A non-overloaded function whose name appears as a potentially-evaluated 18338 // expression or a member of a set of candidate functions, if selected by 18339 // overload resolution when referred to from a potentially-evaluated 18340 // expression, is odr-used, unless it is a pure virtual function and its 18341 // name is not explicitly qualified. 18342 bool MightBeOdrUse = true; 18343 if (E->performsVirtualDispatch(getLangOpts())) { 18344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18345 if (Method->isPure()) 18346 MightBeOdrUse = false; 18347 } 18348 SourceLocation Loc = 18349 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18350 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18351 } 18352 18353 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18354 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18355 for (VarDecl *VD : *E) 18356 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18357 } 18358 18359 /// Perform marking for a reference to an arbitrary declaration. It 18360 /// marks the declaration referenced, and performs odr-use checking for 18361 /// functions and variables. This method should not be used when building a 18362 /// normal expression which refers to a variable. 18363 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18364 bool MightBeOdrUse) { 18365 if (MightBeOdrUse) { 18366 if (auto *VD = dyn_cast<VarDecl>(D)) { 18367 MarkVariableReferenced(Loc, VD); 18368 return; 18369 } 18370 } 18371 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18372 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18373 return; 18374 } 18375 D->setReferenced(); 18376 } 18377 18378 namespace { 18379 // Mark all of the declarations used by a type as referenced. 18380 // FIXME: Not fully implemented yet! We need to have a better understanding 18381 // of when we're entering a context we should not recurse into. 18382 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18383 // TreeTransforms rebuilding the type in a new context. Rather than 18384 // duplicating the TreeTransform logic, we should consider reusing it here. 18385 // Currently that causes problems when rebuilding LambdaExprs. 18386 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18387 Sema &S; 18388 SourceLocation Loc; 18389 18390 public: 18391 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18392 18393 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18394 18395 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18396 }; 18397 } 18398 18399 bool MarkReferencedDecls::TraverseTemplateArgument( 18400 const TemplateArgument &Arg) { 18401 { 18402 // A non-type template argument is a constant-evaluated context. 18403 EnterExpressionEvaluationContext Evaluated( 18404 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18405 if (Arg.getKind() == TemplateArgument::Declaration) { 18406 if (Decl *D = Arg.getAsDecl()) 18407 S.MarkAnyDeclReferenced(Loc, D, true); 18408 } else if (Arg.getKind() == TemplateArgument::Expression) { 18409 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18410 } 18411 } 18412 18413 return Inherited::TraverseTemplateArgument(Arg); 18414 } 18415 18416 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18417 MarkReferencedDecls Marker(*this, Loc); 18418 Marker.TraverseType(T); 18419 } 18420 18421 namespace { 18422 /// Helper class that marks all of the declarations referenced by 18423 /// potentially-evaluated subexpressions as "referenced". 18424 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18425 public: 18426 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18427 bool SkipLocalVariables; 18428 18429 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18430 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18431 18432 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18433 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18434 } 18435 18436 void VisitDeclRefExpr(DeclRefExpr *E) { 18437 // If we were asked not to visit local variables, don't. 18438 if (SkipLocalVariables) { 18439 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18440 if (VD->hasLocalStorage()) 18441 return; 18442 } 18443 18444 // FIXME: This can trigger the instantiation of the initializer of a 18445 // variable, which can cause the expression to become value-dependent 18446 // or error-dependent. Do we need to propagate the new dependence bits? 18447 S.MarkDeclRefReferenced(E); 18448 } 18449 18450 void VisitMemberExpr(MemberExpr *E) { 18451 S.MarkMemberReferenced(E); 18452 Visit(E->getBase()); 18453 } 18454 }; 18455 } // namespace 18456 18457 /// Mark any declarations that appear within this expression or any 18458 /// potentially-evaluated subexpressions as "referenced". 18459 /// 18460 /// \param SkipLocalVariables If true, don't mark local variables as 18461 /// 'referenced'. 18462 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18463 bool SkipLocalVariables) { 18464 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18465 } 18466 18467 /// Emit a diagnostic that describes an effect on the run-time behavior 18468 /// of the program being compiled. 18469 /// 18470 /// This routine emits the given diagnostic when the code currently being 18471 /// type-checked is "potentially evaluated", meaning that there is a 18472 /// possibility that the code will actually be executable. Code in sizeof() 18473 /// expressions, code used only during overload resolution, etc., are not 18474 /// potentially evaluated. This routine will suppress such diagnostics or, 18475 /// in the absolutely nutty case of potentially potentially evaluated 18476 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18477 /// later. 18478 /// 18479 /// This routine should be used for all diagnostics that describe the run-time 18480 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18481 /// Failure to do so will likely result in spurious diagnostics or failures 18482 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18483 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18484 const PartialDiagnostic &PD) { 18485 switch (ExprEvalContexts.back().Context) { 18486 case ExpressionEvaluationContext::Unevaluated: 18487 case ExpressionEvaluationContext::UnevaluatedList: 18488 case ExpressionEvaluationContext::UnevaluatedAbstract: 18489 case ExpressionEvaluationContext::DiscardedStatement: 18490 // The argument will never be evaluated, so don't complain. 18491 break; 18492 18493 case ExpressionEvaluationContext::ConstantEvaluated: 18494 // Relevant diagnostics should be produced by constant evaluation. 18495 break; 18496 18497 case ExpressionEvaluationContext::PotentiallyEvaluated: 18498 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18499 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18500 FunctionScopes.back()->PossiblyUnreachableDiags. 18501 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18502 return true; 18503 } 18504 18505 // The initializer of a constexpr variable or of the first declaration of a 18506 // static data member is not syntactically a constant evaluated constant, 18507 // but nonetheless is always required to be a constant expression, so we 18508 // can skip diagnosing. 18509 // FIXME: Using the mangling context here is a hack. 18510 if (auto *VD = dyn_cast_or_null<VarDecl>( 18511 ExprEvalContexts.back().ManglingContextDecl)) { 18512 if (VD->isConstexpr() || 18513 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18514 break; 18515 // FIXME: For any other kind of variable, we should build a CFG for its 18516 // initializer and check whether the context in question is reachable. 18517 } 18518 18519 Diag(Loc, PD); 18520 return true; 18521 } 18522 18523 return false; 18524 } 18525 18526 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18527 const PartialDiagnostic &PD) { 18528 return DiagRuntimeBehavior( 18529 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18530 } 18531 18532 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18533 CallExpr *CE, FunctionDecl *FD) { 18534 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18535 return false; 18536 18537 // If we're inside a decltype's expression, don't check for a valid return 18538 // type or construct temporaries until we know whether this is the last call. 18539 if (ExprEvalContexts.back().ExprContext == 18540 ExpressionEvaluationContextRecord::EK_Decltype) { 18541 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18542 return false; 18543 } 18544 18545 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18546 FunctionDecl *FD; 18547 CallExpr *CE; 18548 18549 public: 18550 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18551 : FD(FD), CE(CE) { } 18552 18553 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18554 if (!FD) { 18555 S.Diag(Loc, diag::err_call_incomplete_return) 18556 << T << CE->getSourceRange(); 18557 return; 18558 } 18559 18560 S.Diag(Loc, diag::err_call_function_incomplete_return) 18561 << CE->getSourceRange() << FD << T; 18562 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18563 << FD->getDeclName(); 18564 } 18565 } Diagnoser(FD, CE); 18566 18567 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18568 return true; 18569 18570 return false; 18571 } 18572 18573 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18574 // will prevent this condition from triggering, which is what we want. 18575 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18576 SourceLocation Loc; 18577 18578 unsigned diagnostic = diag::warn_condition_is_assignment; 18579 bool IsOrAssign = false; 18580 18581 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18582 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18583 return; 18584 18585 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18586 18587 // Greylist some idioms by putting them into a warning subcategory. 18588 if (ObjCMessageExpr *ME 18589 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18590 Selector Sel = ME->getSelector(); 18591 18592 // self = [<foo> init...] 18593 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18594 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18595 18596 // <foo> = [<bar> nextObject] 18597 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18598 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18599 } 18600 18601 Loc = Op->getOperatorLoc(); 18602 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18603 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18604 return; 18605 18606 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18607 Loc = Op->getOperatorLoc(); 18608 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18609 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18610 else { 18611 // Not an assignment. 18612 return; 18613 } 18614 18615 Diag(Loc, diagnostic) << E->getSourceRange(); 18616 18617 SourceLocation Open = E->getBeginLoc(); 18618 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18619 Diag(Loc, diag::note_condition_assign_silence) 18620 << FixItHint::CreateInsertion(Open, "(") 18621 << FixItHint::CreateInsertion(Close, ")"); 18622 18623 if (IsOrAssign) 18624 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18625 << FixItHint::CreateReplacement(Loc, "!="); 18626 else 18627 Diag(Loc, diag::note_condition_assign_to_comparison) 18628 << FixItHint::CreateReplacement(Loc, "=="); 18629 } 18630 18631 /// Redundant parentheses over an equality comparison can indicate 18632 /// that the user intended an assignment used as condition. 18633 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18634 // Don't warn if the parens came from a macro. 18635 SourceLocation parenLoc = ParenE->getBeginLoc(); 18636 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18637 return; 18638 // Don't warn for dependent expressions. 18639 if (ParenE->isTypeDependent()) 18640 return; 18641 18642 Expr *E = ParenE->IgnoreParens(); 18643 18644 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18645 if (opE->getOpcode() == BO_EQ && 18646 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18647 == Expr::MLV_Valid) { 18648 SourceLocation Loc = opE->getOperatorLoc(); 18649 18650 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18651 SourceRange ParenERange = ParenE->getSourceRange(); 18652 Diag(Loc, diag::note_equality_comparison_silence) 18653 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18654 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18655 Diag(Loc, diag::note_equality_comparison_to_assign) 18656 << FixItHint::CreateReplacement(Loc, "="); 18657 } 18658 } 18659 18660 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18661 bool IsConstexpr) { 18662 DiagnoseAssignmentAsCondition(E); 18663 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18664 DiagnoseEqualityWithExtraParens(parenE); 18665 18666 ExprResult result = CheckPlaceholderExpr(E); 18667 if (result.isInvalid()) return ExprError(); 18668 E = result.get(); 18669 18670 if (!E->isTypeDependent()) { 18671 if (getLangOpts().CPlusPlus) 18672 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18673 18674 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18675 if (ERes.isInvalid()) 18676 return ExprError(); 18677 E = ERes.get(); 18678 18679 QualType T = E->getType(); 18680 if (!T->isScalarType()) { // C99 6.8.4.1p1 18681 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18682 << T << E->getSourceRange(); 18683 return ExprError(); 18684 } 18685 CheckBoolLikeConversion(E, Loc); 18686 } 18687 18688 return E; 18689 } 18690 18691 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18692 Expr *SubExpr, ConditionKind CK) { 18693 // Empty conditions are valid in for-statements. 18694 if (!SubExpr) 18695 return ConditionResult(); 18696 18697 ExprResult Cond; 18698 switch (CK) { 18699 case ConditionKind::Boolean: 18700 Cond = CheckBooleanCondition(Loc, SubExpr); 18701 break; 18702 18703 case ConditionKind::ConstexprIf: 18704 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18705 break; 18706 18707 case ConditionKind::Switch: 18708 Cond = CheckSwitchCondition(Loc, SubExpr); 18709 break; 18710 } 18711 if (Cond.isInvalid()) { 18712 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18713 {SubExpr}); 18714 if (!Cond.get()) 18715 return ConditionError(); 18716 } 18717 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18718 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18719 if (!FullExpr.get()) 18720 return ConditionError(); 18721 18722 return ConditionResult(*this, nullptr, FullExpr, 18723 CK == ConditionKind::ConstexprIf); 18724 } 18725 18726 namespace { 18727 /// A visitor for rebuilding a call to an __unknown_any expression 18728 /// to have an appropriate type. 18729 struct RebuildUnknownAnyFunction 18730 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18731 18732 Sema &S; 18733 18734 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18735 18736 ExprResult VisitStmt(Stmt *S) { 18737 llvm_unreachable("unexpected statement!"); 18738 } 18739 18740 ExprResult VisitExpr(Expr *E) { 18741 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18742 << E->getSourceRange(); 18743 return ExprError(); 18744 } 18745 18746 /// Rebuild an expression which simply semantically wraps another 18747 /// expression which it shares the type and value kind of. 18748 template <class T> ExprResult rebuildSugarExpr(T *E) { 18749 ExprResult SubResult = Visit(E->getSubExpr()); 18750 if (SubResult.isInvalid()) return ExprError(); 18751 18752 Expr *SubExpr = SubResult.get(); 18753 E->setSubExpr(SubExpr); 18754 E->setType(SubExpr->getType()); 18755 E->setValueKind(SubExpr->getValueKind()); 18756 assert(E->getObjectKind() == OK_Ordinary); 18757 return E; 18758 } 18759 18760 ExprResult VisitParenExpr(ParenExpr *E) { 18761 return rebuildSugarExpr(E); 18762 } 18763 18764 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18765 return rebuildSugarExpr(E); 18766 } 18767 18768 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18769 ExprResult SubResult = Visit(E->getSubExpr()); 18770 if (SubResult.isInvalid()) return ExprError(); 18771 18772 Expr *SubExpr = SubResult.get(); 18773 E->setSubExpr(SubExpr); 18774 E->setType(S.Context.getPointerType(SubExpr->getType())); 18775 assert(E->getValueKind() == VK_RValue); 18776 assert(E->getObjectKind() == OK_Ordinary); 18777 return E; 18778 } 18779 18780 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18781 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18782 18783 E->setType(VD->getType()); 18784 18785 assert(E->getValueKind() == VK_RValue); 18786 if (S.getLangOpts().CPlusPlus && 18787 !(isa<CXXMethodDecl>(VD) && 18788 cast<CXXMethodDecl>(VD)->isInstance())) 18789 E->setValueKind(VK_LValue); 18790 18791 return E; 18792 } 18793 18794 ExprResult VisitMemberExpr(MemberExpr *E) { 18795 return resolveDecl(E, E->getMemberDecl()); 18796 } 18797 18798 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18799 return resolveDecl(E, E->getDecl()); 18800 } 18801 }; 18802 } 18803 18804 /// Given a function expression of unknown-any type, try to rebuild it 18805 /// to have a function type. 18806 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18807 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18808 if (Result.isInvalid()) return ExprError(); 18809 return S.DefaultFunctionArrayConversion(Result.get()); 18810 } 18811 18812 namespace { 18813 /// A visitor for rebuilding an expression of type __unknown_anytype 18814 /// into one which resolves the type directly on the referring 18815 /// expression. Strict preservation of the original source 18816 /// structure is not a goal. 18817 struct RebuildUnknownAnyExpr 18818 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18819 18820 Sema &S; 18821 18822 /// The current destination type. 18823 QualType DestType; 18824 18825 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18826 : S(S), DestType(CastType) {} 18827 18828 ExprResult VisitStmt(Stmt *S) { 18829 llvm_unreachable("unexpected statement!"); 18830 } 18831 18832 ExprResult VisitExpr(Expr *E) { 18833 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18834 << E->getSourceRange(); 18835 return ExprError(); 18836 } 18837 18838 ExprResult VisitCallExpr(CallExpr *E); 18839 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18840 18841 /// Rebuild an expression which simply semantically wraps another 18842 /// expression which it shares the type and value kind of. 18843 template <class T> ExprResult rebuildSugarExpr(T *E) { 18844 ExprResult SubResult = Visit(E->getSubExpr()); 18845 if (SubResult.isInvalid()) return ExprError(); 18846 Expr *SubExpr = SubResult.get(); 18847 E->setSubExpr(SubExpr); 18848 E->setType(SubExpr->getType()); 18849 E->setValueKind(SubExpr->getValueKind()); 18850 assert(E->getObjectKind() == OK_Ordinary); 18851 return E; 18852 } 18853 18854 ExprResult VisitParenExpr(ParenExpr *E) { 18855 return rebuildSugarExpr(E); 18856 } 18857 18858 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18859 return rebuildSugarExpr(E); 18860 } 18861 18862 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18863 const PointerType *Ptr = DestType->getAs<PointerType>(); 18864 if (!Ptr) { 18865 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18866 << E->getSourceRange(); 18867 return ExprError(); 18868 } 18869 18870 if (isa<CallExpr>(E->getSubExpr())) { 18871 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18872 << E->getSourceRange(); 18873 return ExprError(); 18874 } 18875 18876 assert(E->getValueKind() == VK_RValue); 18877 assert(E->getObjectKind() == OK_Ordinary); 18878 E->setType(DestType); 18879 18880 // Build the sub-expression as if it were an object of the pointee type. 18881 DestType = Ptr->getPointeeType(); 18882 ExprResult SubResult = Visit(E->getSubExpr()); 18883 if (SubResult.isInvalid()) return ExprError(); 18884 E->setSubExpr(SubResult.get()); 18885 return E; 18886 } 18887 18888 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18889 18890 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18891 18892 ExprResult VisitMemberExpr(MemberExpr *E) { 18893 return resolveDecl(E, E->getMemberDecl()); 18894 } 18895 18896 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18897 return resolveDecl(E, E->getDecl()); 18898 } 18899 }; 18900 } 18901 18902 /// Rebuilds a call expression which yielded __unknown_anytype. 18903 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18904 Expr *CalleeExpr = E->getCallee(); 18905 18906 enum FnKind { 18907 FK_MemberFunction, 18908 FK_FunctionPointer, 18909 FK_BlockPointer 18910 }; 18911 18912 FnKind Kind; 18913 QualType CalleeType = CalleeExpr->getType(); 18914 if (CalleeType == S.Context.BoundMemberTy) { 18915 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18916 Kind = FK_MemberFunction; 18917 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18918 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18919 CalleeType = Ptr->getPointeeType(); 18920 Kind = FK_FunctionPointer; 18921 } else { 18922 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18923 Kind = FK_BlockPointer; 18924 } 18925 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18926 18927 // Verify that this is a legal result type of a function. 18928 if (DestType->isArrayType() || DestType->isFunctionType()) { 18929 unsigned diagID = diag::err_func_returning_array_function; 18930 if (Kind == FK_BlockPointer) 18931 diagID = diag::err_block_returning_array_function; 18932 18933 S.Diag(E->getExprLoc(), diagID) 18934 << DestType->isFunctionType() << DestType; 18935 return ExprError(); 18936 } 18937 18938 // Otherwise, go ahead and set DestType as the call's result. 18939 E->setType(DestType.getNonLValueExprType(S.Context)); 18940 E->setValueKind(Expr::getValueKindForType(DestType)); 18941 assert(E->getObjectKind() == OK_Ordinary); 18942 18943 // Rebuild the function type, replacing the result type with DestType. 18944 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18945 if (Proto) { 18946 // __unknown_anytype(...) is a special case used by the debugger when 18947 // it has no idea what a function's signature is. 18948 // 18949 // We want to build this call essentially under the K&R 18950 // unprototyped rules, but making a FunctionNoProtoType in C++ 18951 // would foul up all sorts of assumptions. However, we cannot 18952 // simply pass all arguments as variadic arguments, nor can we 18953 // portably just call the function under a non-variadic type; see 18954 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18955 // However, it turns out that in practice it is generally safe to 18956 // call a function declared as "A foo(B,C,D);" under the prototype 18957 // "A foo(B,C,D,...);". The only known exception is with the 18958 // Windows ABI, where any variadic function is implicitly cdecl 18959 // regardless of its normal CC. Therefore we change the parameter 18960 // types to match the types of the arguments. 18961 // 18962 // This is a hack, but it is far superior to moving the 18963 // corresponding target-specific code from IR-gen to Sema/AST. 18964 18965 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18966 SmallVector<QualType, 8> ArgTypes; 18967 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18968 ArgTypes.reserve(E->getNumArgs()); 18969 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18970 Expr *Arg = E->getArg(i); 18971 QualType ArgType = Arg->getType(); 18972 if (E->isLValue()) { 18973 ArgType = S.Context.getLValueReferenceType(ArgType); 18974 } else if (E->isXValue()) { 18975 ArgType = S.Context.getRValueReferenceType(ArgType); 18976 } 18977 ArgTypes.push_back(ArgType); 18978 } 18979 ParamTypes = ArgTypes; 18980 } 18981 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18982 Proto->getExtProtoInfo()); 18983 } else { 18984 DestType = S.Context.getFunctionNoProtoType(DestType, 18985 FnType->getExtInfo()); 18986 } 18987 18988 // Rebuild the appropriate pointer-to-function type. 18989 switch (Kind) { 18990 case FK_MemberFunction: 18991 // Nothing to do. 18992 break; 18993 18994 case FK_FunctionPointer: 18995 DestType = S.Context.getPointerType(DestType); 18996 break; 18997 18998 case FK_BlockPointer: 18999 DestType = S.Context.getBlockPointerType(DestType); 19000 break; 19001 } 19002 19003 // Finally, we can recurse. 19004 ExprResult CalleeResult = Visit(CalleeExpr); 19005 if (!CalleeResult.isUsable()) return ExprError(); 19006 E->setCallee(CalleeResult.get()); 19007 19008 // Bind a temporary if necessary. 19009 return S.MaybeBindToTemporary(E); 19010 } 19011 19012 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19013 // Verify that this is a legal result type of a call. 19014 if (DestType->isArrayType() || DestType->isFunctionType()) { 19015 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19016 << DestType->isFunctionType() << DestType; 19017 return ExprError(); 19018 } 19019 19020 // Rewrite the method result type if available. 19021 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19022 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19023 Method->setReturnType(DestType); 19024 } 19025 19026 // Change the type of the message. 19027 E->setType(DestType.getNonReferenceType()); 19028 E->setValueKind(Expr::getValueKindForType(DestType)); 19029 19030 return S.MaybeBindToTemporary(E); 19031 } 19032 19033 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19034 // The only case we should ever see here is a function-to-pointer decay. 19035 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19036 assert(E->getValueKind() == VK_RValue); 19037 assert(E->getObjectKind() == OK_Ordinary); 19038 19039 E->setType(DestType); 19040 19041 // Rebuild the sub-expression as the pointee (function) type. 19042 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19043 19044 ExprResult Result = Visit(E->getSubExpr()); 19045 if (!Result.isUsable()) return ExprError(); 19046 19047 E->setSubExpr(Result.get()); 19048 return E; 19049 } else if (E->getCastKind() == CK_LValueToRValue) { 19050 assert(E->getValueKind() == VK_RValue); 19051 assert(E->getObjectKind() == OK_Ordinary); 19052 19053 assert(isa<BlockPointerType>(E->getType())); 19054 19055 E->setType(DestType); 19056 19057 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19058 DestType = S.Context.getLValueReferenceType(DestType); 19059 19060 ExprResult Result = Visit(E->getSubExpr()); 19061 if (!Result.isUsable()) return ExprError(); 19062 19063 E->setSubExpr(Result.get()); 19064 return E; 19065 } else { 19066 llvm_unreachable("Unhandled cast type!"); 19067 } 19068 } 19069 19070 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19071 ExprValueKind ValueKind = VK_LValue; 19072 QualType Type = DestType; 19073 19074 // We know how to make this work for certain kinds of decls: 19075 19076 // - functions 19077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19078 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19079 DestType = Ptr->getPointeeType(); 19080 ExprResult Result = resolveDecl(E, VD); 19081 if (Result.isInvalid()) return ExprError(); 19082 return S.ImpCastExprToType(Result.get(), Type, 19083 CK_FunctionToPointerDecay, VK_RValue); 19084 } 19085 19086 if (!Type->isFunctionType()) { 19087 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19088 << VD << E->getSourceRange(); 19089 return ExprError(); 19090 } 19091 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19092 // We must match the FunctionDecl's type to the hack introduced in 19093 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19094 // type. See the lengthy commentary in that routine. 19095 QualType FDT = FD->getType(); 19096 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19097 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19098 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19099 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19100 SourceLocation Loc = FD->getLocation(); 19101 FunctionDecl *NewFD = FunctionDecl::Create( 19102 S.Context, FD->getDeclContext(), Loc, Loc, 19103 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19104 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19105 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19106 19107 if (FD->getQualifier()) 19108 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19109 19110 SmallVector<ParmVarDecl*, 16> Params; 19111 for (const auto &AI : FT->param_types()) { 19112 ParmVarDecl *Param = 19113 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19114 Param->setScopeInfo(0, Params.size()); 19115 Params.push_back(Param); 19116 } 19117 NewFD->setParams(Params); 19118 DRE->setDecl(NewFD); 19119 VD = DRE->getDecl(); 19120 } 19121 } 19122 19123 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19124 if (MD->isInstance()) { 19125 ValueKind = VK_RValue; 19126 Type = S.Context.BoundMemberTy; 19127 } 19128 19129 // Function references aren't l-values in C. 19130 if (!S.getLangOpts().CPlusPlus) 19131 ValueKind = VK_RValue; 19132 19133 // - variables 19134 } else if (isa<VarDecl>(VD)) { 19135 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19136 Type = RefTy->getPointeeType(); 19137 } else if (Type->isFunctionType()) { 19138 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19139 << VD << E->getSourceRange(); 19140 return ExprError(); 19141 } 19142 19143 // - nothing else 19144 } else { 19145 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19146 << VD << E->getSourceRange(); 19147 return ExprError(); 19148 } 19149 19150 // Modifying the declaration like this is friendly to IR-gen but 19151 // also really dangerous. 19152 VD->setType(DestType); 19153 E->setType(Type); 19154 E->setValueKind(ValueKind); 19155 return E; 19156 } 19157 19158 /// Check a cast of an unknown-any type. We intentionally only 19159 /// trigger this for C-style casts. 19160 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19161 Expr *CastExpr, CastKind &CastKind, 19162 ExprValueKind &VK, CXXCastPath &Path) { 19163 // The type we're casting to must be either void or complete. 19164 if (!CastType->isVoidType() && 19165 RequireCompleteType(TypeRange.getBegin(), CastType, 19166 diag::err_typecheck_cast_to_incomplete)) 19167 return ExprError(); 19168 19169 // Rewrite the casted expression from scratch. 19170 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19171 if (!result.isUsable()) return ExprError(); 19172 19173 CastExpr = result.get(); 19174 VK = CastExpr->getValueKind(); 19175 CastKind = CK_NoOp; 19176 19177 return CastExpr; 19178 } 19179 19180 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19181 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19182 } 19183 19184 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19185 Expr *arg, QualType ¶mType) { 19186 // If the syntactic form of the argument is not an explicit cast of 19187 // any sort, just do default argument promotion. 19188 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19189 if (!castArg) { 19190 ExprResult result = DefaultArgumentPromotion(arg); 19191 if (result.isInvalid()) return ExprError(); 19192 paramType = result.get()->getType(); 19193 return result; 19194 } 19195 19196 // Otherwise, use the type that was written in the explicit cast. 19197 assert(!arg->hasPlaceholderType()); 19198 paramType = castArg->getTypeAsWritten(); 19199 19200 // Copy-initialize a parameter of that type. 19201 InitializedEntity entity = 19202 InitializedEntity::InitializeParameter(Context, paramType, 19203 /*consumed*/ false); 19204 return PerformCopyInitialization(entity, callLoc, arg); 19205 } 19206 19207 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19208 Expr *orig = E; 19209 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19210 while (true) { 19211 E = E->IgnoreParenImpCasts(); 19212 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19213 E = call->getCallee(); 19214 diagID = diag::err_uncasted_call_of_unknown_any; 19215 } else { 19216 break; 19217 } 19218 } 19219 19220 SourceLocation loc; 19221 NamedDecl *d; 19222 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19223 loc = ref->getLocation(); 19224 d = ref->getDecl(); 19225 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19226 loc = mem->getMemberLoc(); 19227 d = mem->getMemberDecl(); 19228 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19229 diagID = diag::err_uncasted_call_of_unknown_any; 19230 loc = msg->getSelectorStartLoc(); 19231 d = msg->getMethodDecl(); 19232 if (!d) { 19233 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19234 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19235 << orig->getSourceRange(); 19236 return ExprError(); 19237 } 19238 } else { 19239 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19240 << E->getSourceRange(); 19241 return ExprError(); 19242 } 19243 19244 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19245 19246 // Never recoverable. 19247 return ExprError(); 19248 } 19249 19250 /// Check for operands with placeholder types and complain if found. 19251 /// Returns ExprError() if there was an error and no recovery was possible. 19252 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19253 if (!Context.isDependenceAllowed()) { 19254 // C cannot handle TypoExpr nodes on either side of a binop because it 19255 // doesn't handle dependent types properly, so make sure any TypoExprs have 19256 // been dealt with before checking the operands. 19257 ExprResult Result = CorrectDelayedTyposInExpr(E); 19258 if (!Result.isUsable()) return ExprError(); 19259 E = Result.get(); 19260 } 19261 19262 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19263 if (!placeholderType) return E; 19264 19265 switch (placeholderType->getKind()) { 19266 19267 // Overloaded expressions. 19268 case BuiltinType::Overload: { 19269 // Try to resolve a single function template specialization. 19270 // This is obligatory. 19271 ExprResult Result = E; 19272 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19273 return Result; 19274 19275 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19276 // leaves Result unchanged on failure. 19277 Result = E; 19278 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19279 return Result; 19280 19281 // If that failed, try to recover with a call. 19282 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19283 /*complain*/ true); 19284 return Result; 19285 } 19286 19287 // Bound member functions. 19288 case BuiltinType::BoundMember: { 19289 ExprResult result = E; 19290 const Expr *BME = E->IgnoreParens(); 19291 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19292 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19293 if (isa<CXXPseudoDestructorExpr>(BME)) { 19294 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19295 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19296 if (ME->getMemberNameInfo().getName().getNameKind() == 19297 DeclarationName::CXXDestructorName) 19298 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19299 } 19300 tryToRecoverWithCall(result, PD, 19301 /*complain*/ true); 19302 return result; 19303 } 19304 19305 // ARC unbridged casts. 19306 case BuiltinType::ARCUnbridgedCast: { 19307 Expr *realCast = stripARCUnbridgedCast(E); 19308 diagnoseARCUnbridgedCast(realCast); 19309 return realCast; 19310 } 19311 19312 // Expressions of unknown type. 19313 case BuiltinType::UnknownAny: 19314 return diagnoseUnknownAnyExpr(*this, E); 19315 19316 // Pseudo-objects. 19317 case BuiltinType::PseudoObject: 19318 return checkPseudoObjectRValue(E); 19319 19320 case BuiltinType::BuiltinFn: { 19321 // Accept __noop without parens by implicitly converting it to a call expr. 19322 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19323 if (DRE) { 19324 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19325 if (FD->getBuiltinID() == Builtin::BI__noop) { 19326 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19327 CK_BuiltinFnToFnPtr) 19328 .get(); 19329 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19330 VK_RValue, SourceLocation(), 19331 FPOptionsOverride()); 19332 } 19333 } 19334 19335 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19336 return ExprError(); 19337 } 19338 19339 case BuiltinType::IncompleteMatrixIdx: 19340 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19341 ->getRowIdx() 19342 ->getBeginLoc(), 19343 diag::err_matrix_incomplete_index); 19344 return ExprError(); 19345 19346 // Expressions of unknown type. 19347 case BuiltinType::OMPArraySection: 19348 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19349 return ExprError(); 19350 19351 // Expressions of unknown type. 19352 case BuiltinType::OMPArrayShaping: 19353 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19354 19355 case BuiltinType::OMPIterator: 19356 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19357 19358 // Everything else should be impossible. 19359 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19360 case BuiltinType::Id: 19361 #include "clang/Basic/OpenCLImageTypes.def" 19362 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19363 case BuiltinType::Id: 19364 #include "clang/Basic/OpenCLExtensionTypes.def" 19365 #define SVE_TYPE(Name, Id, SingletonId) \ 19366 case BuiltinType::Id: 19367 #include "clang/Basic/AArch64SVEACLETypes.def" 19368 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19369 case BuiltinType::Id: 19370 #include "clang/Basic/PPCTypes.def" 19371 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19372 #include "clang/Basic/RISCVVTypes.def" 19373 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19374 #define PLACEHOLDER_TYPE(Id, SingletonId) 19375 #include "clang/AST/BuiltinTypes.def" 19376 break; 19377 } 19378 19379 llvm_unreachable("invalid placeholder type!"); 19380 } 19381 19382 bool Sema::CheckCaseExpression(Expr *E) { 19383 if (E->isTypeDependent()) 19384 return true; 19385 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19386 return E->getType()->isIntegralOrEnumerationType(); 19387 return false; 19388 } 19389 19390 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19391 ExprResult 19392 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19393 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19394 "Unknown Objective-C Boolean value!"); 19395 QualType BoolT = Context.ObjCBuiltinBoolTy; 19396 if (!Context.getBOOLDecl()) { 19397 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19398 Sema::LookupOrdinaryName); 19399 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19400 NamedDecl *ND = Result.getFoundDecl(); 19401 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19402 Context.setBOOLDecl(TD); 19403 } 19404 } 19405 if (Context.getBOOLDecl()) 19406 BoolT = Context.getBOOLType(); 19407 return new (Context) 19408 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19409 } 19410 19411 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19412 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19413 SourceLocation RParen) { 19414 19415 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19416 19417 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19418 return Spec.getPlatform() == Platform; 19419 }); 19420 19421 VersionTuple Version; 19422 if (Spec != AvailSpecs.end()) 19423 Version = Spec->getVersion(); 19424 19425 // The use of `@available` in the enclosing function should be analyzed to 19426 // warn when it's used inappropriately (i.e. not if(@available)). 19427 if (getCurFunctionOrMethodDecl()) 19428 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19429 else if (getCurBlock() || getCurLambda()) 19430 getCurFunction()->HasPotentialAvailabilityViolations = true; 19431 19432 return new (Context) 19433 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19434 } 19435 19436 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19437 ArrayRef<Expr *> SubExprs, QualType T) { 19438 if (!Context.getLangOpts().RecoveryAST) 19439 return ExprError(); 19440 19441 if (isSFINAEContext()) 19442 return ExprError(); 19443 19444 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19445 // We don't know the concrete type, fallback to dependent type. 19446 T = Context.DependentTy; 19447 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19448 } 19449