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/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/FixedPoint.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 54 /// Determine whether the use of this declaration is valid, without 55 /// emitting diagnostics. 56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 57 // See if this is an auto-typed variable whose initializer we are parsing. 58 if (ParsingInitForAutoVars.count(D)) 59 return false; 60 61 // See if this is a deleted function. 62 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 63 if (FD->isDeleted()) 64 return false; 65 66 // If the function has a deduced return type, and we can't deduce it, 67 // then we can't use it either. 68 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 69 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 70 return false; 71 72 // See if this is an aligned allocation/deallocation function that is 73 // unavailable. 74 if (TreatUnavailableAsInvalid && 75 isUnavailableAlignedAllocationFunction(*FD)) 76 return false; 77 } 78 79 // See if this function is unavailable. 80 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 81 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 82 return false; 83 84 return true; 85 } 86 87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 88 // Warn if this is used but marked unused. 89 if (const auto *A = D->getAttr<UnusedAttr>()) { 90 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 91 // should diagnose them. 92 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 93 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 94 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 95 if (DC && !DC->hasAttr<UnusedAttr>()) 96 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 97 } 98 } 99 } 100 101 /// Emit a note explaining that this function is deleted. 102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 103 assert(Decl && Decl->isDeleted()); 104 105 if (Decl->isDefaulted()) { 106 // If the method was explicitly defaulted, point at that declaration. 107 if (!Decl->isImplicit()) 108 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 109 110 // Try to diagnose why this special member function was implicitly 111 // deleted. This might fail, if that reason no longer applies. 112 DiagnoseDeletedDefaultedFunction(Decl); 113 return; 114 } 115 116 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 117 if (Ctor && Ctor->isInheritingConstructor()) 118 return NoteDeletedInheritingConstructor(Ctor); 119 120 Diag(Decl->getLocation(), diag::note_availability_specified_here) 121 << Decl << 1; 122 } 123 124 /// Determine whether a FunctionDecl was ever declared with an 125 /// explicit storage class. 126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 127 for (auto I : D->redecls()) { 128 if (I->getStorageClass() != SC_None) 129 return true; 130 } 131 return false; 132 } 133 134 /// Check whether we're in an extern inline function and referring to a 135 /// variable or function with internal linkage (C11 6.7.4p3). 136 /// 137 /// This is only a warning because we used to silently accept this code, but 138 /// in many cases it will not behave correctly. This is not enabled in C++ mode 139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 140 /// and so while there may still be user mistakes, most of the time we can't 141 /// prove that there are errors. 142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 143 const NamedDecl *D, 144 SourceLocation Loc) { 145 // This is disabled under C++; there are too many ways for this to fire in 146 // contexts where the warning is a false positive, or where it is technically 147 // correct but benign. 148 if (S.getLangOpts().CPlusPlus) 149 return; 150 151 // Check if this is an inlined function or method. 152 FunctionDecl *Current = S.getCurFunctionDecl(); 153 if (!Current) 154 return; 155 if (!Current->isInlined()) 156 return; 157 if (!Current->isExternallyVisible()) 158 return; 159 160 // Check if the decl has internal linkage. 161 if (D->getFormalLinkage() != InternalLinkage) 162 return; 163 164 // Downgrade from ExtWarn to Extension if 165 // (1) the supposedly external inline function is in the main file, 166 // and probably won't be included anywhere else. 167 // (2) the thing we're referencing is a pure function. 168 // (3) the thing we're referencing is another inline function. 169 // This last can give us false negatives, but it's better than warning on 170 // wrappers for simple C library functions. 171 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 172 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 173 if (!DowngradeWarning && UsedFn) 174 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 175 176 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 177 : diag::ext_internal_in_extern_inline) 178 << /*IsVar=*/!UsedFn << D; 179 180 S.MaybeSuggestAddingStaticToDecl(Current); 181 182 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 183 << D; 184 } 185 186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 187 const FunctionDecl *First = Cur->getFirstDecl(); 188 189 // Suggest "static" on the function, if possible. 190 if (!hasAnyExplicitStorageClass(First)) { 191 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 192 Diag(DeclBegin, diag::note_convert_inline_to_static) 193 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 194 } 195 } 196 197 /// Determine whether the use of this declaration is valid, and 198 /// emit any corresponding diagnostics. 199 /// 200 /// This routine diagnoses various problems with referencing 201 /// declarations that can occur when using a declaration. For example, 202 /// it might warn if a deprecated or unavailable declaration is being 203 /// used, or produce an error (and return true) if a C++0x deleted 204 /// function is being used. 205 /// 206 /// \returns true if there was an error (this declaration cannot be 207 /// referenced), false otherwise. 208 /// 209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 210 const ObjCInterfaceDecl *UnknownObjCClass, 211 bool ObjCPropertyAccess, 212 bool AvoidPartialAvailabilityChecks, 213 ObjCInterfaceDecl *ClassReceiver) { 214 SourceLocation Loc = Locs.front(); 215 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 216 // If there were any diagnostics suppressed by template argument deduction, 217 // emit them now. 218 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 219 if (Pos != SuppressedDiagnostics.end()) { 220 for (const PartialDiagnosticAt &Suppressed : Pos->second) 221 Diag(Suppressed.first, Suppressed.second); 222 223 // Clear out the list of suppressed diagnostics, so that we don't emit 224 // them again for this specialization. However, we don't obsolete this 225 // entry from the table, because we want to avoid ever emitting these 226 // diagnostics again. 227 Pos->second.clear(); 228 } 229 230 // C++ [basic.start.main]p3: 231 // The function 'main' shall not be used within a program. 232 if (cast<FunctionDecl>(D)->isMain()) 233 Diag(Loc, diag::ext_main_used); 234 235 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 236 } 237 238 // See if this is an auto-typed variable whose initializer we are parsing. 239 if (ParsingInitForAutoVars.count(D)) { 240 if (isa<BindingDecl>(D)) { 241 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 242 << D->getDeclName(); 243 } else { 244 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 245 << D->getDeclName() << cast<VarDecl>(D)->getType(); 246 } 247 return true; 248 } 249 250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 251 // See if this is a deleted function. 252 if (FD->isDeleted()) { 253 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 254 if (Ctor && Ctor->isInheritingConstructor()) 255 Diag(Loc, diag::err_deleted_inherited_ctor_use) 256 << Ctor->getParent() 257 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 258 else 259 Diag(Loc, diag::err_deleted_function_use); 260 NoteDeletedFunction(FD); 261 return true; 262 } 263 264 // [expr.prim.id]p4 265 // A program that refers explicitly or implicitly to a function with a 266 // trailing requires-clause whose constraint-expression is not satisfied, 267 // other than to declare it, is ill-formed. [...] 268 // 269 // See if this is a function with constraints that need to be satisfied. 270 // Check this before deducing the return type, as it might instantiate the 271 // definition. 272 if (FD->getTrailingRequiresClause()) { 273 ConstraintSatisfaction Satisfaction; 274 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 275 // A diagnostic will have already been generated (non-constant 276 // constraint expression, for example) 277 return true; 278 if (!Satisfaction.IsSatisfied) { 279 Diag(Loc, 280 diag::err_reference_to_function_with_unsatisfied_constraints) 281 << D; 282 DiagnoseUnsatisfiedConstraint(Satisfaction); 283 return true; 284 } 285 } 286 287 // If the function has a deduced return type, and we can't deduce it, 288 // then we can't use it either. 289 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 290 DeduceReturnType(FD, Loc)) 291 return true; 292 293 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 294 return true; 295 } 296 297 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 298 // Lambdas are only default-constructible or assignable in C++2a onwards. 299 if (MD->getParent()->isLambda() && 300 ((isa<CXXConstructorDecl>(MD) && 301 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 302 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 303 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 304 << !isa<CXXConstructorDecl>(MD); 305 } 306 } 307 308 auto getReferencedObjCProp = [](const NamedDecl *D) -> 309 const ObjCPropertyDecl * { 310 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 311 return MD->findPropertyDecl(); 312 return nullptr; 313 }; 314 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 315 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 316 return true; 317 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 318 return true; 319 } 320 321 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 322 // Only the variables omp_in and omp_out are allowed in the combiner. 323 // Only the variables omp_priv and omp_orig are allowed in the 324 // initializer-clause. 325 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 326 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 327 isa<VarDecl>(D)) { 328 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 329 << getCurFunction()->HasOMPDeclareReductionCombiner; 330 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 331 return true; 332 } 333 334 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 335 // List-items in map clauses on this construct may only refer to the declared 336 // variable var and entities that could be referenced by a procedure defined 337 // at the same location 338 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 339 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 340 isa<VarDecl>(D)) { 341 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 342 << DMD->getVarName().getAsString(); 343 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 344 return true; 345 } 346 347 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 348 AvoidPartialAvailabilityChecks, ClassReceiver); 349 350 DiagnoseUnusedOfDecl(*this, D, Loc); 351 352 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 353 354 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 355 !isUnevaluatedContext()) { 356 // C++ [expr.prim.req.nested] p3 357 // A local parameter shall only appear as an unevaluated operand 358 // (Clause 8) within the constraint-expression. 359 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 360 << D; 361 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 362 return true; 363 } 364 365 return false; 366 } 367 368 /// DiagnoseSentinelCalls - This routine checks whether a call or 369 /// message-send is to a declaration with the sentinel attribute, and 370 /// if so, it checks that the requirements of the sentinel are 371 /// satisfied. 372 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 373 ArrayRef<Expr *> Args) { 374 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 375 if (!attr) 376 return; 377 378 // The number of formal parameters of the declaration. 379 unsigned numFormalParams; 380 381 // The kind of declaration. This is also an index into a %select in 382 // the diagnostic. 383 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 384 385 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 386 numFormalParams = MD->param_size(); 387 calleeType = CT_Method; 388 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 389 numFormalParams = FD->param_size(); 390 calleeType = CT_Function; 391 } else if (isa<VarDecl>(D)) { 392 QualType type = cast<ValueDecl>(D)->getType(); 393 const FunctionType *fn = nullptr; 394 if (const PointerType *ptr = type->getAs<PointerType>()) { 395 fn = ptr->getPointeeType()->getAs<FunctionType>(); 396 if (!fn) return; 397 calleeType = CT_Function; 398 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 399 fn = ptr->getPointeeType()->castAs<FunctionType>(); 400 calleeType = CT_Block; 401 } else { 402 return; 403 } 404 405 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 406 numFormalParams = proto->getNumParams(); 407 } else { 408 numFormalParams = 0; 409 } 410 } else { 411 return; 412 } 413 414 // "nullPos" is the number of formal parameters at the end which 415 // effectively count as part of the variadic arguments. This is 416 // useful if you would prefer to not have *any* formal parameters, 417 // but the language forces you to have at least one. 418 unsigned nullPos = attr->getNullPos(); 419 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 420 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 421 422 // The number of arguments which should follow the sentinel. 423 unsigned numArgsAfterSentinel = attr->getSentinel(); 424 425 // If there aren't enough arguments for all the formal parameters, 426 // the sentinel, and the args after the sentinel, complain. 427 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 428 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 429 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 430 return; 431 } 432 433 // Otherwise, find the sentinel expression. 434 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 435 if (!sentinelExpr) return; 436 if (sentinelExpr->isValueDependent()) return; 437 if (Context.isSentinelNullExpr(sentinelExpr)) return; 438 439 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 440 // or 'NULL' if those are actually defined in the context. Only use 441 // 'nil' for ObjC methods, where it's much more likely that the 442 // variadic arguments form a list of object pointers. 443 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 444 std::string NullValue; 445 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 446 NullValue = "nil"; 447 else if (getLangOpts().CPlusPlus11) 448 NullValue = "nullptr"; 449 else if (PP.isMacroDefined("NULL")) 450 NullValue = "NULL"; 451 else 452 NullValue = "(void*) 0"; 453 454 if (MissingNilLoc.isInvalid()) 455 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 456 else 457 Diag(MissingNilLoc, diag::warn_missing_sentinel) 458 << int(calleeType) 459 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 460 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 461 } 462 463 SourceRange Sema::getExprRange(Expr *E) const { 464 return E ? E->getSourceRange() : SourceRange(); 465 } 466 467 //===----------------------------------------------------------------------===// 468 // Standard Promotions and Conversions 469 //===----------------------------------------------------------------------===// 470 471 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 472 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 473 // Handle any placeholder expressions which made it here. 474 if (E->getType()->isPlaceholderType()) { 475 ExprResult result = CheckPlaceholderExpr(E); 476 if (result.isInvalid()) return ExprError(); 477 E = result.get(); 478 } 479 480 QualType Ty = E->getType(); 481 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 482 483 if (Ty->isFunctionType()) { 484 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 485 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 486 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 487 return ExprError(); 488 489 E = ImpCastExprToType(E, Context.getPointerType(Ty), 490 CK_FunctionToPointerDecay).get(); 491 } else if (Ty->isArrayType()) { 492 // In C90 mode, arrays only promote to pointers if the array expression is 493 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 494 // type 'array of type' is converted to an expression that has type 'pointer 495 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 496 // that has type 'array of type' ...". The relevant change is "an lvalue" 497 // (C90) to "an expression" (C99). 498 // 499 // C++ 4.2p1: 500 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 501 // T" can be converted to an rvalue of type "pointer to T". 502 // 503 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 504 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 505 CK_ArrayToPointerDecay).get(); 506 } 507 return E; 508 } 509 510 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 511 // Check to see if we are dereferencing a null pointer. If so, 512 // and if not volatile-qualified, this is undefined behavior that the 513 // optimizer will delete, so warn about it. People sometimes try to use this 514 // to get a deterministic trap and are surprised by clang's behavior. This 515 // only handles the pattern "*null", which is a very syntactic check. 516 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 517 if (UO && UO->getOpcode() == UO_Deref && 518 UO->getSubExpr()->getType()->isPointerType()) { 519 const LangAS AS = 520 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 521 if ((!isTargetAddressSpace(AS) || 522 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 523 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 524 S.Context, Expr::NPC_ValueDependentIsNotNull) && 525 !UO->getType().isVolatileQualified()) { 526 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 527 S.PDiag(diag::warn_indirection_through_null) 528 << UO->getSubExpr()->getSourceRange()); 529 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 530 S.PDiag(diag::note_indirection_through_null)); 531 } 532 } 533 } 534 535 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 536 SourceLocation AssignLoc, 537 const Expr* RHS) { 538 const ObjCIvarDecl *IV = OIRE->getDecl(); 539 if (!IV) 540 return; 541 542 DeclarationName MemberName = IV->getDeclName(); 543 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 544 if (!Member || !Member->isStr("isa")) 545 return; 546 547 const Expr *Base = OIRE->getBase(); 548 QualType BaseType = Base->getType(); 549 if (OIRE->isArrow()) 550 BaseType = BaseType->getPointeeType(); 551 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 552 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 553 ObjCInterfaceDecl *ClassDeclared = nullptr; 554 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 555 if (!ClassDeclared->getSuperClass() 556 && (*ClassDeclared->ivar_begin()) == IV) { 557 if (RHS) { 558 NamedDecl *ObjectSetClass = 559 S.LookupSingleName(S.TUScope, 560 &S.Context.Idents.get("object_setClass"), 561 SourceLocation(), S.LookupOrdinaryName); 562 if (ObjectSetClass) { 563 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 564 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 565 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 566 "object_setClass(") 567 << FixItHint::CreateReplacement( 568 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 569 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 570 } 571 else 572 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 573 } else { 574 NamedDecl *ObjectGetClass = 575 S.LookupSingleName(S.TUScope, 576 &S.Context.Idents.get("object_getClass"), 577 SourceLocation(), S.LookupOrdinaryName); 578 if (ObjectGetClass) 579 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 580 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 581 "object_getClass(") 582 << FixItHint::CreateReplacement( 583 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 584 else 585 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 586 } 587 S.Diag(IV->getLocation(), diag::note_ivar_decl); 588 } 589 } 590 } 591 592 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 593 // Handle any placeholder expressions which made it here. 594 if (E->getType()->isPlaceholderType()) { 595 ExprResult result = CheckPlaceholderExpr(E); 596 if (result.isInvalid()) return ExprError(); 597 E = result.get(); 598 } 599 600 // C++ [conv.lval]p1: 601 // A glvalue of a non-function, non-array type T can be 602 // converted to a prvalue. 603 if (!E->isGLValue()) return E; 604 605 QualType T = E->getType(); 606 assert(!T.isNull() && "r-value conversion on typeless expression?"); 607 608 // We don't want to throw lvalue-to-rvalue casts on top of 609 // expressions of certain types in C++. 610 if (getLangOpts().CPlusPlus && 611 (E->getType() == Context.OverloadTy || 612 T->isDependentType() || 613 T->isRecordType())) 614 return E; 615 616 // The C standard is actually really unclear on this point, and 617 // DR106 tells us what the result should be but not why. It's 618 // generally best to say that void types just doesn't undergo 619 // lvalue-to-rvalue at all. Note that expressions of unqualified 620 // 'void' type are never l-values, but qualified void can be. 621 if (T->isVoidType()) 622 return E; 623 624 // OpenCL usually rejects direct accesses to values of 'half' type. 625 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 626 T->isHalfType()) { 627 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 628 << 0 << T; 629 return ExprError(); 630 } 631 632 CheckForNullPointerDereference(*this, E); 633 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 634 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 635 &Context.Idents.get("object_getClass"), 636 SourceLocation(), LookupOrdinaryName); 637 if (ObjectGetClass) 638 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 639 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 640 << FixItHint::CreateReplacement( 641 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 642 else 643 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 644 } 645 else if (const ObjCIvarRefExpr *OIRE = 646 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 647 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 648 649 // C++ [conv.lval]p1: 650 // [...] If T is a non-class type, the type of the prvalue is the 651 // cv-unqualified version of T. Otherwise, the type of the 652 // rvalue is T. 653 // 654 // C99 6.3.2.1p2: 655 // If the lvalue has qualified type, the value has the unqualified 656 // version of the type of the lvalue; otherwise, the value has the 657 // type of the lvalue. 658 if (T.hasQualifiers()) 659 T = T.getUnqualifiedType(); 660 661 // Under the MS ABI, lock down the inheritance model now. 662 if (T->isMemberPointerType() && 663 Context.getTargetInfo().getCXXABI().isMicrosoft()) 664 (void)isCompleteType(E->getExprLoc(), T); 665 666 ExprResult Res = CheckLValueToRValueConversionOperand(E); 667 if (Res.isInvalid()) 668 return Res; 669 E = Res.get(); 670 671 // Loading a __weak object implicitly retains the value, so we need a cleanup to 672 // balance that. 673 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 674 Cleanup.setExprNeedsCleanups(true); 675 676 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 677 Cleanup.setExprNeedsCleanups(true); 678 679 // C++ [conv.lval]p3: 680 // If T is cv std::nullptr_t, the result is a null pointer constant. 681 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 682 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 683 684 // C11 6.3.2.1p2: 685 // ... if the lvalue has atomic type, the value has the non-atomic version 686 // of the type of the lvalue ... 687 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 688 T = Atomic->getValueType().getUnqualifiedType(); 689 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 690 nullptr, VK_RValue); 691 } 692 693 return Res; 694 } 695 696 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 697 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 698 if (Res.isInvalid()) 699 return ExprError(); 700 Res = DefaultLvalueConversion(Res.get()); 701 if (Res.isInvalid()) 702 return ExprError(); 703 return Res; 704 } 705 706 /// CallExprUnaryConversions - a special case of an unary conversion 707 /// performed on a function designator of a call expression. 708 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 709 QualType Ty = E->getType(); 710 ExprResult Res = E; 711 // Only do implicit cast for a function type, but not for a pointer 712 // to function type. 713 if (Ty->isFunctionType()) { 714 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 715 CK_FunctionToPointerDecay).get(); 716 if (Res.isInvalid()) 717 return ExprError(); 718 } 719 Res = DefaultLvalueConversion(Res.get()); 720 if (Res.isInvalid()) 721 return ExprError(); 722 return Res.get(); 723 } 724 725 /// UsualUnaryConversions - Performs various conversions that are common to most 726 /// operators (C99 6.3). The conversions of array and function types are 727 /// sometimes suppressed. For example, the array->pointer conversion doesn't 728 /// apply if the array is an argument to the sizeof or address (&) operators. 729 /// In these instances, this routine should *not* be called. 730 ExprResult Sema::UsualUnaryConversions(Expr *E) { 731 // First, convert to an r-value. 732 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 733 if (Res.isInvalid()) 734 return ExprError(); 735 E = Res.get(); 736 737 QualType Ty = E->getType(); 738 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 739 740 // Half FP have to be promoted to float unless it is natively supported 741 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 742 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 743 744 // Try to perform integral promotions if the object has a theoretically 745 // promotable type. 746 if (Ty->isIntegralOrUnscopedEnumerationType()) { 747 // C99 6.3.1.1p2: 748 // 749 // The following may be used in an expression wherever an int or 750 // unsigned int may be used: 751 // - an object or expression with an integer type whose integer 752 // conversion rank is less than or equal to the rank of int 753 // and unsigned int. 754 // - A bit-field of type _Bool, int, signed int, or unsigned int. 755 // 756 // If an int can represent all values of the original type, the 757 // value is converted to an int; otherwise, it is converted to an 758 // unsigned int. These are called the integer promotions. All 759 // other types are unchanged by the integer promotions. 760 761 QualType PTy = Context.isPromotableBitField(E); 762 if (!PTy.isNull()) { 763 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 764 return E; 765 } 766 if (Ty->isPromotableIntegerType()) { 767 QualType PT = Context.getPromotedIntegerType(Ty); 768 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 769 return E; 770 } 771 } 772 return E; 773 } 774 775 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 776 /// do not have a prototype. Arguments that have type float or __fp16 777 /// are promoted to double. All other argument types are converted by 778 /// UsualUnaryConversions(). 779 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 780 QualType Ty = E->getType(); 781 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 782 783 ExprResult Res = UsualUnaryConversions(E); 784 if (Res.isInvalid()) 785 return ExprError(); 786 E = Res.get(); 787 788 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 789 // promote to double. 790 // Note that default argument promotion applies only to float (and 791 // half/fp16); it does not apply to _Float16. 792 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 793 if (BTy && (BTy->getKind() == BuiltinType::Half || 794 BTy->getKind() == BuiltinType::Float)) { 795 if (getLangOpts().OpenCL && 796 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 797 if (BTy->getKind() == BuiltinType::Half) { 798 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 799 } 800 } else { 801 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 802 } 803 } 804 805 // C++ performs lvalue-to-rvalue conversion as a default argument 806 // promotion, even on class types, but note: 807 // C++11 [conv.lval]p2: 808 // When an lvalue-to-rvalue conversion occurs in an unevaluated 809 // operand or a subexpression thereof the value contained in the 810 // referenced object is not accessed. Otherwise, if the glvalue 811 // has a class type, the conversion copy-initializes a temporary 812 // of type T from the glvalue and the result of the conversion 813 // is a prvalue for the temporary. 814 // FIXME: add some way to gate this entire thing for correctness in 815 // potentially potentially evaluated contexts. 816 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 817 ExprResult Temp = PerformCopyInitialization( 818 InitializedEntity::InitializeTemporary(E->getType()), 819 E->getExprLoc(), E); 820 if (Temp.isInvalid()) 821 return ExprError(); 822 E = Temp.get(); 823 } 824 825 return E; 826 } 827 828 /// Determine the degree of POD-ness for an expression. 829 /// Incomplete types are considered POD, since this check can be performed 830 /// when we're in an unevaluated context. 831 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 832 if (Ty->isIncompleteType()) { 833 // C++11 [expr.call]p7: 834 // After these conversions, if the argument does not have arithmetic, 835 // enumeration, pointer, pointer to member, or class type, the program 836 // is ill-formed. 837 // 838 // Since we've already performed array-to-pointer and function-to-pointer 839 // decay, the only such type in C++ is cv void. This also handles 840 // initializer lists as variadic arguments. 841 if (Ty->isVoidType()) 842 return VAK_Invalid; 843 844 if (Ty->isObjCObjectType()) 845 return VAK_Invalid; 846 return VAK_Valid; 847 } 848 849 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 850 return VAK_Invalid; 851 852 if (Ty.isCXX98PODType(Context)) 853 return VAK_Valid; 854 855 // C++11 [expr.call]p7: 856 // Passing a potentially-evaluated argument of class type (Clause 9) 857 // having a non-trivial copy constructor, a non-trivial move constructor, 858 // or a non-trivial destructor, with no corresponding parameter, 859 // is conditionally-supported with implementation-defined semantics. 860 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 861 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 862 if (!Record->hasNonTrivialCopyConstructor() && 863 !Record->hasNonTrivialMoveConstructor() && 864 !Record->hasNonTrivialDestructor()) 865 return VAK_ValidInCXX11; 866 867 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 868 return VAK_Valid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 873 if (getLangOpts().MSVCCompat) 874 return VAK_MSVCUndefined; 875 876 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 877 // permitted to reject them. We should consider doing so. 878 return VAK_Undefined; 879 } 880 881 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 882 // Don't allow one to pass an Objective-C interface to a vararg. 883 const QualType &Ty = E->getType(); 884 VarArgKind VAK = isValidVarArgType(Ty); 885 886 // Complain about passing non-POD types through varargs. 887 switch (VAK) { 888 case VAK_ValidInCXX11: 889 DiagRuntimeBehavior( 890 E->getBeginLoc(), nullptr, 891 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 892 LLVM_FALLTHROUGH; 893 case VAK_Valid: 894 if (Ty->isRecordType()) { 895 // This is unlikely to be what the user intended. If the class has a 896 // 'c_str' member function, the user probably meant to call that. 897 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 898 PDiag(diag::warn_pass_class_arg_to_vararg) 899 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 900 } 901 break; 902 903 case VAK_Undefined: 904 case VAK_MSVCUndefined: 905 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 906 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 907 << getLangOpts().CPlusPlus11 << Ty << CT); 908 break; 909 910 case VAK_Invalid: 911 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 912 Diag(E->getBeginLoc(), 913 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 914 << Ty << CT; 915 else if (Ty->isObjCObjectType()) 916 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 917 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 918 << Ty << CT); 919 else 920 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 921 << isa<InitListExpr>(E) << Ty << CT; 922 break; 923 } 924 } 925 926 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 927 /// will create a trap if the resulting type is not a POD type. 928 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 929 FunctionDecl *FDecl) { 930 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 931 // Strip the unbridged-cast placeholder expression off, if applicable. 932 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 933 (CT == VariadicMethod || 934 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 935 E = stripARCUnbridgedCast(E); 936 937 // Otherwise, do normal placeholder checking. 938 } else { 939 ExprResult ExprRes = CheckPlaceholderExpr(E); 940 if (ExprRes.isInvalid()) 941 return ExprError(); 942 E = ExprRes.get(); 943 } 944 } 945 946 ExprResult ExprRes = DefaultArgumentPromotion(E); 947 if (ExprRes.isInvalid()) 948 return ExprError(); 949 E = ExprRes.get(); 950 951 // Diagnostics regarding non-POD argument types are 952 // emitted along with format string checking in Sema::CheckFunctionCall(). 953 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 954 // Turn this into a trap. 955 CXXScopeSpec SS; 956 SourceLocation TemplateKWLoc; 957 UnqualifiedId Name; 958 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 959 E->getBeginLoc()); 960 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 961 /*HasTrailingLParen=*/true, 962 /*IsAddressOfOperand=*/false); 963 if (TrapFn.isInvalid()) 964 return ExprError(); 965 966 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 967 None, E->getEndLoc()); 968 if (Call.isInvalid()) 969 return ExprError(); 970 971 ExprResult Comma = 972 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 973 if (Comma.isInvalid()) 974 return ExprError(); 975 return Comma.get(); 976 } 977 978 if (!getLangOpts().CPlusPlus && 979 RequireCompleteType(E->getExprLoc(), E->getType(), 980 diag::err_call_incomplete_argument)) 981 return ExprError(); 982 983 return E; 984 } 985 986 /// Converts an integer to complex float type. Helper function of 987 /// UsualArithmeticConversions() 988 /// 989 /// \return false if the integer expression is an integer type and is 990 /// successfully converted to the complex type. 991 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 992 ExprResult &ComplexExpr, 993 QualType IntTy, 994 QualType ComplexTy, 995 bool SkipCast) { 996 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 997 if (SkipCast) return false; 998 if (IntTy->isIntegerType()) { 999 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1000 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1002 CK_FloatingRealToComplex); 1003 } else { 1004 assert(IntTy->isComplexIntegerType()); 1005 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1006 CK_IntegralComplexToFloatingComplex); 1007 } 1008 return false; 1009 } 1010 1011 /// Handle arithmetic conversion with complex types. Helper function of 1012 /// UsualArithmeticConversions() 1013 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1014 ExprResult &RHS, QualType LHSType, 1015 QualType RHSType, 1016 bool IsCompAssign) { 1017 // if we have an integer operand, the result is the complex type. 1018 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1019 /*skipCast*/false)) 1020 return LHSType; 1021 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1022 /*skipCast*/IsCompAssign)) 1023 return RHSType; 1024 1025 // This handles complex/complex, complex/float, or float/complex. 1026 // When both operands are complex, the shorter operand is converted to the 1027 // type of the longer, and that is the type of the result. This corresponds 1028 // to what is done when combining two real floating-point operands. 1029 // The fun begins when size promotion occur across type domains. 1030 // From H&S 6.3.4: When one operand is complex and the other is a real 1031 // floating-point type, the less precise type is converted, within it's 1032 // real or complex domain, to the precision of the other type. For example, 1033 // when combining a "long double" with a "double _Complex", the 1034 // "double _Complex" is promoted to "long double _Complex". 1035 1036 // Compute the rank of the two types, regardless of whether they are complex. 1037 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1038 1039 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1040 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1041 QualType LHSElementType = 1042 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1043 QualType RHSElementType = 1044 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1045 1046 QualType ResultType = S.Context.getComplexType(LHSElementType); 1047 if (Order < 0) { 1048 // Promote the precision of the LHS if not an assignment. 1049 ResultType = S.Context.getComplexType(RHSElementType); 1050 if (!IsCompAssign) { 1051 if (LHSComplexType) 1052 LHS = 1053 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1054 else 1055 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1056 } 1057 } else if (Order > 0) { 1058 // Promote the precision of the RHS. 1059 if (RHSComplexType) 1060 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1061 else 1062 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1063 } 1064 return ResultType; 1065 } 1066 1067 /// Handle arithmetic conversion from integer to float. Helper function 1068 /// of UsualArithmeticConversions() 1069 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1070 ExprResult &IntExpr, 1071 QualType FloatTy, QualType IntTy, 1072 bool ConvertFloat, bool ConvertInt) { 1073 if (IntTy->isIntegerType()) { 1074 if (ConvertInt) 1075 // Convert intExpr to the lhs floating point type. 1076 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1077 CK_IntegralToFloating); 1078 return FloatTy; 1079 } 1080 1081 // Convert both sides to the appropriate complex float. 1082 assert(IntTy->isComplexIntegerType()); 1083 QualType result = S.Context.getComplexType(FloatTy); 1084 1085 // _Complex int -> _Complex float 1086 if (ConvertInt) 1087 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1088 CK_IntegralComplexToFloatingComplex); 1089 1090 // float -> _Complex float 1091 if (ConvertFloat) 1092 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1093 CK_FloatingRealToComplex); 1094 1095 return result; 1096 } 1097 1098 /// Handle arithmethic conversion with floating point types. Helper 1099 /// function of UsualArithmeticConversions() 1100 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1101 ExprResult &RHS, QualType LHSType, 1102 QualType RHSType, bool IsCompAssign) { 1103 bool LHSFloat = LHSType->isRealFloatingType(); 1104 bool RHSFloat = RHSType->isRealFloatingType(); 1105 1106 // If we have two real floating types, convert the smaller operand 1107 // to the bigger result. 1108 if (LHSFloat && RHSFloat) { 1109 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1110 if (order > 0) { 1111 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1112 return LHSType; 1113 } 1114 1115 assert(order < 0 && "illegal float comparison"); 1116 if (!IsCompAssign) 1117 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1118 return RHSType; 1119 } 1120 1121 if (LHSFloat) { 1122 // Half FP has to be promoted to float unless it is natively supported 1123 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1124 LHSType = S.Context.FloatTy; 1125 1126 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1127 /*ConvertFloat=*/!IsCompAssign, 1128 /*ConvertInt=*/ true); 1129 } 1130 assert(RHSFloat); 1131 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1132 /*convertInt=*/ true, 1133 /*convertFloat=*/!IsCompAssign); 1134 } 1135 1136 /// Diagnose attempts to convert between __float128 and long double if 1137 /// there is no support for such conversion. Helper function of 1138 /// UsualArithmeticConversions(). 1139 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1140 QualType RHSType) { 1141 /* No issue converting if at least one of the types is not a floating point 1142 type or the two types have the same rank. 1143 */ 1144 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1145 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1146 return false; 1147 1148 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1149 "The remaining types must be floating point types."); 1150 1151 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1152 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1153 1154 QualType LHSElemType = LHSComplex ? 1155 LHSComplex->getElementType() : LHSType; 1156 QualType RHSElemType = RHSComplex ? 1157 RHSComplex->getElementType() : RHSType; 1158 1159 // No issue if the two types have the same representation 1160 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1161 &S.Context.getFloatTypeSemantics(RHSElemType)) 1162 return false; 1163 1164 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1165 RHSElemType == S.Context.LongDoubleTy); 1166 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1167 RHSElemType == S.Context.Float128Ty); 1168 1169 // We've handled the situation where __float128 and long double have the same 1170 // representation. We allow all conversions for all possible long double types 1171 // except PPC's double double. 1172 return Float128AndLongDouble && 1173 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1174 &llvm::APFloat::PPCDoubleDouble()); 1175 } 1176 1177 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1178 1179 namespace { 1180 /// These helper callbacks are placed in an anonymous namespace to 1181 /// permit their use as function template parameters. 1182 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1183 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1184 } 1185 1186 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1187 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1188 CK_IntegralComplexCast); 1189 } 1190 } 1191 1192 /// Handle integer arithmetic conversions. Helper function of 1193 /// UsualArithmeticConversions() 1194 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1195 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1196 ExprResult &RHS, QualType LHSType, 1197 QualType RHSType, bool IsCompAssign) { 1198 // The rules for this case are in C99 6.3.1.8 1199 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1200 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1201 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1202 if (LHSSigned == RHSSigned) { 1203 // Same signedness; use the higher-ranked type 1204 if (order >= 0) { 1205 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1206 return LHSType; 1207 } else if (!IsCompAssign) 1208 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1209 return RHSType; 1210 } else if (order != (LHSSigned ? 1 : -1)) { 1211 // The unsigned type has greater than or equal rank to the 1212 // signed type, so use the unsigned type 1213 if (RHSSigned) { 1214 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1215 return LHSType; 1216 } else if (!IsCompAssign) 1217 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1218 return RHSType; 1219 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1220 // The two types are different widths; if we are here, that 1221 // means the signed type is larger than the unsigned type, so 1222 // use the signed type. 1223 if (LHSSigned) { 1224 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1225 return LHSType; 1226 } else if (!IsCompAssign) 1227 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1228 return RHSType; 1229 } else { 1230 // The signed type is higher-ranked than the unsigned type, 1231 // but isn't actually any bigger (like unsigned int and long 1232 // on most 32-bit systems). Use the unsigned type corresponding 1233 // to the signed type. 1234 QualType result = 1235 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1236 RHS = (*doRHSCast)(S, RHS.get(), result); 1237 if (!IsCompAssign) 1238 LHS = (*doLHSCast)(S, LHS.get(), result); 1239 return result; 1240 } 1241 } 1242 1243 /// Handle conversions with GCC complex int extension. Helper function 1244 /// of UsualArithmeticConversions() 1245 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1246 ExprResult &RHS, QualType LHSType, 1247 QualType RHSType, 1248 bool IsCompAssign) { 1249 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1250 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1251 1252 if (LHSComplexInt && RHSComplexInt) { 1253 QualType LHSEltType = LHSComplexInt->getElementType(); 1254 QualType RHSEltType = RHSComplexInt->getElementType(); 1255 QualType ScalarType = 1256 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1257 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1258 1259 return S.Context.getComplexType(ScalarType); 1260 } 1261 1262 if (LHSComplexInt) { 1263 QualType LHSEltType = LHSComplexInt->getElementType(); 1264 QualType ScalarType = 1265 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1266 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1267 QualType ComplexType = S.Context.getComplexType(ScalarType); 1268 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1269 CK_IntegralRealToComplex); 1270 1271 return ComplexType; 1272 } 1273 1274 assert(RHSComplexInt); 1275 1276 QualType RHSEltType = RHSComplexInt->getElementType(); 1277 QualType ScalarType = 1278 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1279 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1280 QualType ComplexType = S.Context.getComplexType(ScalarType); 1281 1282 if (!IsCompAssign) 1283 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1284 CK_IntegralRealToComplex); 1285 return ComplexType; 1286 } 1287 1288 /// Return the rank of a given fixed point or integer type. The value itself 1289 /// doesn't matter, but the values must be increasing with proper increasing 1290 /// rank as described in N1169 4.1.1. 1291 static unsigned GetFixedPointRank(QualType Ty) { 1292 const auto *BTy = Ty->getAs<BuiltinType>(); 1293 assert(BTy && "Expected a builtin type."); 1294 1295 switch (BTy->getKind()) { 1296 case BuiltinType::ShortFract: 1297 case BuiltinType::UShortFract: 1298 case BuiltinType::SatShortFract: 1299 case BuiltinType::SatUShortFract: 1300 return 1; 1301 case BuiltinType::Fract: 1302 case BuiltinType::UFract: 1303 case BuiltinType::SatFract: 1304 case BuiltinType::SatUFract: 1305 return 2; 1306 case BuiltinType::LongFract: 1307 case BuiltinType::ULongFract: 1308 case BuiltinType::SatLongFract: 1309 case BuiltinType::SatULongFract: 1310 return 3; 1311 case BuiltinType::ShortAccum: 1312 case BuiltinType::UShortAccum: 1313 case BuiltinType::SatShortAccum: 1314 case BuiltinType::SatUShortAccum: 1315 return 4; 1316 case BuiltinType::Accum: 1317 case BuiltinType::UAccum: 1318 case BuiltinType::SatAccum: 1319 case BuiltinType::SatUAccum: 1320 return 5; 1321 case BuiltinType::LongAccum: 1322 case BuiltinType::ULongAccum: 1323 case BuiltinType::SatLongAccum: 1324 case BuiltinType::SatULongAccum: 1325 return 6; 1326 default: 1327 if (BTy->isInteger()) 1328 return 0; 1329 llvm_unreachable("Unexpected fixed point or integer type"); 1330 } 1331 } 1332 1333 /// handleFixedPointConversion - Fixed point operations between fixed 1334 /// point types and integers or other fixed point types do not fall under 1335 /// usual arithmetic conversion since these conversions could result in loss 1336 /// of precsision (N1169 4.1.4). These operations should be calculated with 1337 /// the full precision of their result type (N1169 4.1.6.2.1). 1338 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1339 QualType RHSTy) { 1340 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1341 "Expected at least one of the operands to be a fixed point type"); 1342 assert((LHSTy->isFixedPointOrIntegerType() || 1343 RHSTy->isFixedPointOrIntegerType()) && 1344 "Special fixed point arithmetic operation conversions are only " 1345 "applied to ints or other fixed point types"); 1346 1347 // If one operand has signed fixed-point type and the other operand has 1348 // unsigned fixed-point type, then the unsigned fixed-point operand is 1349 // converted to its corresponding signed fixed-point type and the resulting 1350 // type is the type of the converted operand. 1351 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1352 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1353 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1354 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1355 1356 // The result type is the type with the highest rank, whereby a fixed-point 1357 // conversion rank is always greater than an integer conversion rank; if the 1358 // type of either of the operands is a saturating fixedpoint type, the result 1359 // type shall be the saturating fixed-point type corresponding to the type 1360 // with the highest rank; the resulting value is converted (taking into 1361 // account rounding and overflow) to the precision of the resulting type. 1362 // Same ranks between signed and unsigned types are resolved earlier, so both 1363 // types are either signed or both unsigned at this point. 1364 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1365 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1366 1367 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1368 1369 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1370 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1371 1372 return ResultTy; 1373 } 1374 1375 /// Check that the usual arithmetic conversions can be performed on this pair of 1376 /// expressions that might be of enumeration type. 1377 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1378 SourceLocation Loc, 1379 Sema::ArithConvKind ACK) { 1380 // C++2a [expr.arith.conv]p1: 1381 // If one operand is of enumeration type and the other operand is of a 1382 // different enumeration type or a floating-point type, this behavior is 1383 // deprecated ([depr.arith.conv.enum]). 1384 // 1385 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1386 // Eventually we will presumably reject these cases (in C++23 onwards?). 1387 QualType L = LHS->getType(), R = RHS->getType(); 1388 bool LEnum = L->isUnscopedEnumerationType(), 1389 REnum = R->isUnscopedEnumerationType(); 1390 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1391 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1392 (REnum && L->isFloatingType())) { 1393 S.Diag(Loc, S.getLangOpts().CPlusPlus2a 1394 ? diag::warn_arith_conv_enum_float_cxx2a 1395 : diag::warn_arith_conv_enum_float) 1396 << LHS->getSourceRange() << RHS->getSourceRange() 1397 << (int)ACK << LEnum << L << R; 1398 } else if (!IsCompAssign && LEnum && REnum && 1399 !S.Context.hasSameUnqualifiedType(L, R)) { 1400 unsigned DiagID; 1401 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1402 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1403 // If either enumeration type is unnamed, it's less likely that the 1404 // user cares about this, but this situation is still deprecated in 1405 // C++2a. Use a different warning group. 1406 DiagID = S.getLangOpts().CPlusPlus2a 1407 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a 1408 : diag::warn_arith_conv_mixed_anon_enum_types; 1409 } else if (ACK == Sema::ACK_Conditional) { 1410 // Conditional expressions are separated out because they have 1411 // historically had a different warning flag. 1412 DiagID = S.getLangOpts().CPlusPlus2a 1413 ? diag::warn_conditional_mixed_enum_types_cxx2a 1414 : diag::warn_conditional_mixed_enum_types; 1415 } else if (ACK == Sema::ACK_Comparison) { 1416 // Comparison expressions are separated out because they have 1417 // historically had a different warning flag. 1418 DiagID = S.getLangOpts().CPlusPlus2a 1419 ? diag::warn_comparison_mixed_enum_types_cxx2a 1420 : diag::warn_comparison_mixed_enum_types; 1421 } else { 1422 DiagID = S.getLangOpts().CPlusPlus2a 1423 ? diag::warn_arith_conv_mixed_enum_types_cxx2a 1424 : diag::warn_arith_conv_mixed_enum_types; 1425 } 1426 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1427 << (int)ACK << L << R; 1428 } 1429 } 1430 1431 /// UsualArithmeticConversions - Performs various conversions that are common to 1432 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1433 /// routine returns the first non-arithmetic type found. The client is 1434 /// responsible for emitting appropriate error diagnostics. 1435 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1436 SourceLocation Loc, 1437 ArithConvKind ACK) { 1438 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1439 1440 if (ACK != ACK_CompAssign) { 1441 LHS = UsualUnaryConversions(LHS.get()); 1442 if (LHS.isInvalid()) 1443 return QualType(); 1444 } 1445 1446 RHS = UsualUnaryConversions(RHS.get()); 1447 if (RHS.isInvalid()) 1448 return QualType(); 1449 1450 // For conversion purposes, we ignore any qualifiers. 1451 // For example, "const float" and "float" are equivalent. 1452 QualType LHSType = 1453 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1454 QualType RHSType = 1455 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1456 1457 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1458 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1459 LHSType = AtomicLHS->getValueType(); 1460 1461 // If both types are identical, no conversion is needed. 1462 if (LHSType == RHSType) 1463 return LHSType; 1464 1465 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1466 // The caller can deal with this (e.g. pointer + int). 1467 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1468 return QualType(); 1469 1470 // Apply unary and bitfield promotions to the LHS's type. 1471 QualType LHSUnpromotedType = LHSType; 1472 if (LHSType->isPromotableIntegerType()) 1473 LHSType = Context.getPromotedIntegerType(LHSType); 1474 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1475 if (!LHSBitfieldPromoteTy.isNull()) 1476 LHSType = LHSBitfieldPromoteTy; 1477 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1478 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1479 1480 // If both types are identical, no conversion is needed. 1481 if (LHSType == RHSType) 1482 return LHSType; 1483 1484 // At this point, we have two different arithmetic types. 1485 1486 // Diagnose attempts to convert between __float128 and long double where 1487 // such conversions currently can't be handled. 1488 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1489 return QualType(); 1490 1491 // Handle complex types first (C99 6.3.1.8p1). 1492 if (LHSType->isComplexType() || RHSType->isComplexType()) 1493 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1494 ACK == ACK_CompAssign); 1495 1496 // Now handle "real" floating types (i.e. float, double, long double). 1497 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1498 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1499 ACK == ACK_CompAssign); 1500 1501 // Handle GCC complex int extension. 1502 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1503 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1504 ACK == ACK_CompAssign); 1505 1506 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1507 return handleFixedPointConversion(*this, LHSType, RHSType); 1508 1509 // Finally, we have two differing integer types. 1510 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1511 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1512 } 1513 1514 //===----------------------------------------------------------------------===// 1515 // Semantic Analysis for various Expression Types 1516 //===----------------------------------------------------------------------===// 1517 1518 1519 ExprResult 1520 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1521 SourceLocation DefaultLoc, 1522 SourceLocation RParenLoc, 1523 Expr *ControllingExpr, 1524 ArrayRef<ParsedType> ArgTypes, 1525 ArrayRef<Expr *> ArgExprs) { 1526 unsigned NumAssocs = ArgTypes.size(); 1527 assert(NumAssocs == ArgExprs.size()); 1528 1529 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1530 for (unsigned i = 0; i < NumAssocs; ++i) { 1531 if (ArgTypes[i]) 1532 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1533 else 1534 Types[i] = nullptr; 1535 } 1536 1537 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1538 ControllingExpr, 1539 llvm::makeArrayRef(Types, NumAssocs), 1540 ArgExprs); 1541 delete [] Types; 1542 return ER; 1543 } 1544 1545 ExprResult 1546 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1547 SourceLocation DefaultLoc, 1548 SourceLocation RParenLoc, 1549 Expr *ControllingExpr, 1550 ArrayRef<TypeSourceInfo *> Types, 1551 ArrayRef<Expr *> Exprs) { 1552 unsigned NumAssocs = Types.size(); 1553 assert(NumAssocs == Exprs.size()); 1554 1555 // Decay and strip qualifiers for the controlling expression type, and handle 1556 // placeholder type replacement. See committee discussion from WG14 DR423. 1557 { 1558 EnterExpressionEvaluationContext Unevaluated( 1559 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1560 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1561 if (R.isInvalid()) 1562 return ExprError(); 1563 ControllingExpr = R.get(); 1564 } 1565 1566 // The controlling expression is an unevaluated operand, so side effects are 1567 // likely unintended. 1568 if (!inTemplateInstantiation() && 1569 ControllingExpr->HasSideEffects(Context, false)) 1570 Diag(ControllingExpr->getExprLoc(), 1571 diag::warn_side_effects_unevaluated_context); 1572 1573 bool TypeErrorFound = false, 1574 IsResultDependent = ControllingExpr->isTypeDependent(), 1575 ContainsUnexpandedParameterPack 1576 = ControllingExpr->containsUnexpandedParameterPack(); 1577 1578 for (unsigned i = 0; i < NumAssocs; ++i) { 1579 if (Exprs[i]->containsUnexpandedParameterPack()) 1580 ContainsUnexpandedParameterPack = true; 1581 1582 if (Types[i]) { 1583 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1584 ContainsUnexpandedParameterPack = true; 1585 1586 if (Types[i]->getType()->isDependentType()) { 1587 IsResultDependent = true; 1588 } else { 1589 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1590 // complete object type other than a variably modified type." 1591 unsigned D = 0; 1592 if (Types[i]->getType()->isIncompleteType()) 1593 D = diag::err_assoc_type_incomplete; 1594 else if (!Types[i]->getType()->isObjectType()) 1595 D = diag::err_assoc_type_nonobject; 1596 else if (Types[i]->getType()->isVariablyModifiedType()) 1597 D = diag::err_assoc_type_variably_modified; 1598 1599 if (D != 0) { 1600 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1601 << Types[i]->getTypeLoc().getSourceRange() 1602 << Types[i]->getType(); 1603 TypeErrorFound = true; 1604 } 1605 1606 // C11 6.5.1.1p2 "No two generic associations in the same generic 1607 // selection shall specify compatible types." 1608 for (unsigned j = i+1; j < NumAssocs; ++j) 1609 if (Types[j] && !Types[j]->getType()->isDependentType() && 1610 Context.typesAreCompatible(Types[i]->getType(), 1611 Types[j]->getType())) { 1612 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1613 diag::err_assoc_compatible_types) 1614 << Types[j]->getTypeLoc().getSourceRange() 1615 << Types[j]->getType() 1616 << Types[i]->getType(); 1617 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1618 diag::note_compat_assoc) 1619 << Types[i]->getTypeLoc().getSourceRange() 1620 << Types[i]->getType(); 1621 TypeErrorFound = true; 1622 } 1623 } 1624 } 1625 } 1626 if (TypeErrorFound) 1627 return ExprError(); 1628 1629 // If we determined that the generic selection is result-dependent, don't 1630 // try to compute the result expression. 1631 if (IsResultDependent) 1632 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1633 Exprs, DefaultLoc, RParenLoc, 1634 ContainsUnexpandedParameterPack); 1635 1636 SmallVector<unsigned, 1> CompatIndices; 1637 unsigned DefaultIndex = -1U; 1638 for (unsigned i = 0; i < NumAssocs; ++i) { 1639 if (!Types[i]) 1640 DefaultIndex = i; 1641 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1642 Types[i]->getType())) 1643 CompatIndices.push_back(i); 1644 } 1645 1646 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1647 // type compatible with at most one of the types named in its generic 1648 // association list." 1649 if (CompatIndices.size() > 1) { 1650 // We strip parens here because the controlling expression is typically 1651 // parenthesized in macro definitions. 1652 ControllingExpr = ControllingExpr->IgnoreParens(); 1653 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1654 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1655 << (unsigned)CompatIndices.size(); 1656 for (unsigned I : CompatIndices) { 1657 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1658 diag::note_compat_assoc) 1659 << Types[I]->getTypeLoc().getSourceRange() 1660 << Types[I]->getType(); 1661 } 1662 return ExprError(); 1663 } 1664 1665 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1666 // its controlling expression shall have type compatible with exactly one of 1667 // the types named in its generic association list." 1668 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1669 // We strip parens here because the controlling expression is typically 1670 // parenthesized in macro definitions. 1671 ControllingExpr = ControllingExpr->IgnoreParens(); 1672 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1673 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1674 return ExprError(); 1675 } 1676 1677 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1678 // type name that is compatible with the type of the controlling expression, 1679 // then the result expression of the generic selection is the expression 1680 // in that generic association. Otherwise, the result expression of the 1681 // generic selection is the expression in the default generic association." 1682 unsigned ResultIndex = 1683 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1684 1685 return GenericSelectionExpr::Create( 1686 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack, ResultIndex); 1688 } 1689 1690 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1691 /// location of the token and the offset of the ud-suffix within it. 1692 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1693 unsigned Offset) { 1694 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1695 S.getLangOpts()); 1696 } 1697 1698 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1699 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1700 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1701 IdentifierInfo *UDSuffix, 1702 SourceLocation UDSuffixLoc, 1703 ArrayRef<Expr*> Args, 1704 SourceLocation LitEndLoc) { 1705 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1706 1707 QualType ArgTy[2]; 1708 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1709 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1710 if (ArgTy[ArgIdx]->isArrayType()) 1711 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1712 } 1713 1714 DeclarationName OpName = 1715 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1716 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1717 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1718 1719 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1720 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1721 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1722 /*AllowStringTemplate*/ false, 1723 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1724 return ExprError(); 1725 1726 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1727 } 1728 1729 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1730 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1731 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1732 /// multiple tokens. However, the common case is that StringToks points to one 1733 /// string. 1734 /// 1735 ExprResult 1736 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1737 assert(!StringToks.empty() && "Must have at least one string!"); 1738 1739 StringLiteralParser Literal(StringToks, PP); 1740 if (Literal.hadError) 1741 return ExprError(); 1742 1743 SmallVector<SourceLocation, 4> StringTokLocs; 1744 for (const Token &Tok : StringToks) 1745 StringTokLocs.push_back(Tok.getLocation()); 1746 1747 QualType CharTy = Context.CharTy; 1748 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1749 if (Literal.isWide()) { 1750 CharTy = Context.getWideCharType(); 1751 Kind = StringLiteral::Wide; 1752 } else if (Literal.isUTF8()) { 1753 if (getLangOpts().Char8) 1754 CharTy = Context.Char8Ty; 1755 Kind = StringLiteral::UTF8; 1756 } else if (Literal.isUTF16()) { 1757 CharTy = Context.Char16Ty; 1758 Kind = StringLiteral::UTF16; 1759 } else if (Literal.isUTF32()) { 1760 CharTy = Context.Char32Ty; 1761 Kind = StringLiteral::UTF32; 1762 } else if (Literal.isPascal()) { 1763 CharTy = Context.UnsignedCharTy; 1764 } 1765 1766 // Warn on initializing an array of char from a u8 string literal; this 1767 // becomes ill-formed in C++2a. 1768 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1769 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1770 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1771 1772 // Create removals for all 'u8' prefixes in the string literal(s). This 1773 // ensures C++2a compatibility (but may change the program behavior when 1774 // built by non-Clang compilers for which the execution character set is 1775 // not always UTF-8). 1776 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1777 SourceLocation RemovalDiagLoc; 1778 for (const Token &Tok : StringToks) { 1779 if (Tok.getKind() == tok::utf8_string_literal) { 1780 if (RemovalDiagLoc.isInvalid()) 1781 RemovalDiagLoc = Tok.getLocation(); 1782 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1783 Tok.getLocation(), 1784 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1785 getSourceManager(), getLangOpts()))); 1786 } 1787 } 1788 Diag(RemovalDiagLoc, RemovalDiag); 1789 } 1790 1791 QualType StrTy = 1792 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1793 1794 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1795 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1796 Kind, Literal.Pascal, StrTy, 1797 &StringTokLocs[0], 1798 StringTokLocs.size()); 1799 if (Literal.getUDSuffix().empty()) 1800 return Lit; 1801 1802 // We're building a user-defined literal. 1803 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1804 SourceLocation UDSuffixLoc = 1805 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1806 Literal.getUDSuffixOffset()); 1807 1808 // Make sure we're allowed user-defined literals here. 1809 if (!UDLScope) 1810 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1811 1812 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1813 // operator "" X (str, len) 1814 QualType SizeType = Context.getSizeType(); 1815 1816 DeclarationName OpName = 1817 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1818 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1819 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1820 1821 QualType ArgTy[] = { 1822 Context.getArrayDecayedType(StrTy), SizeType 1823 }; 1824 1825 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1826 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1827 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1828 /*AllowStringTemplate*/ true, 1829 /*DiagnoseMissing*/ true)) { 1830 1831 case LOLR_Cooked: { 1832 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1833 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1834 StringTokLocs[0]); 1835 Expr *Args[] = { Lit, LenArg }; 1836 1837 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1838 } 1839 1840 case LOLR_StringTemplate: { 1841 TemplateArgumentListInfo ExplicitArgs; 1842 1843 unsigned CharBits = Context.getIntWidth(CharTy); 1844 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1845 llvm::APSInt Value(CharBits, CharIsUnsigned); 1846 1847 TemplateArgument TypeArg(CharTy); 1848 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1849 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1850 1851 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1852 Value = Lit->getCodeUnit(I); 1853 TemplateArgument Arg(Context, Value, CharTy); 1854 TemplateArgumentLocInfo ArgInfo; 1855 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1856 } 1857 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1858 &ExplicitArgs); 1859 } 1860 case LOLR_Raw: 1861 case LOLR_Template: 1862 case LOLR_ErrorNoDiagnostic: 1863 llvm_unreachable("unexpected literal operator lookup result"); 1864 case LOLR_Error: 1865 return ExprError(); 1866 } 1867 llvm_unreachable("unexpected literal operator lookup result"); 1868 } 1869 1870 DeclRefExpr * 1871 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1872 SourceLocation Loc, 1873 const CXXScopeSpec *SS) { 1874 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1875 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1876 } 1877 1878 DeclRefExpr * 1879 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1880 const DeclarationNameInfo &NameInfo, 1881 const CXXScopeSpec *SS, NamedDecl *FoundD, 1882 SourceLocation TemplateKWLoc, 1883 const TemplateArgumentListInfo *TemplateArgs) { 1884 NestedNameSpecifierLoc NNS = 1885 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1886 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1887 TemplateArgs); 1888 } 1889 1890 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1891 // A declaration named in an unevaluated operand never constitutes an odr-use. 1892 if (isUnevaluatedContext()) 1893 return NOUR_Unevaluated; 1894 1895 // C++2a [basic.def.odr]p4: 1896 // A variable x whose name appears as a potentially-evaluated expression e 1897 // is odr-used by e unless [...] x is a reference that is usable in 1898 // constant expressions. 1899 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1900 if (VD->getType()->isReferenceType() && 1901 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1902 VD->isUsableInConstantExpressions(Context)) 1903 return NOUR_Constant; 1904 } 1905 1906 // All remaining non-variable cases constitute an odr-use. For variables, we 1907 // need to wait and see how the expression is used. 1908 return NOUR_None; 1909 } 1910 1911 /// BuildDeclRefExpr - Build an expression that references a 1912 /// declaration that does not require a closure capture. 1913 DeclRefExpr * 1914 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1915 const DeclarationNameInfo &NameInfo, 1916 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1917 SourceLocation TemplateKWLoc, 1918 const TemplateArgumentListInfo *TemplateArgs) { 1919 bool RefersToCapturedVariable = 1920 isa<VarDecl>(D) && 1921 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1922 1923 DeclRefExpr *E = DeclRefExpr::Create( 1924 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1925 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1926 MarkDeclRefReferenced(E); 1927 1928 // C++ [except.spec]p17: 1929 // An exception-specification is considered to be needed when: 1930 // - in an expression, the function is the unique lookup result or 1931 // the selected member of a set of overloaded functions. 1932 // 1933 // We delay doing this until after we've built the function reference and 1934 // marked it as used so that: 1935 // a) if the function is defaulted, we get errors from defining it before / 1936 // instead of errors from computing its exception specification, and 1937 // b) if the function is a defaulted comparison, we can use the body we 1938 // build when defining it as input to the exception specification 1939 // computation rather than computing a new body. 1940 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1941 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1942 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1943 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1944 } 1945 } 1946 1947 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1948 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1949 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1950 getCurFunction()->recordUseOfWeak(E); 1951 1952 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1953 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1954 FD = IFD->getAnonField(); 1955 if (FD) { 1956 UnusedPrivateFields.remove(FD); 1957 // Just in case we're building an illegal pointer-to-member. 1958 if (FD->isBitField()) 1959 E->setObjectKind(OK_BitField); 1960 } 1961 1962 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1963 // designates a bit-field. 1964 if (auto *BD = dyn_cast<BindingDecl>(D)) 1965 if (auto *BE = BD->getBinding()) 1966 E->setObjectKind(BE->getObjectKind()); 1967 1968 return E; 1969 } 1970 1971 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1972 /// possibly a list of template arguments. 1973 /// 1974 /// If this produces template arguments, it is permitted to call 1975 /// DecomposeTemplateName. 1976 /// 1977 /// This actually loses a lot of source location information for 1978 /// non-standard name kinds; we should consider preserving that in 1979 /// some way. 1980 void 1981 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1982 TemplateArgumentListInfo &Buffer, 1983 DeclarationNameInfo &NameInfo, 1984 const TemplateArgumentListInfo *&TemplateArgs) { 1985 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1986 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1987 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1988 1989 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1990 Id.TemplateId->NumArgs); 1991 translateTemplateArguments(TemplateArgsPtr, Buffer); 1992 1993 TemplateName TName = Id.TemplateId->Template.get(); 1994 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1995 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1996 TemplateArgs = &Buffer; 1997 } else { 1998 NameInfo = GetNameFromUnqualifiedId(Id); 1999 TemplateArgs = nullptr; 2000 } 2001 } 2002 2003 static void emitEmptyLookupTypoDiagnostic( 2004 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2005 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2006 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2007 DeclContext *Ctx = 2008 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2009 if (!TC) { 2010 // Emit a special diagnostic for failed member lookups. 2011 // FIXME: computing the declaration context might fail here (?) 2012 if (Ctx) 2013 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2014 << SS.getRange(); 2015 else 2016 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2017 return; 2018 } 2019 2020 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2021 bool DroppedSpecifier = 2022 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2023 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2024 ? diag::note_implicit_param_decl 2025 : diag::note_previous_decl; 2026 if (!Ctx) 2027 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2028 SemaRef.PDiag(NoteID)); 2029 else 2030 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2031 << Typo << Ctx << DroppedSpecifier 2032 << SS.getRange(), 2033 SemaRef.PDiag(NoteID)); 2034 } 2035 2036 /// Diagnose an empty lookup. 2037 /// 2038 /// \return false if new lookup candidates were found 2039 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2040 CorrectionCandidateCallback &CCC, 2041 TemplateArgumentListInfo *ExplicitTemplateArgs, 2042 ArrayRef<Expr *> Args, TypoExpr **Out) { 2043 DeclarationName Name = R.getLookupName(); 2044 2045 unsigned diagnostic = diag::err_undeclared_var_use; 2046 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2047 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2048 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2049 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2050 diagnostic = diag::err_undeclared_use; 2051 diagnostic_suggest = diag::err_undeclared_use_suggest; 2052 } 2053 2054 // If the original lookup was an unqualified lookup, fake an 2055 // unqualified lookup. This is useful when (for example) the 2056 // original lookup would not have found something because it was a 2057 // dependent name. 2058 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2059 while (DC) { 2060 if (isa<CXXRecordDecl>(DC)) { 2061 LookupQualifiedName(R, DC); 2062 2063 if (!R.empty()) { 2064 // Don't give errors about ambiguities in this lookup. 2065 R.suppressDiagnostics(); 2066 2067 // During a default argument instantiation the CurContext points 2068 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2069 // function parameter list, hence add an explicit check. 2070 bool isDefaultArgument = 2071 !CodeSynthesisContexts.empty() && 2072 CodeSynthesisContexts.back().Kind == 2073 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2074 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2075 bool isInstance = CurMethod && 2076 CurMethod->isInstance() && 2077 DC == CurMethod->getParent() && !isDefaultArgument; 2078 2079 // Give a code modification hint to insert 'this->'. 2080 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2081 // Actually quite difficult! 2082 if (getLangOpts().MSVCCompat) 2083 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2084 if (isInstance) { 2085 Diag(R.getNameLoc(), diagnostic) << Name 2086 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2087 CheckCXXThisCapture(R.getNameLoc()); 2088 } else { 2089 Diag(R.getNameLoc(), diagnostic) << Name; 2090 } 2091 2092 // Do we really want to note all of these? 2093 for (NamedDecl *D : R) 2094 Diag(D->getLocation(), diag::note_dependent_var_use); 2095 2096 // Return true if we are inside a default argument instantiation 2097 // and the found name refers to an instance member function, otherwise 2098 // the function calling DiagnoseEmptyLookup will try to create an 2099 // implicit member call and this is wrong for default argument. 2100 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2101 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2102 return true; 2103 } 2104 2105 // Tell the callee to try to recover. 2106 return false; 2107 } 2108 2109 R.clear(); 2110 } 2111 2112 DC = DC->getLookupParent(); 2113 } 2114 2115 // We didn't find anything, so try to correct for a typo. 2116 TypoCorrection Corrected; 2117 if (S && Out) { 2118 SourceLocation TypoLoc = R.getNameLoc(); 2119 assert(!ExplicitTemplateArgs && 2120 "Diagnosing an empty lookup with explicit template args!"); 2121 *Out = CorrectTypoDelayed( 2122 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2123 [=](const TypoCorrection &TC) { 2124 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2125 diagnostic, diagnostic_suggest); 2126 }, 2127 nullptr, CTK_ErrorRecovery); 2128 if (*Out) 2129 return true; 2130 } else if (S && 2131 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2132 S, &SS, CCC, CTK_ErrorRecovery))) { 2133 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2134 bool DroppedSpecifier = 2135 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2136 R.setLookupName(Corrected.getCorrection()); 2137 2138 bool AcceptableWithRecovery = false; 2139 bool AcceptableWithoutRecovery = false; 2140 NamedDecl *ND = Corrected.getFoundDecl(); 2141 if (ND) { 2142 if (Corrected.isOverloaded()) { 2143 OverloadCandidateSet OCS(R.getNameLoc(), 2144 OverloadCandidateSet::CSK_Normal); 2145 OverloadCandidateSet::iterator Best; 2146 for (NamedDecl *CD : Corrected) { 2147 if (FunctionTemplateDecl *FTD = 2148 dyn_cast<FunctionTemplateDecl>(CD)) 2149 AddTemplateOverloadCandidate( 2150 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2151 Args, OCS); 2152 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2153 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2154 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2155 Args, OCS); 2156 } 2157 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2158 case OR_Success: 2159 ND = Best->FoundDecl; 2160 Corrected.setCorrectionDecl(ND); 2161 break; 2162 default: 2163 // FIXME: Arbitrarily pick the first declaration for the note. 2164 Corrected.setCorrectionDecl(ND); 2165 break; 2166 } 2167 } 2168 R.addDecl(ND); 2169 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2170 CXXRecordDecl *Record = nullptr; 2171 if (Corrected.getCorrectionSpecifier()) { 2172 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2173 Record = Ty->getAsCXXRecordDecl(); 2174 } 2175 if (!Record) 2176 Record = cast<CXXRecordDecl>( 2177 ND->getDeclContext()->getRedeclContext()); 2178 R.setNamingClass(Record); 2179 } 2180 2181 auto *UnderlyingND = ND->getUnderlyingDecl(); 2182 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2183 isa<FunctionTemplateDecl>(UnderlyingND); 2184 // FIXME: If we ended up with a typo for a type name or 2185 // Objective-C class name, we're in trouble because the parser 2186 // is in the wrong place to recover. Suggest the typo 2187 // correction, but don't make it a fix-it since we're not going 2188 // to recover well anyway. 2189 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2190 getAsTypeTemplateDecl(UnderlyingND) || 2191 isa<ObjCInterfaceDecl>(UnderlyingND); 2192 } else { 2193 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2194 // because we aren't able to recover. 2195 AcceptableWithoutRecovery = true; 2196 } 2197 2198 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2199 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2200 ? diag::note_implicit_param_decl 2201 : diag::note_previous_decl; 2202 if (SS.isEmpty()) 2203 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2204 PDiag(NoteID), AcceptableWithRecovery); 2205 else 2206 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2207 << Name << computeDeclContext(SS, false) 2208 << DroppedSpecifier << SS.getRange(), 2209 PDiag(NoteID), AcceptableWithRecovery); 2210 2211 // Tell the callee whether to try to recover. 2212 return !AcceptableWithRecovery; 2213 } 2214 } 2215 R.clear(); 2216 2217 // Emit a special diagnostic for failed member lookups. 2218 // FIXME: computing the declaration context might fail here (?) 2219 if (!SS.isEmpty()) { 2220 Diag(R.getNameLoc(), diag::err_no_member) 2221 << Name << computeDeclContext(SS, false) 2222 << SS.getRange(); 2223 return true; 2224 } 2225 2226 // Give up, we can't recover. 2227 Diag(R.getNameLoc(), diagnostic) << Name; 2228 return true; 2229 } 2230 2231 /// In Microsoft mode, if we are inside a template class whose parent class has 2232 /// dependent base classes, and we can't resolve an unqualified identifier, then 2233 /// assume the identifier is a member of a dependent base class. We can only 2234 /// recover successfully in static methods, instance methods, and other contexts 2235 /// where 'this' is available. This doesn't precisely match MSVC's 2236 /// instantiation model, but it's close enough. 2237 static Expr * 2238 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2239 DeclarationNameInfo &NameInfo, 2240 SourceLocation TemplateKWLoc, 2241 const TemplateArgumentListInfo *TemplateArgs) { 2242 // Only try to recover from lookup into dependent bases in static methods or 2243 // contexts where 'this' is available. 2244 QualType ThisType = S.getCurrentThisType(); 2245 const CXXRecordDecl *RD = nullptr; 2246 if (!ThisType.isNull()) 2247 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2248 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2249 RD = MD->getParent(); 2250 if (!RD || !RD->hasAnyDependentBases()) 2251 return nullptr; 2252 2253 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2254 // is available, suggest inserting 'this->' as a fixit. 2255 SourceLocation Loc = NameInfo.getLoc(); 2256 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2257 DB << NameInfo.getName() << RD; 2258 2259 if (!ThisType.isNull()) { 2260 DB << FixItHint::CreateInsertion(Loc, "this->"); 2261 return CXXDependentScopeMemberExpr::Create( 2262 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2263 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2264 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2265 } 2266 2267 // Synthesize a fake NNS that points to the derived class. This will 2268 // perform name lookup during template instantiation. 2269 CXXScopeSpec SS; 2270 auto *NNS = 2271 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2272 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2273 return DependentScopeDeclRefExpr::Create( 2274 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2275 TemplateArgs); 2276 } 2277 2278 ExprResult 2279 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2280 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2281 bool HasTrailingLParen, bool IsAddressOfOperand, 2282 CorrectionCandidateCallback *CCC, 2283 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2284 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2285 "cannot be direct & operand and have a trailing lparen"); 2286 if (SS.isInvalid()) 2287 return ExprError(); 2288 2289 TemplateArgumentListInfo TemplateArgsBuffer; 2290 2291 // Decompose the UnqualifiedId into the following data. 2292 DeclarationNameInfo NameInfo; 2293 const TemplateArgumentListInfo *TemplateArgs; 2294 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2295 2296 DeclarationName Name = NameInfo.getName(); 2297 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2298 SourceLocation NameLoc = NameInfo.getLoc(); 2299 2300 if (II && II->isEditorPlaceholder()) { 2301 // FIXME: When typed placeholders are supported we can create a typed 2302 // placeholder expression node. 2303 return ExprError(); 2304 } 2305 2306 // C++ [temp.dep.expr]p3: 2307 // An id-expression is type-dependent if it contains: 2308 // -- an identifier that was declared with a dependent type, 2309 // (note: handled after lookup) 2310 // -- a template-id that is dependent, 2311 // (note: handled in BuildTemplateIdExpr) 2312 // -- a conversion-function-id that specifies a dependent type, 2313 // -- a nested-name-specifier that contains a class-name that 2314 // names a dependent type. 2315 // Determine whether this is a member of an unknown specialization; 2316 // we need to handle these differently. 2317 bool DependentID = false; 2318 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2319 Name.getCXXNameType()->isDependentType()) { 2320 DependentID = true; 2321 } else if (SS.isSet()) { 2322 if (DeclContext *DC = computeDeclContext(SS, false)) { 2323 if (RequireCompleteDeclContext(SS, DC)) 2324 return ExprError(); 2325 } else { 2326 DependentID = true; 2327 } 2328 } 2329 2330 if (DependentID) 2331 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2332 IsAddressOfOperand, TemplateArgs); 2333 2334 // Perform the required lookup. 2335 LookupResult R(*this, NameInfo, 2336 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2337 ? LookupObjCImplicitSelfParam 2338 : LookupOrdinaryName); 2339 if (TemplateKWLoc.isValid() || TemplateArgs) { 2340 // Lookup the template name again to correctly establish the context in 2341 // which it was found. This is really unfortunate as we already did the 2342 // lookup to determine that it was a template name in the first place. If 2343 // this becomes a performance hit, we can work harder to preserve those 2344 // results until we get here but it's likely not worth it. 2345 bool MemberOfUnknownSpecialization; 2346 AssumedTemplateKind AssumedTemplate; 2347 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2348 MemberOfUnknownSpecialization, TemplateKWLoc, 2349 &AssumedTemplate)) 2350 return ExprError(); 2351 2352 if (MemberOfUnknownSpecialization || 2353 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2354 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2355 IsAddressOfOperand, TemplateArgs); 2356 } else { 2357 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2358 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2359 2360 // If the result might be in a dependent base class, this is a dependent 2361 // id-expression. 2362 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2363 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2364 IsAddressOfOperand, TemplateArgs); 2365 2366 // If this reference is in an Objective-C method, then we need to do 2367 // some special Objective-C lookup, too. 2368 if (IvarLookupFollowUp) { 2369 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2370 if (E.isInvalid()) 2371 return ExprError(); 2372 2373 if (Expr *Ex = E.getAs<Expr>()) 2374 return Ex; 2375 } 2376 } 2377 2378 if (R.isAmbiguous()) 2379 return ExprError(); 2380 2381 // This could be an implicitly declared function reference (legal in C90, 2382 // extension in C99, forbidden in C++). 2383 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2384 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2385 if (D) R.addDecl(D); 2386 } 2387 2388 // Determine whether this name might be a candidate for 2389 // argument-dependent lookup. 2390 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2391 2392 if (R.empty() && !ADL) { 2393 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2394 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2395 TemplateKWLoc, TemplateArgs)) 2396 return E; 2397 } 2398 2399 // Don't diagnose an empty lookup for inline assembly. 2400 if (IsInlineAsmIdentifier) 2401 return ExprError(); 2402 2403 // If this name wasn't predeclared and if this is not a function 2404 // call, diagnose the problem. 2405 TypoExpr *TE = nullptr; 2406 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2407 : nullptr); 2408 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2409 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2410 "Typo correction callback misconfigured"); 2411 if (CCC) { 2412 // Make sure the callback knows what the typo being diagnosed is. 2413 CCC->setTypoName(II); 2414 if (SS.isValid()) 2415 CCC->setTypoNNS(SS.getScopeRep()); 2416 } 2417 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2418 // a template name, but we happen to have always already looked up the name 2419 // before we get here if it must be a template name. 2420 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2421 None, &TE)) { 2422 if (TE && KeywordReplacement) { 2423 auto &State = getTypoExprState(TE); 2424 auto BestTC = State.Consumer->getNextCorrection(); 2425 if (BestTC.isKeyword()) { 2426 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2427 if (State.DiagHandler) 2428 State.DiagHandler(BestTC); 2429 KeywordReplacement->startToken(); 2430 KeywordReplacement->setKind(II->getTokenID()); 2431 KeywordReplacement->setIdentifierInfo(II); 2432 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2433 // Clean up the state associated with the TypoExpr, since it has 2434 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2435 clearDelayedTypo(TE); 2436 // Signal that a correction to a keyword was performed by returning a 2437 // valid-but-null ExprResult. 2438 return (Expr*)nullptr; 2439 } 2440 State.Consumer->resetCorrectionStream(); 2441 } 2442 return TE ? TE : ExprError(); 2443 } 2444 2445 assert(!R.empty() && 2446 "DiagnoseEmptyLookup returned false but added no results"); 2447 2448 // If we found an Objective-C instance variable, let 2449 // LookupInObjCMethod build the appropriate expression to 2450 // reference the ivar. 2451 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2452 R.clear(); 2453 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2454 // In a hopelessly buggy code, Objective-C instance variable 2455 // lookup fails and no expression will be built to reference it. 2456 if (!E.isInvalid() && !E.get()) 2457 return ExprError(); 2458 return E; 2459 } 2460 } 2461 2462 // This is guaranteed from this point on. 2463 assert(!R.empty() || ADL); 2464 2465 // Check whether this might be a C++ implicit instance member access. 2466 // C++ [class.mfct.non-static]p3: 2467 // When an id-expression that is not part of a class member access 2468 // syntax and not used to form a pointer to member is used in the 2469 // body of a non-static member function of class X, if name lookup 2470 // resolves the name in the id-expression to a non-static non-type 2471 // member of some class C, the id-expression is transformed into a 2472 // class member access expression using (*this) as the 2473 // postfix-expression to the left of the . operator. 2474 // 2475 // But we don't actually need to do this for '&' operands if R 2476 // resolved to a function or overloaded function set, because the 2477 // expression is ill-formed if it actually works out to be a 2478 // non-static member function: 2479 // 2480 // C++ [expr.ref]p4: 2481 // Otherwise, if E1.E2 refers to a non-static member function. . . 2482 // [t]he expression can be used only as the left-hand operand of a 2483 // member function call. 2484 // 2485 // There are other safeguards against such uses, but it's important 2486 // to get this right here so that we don't end up making a 2487 // spuriously dependent expression if we're inside a dependent 2488 // instance method. 2489 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2490 bool MightBeImplicitMember; 2491 if (!IsAddressOfOperand) 2492 MightBeImplicitMember = true; 2493 else if (!SS.isEmpty()) 2494 MightBeImplicitMember = false; 2495 else if (R.isOverloadedResult()) 2496 MightBeImplicitMember = false; 2497 else if (R.isUnresolvableResult()) 2498 MightBeImplicitMember = true; 2499 else 2500 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2501 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2502 isa<MSPropertyDecl>(R.getFoundDecl()); 2503 2504 if (MightBeImplicitMember) 2505 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2506 R, TemplateArgs, S); 2507 } 2508 2509 if (TemplateArgs || TemplateKWLoc.isValid()) { 2510 2511 // In C++1y, if this is a variable template id, then check it 2512 // in BuildTemplateIdExpr(). 2513 // The single lookup result must be a variable template declaration. 2514 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2515 Id.TemplateId->Kind == TNK_Var_template) { 2516 assert(R.getAsSingle<VarTemplateDecl>() && 2517 "There should only be one declaration found."); 2518 } 2519 2520 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2521 } 2522 2523 return BuildDeclarationNameExpr(SS, R, ADL); 2524 } 2525 2526 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2527 /// declaration name, generally during template instantiation. 2528 /// There's a large number of things which don't need to be done along 2529 /// this path. 2530 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2531 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2532 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2533 DeclContext *DC = computeDeclContext(SS, false); 2534 if (!DC) 2535 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2536 NameInfo, /*TemplateArgs=*/nullptr); 2537 2538 if (RequireCompleteDeclContext(SS, DC)) 2539 return ExprError(); 2540 2541 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2542 LookupQualifiedName(R, DC); 2543 2544 if (R.isAmbiguous()) 2545 return ExprError(); 2546 2547 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2548 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2549 NameInfo, /*TemplateArgs=*/nullptr); 2550 2551 if (R.empty()) { 2552 Diag(NameInfo.getLoc(), diag::err_no_member) 2553 << NameInfo.getName() << DC << SS.getRange(); 2554 return ExprError(); 2555 } 2556 2557 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2558 // Diagnose a missing typename if this resolved unambiguously to a type in 2559 // a dependent context. If we can recover with a type, downgrade this to 2560 // a warning in Microsoft compatibility mode. 2561 unsigned DiagID = diag::err_typename_missing; 2562 if (RecoveryTSI && getLangOpts().MSVCCompat) 2563 DiagID = diag::ext_typename_missing; 2564 SourceLocation Loc = SS.getBeginLoc(); 2565 auto D = Diag(Loc, DiagID); 2566 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2567 << SourceRange(Loc, NameInfo.getEndLoc()); 2568 2569 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2570 // context. 2571 if (!RecoveryTSI) 2572 return ExprError(); 2573 2574 // Only issue the fixit if we're prepared to recover. 2575 D << FixItHint::CreateInsertion(Loc, "typename "); 2576 2577 // Recover by pretending this was an elaborated type. 2578 QualType Ty = Context.getTypeDeclType(TD); 2579 TypeLocBuilder TLB; 2580 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2581 2582 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2583 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2584 QTL.setElaboratedKeywordLoc(SourceLocation()); 2585 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2586 2587 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2588 2589 return ExprEmpty(); 2590 } 2591 2592 // Defend against this resolving to an implicit member access. We usually 2593 // won't get here if this might be a legitimate a class member (we end up in 2594 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2595 // a pointer-to-member or in an unevaluated context in C++11. 2596 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2597 return BuildPossibleImplicitMemberExpr(SS, 2598 /*TemplateKWLoc=*/SourceLocation(), 2599 R, /*TemplateArgs=*/nullptr, S); 2600 2601 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2602 } 2603 2604 /// The parser has read a name in, and Sema has detected that we're currently 2605 /// inside an ObjC method. Perform some additional checks and determine if we 2606 /// should form a reference to an ivar. 2607 /// 2608 /// Ideally, most of this would be done by lookup, but there's 2609 /// actually quite a lot of extra work involved. 2610 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2611 IdentifierInfo *II) { 2612 SourceLocation Loc = Lookup.getNameLoc(); 2613 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2614 2615 // Check for error condition which is already reported. 2616 if (!CurMethod) 2617 return DeclResult(true); 2618 2619 // There are two cases to handle here. 1) scoped lookup could have failed, 2620 // in which case we should look for an ivar. 2) scoped lookup could have 2621 // found a decl, but that decl is outside the current instance method (i.e. 2622 // a global variable). In these two cases, we do a lookup for an ivar with 2623 // this name, if the lookup sucedes, we replace it our current decl. 2624 2625 // If we're in a class method, we don't normally want to look for 2626 // ivars. But if we don't find anything else, and there's an 2627 // ivar, that's an error. 2628 bool IsClassMethod = CurMethod->isClassMethod(); 2629 2630 bool LookForIvars; 2631 if (Lookup.empty()) 2632 LookForIvars = true; 2633 else if (IsClassMethod) 2634 LookForIvars = false; 2635 else 2636 LookForIvars = (Lookup.isSingleResult() && 2637 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2638 ObjCInterfaceDecl *IFace = nullptr; 2639 if (LookForIvars) { 2640 IFace = CurMethod->getClassInterface(); 2641 ObjCInterfaceDecl *ClassDeclared; 2642 ObjCIvarDecl *IV = nullptr; 2643 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2644 // Diagnose using an ivar in a class method. 2645 if (IsClassMethod) { 2646 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2647 return DeclResult(true); 2648 } 2649 2650 // Diagnose the use of an ivar outside of the declaring class. 2651 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2652 !declaresSameEntity(ClassDeclared, IFace) && 2653 !getLangOpts().DebuggerSupport) 2654 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2655 2656 // Success. 2657 return IV; 2658 } 2659 } else if (CurMethod->isInstanceMethod()) { 2660 // We should warn if a local variable hides an ivar. 2661 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2662 ObjCInterfaceDecl *ClassDeclared; 2663 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2664 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2665 declaresSameEntity(IFace, ClassDeclared)) 2666 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2667 } 2668 } 2669 } else if (Lookup.isSingleResult() && 2670 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2671 // If accessing a stand-alone ivar in a class method, this is an error. 2672 if (const ObjCIvarDecl *IV = 2673 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2674 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2675 return DeclResult(true); 2676 } 2677 } 2678 2679 // Didn't encounter an error, didn't find an ivar. 2680 return DeclResult(false); 2681 } 2682 2683 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2684 ObjCIvarDecl *IV) { 2685 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2686 assert(CurMethod && CurMethod->isInstanceMethod() && 2687 "should not reference ivar from this context"); 2688 2689 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2690 assert(IFace && "should not reference ivar from this context"); 2691 2692 // If we're referencing an invalid decl, just return this as a silent 2693 // error node. The error diagnostic was already emitted on the decl. 2694 if (IV->isInvalidDecl()) 2695 return ExprError(); 2696 2697 // Check if referencing a field with __attribute__((deprecated)). 2698 if (DiagnoseUseOfDecl(IV, Loc)) 2699 return ExprError(); 2700 2701 // FIXME: This should use a new expr for a direct reference, don't 2702 // turn this into Self->ivar, just return a BareIVarExpr or something. 2703 IdentifierInfo &II = Context.Idents.get("self"); 2704 UnqualifiedId SelfName; 2705 SelfName.setIdentifier(&II, SourceLocation()); 2706 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2707 CXXScopeSpec SelfScopeSpec; 2708 SourceLocation TemplateKWLoc; 2709 ExprResult SelfExpr = 2710 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2711 /*HasTrailingLParen=*/false, 2712 /*IsAddressOfOperand=*/false); 2713 if (SelfExpr.isInvalid()) 2714 return ExprError(); 2715 2716 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2717 if (SelfExpr.isInvalid()) 2718 return ExprError(); 2719 2720 MarkAnyDeclReferenced(Loc, IV, true); 2721 2722 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2723 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2724 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2725 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2726 2727 ObjCIvarRefExpr *Result = new (Context) 2728 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2729 IV->getLocation(), SelfExpr.get(), true, true); 2730 2731 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2732 if (!isUnevaluatedContext() && 2733 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2734 getCurFunction()->recordUseOfWeak(Result); 2735 } 2736 if (getLangOpts().ObjCAutoRefCount) 2737 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2738 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2739 2740 return Result; 2741 } 2742 2743 /// The parser has read a name in, and Sema has detected that we're currently 2744 /// inside an ObjC method. Perform some additional checks and determine if we 2745 /// should form a reference to an ivar. If so, build an expression referencing 2746 /// that ivar. 2747 ExprResult 2748 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2749 IdentifierInfo *II, bool AllowBuiltinCreation) { 2750 // FIXME: Integrate this lookup step into LookupParsedName. 2751 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2752 if (Ivar.isInvalid()) 2753 return ExprError(); 2754 if (Ivar.isUsable()) 2755 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2756 cast<ObjCIvarDecl>(Ivar.get())); 2757 2758 if (Lookup.empty() && II && AllowBuiltinCreation) 2759 LookupBuiltin(Lookup); 2760 2761 // Sentinel value saying that we didn't do anything special. 2762 return ExprResult(false); 2763 } 2764 2765 /// Cast a base object to a member's actual type. 2766 /// 2767 /// Logically this happens in three phases: 2768 /// 2769 /// * First we cast from the base type to the naming class. 2770 /// The naming class is the class into which we were looking 2771 /// when we found the member; it's the qualifier type if a 2772 /// qualifier was provided, and otherwise it's the base type. 2773 /// 2774 /// * Next we cast from the naming class to the declaring class. 2775 /// If the member we found was brought into a class's scope by 2776 /// a using declaration, this is that class; otherwise it's 2777 /// the class declaring the member. 2778 /// 2779 /// * Finally we cast from the declaring class to the "true" 2780 /// declaring class of the member. This conversion does not 2781 /// obey access control. 2782 ExprResult 2783 Sema::PerformObjectMemberConversion(Expr *From, 2784 NestedNameSpecifier *Qualifier, 2785 NamedDecl *FoundDecl, 2786 NamedDecl *Member) { 2787 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2788 if (!RD) 2789 return From; 2790 2791 QualType DestRecordType; 2792 QualType DestType; 2793 QualType FromRecordType; 2794 QualType FromType = From->getType(); 2795 bool PointerConversions = false; 2796 if (isa<FieldDecl>(Member)) { 2797 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2798 auto FromPtrType = FromType->getAs<PointerType>(); 2799 DestRecordType = Context.getAddrSpaceQualType( 2800 DestRecordType, FromPtrType 2801 ? FromType->getPointeeType().getAddressSpace() 2802 : FromType.getAddressSpace()); 2803 2804 if (FromPtrType) { 2805 DestType = Context.getPointerType(DestRecordType); 2806 FromRecordType = FromPtrType->getPointeeType(); 2807 PointerConversions = true; 2808 } else { 2809 DestType = DestRecordType; 2810 FromRecordType = FromType; 2811 } 2812 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2813 if (Method->isStatic()) 2814 return From; 2815 2816 DestType = Method->getThisType(); 2817 DestRecordType = DestType->getPointeeType(); 2818 2819 if (FromType->getAs<PointerType>()) { 2820 FromRecordType = FromType->getPointeeType(); 2821 PointerConversions = true; 2822 } else { 2823 FromRecordType = FromType; 2824 DestType = DestRecordType; 2825 } 2826 2827 LangAS FromAS = FromRecordType.getAddressSpace(); 2828 LangAS DestAS = DestRecordType.getAddressSpace(); 2829 if (FromAS != DestAS) { 2830 QualType FromRecordTypeWithoutAS = 2831 Context.removeAddrSpaceQualType(FromRecordType); 2832 QualType FromTypeWithDestAS = 2833 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2834 if (PointerConversions) 2835 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2836 From = ImpCastExprToType(From, FromTypeWithDestAS, 2837 CK_AddressSpaceConversion, From->getValueKind()) 2838 .get(); 2839 } 2840 } else { 2841 // No conversion necessary. 2842 return From; 2843 } 2844 2845 if (DestType->isDependentType() || FromType->isDependentType()) 2846 return From; 2847 2848 // If the unqualified types are the same, no conversion is necessary. 2849 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2850 return From; 2851 2852 SourceRange FromRange = From->getSourceRange(); 2853 SourceLocation FromLoc = FromRange.getBegin(); 2854 2855 ExprValueKind VK = From->getValueKind(); 2856 2857 // C++ [class.member.lookup]p8: 2858 // [...] Ambiguities can often be resolved by qualifying a name with its 2859 // class name. 2860 // 2861 // If the member was a qualified name and the qualified referred to a 2862 // specific base subobject type, we'll cast to that intermediate type 2863 // first and then to the object in which the member is declared. That allows 2864 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2865 // 2866 // class Base { public: int x; }; 2867 // class Derived1 : public Base { }; 2868 // class Derived2 : public Base { }; 2869 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2870 // 2871 // void VeryDerived::f() { 2872 // x = 17; // error: ambiguous base subobjects 2873 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2874 // } 2875 if (Qualifier && Qualifier->getAsType()) { 2876 QualType QType = QualType(Qualifier->getAsType(), 0); 2877 assert(QType->isRecordType() && "lookup done with non-record type"); 2878 2879 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2880 2881 // In C++98, the qualifier type doesn't actually have to be a base 2882 // type of the object type, in which case we just ignore it. 2883 // Otherwise build the appropriate casts. 2884 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2885 CXXCastPath BasePath; 2886 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2887 FromLoc, FromRange, &BasePath)) 2888 return ExprError(); 2889 2890 if (PointerConversions) 2891 QType = Context.getPointerType(QType); 2892 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2893 VK, &BasePath).get(); 2894 2895 FromType = QType; 2896 FromRecordType = QRecordType; 2897 2898 // If the qualifier type was the same as the destination type, 2899 // we're done. 2900 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2901 return From; 2902 } 2903 } 2904 2905 bool IgnoreAccess = false; 2906 2907 // If we actually found the member through a using declaration, cast 2908 // down to the using declaration's type. 2909 // 2910 // Pointer equality is fine here because only one declaration of a 2911 // class ever has member declarations. 2912 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2913 assert(isa<UsingShadowDecl>(FoundDecl)); 2914 QualType URecordType = Context.getTypeDeclType( 2915 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2916 2917 // We only need to do this if the naming-class to declaring-class 2918 // conversion is non-trivial. 2919 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2920 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2921 CXXCastPath BasePath; 2922 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2923 FromLoc, FromRange, &BasePath)) 2924 return ExprError(); 2925 2926 QualType UType = URecordType; 2927 if (PointerConversions) 2928 UType = Context.getPointerType(UType); 2929 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2930 VK, &BasePath).get(); 2931 FromType = UType; 2932 FromRecordType = URecordType; 2933 } 2934 2935 // We don't do access control for the conversion from the 2936 // declaring class to the true declaring class. 2937 IgnoreAccess = true; 2938 } 2939 2940 CXXCastPath BasePath; 2941 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2942 FromLoc, FromRange, &BasePath, 2943 IgnoreAccess)) 2944 return ExprError(); 2945 2946 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2947 VK, &BasePath); 2948 } 2949 2950 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2951 const LookupResult &R, 2952 bool HasTrailingLParen) { 2953 // Only when used directly as the postfix-expression of a call. 2954 if (!HasTrailingLParen) 2955 return false; 2956 2957 // Never if a scope specifier was provided. 2958 if (SS.isSet()) 2959 return false; 2960 2961 // Only in C++ or ObjC++. 2962 if (!getLangOpts().CPlusPlus) 2963 return false; 2964 2965 // Turn off ADL when we find certain kinds of declarations during 2966 // normal lookup: 2967 for (NamedDecl *D : R) { 2968 // C++0x [basic.lookup.argdep]p3: 2969 // -- a declaration of a class member 2970 // Since using decls preserve this property, we check this on the 2971 // original decl. 2972 if (D->isCXXClassMember()) 2973 return false; 2974 2975 // C++0x [basic.lookup.argdep]p3: 2976 // -- a block-scope function declaration that is not a 2977 // using-declaration 2978 // NOTE: we also trigger this for function templates (in fact, we 2979 // don't check the decl type at all, since all other decl types 2980 // turn off ADL anyway). 2981 if (isa<UsingShadowDecl>(D)) 2982 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2983 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2984 return false; 2985 2986 // C++0x [basic.lookup.argdep]p3: 2987 // -- a declaration that is neither a function or a function 2988 // template 2989 // And also for builtin functions. 2990 if (isa<FunctionDecl>(D)) { 2991 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2992 2993 // But also builtin functions. 2994 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2995 return false; 2996 } else if (!isa<FunctionTemplateDecl>(D)) 2997 return false; 2998 } 2999 3000 return true; 3001 } 3002 3003 3004 /// Diagnoses obvious problems with the use of the given declaration 3005 /// as an expression. This is only actually called for lookups that 3006 /// were not overloaded, and it doesn't promise that the declaration 3007 /// will in fact be used. 3008 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3009 if (D->isInvalidDecl()) 3010 return true; 3011 3012 if (isa<TypedefNameDecl>(D)) { 3013 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3014 return true; 3015 } 3016 3017 if (isa<ObjCInterfaceDecl>(D)) { 3018 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3019 return true; 3020 } 3021 3022 if (isa<NamespaceDecl>(D)) { 3023 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3024 return true; 3025 } 3026 3027 return false; 3028 } 3029 3030 // Certain multiversion types should be treated as overloaded even when there is 3031 // only one result. 3032 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3033 assert(R.isSingleResult() && "Expected only a single result"); 3034 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3035 return FD && 3036 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3037 } 3038 3039 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3040 LookupResult &R, bool NeedsADL, 3041 bool AcceptInvalidDecl) { 3042 // If this is a single, fully-resolved result and we don't need ADL, 3043 // just build an ordinary singleton decl ref. 3044 if (!NeedsADL && R.isSingleResult() && 3045 !R.getAsSingle<FunctionTemplateDecl>() && 3046 !ShouldLookupResultBeMultiVersionOverload(R)) 3047 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3048 R.getRepresentativeDecl(), nullptr, 3049 AcceptInvalidDecl); 3050 3051 // We only need to check the declaration if there's exactly one 3052 // result, because in the overloaded case the results can only be 3053 // functions and function templates. 3054 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3055 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3056 return ExprError(); 3057 3058 // Otherwise, just build an unresolved lookup expression. Suppress 3059 // any lookup-related diagnostics; we'll hash these out later, when 3060 // we've picked a target. 3061 R.suppressDiagnostics(); 3062 3063 UnresolvedLookupExpr *ULE 3064 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3065 SS.getWithLocInContext(Context), 3066 R.getLookupNameInfo(), 3067 NeedsADL, R.isOverloadedResult(), 3068 R.begin(), R.end()); 3069 3070 return ULE; 3071 } 3072 3073 static void 3074 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3075 ValueDecl *var, DeclContext *DC); 3076 3077 /// Complete semantic analysis for a reference to the given declaration. 3078 ExprResult Sema::BuildDeclarationNameExpr( 3079 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3080 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3081 bool AcceptInvalidDecl) { 3082 assert(D && "Cannot refer to a NULL declaration"); 3083 assert(!isa<FunctionTemplateDecl>(D) && 3084 "Cannot refer unambiguously to a function template"); 3085 3086 SourceLocation Loc = NameInfo.getLoc(); 3087 if (CheckDeclInExpr(*this, Loc, D)) 3088 return ExprError(); 3089 3090 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3091 // Specifically diagnose references to class templates that are missing 3092 // a template argument list. 3093 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3094 return ExprError(); 3095 } 3096 3097 // Make sure that we're referring to a value. 3098 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3099 if (!VD) { 3100 Diag(Loc, diag::err_ref_non_value) 3101 << D << SS.getRange(); 3102 Diag(D->getLocation(), diag::note_declared_at); 3103 return ExprError(); 3104 } 3105 3106 // Check whether this declaration can be used. Note that we suppress 3107 // this check when we're going to perform argument-dependent lookup 3108 // on this function name, because this might not be the function 3109 // that overload resolution actually selects. 3110 if (DiagnoseUseOfDecl(VD, Loc)) 3111 return ExprError(); 3112 3113 // Only create DeclRefExpr's for valid Decl's. 3114 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3115 return ExprError(); 3116 3117 // Handle members of anonymous structs and unions. If we got here, 3118 // and the reference is to a class member indirect field, then this 3119 // must be the subject of a pointer-to-member expression. 3120 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3121 if (!indirectField->isCXXClassMember()) 3122 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3123 indirectField); 3124 3125 { 3126 QualType type = VD->getType(); 3127 if (type.isNull()) 3128 return ExprError(); 3129 ExprValueKind valueKind = VK_RValue; 3130 3131 switch (D->getKind()) { 3132 // Ignore all the non-ValueDecl kinds. 3133 #define ABSTRACT_DECL(kind) 3134 #define VALUE(type, base) 3135 #define DECL(type, base) \ 3136 case Decl::type: 3137 #include "clang/AST/DeclNodes.inc" 3138 llvm_unreachable("invalid value decl kind"); 3139 3140 // These shouldn't make it here. 3141 case Decl::ObjCAtDefsField: 3142 llvm_unreachable("forming non-member reference to ivar?"); 3143 3144 // Enum constants are always r-values and never references. 3145 // Unresolved using declarations are dependent. 3146 case Decl::EnumConstant: 3147 case Decl::UnresolvedUsingValue: 3148 case Decl::OMPDeclareReduction: 3149 case Decl::OMPDeclareMapper: 3150 valueKind = VK_RValue; 3151 break; 3152 3153 // Fields and indirect fields that got here must be for 3154 // pointer-to-member expressions; we just call them l-values for 3155 // internal consistency, because this subexpression doesn't really 3156 // exist in the high-level semantics. 3157 case Decl::Field: 3158 case Decl::IndirectField: 3159 case Decl::ObjCIvar: 3160 assert(getLangOpts().CPlusPlus && 3161 "building reference to field in C?"); 3162 3163 // These can't have reference type in well-formed programs, but 3164 // for internal consistency we do this anyway. 3165 type = type.getNonReferenceType(); 3166 valueKind = VK_LValue; 3167 break; 3168 3169 // Non-type template parameters are either l-values or r-values 3170 // depending on the type. 3171 case Decl::NonTypeTemplateParm: { 3172 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3173 type = reftype->getPointeeType(); 3174 valueKind = VK_LValue; // even if the parameter is an r-value reference 3175 break; 3176 } 3177 3178 // For non-references, we need to strip qualifiers just in case 3179 // the template parameter was declared as 'const int' or whatever. 3180 valueKind = VK_RValue; 3181 type = type.getUnqualifiedType(); 3182 break; 3183 } 3184 3185 case Decl::Var: 3186 case Decl::VarTemplateSpecialization: 3187 case Decl::VarTemplatePartialSpecialization: 3188 case Decl::Decomposition: 3189 case Decl::OMPCapturedExpr: 3190 // In C, "extern void blah;" is valid and is an r-value. 3191 if (!getLangOpts().CPlusPlus && 3192 !type.hasQualifiers() && 3193 type->isVoidType()) { 3194 valueKind = VK_RValue; 3195 break; 3196 } 3197 LLVM_FALLTHROUGH; 3198 3199 case Decl::ImplicitParam: 3200 case Decl::ParmVar: { 3201 // These are always l-values. 3202 valueKind = VK_LValue; 3203 type = type.getNonReferenceType(); 3204 3205 // FIXME: Does the addition of const really only apply in 3206 // potentially-evaluated contexts? Since the variable isn't actually 3207 // captured in an unevaluated context, it seems that the answer is no. 3208 if (!isUnevaluatedContext()) { 3209 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3210 if (!CapturedType.isNull()) 3211 type = CapturedType; 3212 } 3213 3214 break; 3215 } 3216 3217 case Decl::Binding: { 3218 // These are always lvalues. 3219 valueKind = VK_LValue; 3220 type = type.getNonReferenceType(); 3221 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3222 // decides how that's supposed to work. 3223 auto *BD = cast<BindingDecl>(VD); 3224 if (BD->getDeclContext() != CurContext) { 3225 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3226 if (DD && DD->hasLocalStorage()) 3227 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3228 } 3229 break; 3230 } 3231 3232 case Decl::Function: { 3233 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3234 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3235 type = Context.BuiltinFnTy; 3236 valueKind = VK_RValue; 3237 break; 3238 } 3239 } 3240 3241 const FunctionType *fty = type->castAs<FunctionType>(); 3242 3243 // If we're referring to a function with an __unknown_anytype 3244 // result type, make the entire expression __unknown_anytype. 3245 if (fty->getReturnType() == Context.UnknownAnyTy) { 3246 type = Context.UnknownAnyTy; 3247 valueKind = VK_RValue; 3248 break; 3249 } 3250 3251 // Functions are l-values in C++. 3252 if (getLangOpts().CPlusPlus) { 3253 valueKind = VK_LValue; 3254 break; 3255 } 3256 3257 // C99 DR 316 says that, if a function type comes from a 3258 // function definition (without a prototype), that type is only 3259 // used for checking compatibility. Therefore, when referencing 3260 // the function, we pretend that we don't have the full function 3261 // type. 3262 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3263 isa<FunctionProtoType>(fty)) 3264 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3265 fty->getExtInfo()); 3266 3267 // Functions are r-values in C. 3268 valueKind = VK_RValue; 3269 break; 3270 } 3271 3272 case Decl::CXXDeductionGuide: 3273 llvm_unreachable("building reference to deduction guide"); 3274 3275 case Decl::MSProperty: 3276 valueKind = VK_LValue; 3277 break; 3278 3279 case Decl::CXXMethod: 3280 // If we're referring to a method with an __unknown_anytype 3281 // result type, make the entire expression __unknown_anytype. 3282 // This should only be possible with a type written directly. 3283 if (const FunctionProtoType *proto 3284 = dyn_cast<FunctionProtoType>(VD->getType())) 3285 if (proto->getReturnType() == Context.UnknownAnyTy) { 3286 type = Context.UnknownAnyTy; 3287 valueKind = VK_RValue; 3288 break; 3289 } 3290 3291 // C++ methods are l-values if static, r-values if non-static. 3292 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3293 valueKind = VK_LValue; 3294 break; 3295 } 3296 LLVM_FALLTHROUGH; 3297 3298 case Decl::CXXConversion: 3299 case Decl::CXXDestructor: 3300 case Decl::CXXConstructor: 3301 valueKind = VK_RValue; 3302 break; 3303 } 3304 3305 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3306 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3307 TemplateArgs); 3308 } 3309 } 3310 3311 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3312 SmallString<32> &Target) { 3313 Target.resize(CharByteWidth * (Source.size() + 1)); 3314 char *ResultPtr = &Target[0]; 3315 const llvm::UTF8 *ErrorPtr; 3316 bool success = 3317 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3318 (void)success; 3319 assert(success); 3320 Target.resize(ResultPtr - &Target[0]); 3321 } 3322 3323 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3324 PredefinedExpr::IdentKind IK) { 3325 // Pick the current block, lambda, captured statement or function. 3326 Decl *currentDecl = nullptr; 3327 if (const BlockScopeInfo *BSI = getCurBlock()) 3328 currentDecl = BSI->TheDecl; 3329 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3330 currentDecl = LSI->CallOperator; 3331 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3332 currentDecl = CSI->TheCapturedDecl; 3333 else 3334 currentDecl = getCurFunctionOrMethodDecl(); 3335 3336 if (!currentDecl) { 3337 Diag(Loc, diag::ext_predef_outside_function); 3338 currentDecl = Context.getTranslationUnitDecl(); 3339 } 3340 3341 QualType ResTy; 3342 StringLiteral *SL = nullptr; 3343 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3344 ResTy = Context.DependentTy; 3345 else { 3346 // Pre-defined identifiers are of type char[x], where x is the length of 3347 // the string. 3348 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3349 unsigned Length = Str.length(); 3350 3351 llvm::APInt LengthI(32, Length + 1); 3352 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3353 ResTy = 3354 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3355 SmallString<32> RawChars; 3356 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3357 Str, RawChars); 3358 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3359 ArrayType::Normal, 3360 /*IndexTypeQuals*/ 0); 3361 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3362 /*Pascal*/ false, ResTy, Loc); 3363 } else { 3364 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3365 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3366 ArrayType::Normal, 3367 /*IndexTypeQuals*/ 0); 3368 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3369 /*Pascal*/ false, ResTy, Loc); 3370 } 3371 } 3372 3373 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3374 } 3375 3376 static std::pair<QualType, StringLiteral *> 3377 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3378 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3379 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3380 3381 if (OpType->isDependentType()) { 3382 Result.first = Context.DependentTy; 3383 return Result; 3384 } 3385 3386 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3387 llvm::APInt Length(32, Str.length() + 1); 3388 Result.first = 3389 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3390 Result.first = Context.getConstantArrayType( 3391 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3392 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3393 /*Pascal*/ false, Result.first, OpLoc); 3394 return Result; 3395 } 3396 3397 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3398 TypeSourceInfo *Operand) { 3399 QualType ResultTy; 3400 StringLiteral *SL; 3401 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3402 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3403 3404 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3405 PredefinedExpr::UniqueStableNameType, SL, 3406 Operand); 3407 } 3408 3409 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3410 Expr *E) { 3411 QualType ResultTy; 3412 StringLiteral *SL; 3413 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3414 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3415 3416 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3417 PredefinedExpr::UniqueStableNameExpr, SL, E); 3418 } 3419 3420 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3421 SourceLocation L, SourceLocation R, 3422 ParsedType Ty) { 3423 TypeSourceInfo *TInfo = nullptr; 3424 QualType T = GetTypeFromParser(Ty, &TInfo); 3425 3426 if (T.isNull()) 3427 return ExprError(); 3428 if (!TInfo) 3429 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3430 3431 return BuildUniqueStableName(OpLoc, TInfo); 3432 } 3433 3434 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3435 SourceLocation L, SourceLocation R, 3436 Expr *E) { 3437 return BuildUniqueStableName(OpLoc, E); 3438 } 3439 3440 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3441 PredefinedExpr::IdentKind IK; 3442 3443 switch (Kind) { 3444 default: llvm_unreachable("Unknown simple primary expr!"); 3445 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3446 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3447 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3448 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3449 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3450 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3451 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3452 } 3453 3454 return BuildPredefinedExpr(Loc, IK); 3455 } 3456 3457 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3458 SmallString<16> CharBuffer; 3459 bool Invalid = false; 3460 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3461 if (Invalid) 3462 return ExprError(); 3463 3464 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3465 PP, Tok.getKind()); 3466 if (Literal.hadError()) 3467 return ExprError(); 3468 3469 QualType Ty; 3470 if (Literal.isWide()) 3471 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3472 else if (Literal.isUTF8() && getLangOpts().Char8) 3473 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3474 else if (Literal.isUTF16()) 3475 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3476 else if (Literal.isUTF32()) 3477 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3478 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3479 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3480 else 3481 Ty = Context.CharTy; // 'x' -> char in C++ 3482 3483 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3484 if (Literal.isWide()) 3485 Kind = CharacterLiteral::Wide; 3486 else if (Literal.isUTF16()) 3487 Kind = CharacterLiteral::UTF16; 3488 else if (Literal.isUTF32()) 3489 Kind = CharacterLiteral::UTF32; 3490 else if (Literal.isUTF8()) 3491 Kind = CharacterLiteral::UTF8; 3492 3493 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3494 Tok.getLocation()); 3495 3496 if (Literal.getUDSuffix().empty()) 3497 return Lit; 3498 3499 // We're building a user-defined literal. 3500 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3501 SourceLocation UDSuffixLoc = 3502 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3503 3504 // Make sure we're allowed user-defined literals here. 3505 if (!UDLScope) 3506 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3507 3508 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3509 // operator "" X (ch) 3510 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3511 Lit, Tok.getLocation()); 3512 } 3513 3514 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3515 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3516 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3517 Context.IntTy, Loc); 3518 } 3519 3520 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3521 QualType Ty, SourceLocation Loc) { 3522 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3523 3524 using llvm::APFloat; 3525 APFloat Val(Format); 3526 3527 APFloat::opStatus result = Literal.GetFloatValue(Val); 3528 3529 // Overflow is always an error, but underflow is only an error if 3530 // we underflowed to zero (APFloat reports denormals as underflow). 3531 if ((result & APFloat::opOverflow) || 3532 ((result & APFloat::opUnderflow) && Val.isZero())) { 3533 unsigned diagnostic; 3534 SmallString<20> buffer; 3535 if (result & APFloat::opOverflow) { 3536 diagnostic = diag::warn_float_overflow; 3537 APFloat::getLargest(Format).toString(buffer); 3538 } else { 3539 diagnostic = diag::warn_float_underflow; 3540 APFloat::getSmallest(Format).toString(buffer); 3541 } 3542 3543 S.Diag(Loc, diagnostic) 3544 << Ty 3545 << StringRef(buffer.data(), buffer.size()); 3546 } 3547 3548 bool isExact = (result == APFloat::opOK); 3549 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3550 } 3551 3552 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3553 assert(E && "Invalid expression"); 3554 3555 if (E->isValueDependent()) 3556 return false; 3557 3558 QualType QT = E->getType(); 3559 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3560 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3561 return true; 3562 } 3563 3564 llvm::APSInt ValueAPS; 3565 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3566 3567 if (R.isInvalid()) 3568 return true; 3569 3570 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3571 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3572 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3573 << ValueAPS.toString(10) << ValueIsPositive; 3574 return true; 3575 } 3576 3577 return false; 3578 } 3579 3580 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3581 // Fast path for a single digit (which is quite common). A single digit 3582 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3583 if (Tok.getLength() == 1) { 3584 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3585 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3586 } 3587 3588 SmallString<128> SpellingBuffer; 3589 // NumericLiteralParser wants to overread by one character. Add padding to 3590 // the buffer in case the token is copied to the buffer. If getSpelling() 3591 // returns a StringRef to the memory buffer, it should have a null char at 3592 // the EOF, so it is also safe. 3593 SpellingBuffer.resize(Tok.getLength() + 1); 3594 3595 // Get the spelling of the token, which eliminates trigraphs, etc. 3596 bool Invalid = false; 3597 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3598 if (Invalid) 3599 return ExprError(); 3600 3601 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3602 if (Literal.hadError) 3603 return ExprError(); 3604 3605 if (Literal.hasUDSuffix()) { 3606 // We're building a user-defined literal. 3607 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3608 SourceLocation UDSuffixLoc = 3609 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3610 3611 // Make sure we're allowed user-defined literals here. 3612 if (!UDLScope) 3613 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3614 3615 QualType CookedTy; 3616 if (Literal.isFloatingLiteral()) { 3617 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3618 // long double, the literal is treated as a call of the form 3619 // operator "" X (f L) 3620 CookedTy = Context.LongDoubleTy; 3621 } else { 3622 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3623 // unsigned long long, the literal is treated as a call of the form 3624 // operator "" X (n ULL) 3625 CookedTy = Context.UnsignedLongLongTy; 3626 } 3627 3628 DeclarationName OpName = 3629 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3630 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3631 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3632 3633 SourceLocation TokLoc = Tok.getLocation(); 3634 3635 // Perform literal operator lookup to determine if we're building a raw 3636 // literal or a cooked one. 3637 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3638 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3639 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3640 /*AllowStringTemplate*/ false, 3641 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3642 case LOLR_ErrorNoDiagnostic: 3643 // Lookup failure for imaginary constants isn't fatal, there's still the 3644 // GNU extension producing _Complex types. 3645 break; 3646 case LOLR_Error: 3647 return ExprError(); 3648 case LOLR_Cooked: { 3649 Expr *Lit; 3650 if (Literal.isFloatingLiteral()) { 3651 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3652 } else { 3653 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3654 if (Literal.GetIntegerValue(ResultVal)) 3655 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3656 << /* Unsigned */ 1; 3657 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3658 Tok.getLocation()); 3659 } 3660 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3661 } 3662 3663 case LOLR_Raw: { 3664 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3665 // literal is treated as a call of the form 3666 // operator "" X ("n") 3667 unsigned Length = Literal.getUDSuffixOffset(); 3668 QualType StrTy = Context.getConstantArrayType( 3669 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3670 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3671 Expr *Lit = StringLiteral::Create( 3672 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3673 /*Pascal*/false, StrTy, &TokLoc, 1); 3674 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3675 } 3676 3677 case LOLR_Template: { 3678 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3679 // template), L is treated as a call fo the form 3680 // operator "" X <'c1', 'c2', ... 'ck'>() 3681 // where n is the source character sequence c1 c2 ... ck. 3682 TemplateArgumentListInfo ExplicitArgs; 3683 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3684 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3685 llvm::APSInt Value(CharBits, CharIsUnsigned); 3686 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3687 Value = TokSpelling[I]; 3688 TemplateArgument Arg(Context, Value, Context.CharTy); 3689 TemplateArgumentLocInfo ArgInfo; 3690 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3691 } 3692 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3693 &ExplicitArgs); 3694 } 3695 case LOLR_StringTemplate: 3696 llvm_unreachable("unexpected literal operator lookup result"); 3697 } 3698 } 3699 3700 Expr *Res; 3701 3702 if (Literal.isFixedPointLiteral()) { 3703 QualType Ty; 3704 3705 if (Literal.isAccum) { 3706 if (Literal.isHalf) { 3707 Ty = Context.ShortAccumTy; 3708 } else if (Literal.isLong) { 3709 Ty = Context.LongAccumTy; 3710 } else { 3711 Ty = Context.AccumTy; 3712 } 3713 } else if (Literal.isFract) { 3714 if (Literal.isHalf) { 3715 Ty = Context.ShortFractTy; 3716 } else if (Literal.isLong) { 3717 Ty = Context.LongFractTy; 3718 } else { 3719 Ty = Context.FractTy; 3720 } 3721 } 3722 3723 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3724 3725 bool isSigned = !Literal.isUnsigned; 3726 unsigned scale = Context.getFixedPointScale(Ty); 3727 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3728 3729 llvm::APInt Val(bit_width, 0, isSigned); 3730 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3731 bool ValIsZero = Val.isNullValue() && !Overflowed; 3732 3733 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3734 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3735 // Clause 6.4.4 - The value of a constant shall be in the range of 3736 // representable values for its type, with exception for constants of a 3737 // fract type with a value of exactly 1; such a constant shall denote 3738 // the maximal value for the type. 3739 --Val; 3740 else if (Val.ugt(MaxVal) || Overflowed) 3741 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3742 3743 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3744 Tok.getLocation(), scale); 3745 } else if (Literal.isFloatingLiteral()) { 3746 QualType Ty; 3747 if (Literal.isHalf){ 3748 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3749 Ty = Context.HalfTy; 3750 else { 3751 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3752 return ExprError(); 3753 } 3754 } else if (Literal.isFloat) 3755 Ty = Context.FloatTy; 3756 else if (Literal.isLong) 3757 Ty = Context.LongDoubleTy; 3758 else if (Literal.isFloat16) 3759 Ty = Context.Float16Ty; 3760 else if (Literal.isFloat128) 3761 Ty = Context.Float128Ty; 3762 else 3763 Ty = Context.DoubleTy; 3764 3765 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3766 3767 if (Ty == Context.DoubleTy) { 3768 if (getLangOpts().SinglePrecisionConstants) { 3769 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3770 if (BTy->getKind() != BuiltinType::Float) { 3771 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3772 } 3773 } else if (getLangOpts().OpenCL && 3774 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3775 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3776 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3777 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3778 } 3779 } 3780 } else if (!Literal.isIntegerLiteral()) { 3781 return ExprError(); 3782 } else { 3783 QualType Ty; 3784 3785 // 'long long' is a C99 or C++11 feature. 3786 if (!getLangOpts().C99 && Literal.isLongLong) { 3787 if (getLangOpts().CPlusPlus) 3788 Diag(Tok.getLocation(), 3789 getLangOpts().CPlusPlus11 ? 3790 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3791 else 3792 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3793 } 3794 3795 // Get the value in the widest-possible width. 3796 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3797 llvm::APInt ResultVal(MaxWidth, 0); 3798 3799 if (Literal.GetIntegerValue(ResultVal)) { 3800 // If this value didn't fit into uintmax_t, error and force to ull. 3801 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3802 << /* Unsigned */ 1; 3803 Ty = Context.UnsignedLongLongTy; 3804 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3805 "long long is not intmax_t?"); 3806 } else { 3807 // If this value fits into a ULL, try to figure out what else it fits into 3808 // according to the rules of C99 6.4.4.1p5. 3809 3810 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3811 // be an unsigned int. 3812 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3813 3814 // Check from smallest to largest, picking the smallest type we can. 3815 unsigned Width = 0; 3816 3817 // Microsoft specific integer suffixes are explicitly sized. 3818 if (Literal.MicrosoftInteger) { 3819 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3820 Width = 8; 3821 Ty = Context.CharTy; 3822 } else { 3823 Width = Literal.MicrosoftInteger; 3824 Ty = Context.getIntTypeForBitwidth(Width, 3825 /*Signed=*/!Literal.isUnsigned); 3826 } 3827 } 3828 3829 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3830 // Are int/unsigned possibilities? 3831 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3832 3833 // Does it fit in a unsigned int? 3834 if (ResultVal.isIntN(IntSize)) { 3835 // Does it fit in a signed int? 3836 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3837 Ty = Context.IntTy; 3838 else if (AllowUnsigned) 3839 Ty = Context.UnsignedIntTy; 3840 Width = IntSize; 3841 } 3842 } 3843 3844 // Are long/unsigned long possibilities? 3845 if (Ty.isNull() && !Literal.isLongLong) { 3846 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3847 3848 // Does it fit in a unsigned long? 3849 if (ResultVal.isIntN(LongSize)) { 3850 // Does it fit in a signed long? 3851 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3852 Ty = Context.LongTy; 3853 else if (AllowUnsigned) 3854 Ty = Context.UnsignedLongTy; 3855 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3856 // is compatible. 3857 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3858 const unsigned LongLongSize = 3859 Context.getTargetInfo().getLongLongWidth(); 3860 Diag(Tok.getLocation(), 3861 getLangOpts().CPlusPlus 3862 ? Literal.isLong 3863 ? diag::warn_old_implicitly_unsigned_long_cxx 3864 : /*C++98 UB*/ diag:: 3865 ext_old_implicitly_unsigned_long_cxx 3866 : diag::warn_old_implicitly_unsigned_long) 3867 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3868 : /*will be ill-formed*/ 1); 3869 Ty = Context.UnsignedLongTy; 3870 } 3871 Width = LongSize; 3872 } 3873 } 3874 3875 // Check long long if needed. 3876 if (Ty.isNull()) { 3877 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3878 3879 // Does it fit in a unsigned long long? 3880 if (ResultVal.isIntN(LongLongSize)) { 3881 // Does it fit in a signed long long? 3882 // To be compatible with MSVC, hex integer literals ending with the 3883 // LL or i64 suffix are always signed in Microsoft mode. 3884 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3885 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3886 Ty = Context.LongLongTy; 3887 else if (AllowUnsigned) 3888 Ty = Context.UnsignedLongLongTy; 3889 Width = LongLongSize; 3890 } 3891 } 3892 3893 // If we still couldn't decide a type, we probably have something that 3894 // does not fit in a signed long long, but has no U suffix. 3895 if (Ty.isNull()) { 3896 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3897 Ty = Context.UnsignedLongLongTy; 3898 Width = Context.getTargetInfo().getLongLongWidth(); 3899 } 3900 3901 if (ResultVal.getBitWidth() != Width) 3902 ResultVal = ResultVal.trunc(Width); 3903 } 3904 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3905 } 3906 3907 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3908 if (Literal.isImaginary) { 3909 Res = new (Context) ImaginaryLiteral(Res, 3910 Context.getComplexType(Res->getType())); 3911 3912 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3913 } 3914 return Res; 3915 } 3916 3917 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3918 assert(E && "ActOnParenExpr() missing expr"); 3919 return new (Context) ParenExpr(L, R, E); 3920 } 3921 3922 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3923 SourceLocation Loc, 3924 SourceRange ArgRange) { 3925 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3926 // scalar or vector data type argument..." 3927 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3928 // type (C99 6.2.5p18) or void. 3929 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3930 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3931 << T << ArgRange; 3932 return true; 3933 } 3934 3935 assert((T->isVoidType() || !T->isIncompleteType()) && 3936 "Scalar types should always be complete"); 3937 return false; 3938 } 3939 3940 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3941 SourceLocation Loc, 3942 SourceRange ArgRange, 3943 UnaryExprOrTypeTrait TraitKind) { 3944 // Invalid types must be hard errors for SFINAE in C++. 3945 if (S.LangOpts.CPlusPlus) 3946 return true; 3947 3948 // C99 6.5.3.4p1: 3949 if (T->isFunctionType() && 3950 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3951 TraitKind == UETT_PreferredAlignOf)) { 3952 // sizeof(function)/alignof(function) is allowed as an extension. 3953 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3954 << TraitKind << ArgRange; 3955 return false; 3956 } 3957 3958 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3959 // this is an error (OpenCL v1.1 s6.3.k) 3960 if (T->isVoidType()) { 3961 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3962 : diag::ext_sizeof_alignof_void_type; 3963 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3964 return false; 3965 } 3966 3967 return true; 3968 } 3969 3970 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3971 SourceLocation Loc, 3972 SourceRange ArgRange, 3973 UnaryExprOrTypeTrait TraitKind) { 3974 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3975 // runtime doesn't allow it. 3976 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3977 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3978 << T << (TraitKind == UETT_SizeOf) 3979 << ArgRange; 3980 return true; 3981 } 3982 3983 return false; 3984 } 3985 3986 /// Check whether E is a pointer from a decayed array type (the decayed 3987 /// pointer type is equal to T) and emit a warning if it is. 3988 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3989 Expr *E) { 3990 // Don't warn if the operation changed the type. 3991 if (T != E->getType()) 3992 return; 3993 3994 // Now look for array decays. 3995 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3996 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3997 return; 3998 3999 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4000 << ICE->getType() 4001 << ICE->getSubExpr()->getType(); 4002 } 4003 4004 /// Check the constraints on expression operands to unary type expression 4005 /// and type traits. 4006 /// 4007 /// Completes any types necessary and validates the constraints on the operand 4008 /// expression. The logic mostly mirrors the type-based overload, but may modify 4009 /// the expression as it completes the type for that expression through template 4010 /// instantiation, etc. 4011 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4012 UnaryExprOrTypeTrait ExprKind) { 4013 QualType ExprTy = E->getType(); 4014 assert(!ExprTy->isReferenceType()); 4015 4016 bool IsUnevaluatedOperand = 4017 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4018 ExprKind == UETT_PreferredAlignOf); 4019 if (IsUnevaluatedOperand) { 4020 ExprResult Result = CheckUnevaluatedOperand(E); 4021 if (Result.isInvalid()) 4022 return true; 4023 E = Result.get(); 4024 } 4025 4026 if (ExprKind == UETT_VecStep) 4027 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4028 E->getSourceRange()); 4029 4030 // Whitelist some types as extensions 4031 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4032 E->getSourceRange(), ExprKind)) 4033 return false; 4034 4035 // 'alignof' applied to an expression only requires the base element type of 4036 // the expression to be complete. 'sizeof' requires the expression's type to 4037 // be complete (and will attempt to complete it if it's an array of unknown 4038 // bound). 4039 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4040 if (RequireCompleteSizedType( 4041 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4042 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4043 E->getSourceRange())) 4044 return true; 4045 } else { 4046 if (RequireCompleteSizedExprType( 4047 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4048 E->getSourceRange())) 4049 return true; 4050 } 4051 4052 // Completing the expression's type may have changed it. 4053 ExprTy = E->getType(); 4054 assert(!ExprTy->isReferenceType()); 4055 4056 if (ExprTy->isFunctionType()) { 4057 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4058 << ExprKind << E->getSourceRange(); 4059 return true; 4060 } 4061 4062 // The operand for sizeof and alignof is in an unevaluated expression context, 4063 // so side effects could result in unintended consequences. 4064 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4065 E->HasSideEffects(Context, false)) 4066 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4067 4068 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4069 E->getSourceRange(), ExprKind)) 4070 return true; 4071 4072 if (ExprKind == UETT_SizeOf) { 4073 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4074 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4075 QualType OType = PVD->getOriginalType(); 4076 QualType Type = PVD->getType(); 4077 if (Type->isPointerType() && OType->isArrayType()) { 4078 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4079 << Type << OType; 4080 Diag(PVD->getLocation(), diag::note_declared_at); 4081 } 4082 } 4083 } 4084 4085 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4086 // decays into a pointer and returns an unintended result. This is most 4087 // likely a typo for "sizeof(array) op x". 4088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4089 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4090 BO->getLHS()); 4091 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4092 BO->getRHS()); 4093 } 4094 } 4095 4096 return false; 4097 } 4098 4099 /// Check the constraints on operands to unary expression and type 4100 /// traits. 4101 /// 4102 /// This will complete any types necessary, and validate the various constraints 4103 /// on those operands. 4104 /// 4105 /// The UsualUnaryConversions() function is *not* called by this routine. 4106 /// C99 6.3.2.1p[2-4] all state: 4107 /// Except when it is the operand of the sizeof operator ... 4108 /// 4109 /// C++ [expr.sizeof]p4 4110 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4111 /// standard conversions are not applied to the operand of sizeof. 4112 /// 4113 /// This policy is followed for all of the unary trait expressions. 4114 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4115 SourceLocation OpLoc, 4116 SourceRange ExprRange, 4117 UnaryExprOrTypeTrait ExprKind) { 4118 if (ExprType->isDependentType()) 4119 return false; 4120 4121 // C++ [expr.sizeof]p2: 4122 // When applied to a reference or a reference type, the result 4123 // is the size of the referenced type. 4124 // C++11 [expr.alignof]p3: 4125 // When alignof is applied to a reference type, the result 4126 // shall be the alignment of the referenced type. 4127 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4128 ExprType = Ref->getPointeeType(); 4129 4130 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4131 // When alignof or _Alignof is applied to an array type, the result 4132 // is the alignment of the element type. 4133 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4134 ExprKind == UETT_OpenMPRequiredSimdAlign) 4135 ExprType = Context.getBaseElementType(ExprType); 4136 4137 if (ExprKind == UETT_VecStep) 4138 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4139 4140 // Whitelist some types as extensions 4141 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4142 ExprKind)) 4143 return false; 4144 4145 if (RequireCompleteSizedType( 4146 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4147 ExprKind, ExprRange)) 4148 return true; 4149 4150 if (ExprType->isFunctionType()) { 4151 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4152 << ExprKind << ExprRange; 4153 return true; 4154 } 4155 4156 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4157 ExprKind)) 4158 return true; 4159 4160 return false; 4161 } 4162 4163 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4164 // Cannot know anything else if the expression is dependent. 4165 if (E->isTypeDependent()) 4166 return false; 4167 4168 if (E->getObjectKind() == OK_BitField) { 4169 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4170 << 1 << E->getSourceRange(); 4171 return true; 4172 } 4173 4174 ValueDecl *D = nullptr; 4175 Expr *Inner = E->IgnoreParens(); 4176 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4177 D = DRE->getDecl(); 4178 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4179 D = ME->getMemberDecl(); 4180 } 4181 4182 // If it's a field, require the containing struct to have a 4183 // complete definition so that we can compute the layout. 4184 // 4185 // This can happen in C++11 onwards, either by naming the member 4186 // in a way that is not transformed into a member access expression 4187 // (in an unevaluated operand, for instance), or by naming the member 4188 // in a trailing-return-type. 4189 // 4190 // For the record, since __alignof__ on expressions is a GCC 4191 // extension, GCC seems to permit this but always gives the 4192 // nonsensical answer 0. 4193 // 4194 // We don't really need the layout here --- we could instead just 4195 // directly check for all the appropriate alignment-lowing 4196 // attributes --- but that would require duplicating a lot of 4197 // logic that just isn't worth duplicating for such a marginal 4198 // use-case. 4199 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4200 // Fast path this check, since we at least know the record has a 4201 // definition if we can find a member of it. 4202 if (!FD->getParent()->isCompleteDefinition()) { 4203 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4204 << E->getSourceRange(); 4205 return true; 4206 } 4207 4208 // Otherwise, if it's a field, and the field doesn't have 4209 // reference type, then it must have a complete type (or be a 4210 // flexible array member, which we explicitly want to 4211 // white-list anyway), which makes the following checks trivial. 4212 if (!FD->getType()->isReferenceType()) 4213 return false; 4214 } 4215 4216 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4217 } 4218 4219 bool Sema::CheckVecStepExpr(Expr *E) { 4220 E = E->IgnoreParens(); 4221 4222 // Cannot know anything else if the expression is dependent. 4223 if (E->isTypeDependent()) 4224 return false; 4225 4226 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4227 } 4228 4229 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4230 CapturingScopeInfo *CSI) { 4231 assert(T->isVariablyModifiedType()); 4232 assert(CSI != nullptr); 4233 4234 // We're going to walk down into the type and look for VLA expressions. 4235 do { 4236 const Type *Ty = T.getTypePtr(); 4237 switch (Ty->getTypeClass()) { 4238 #define TYPE(Class, Base) 4239 #define ABSTRACT_TYPE(Class, Base) 4240 #define NON_CANONICAL_TYPE(Class, Base) 4241 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4242 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4243 #include "clang/AST/TypeNodes.inc" 4244 T = QualType(); 4245 break; 4246 // These types are never variably-modified. 4247 case Type::Builtin: 4248 case Type::Complex: 4249 case Type::Vector: 4250 case Type::ExtVector: 4251 case Type::Record: 4252 case Type::Enum: 4253 case Type::Elaborated: 4254 case Type::TemplateSpecialization: 4255 case Type::ObjCObject: 4256 case Type::ObjCInterface: 4257 case Type::ObjCObjectPointer: 4258 case Type::ObjCTypeParam: 4259 case Type::Pipe: 4260 llvm_unreachable("type class is never variably-modified!"); 4261 case Type::Adjusted: 4262 T = cast<AdjustedType>(Ty)->getOriginalType(); 4263 break; 4264 case Type::Decayed: 4265 T = cast<DecayedType>(Ty)->getPointeeType(); 4266 break; 4267 case Type::Pointer: 4268 T = cast<PointerType>(Ty)->getPointeeType(); 4269 break; 4270 case Type::BlockPointer: 4271 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4272 break; 4273 case Type::LValueReference: 4274 case Type::RValueReference: 4275 T = cast<ReferenceType>(Ty)->getPointeeType(); 4276 break; 4277 case Type::MemberPointer: 4278 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4279 break; 4280 case Type::ConstantArray: 4281 case Type::IncompleteArray: 4282 // Losing element qualification here is fine. 4283 T = cast<ArrayType>(Ty)->getElementType(); 4284 break; 4285 case Type::VariableArray: { 4286 // Losing element qualification here is fine. 4287 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4288 4289 // Unknown size indication requires no size computation. 4290 // Otherwise, evaluate and record it. 4291 auto Size = VAT->getSizeExpr(); 4292 if (Size && !CSI->isVLATypeCaptured(VAT) && 4293 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4294 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4295 4296 T = VAT->getElementType(); 4297 break; 4298 } 4299 case Type::FunctionProto: 4300 case Type::FunctionNoProto: 4301 T = cast<FunctionType>(Ty)->getReturnType(); 4302 break; 4303 case Type::Paren: 4304 case Type::TypeOf: 4305 case Type::UnaryTransform: 4306 case Type::Attributed: 4307 case Type::SubstTemplateTypeParm: 4308 case Type::PackExpansion: 4309 case Type::MacroQualified: 4310 // Keep walking after single level desugaring. 4311 T = T.getSingleStepDesugaredType(Context); 4312 break; 4313 case Type::Typedef: 4314 T = cast<TypedefType>(Ty)->desugar(); 4315 break; 4316 case Type::Decltype: 4317 T = cast<DecltypeType>(Ty)->desugar(); 4318 break; 4319 case Type::Auto: 4320 case Type::DeducedTemplateSpecialization: 4321 T = cast<DeducedType>(Ty)->getDeducedType(); 4322 break; 4323 case Type::TypeOfExpr: 4324 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4325 break; 4326 case Type::Atomic: 4327 T = cast<AtomicType>(Ty)->getValueType(); 4328 break; 4329 } 4330 } while (!T.isNull() && T->isVariablyModifiedType()); 4331 } 4332 4333 /// Build a sizeof or alignof expression given a type operand. 4334 ExprResult 4335 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4336 SourceLocation OpLoc, 4337 UnaryExprOrTypeTrait ExprKind, 4338 SourceRange R) { 4339 if (!TInfo) 4340 return ExprError(); 4341 4342 QualType T = TInfo->getType(); 4343 4344 if (!T->isDependentType() && 4345 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4346 return ExprError(); 4347 4348 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4349 if (auto *TT = T->getAs<TypedefType>()) { 4350 for (auto I = FunctionScopes.rbegin(), 4351 E = std::prev(FunctionScopes.rend()); 4352 I != E; ++I) { 4353 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4354 if (CSI == nullptr) 4355 break; 4356 DeclContext *DC = nullptr; 4357 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4358 DC = LSI->CallOperator; 4359 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4360 DC = CRSI->TheCapturedDecl; 4361 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4362 DC = BSI->TheDecl; 4363 if (DC) { 4364 if (DC->containsDecl(TT->getDecl())) 4365 break; 4366 captureVariablyModifiedType(Context, T, CSI); 4367 } 4368 } 4369 } 4370 } 4371 4372 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4373 return new (Context) UnaryExprOrTypeTraitExpr( 4374 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4375 } 4376 4377 /// Build a sizeof or alignof expression given an expression 4378 /// operand. 4379 ExprResult 4380 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4381 UnaryExprOrTypeTrait ExprKind) { 4382 ExprResult PE = CheckPlaceholderExpr(E); 4383 if (PE.isInvalid()) 4384 return ExprError(); 4385 4386 E = PE.get(); 4387 4388 // Verify that the operand is valid. 4389 bool isInvalid = false; 4390 if (E->isTypeDependent()) { 4391 // Delay type-checking for type-dependent expressions. 4392 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4393 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4394 } else if (ExprKind == UETT_VecStep) { 4395 isInvalid = CheckVecStepExpr(E); 4396 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4397 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4398 isInvalid = true; 4399 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4400 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4401 isInvalid = true; 4402 } else { 4403 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4404 } 4405 4406 if (isInvalid) 4407 return ExprError(); 4408 4409 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4410 PE = TransformToPotentiallyEvaluated(E); 4411 if (PE.isInvalid()) return ExprError(); 4412 E = PE.get(); 4413 } 4414 4415 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4416 return new (Context) UnaryExprOrTypeTraitExpr( 4417 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4418 } 4419 4420 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4421 /// expr and the same for @c alignof and @c __alignof 4422 /// Note that the ArgRange is invalid if isType is false. 4423 ExprResult 4424 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4425 UnaryExprOrTypeTrait ExprKind, bool IsType, 4426 void *TyOrEx, SourceRange ArgRange) { 4427 // If error parsing type, ignore. 4428 if (!TyOrEx) return ExprError(); 4429 4430 if (IsType) { 4431 TypeSourceInfo *TInfo; 4432 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4433 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4434 } 4435 4436 Expr *ArgEx = (Expr *)TyOrEx; 4437 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4438 return Result; 4439 } 4440 4441 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4442 bool IsReal) { 4443 if (V.get()->isTypeDependent()) 4444 return S.Context.DependentTy; 4445 4446 // _Real and _Imag are only l-values for normal l-values. 4447 if (V.get()->getObjectKind() != OK_Ordinary) { 4448 V = S.DefaultLvalueConversion(V.get()); 4449 if (V.isInvalid()) 4450 return QualType(); 4451 } 4452 4453 // These operators return the element type of a complex type. 4454 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4455 return CT->getElementType(); 4456 4457 // Otherwise they pass through real integer and floating point types here. 4458 if (V.get()->getType()->isArithmeticType()) 4459 return V.get()->getType(); 4460 4461 // Test for placeholders. 4462 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4463 if (PR.isInvalid()) return QualType(); 4464 if (PR.get() != V.get()) { 4465 V = PR; 4466 return CheckRealImagOperand(S, V, Loc, IsReal); 4467 } 4468 4469 // Reject anything else. 4470 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4471 << (IsReal ? "__real" : "__imag"); 4472 return QualType(); 4473 } 4474 4475 4476 4477 ExprResult 4478 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4479 tok::TokenKind Kind, Expr *Input) { 4480 UnaryOperatorKind Opc; 4481 switch (Kind) { 4482 default: llvm_unreachable("Unknown unary op!"); 4483 case tok::plusplus: Opc = UO_PostInc; break; 4484 case tok::minusminus: Opc = UO_PostDec; break; 4485 } 4486 4487 // Since this might is a postfix expression, get rid of ParenListExprs. 4488 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4489 if (Result.isInvalid()) return ExprError(); 4490 Input = Result.get(); 4491 4492 return BuildUnaryOp(S, OpLoc, Opc, Input); 4493 } 4494 4495 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4496 /// 4497 /// \return true on error 4498 static bool checkArithmeticOnObjCPointer(Sema &S, 4499 SourceLocation opLoc, 4500 Expr *op) { 4501 assert(op->getType()->isObjCObjectPointerType()); 4502 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4503 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4504 return false; 4505 4506 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4507 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4508 << op->getSourceRange(); 4509 return true; 4510 } 4511 4512 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4513 auto *BaseNoParens = Base->IgnoreParens(); 4514 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4515 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4516 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4517 } 4518 4519 ExprResult 4520 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4521 Expr *idx, SourceLocation rbLoc) { 4522 if (base && !base->getType().isNull() && 4523 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4524 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4525 /*Length=*/nullptr, rbLoc); 4526 4527 // Since this might be a postfix expression, get rid of ParenListExprs. 4528 if (isa<ParenListExpr>(base)) { 4529 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4530 if (result.isInvalid()) return ExprError(); 4531 base = result.get(); 4532 } 4533 4534 // A comma-expression as the index is deprecated in C++2a onwards. 4535 if (getLangOpts().CPlusPlus2a && 4536 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4537 (isa<CXXOperatorCallExpr>(idx) && 4538 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4539 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4540 << SourceRange(base->getBeginLoc(), rbLoc); 4541 } 4542 4543 // Handle any non-overload placeholder types in the base and index 4544 // expressions. We can't handle overloads here because the other 4545 // operand might be an overloadable type, in which case the overload 4546 // resolution for the operator overload should get the first crack 4547 // at the overload. 4548 bool IsMSPropertySubscript = false; 4549 if (base->getType()->isNonOverloadPlaceholderType()) { 4550 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4551 if (!IsMSPropertySubscript) { 4552 ExprResult result = CheckPlaceholderExpr(base); 4553 if (result.isInvalid()) 4554 return ExprError(); 4555 base = result.get(); 4556 } 4557 } 4558 if (idx->getType()->isNonOverloadPlaceholderType()) { 4559 ExprResult result = CheckPlaceholderExpr(idx); 4560 if (result.isInvalid()) return ExprError(); 4561 idx = result.get(); 4562 } 4563 4564 // Build an unanalyzed expression if either operand is type-dependent. 4565 if (getLangOpts().CPlusPlus && 4566 (base->isTypeDependent() || idx->isTypeDependent())) { 4567 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4568 VK_LValue, OK_Ordinary, rbLoc); 4569 } 4570 4571 // MSDN, property (C++) 4572 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4573 // This attribute can also be used in the declaration of an empty array in a 4574 // class or structure definition. For example: 4575 // __declspec(property(get=GetX, put=PutX)) int x[]; 4576 // The above statement indicates that x[] can be used with one or more array 4577 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4578 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4579 if (IsMSPropertySubscript) { 4580 // Build MS property subscript expression if base is MS property reference 4581 // or MS property subscript. 4582 return new (Context) MSPropertySubscriptExpr( 4583 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4584 } 4585 4586 // Use C++ overloaded-operator rules if either operand has record 4587 // type. The spec says to do this if either type is *overloadable*, 4588 // but enum types can't declare subscript operators or conversion 4589 // operators, so there's nothing interesting for overload resolution 4590 // to do if there aren't any record types involved. 4591 // 4592 // ObjC pointers have their own subscripting logic that is not tied 4593 // to overload resolution and so should not take this path. 4594 if (getLangOpts().CPlusPlus && 4595 (base->getType()->isRecordType() || 4596 (!base->getType()->isObjCObjectPointerType() && 4597 idx->getType()->isRecordType()))) { 4598 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4599 } 4600 4601 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4602 4603 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4604 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4605 4606 return Res; 4607 } 4608 4609 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4610 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4611 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4612 4613 // For expressions like `&(*s).b`, the base is recorded and what should be 4614 // checked. 4615 const MemberExpr *Member = nullptr; 4616 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4617 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4618 4619 LastRecord.PossibleDerefs.erase(StrippedExpr); 4620 } 4621 4622 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4623 QualType ResultTy = E->getType(); 4624 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4625 4626 // Bail if the element is an array since it is not memory access. 4627 if (isa<ArrayType>(ResultTy)) 4628 return; 4629 4630 if (ResultTy->hasAttr(attr::NoDeref)) { 4631 LastRecord.PossibleDerefs.insert(E); 4632 return; 4633 } 4634 4635 // Check if the base type is a pointer to a member access of a struct 4636 // marked with noderef. 4637 const Expr *Base = E->getBase(); 4638 QualType BaseTy = Base->getType(); 4639 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4640 // Not a pointer access 4641 return; 4642 4643 const MemberExpr *Member = nullptr; 4644 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4645 Member->isArrow()) 4646 Base = Member->getBase(); 4647 4648 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4649 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4650 LastRecord.PossibleDerefs.insert(E); 4651 } 4652 } 4653 4654 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4655 Expr *LowerBound, 4656 SourceLocation ColonLoc, Expr *Length, 4657 SourceLocation RBLoc) { 4658 if (Base->getType()->isPlaceholderType() && 4659 !Base->getType()->isSpecificPlaceholderType( 4660 BuiltinType::OMPArraySection)) { 4661 ExprResult Result = CheckPlaceholderExpr(Base); 4662 if (Result.isInvalid()) 4663 return ExprError(); 4664 Base = Result.get(); 4665 } 4666 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4667 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4668 if (Result.isInvalid()) 4669 return ExprError(); 4670 Result = DefaultLvalueConversion(Result.get()); 4671 if (Result.isInvalid()) 4672 return ExprError(); 4673 LowerBound = Result.get(); 4674 } 4675 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4676 ExprResult Result = CheckPlaceholderExpr(Length); 4677 if (Result.isInvalid()) 4678 return ExprError(); 4679 Result = DefaultLvalueConversion(Result.get()); 4680 if (Result.isInvalid()) 4681 return ExprError(); 4682 Length = Result.get(); 4683 } 4684 4685 // Build an unanalyzed expression if either operand is type-dependent. 4686 if (Base->isTypeDependent() || 4687 (LowerBound && 4688 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4689 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4690 return new (Context) 4691 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4692 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4693 } 4694 4695 // Perform default conversions. 4696 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4697 QualType ResultTy; 4698 if (OriginalTy->isAnyPointerType()) { 4699 ResultTy = OriginalTy->getPointeeType(); 4700 } else if (OriginalTy->isArrayType()) { 4701 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4702 } else { 4703 return ExprError( 4704 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4705 << Base->getSourceRange()); 4706 } 4707 // C99 6.5.2.1p1 4708 if (LowerBound) { 4709 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4710 LowerBound); 4711 if (Res.isInvalid()) 4712 return ExprError(Diag(LowerBound->getExprLoc(), 4713 diag::err_omp_typecheck_section_not_integer) 4714 << 0 << LowerBound->getSourceRange()); 4715 LowerBound = Res.get(); 4716 4717 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4718 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4719 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4720 << 0 << LowerBound->getSourceRange(); 4721 } 4722 if (Length) { 4723 auto Res = 4724 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4725 if (Res.isInvalid()) 4726 return ExprError(Diag(Length->getExprLoc(), 4727 diag::err_omp_typecheck_section_not_integer) 4728 << 1 << Length->getSourceRange()); 4729 Length = Res.get(); 4730 4731 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4732 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4733 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4734 << 1 << Length->getSourceRange(); 4735 } 4736 4737 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4738 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4739 // type. Note that functions are not objects, and that (in C99 parlance) 4740 // incomplete types are not object types. 4741 if (ResultTy->isFunctionType()) { 4742 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4743 << ResultTy << Base->getSourceRange(); 4744 return ExprError(); 4745 } 4746 4747 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4748 diag::err_omp_section_incomplete_type, Base)) 4749 return ExprError(); 4750 4751 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4752 Expr::EvalResult Result; 4753 if (LowerBound->EvaluateAsInt(Result, Context)) { 4754 // OpenMP 4.5, [2.4 Array Sections] 4755 // The array section must be a subset of the original array. 4756 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4757 if (LowerBoundValue.isNegative()) { 4758 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4759 << LowerBound->getSourceRange(); 4760 return ExprError(); 4761 } 4762 } 4763 } 4764 4765 if (Length) { 4766 Expr::EvalResult Result; 4767 if (Length->EvaluateAsInt(Result, Context)) { 4768 // OpenMP 4.5, [2.4 Array Sections] 4769 // The length must evaluate to non-negative integers. 4770 llvm::APSInt LengthValue = Result.Val.getInt(); 4771 if (LengthValue.isNegative()) { 4772 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4773 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4774 << Length->getSourceRange(); 4775 return ExprError(); 4776 } 4777 } 4778 } else if (ColonLoc.isValid() && 4779 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4780 !OriginalTy->isVariableArrayType()))) { 4781 // OpenMP 4.5, [2.4 Array Sections] 4782 // When the size of the array dimension is not known, the length must be 4783 // specified explicitly. 4784 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4785 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4786 return ExprError(); 4787 } 4788 4789 if (!Base->getType()->isSpecificPlaceholderType( 4790 BuiltinType::OMPArraySection)) { 4791 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4792 if (Result.isInvalid()) 4793 return ExprError(); 4794 Base = Result.get(); 4795 } 4796 return new (Context) 4797 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4798 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4799 } 4800 4801 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4802 SourceLocation RParenLoc, 4803 ArrayRef<Expr *> Dims, 4804 ArrayRef<SourceRange> Brackets) { 4805 if (Base->getType()->isPlaceholderType()) { 4806 ExprResult Result = CheckPlaceholderExpr(Base); 4807 if (Result.isInvalid()) 4808 return ExprError(); 4809 Result = DefaultLvalueConversion(Result.get()); 4810 if (Result.isInvalid()) 4811 return ExprError(); 4812 Base = Result.get(); 4813 } 4814 QualType BaseTy = Base->getType(); 4815 // Delay analysis of the types/expressions if instantiation/specialization is 4816 // required. 4817 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4818 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4819 LParenLoc, RParenLoc, Dims, Brackets); 4820 if (!BaseTy->isPointerType() || 4821 (!Base->isTypeDependent() && 4822 BaseTy->getPointeeType()->isIncompleteType())) 4823 return ExprError(Diag(Base->getExprLoc(), 4824 diag::err_omp_non_pointer_type_array_shaping_base) 4825 << Base->getSourceRange()); 4826 4827 SmallVector<Expr *, 4> NewDims; 4828 bool ErrorFound = false; 4829 for (Expr *Dim : Dims) { 4830 if (Dim->getType()->isPlaceholderType()) { 4831 ExprResult Result = CheckPlaceholderExpr(Dim); 4832 if (Result.isInvalid()) { 4833 ErrorFound = true; 4834 continue; 4835 } 4836 Result = DefaultLvalueConversion(Result.get()); 4837 if (Result.isInvalid()) { 4838 ErrorFound = true; 4839 continue; 4840 } 4841 Dim = Result.get(); 4842 } 4843 if (!Dim->isTypeDependent()) { 4844 ExprResult Result = 4845 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4846 if (Result.isInvalid()) { 4847 ErrorFound = true; 4848 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 4849 << Dim->getSourceRange(); 4850 continue; 4851 } 4852 Dim = Result.get(); 4853 Expr::EvalResult EvResult; 4854 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 4855 // OpenMP 5.0, [2.1.4 Array Shaping] 4856 // Each si is an integral type expression that must evaluate to a 4857 // positive integer. 4858 llvm::APSInt Value = EvResult.Val.getInt(); 4859 if (!Value.isStrictlyPositive()) { 4860 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 4861 << Value.toString(/*Radix=*/10, /*Signed=*/true) 4862 << Dim->getSourceRange(); 4863 ErrorFound = true; 4864 continue; 4865 } 4866 } 4867 } 4868 NewDims.push_back(Dim); 4869 } 4870 if (ErrorFound) 4871 return ExprError(); 4872 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 4873 LParenLoc, RParenLoc, NewDims, Brackets); 4874 } 4875 4876 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 4877 SourceLocation LLoc, SourceLocation RLoc, 4878 ArrayRef<OMPIteratorData> Data) { 4879 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 4880 bool IsCorrect = true; 4881 for (const OMPIteratorData &D : Data) { 4882 TypeSourceInfo *TInfo = nullptr; 4883 SourceLocation StartLoc; 4884 QualType DeclTy; 4885 if (!D.Type.getAsOpaquePtr()) { 4886 // OpenMP 5.0, 2.1.6 Iterators 4887 // In an iterator-specifier, if the iterator-type is not specified then 4888 // the type of that iterator is of int type. 4889 DeclTy = Context.IntTy; 4890 StartLoc = D.DeclIdentLoc; 4891 } else { 4892 DeclTy = GetTypeFromParser(D.Type, &TInfo); 4893 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 4894 } 4895 4896 bool IsDeclTyDependent = DeclTy->isDependentType() || 4897 DeclTy->containsUnexpandedParameterPack() || 4898 DeclTy->isInstantiationDependentType(); 4899 if (!IsDeclTyDependent) { 4900 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 4901 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4902 // The iterator-type must be an integral or pointer type. 4903 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4904 << DeclTy; 4905 IsCorrect = false; 4906 continue; 4907 } 4908 if (DeclTy.isConstant(Context)) { 4909 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4910 // The iterator-type must not be const qualified. 4911 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4912 << DeclTy; 4913 IsCorrect = false; 4914 continue; 4915 } 4916 } 4917 4918 // Iterator declaration. 4919 assert(D.DeclIdent && "Identifier expected."); 4920 // Always try to create iterator declarator to avoid extra error messages 4921 // about unknown declarations use. 4922 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 4923 D.DeclIdent, DeclTy, TInfo, SC_None); 4924 VD->setImplicit(); 4925 if (S) { 4926 // Check for conflicting previous declaration. 4927 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 4928 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4929 ForVisibleRedeclaration); 4930 Previous.suppressDiagnostics(); 4931 LookupName(Previous, S); 4932 4933 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 4934 /*AllowInlineNamespace=*/false); 4935 if (!Previous.empty()) { 4936 NamedDecl *Old = Previous.getRepresentativeDecl(); 4937 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 4938 Diag(Old->getLocation(), diag::note_previous_definition); 4939 } else { 4940 PushOnScopeChains(VD, S); 4941 } 4942 } else { 4943 CurContext->addDecl(VD); 4944 } 4945 Expr *Begin = D.Range.Begin; 4946 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 4947 ExprResult BeginRes = 4948 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 4949 Begin = BeginRes.get(); 4950 } 4951 Expr *End = D.Range.End; 4952 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 4953 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 4954 End = EndRes.get(); 4955 } 4956 Expr *Step = D.Range.Step; 4957 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 4958 if (!Step->getType()->isIntegralType(Context)) { 4959 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 4960 << Step << Step->getSourceRange(); 4961 IsCorrect = false; 4962 continue; 4963 } 4964 llvm::APSInt Result; 4965 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 4966 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 4967 // If the step expression of a range-specification equals zero, the 4968 // behavior is unspecified. 4969 if (IsConstant && Result.isNullValue()) { 4970 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 4971 << Step << Step->getSourceRange(); 4972 IsCorrect = false; 4973 continue; 4974 } 4975 } 4976 if (!Begin || !End || !IsCorrect) { 4977 IsCorrect = false; 4978 continue; 4979 } 4980 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 4981 IDElem.IteratorDecl = VD; 4982 IDElem.AssignmentLoc = D.AssignLoc; 4983 IDElem.Range.Begin = Begin; 4984 IDElem.Range.End = End; 4985 IDElem.Range.Step = Step; 4986 IDElem.ColonLoc = D.ColonLoc; 4987 IDElem.SecondColonLoc = D.SecColonLoc; 4988 } 4989 if (!IsCorrect) { 4990 // Invalidate all created iterator declarations if error is found. 4991 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 4992 if (Decl *ID = D.IteratorDecl) 4993 ID->setInvalidDecl(); 4994 } 4995 return ExprError(); 4996 } 4997 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 4998 LLoc, RLoc, ID); 4999 } 5000 5001 ExprResult 5002 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5003 Expr *Idx, SourceLocation RLoc) { 5004 Expr *LHSExp = Base; 5005 Expr *RHSExp = Idx; 5006 5007 ExprValueKind VK = VK_LValue; 5008 ExprObjectKind OK = OK_Ordinary; 5009 5010 // Per C++ core issue 1213, the result is an xvalue if either operand is 5011 // a non-lvalue array, and an lvalue otherwise. 5012 if (getLangOpts().CPlusPlus11) { 5013 for (auto *Op : {LHSExp, RHSExp}) { 5014 Op = Op->IgnoreImplicit(); 5015 if (Op->getType()->isArrayType() && !Op->isLValue()) 5016 VK = VK_XValue; 5017 } 5018 } 5019 5020 // Perform default conversions. 5021 if (!LHSExp->getType()->getAs<VectorType>()) { 5022 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5023 if (Result.isInvalid()) 5024 return ExprError(); 5025 LHSExp = Result.get(); 5026 } 5027 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5028 if (Result.isInvalid()) 5029 return ExprError(); 5030 RHSExp = Result.get(); 5031 5032 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5033 5034 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5035 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5036 // in the subscript position. As a result, we need to derive the array base 5037 // and index from the expression types. 5038 Expr *BaseExpr, *IndexExpr; 5039 QualType ResultType; 5040 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5041 BaseExpr = LHSExp; 5042 IndexExpr = RHSExp; 5043 ResultType = Context.DependentTy; 5044 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5045 BaseExpr = LHSExp; 5046 IndexExpr = RHSExp; 5047 ResultType = PTy->getPointeeType(); 5048 } else if (const ObjCObjectPointerType *PTy = 5049 LHSTy->getAs<ObjCObjectPointerType>()) { 5050 BaseExpr = LHSExp; 5051 IndexExpr = RHSExp; 5052 5053 // Use custom logic if this should be the pseudo-object subscript 5054 // expression. 5055 if (!LangOpts.isSubscriptPointerArithmetic()) 5056 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5057 nullptr); 5058 5059 ResultType = PTy->getPointeeType(); 5060 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5061 // Handle the uncommon case of "123[Ptr]". 5062 BaseExpr = RHSExp; 5063 IndexExpr = LHSExp; 5064 ResultType = PTy->getPointeeType(); 5065 } else if (const ObjCObjectPointerType *PTy = 5066 RHSTy->getAs<ObjCObjectPointerType>()) { 5067 // Handle the uncommon case of "123[Ptr]". 5068 BaseExpr = RHSExp; 5069 IndexExpr = LHSExp; 5070 ResultType = PTy->getPointeeType(); 5071 if (!LangOpts.isSubscriptPointerArithmetic()) { 5072 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5073 << ResultType << BaseExpr->getSourceRange(); 5074 return ExprError(); 5075 } 5076 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5077 BaseExpr = LHSExp; // vectors: V[123] 5078 IndexExpr = RHSExp; 5079 // We apply C++ DR1213 to vector subscripting too. 5080 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5081 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5082 if (Materialized.isInvalid()) 5083 return ExprError(); 5084 LHSExp = Materialized.get(); 5085 } 5086 VK = LHSExp->getValueKind(); 5087 if (VK != VK_RValue) 5088 OK = OK_VectorComponent; 5089 5090 ResultType = VTy->getElementType(); 5091 QualType BaseType = BaseExpr->getType(); 5092 Qualifiers BaseQuals = BaseType.getQualifiers(); 5093 Qualifiers MemberQuals = ResultType.getQualifiers(); 5094 Qualifiers Combined = BaseQuals + MemberQuals; 5095 if (Combined != MemberQuals) 5096 ResultType = Context.getQualifiedType(ResultType, Combined); 5097 } else if (LHSTy->isArrayType()) { 5098 // If we see an array that wasn't promoted by 5099 // DefaultFunctionArrayLvalueConversion, it must be an array that 5100 // wasn't promoted because of the C90 rule that doesn't 5101 // allow promoting non-lvalue arrays. Warn, then 5102 // force the promotion here. 5103 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5104 << LHSExp->getSourceRange(); 5105 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5106 CK_ArrayToPointerDecay).get(); 5107 LHSTy = LHSExp->getType(); 5108 5109 BaseExpr = LHSExp; 5110 IndexExpr = RHSExp; 5111 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5112 } else if (RHSTy->isArrayType()) { 5113 // Same as previous, except for 123[f().a] case 5114 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5115 << RHSExp->getSourceRange(); 5116 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5117 CK_ArrayToPointerDecay).get(); 5118 RHSTy = RHSExp->getType(); 5119 5120 BaseExpr = RHSExp; 5121 IndexExpr = LHSExp; 5122 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5123 } else { 5124 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5125 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5126 } 5127 // C99 6.5.2.1p1 5128 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5129 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5130 << IndexExpr->getSourceRange()); 5131 5132 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5133 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5134 && !IndexExpr->isTypeDependent()) 5135 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5136 5137 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5138 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5139 // type. Note that Functions are not objects, and that (in C99 parlance) 5140 // incomplete types are not object types. 5141 if (ResultType->isFunctionType()) { 5142 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5143 << ResultType << BaseExpr->getSourceRange(); 5144 return ExprError(); 5145 } 5146 5147 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5148 // GNU extension: subscripting on pointer to void 5149 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5150 << BaseExpr->getSourceRange(); 5151 5152 // C forbids expressions of unqualified void type from being l-values. 5153 // See IsCForbiddenLValueType. 5154 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5155 } else if (!ResultType->isDependentType() && 5156 RequireCompleteSizedType( 5157 LLoc, ResultType, 5158 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5159 return ExprError(); 5160 5161 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5162 !ResultType.isCForbiddenLValueType()); 5163 5164 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5165 FunctionScopes.size() > 1) { 5166 if (auto *TT = 5167 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5168 for (auto I = FunctionScopes.rbegin(), 5169 E = std::prev(FunctionScopes.rend()); 5170 I != E; ++I) { 5171 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5172 if (CSI == nullptr) 5173 break; 5174 DeclContext *DC = nullptr; 5175 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5176 DC = LSI->CallOperator; 5177 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5178 DC = CRSI->TheCapturedDecl; 5179 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5180 DC = BSI->TheDecl; 5181 if (DC) { 5182 if (DC->containsDecl(TT->getDecl())) 5183 break; 5184 captureVariablyModifiedType( 5185 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5186 } 5187 } 5188 } 5189 } 5190 5191 return new (Context) 5192 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5193 } 5194 5195 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5196 ParmVarDecl *Param) { 5197 if (Param->hasUnparsedDefaultArg()) { 5198 Diag(CallLoc, 5199 diag::err_use_of_default_argument_to_function_declared_later) << 5200 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5201 Diag(UnparsedDefaultArgLocs[Param], 5202 diag::note_default_argument_declared_here); 5203 return true; 5204 } 5205 5206 if (Param->hasUninstantiatedDefaultArg()) { 5207 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5208 5209 EnterExpressionEvaluationContext EvalContext( 5210 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5211 5212 // Instantiate the expression. 5213 // 5214 // FIXME: Pass in a correct Pattern argument, otherwise 5215 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5216 // 5217 // template<typename T> 5218 // struct A { 5219 // static int FooImpl(); 5220 // 5221 // template<typename Tp> 5222 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5223 // // template argument list [[T], [Tp]], should be [[Tp]]. 5224 // friend A<Tp> Foo(int a); 5225 // }; 5226 // 5227 // template<typename T> 5228 // A<T> Foo(int a = A<T>::FooImpl()); 5229 MultiLevelTemplateArgumentList MutiLevelArgList 5230 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5231 5232 InstantiatingTemplate Inst(*this, CallLoc, Param, 5233 MutiLevelArgList.getInnermost()); 5234 if (Inst.isInvalid()) 5235 return true; 5236 if (Inst.isAlreadyInstantiating()) { 5237 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5238 Param->setInvalidDecl(); 5239 return true; 5240 } 5241 5242 ExprResult Result; 5243 { 5244 // C++ [dcl.fct.default]p5: 5245 // The names in the [default argument] expression are bound, and 5246 // the semantic constraints are checked, at the point where the 5247 // default argument expression appears. 5248 ContextRAII SavedContext(*this, FD); 5249 LocalInstantiationScope Local(*this); 5250 runWithSufficientStackSpace(CallLoc, [&] { 5251 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5252 /*DirectInit*/false); 5253 }); 5254 } 5255 if (Result.isInvalid()) 5256 return true; 5257 5258 // Check the expression as an initializer for the parameter. 5259 InitializedEntity Entity 5260 = InitializedEntity::InitializeParameter(Context, Param); 5261 InitializationKind Kind = InitializationKind::CreateCopy( 5262 Param->getLocation(), 5263 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5264 Expr *ResultE = Result.getAs<Expr>(); 5265 5266 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5267 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5268 if (Result.isInvalid()) 5269 return true; 5270 5271 Result = 5272 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5273 /*DiscardedValue*/ false); 5274 if (Result.isInvalid()) 5275 return true; 5276 5277 // Remember the instantiated default argument. 5278 Param->setDefaultArg(Result.getAs<Expr>()); 5279 if (ASTMutationListener *L = getASTMutationListener()) { 5280 L->DefaultArgumentInstantiated(Param); 5281 } 5282 } 5283 5284 // If the default argument expression is not set yet, we are building it now. 5285 if (!Param->hasInit()) { 5286 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5287 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5288 Param->setInvalidDecl(); 5289 return true; 5290 } 5291 5292 // If the default expression creates temporaries, we need to 5293 // push them to the current stack of expression temporaries so they'll 5294 // be properly destroyed. 5295 // FIXME: We should really be rebuilding the default argument with new 5296 // bound temporaries; see the comment in PR5810. 5297 // We don't need to do that with block decls, though, because 5298 // blocks in default argument expression can never capture anything. 5299 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5300 // Set the "needs cleanups" bit regardless of whether there are 5301 // any explicit objects. 5302 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5303 5304 // Append all the objects to the cleanup list. Right now, this 5305 // should always be a no-op, because blocks in default argument 5306 // expressions should never be able to capture anything. 5307 assert(!Init->getNumObjects() && 5308 "default argument expression has capturing blocks?"); 5309 } 5310 5311 // We already type-checked the argument, so we know it works. 5312 // Just mark all of the declarations in this potentially-evaluated expression 5313 // as being "referenced". 5314 EnterExpressionEvaluationContext EvalContext( 5315 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5316 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5317 /*SkipLocalVariables=*/true); 5318 return false; 5319 } 5320 5321 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5322 FunctionDecl *FD, ParmVarDecl *Param) { 5323 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5324 return ExprError(); 5325 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5326 } 5327 5328 Sema::VariadicCallType 5329 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5330 Expr *Fn) { 5331 if (Proto && Proto->isVariadic()) { 5332 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5333 return VariadicConstructor; 5334 else if (Fn && Fn->getType()->isBlockPointerType()) 5335 return VariadicBlock; 5336 else if (FDecl) { 5337 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5338 if (Method->isInstance()) 5339 return VariadicMethod; 5340 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5341 return VariadicMethod; 5342 return VariadicFunction; 5343 } 5344 return VariadicDoesNotApply; 5345 } 5346 5347 namespace { 5348 class FunctionCallCCC final : public FunctionCallFilterCCC { 5349 public: 5350 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5351 unsigned NumArgs, MemberExpr *ME) 5352 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5353 FunctionName(FuncName) {} 5354 5355 bool ValidateCandidate(const TypoCorrection &candidate) override { 5356 if (!candidate.getCorrectionSpecifier() || 5357 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5358 return false; 5359 } 5360 5361 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5362 } 5363 5364 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5365 return std::make_unique<FunctionCallCCC>(*this); 5366 } 5367 5368 private: 5369 const IdentifierInfo *const FunctionName; 5370 }; 5371 } 5372 5373 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5374 FunctionDecl *FDecl, 5375 ArrayRef<Expr *> Args) { 5376 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5377 DeclarationName FuncName = FDecl->getDeclName(); 5378 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5379 5380 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5381 if (TypoCorrection Corrected = S.CorrectTypo( 5382 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5383 S.getScopeForContext(S.CurContext), nullptr, CCC, 5384 Sema::CTK_ErrorRecovery)) { 5385 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5386 if (Corrected.isOverloaded()) { 5387 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5388 OverloadCandidateSet::iterator Best; 5389 for (NamedDecl *CD : Corrected) { 5390 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5391 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5392 OCS); 5393 } 5394 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5395 case OR_Success: 5396 ND = Best->FoundDecl; 5397 Corrected.setCorrectionDecl(ND); 5398 break; 5399 default: 5400 break; 5401 } 5402 } 5403 ND = ND->getUnderlyingDecl(); 5404 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5405 return Corrected; 5406 } 5407 } 5408 return TypoCorrection(); 5409 } 5410 5411 /// ConvertArgumentsForCall - Converts the arguments specified in 5412 /// Args/NumArgs to the parameter types of the function FDecl with 5413 /// function prototype Proto. Call is the call expression itself, and 5414 /// Fn is the function expression. For a C++ member function, this 5415 /// routine does not attempt to convert the object argument. Returns 5416 /// true if the call is ill-formed. 5417 bool 5418 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5419 FunctionDecl *FDecl, 5420 const FunctionProtoType *Proto, 5421 ArrayRef<Expr *> Args, 5422 SourceLocation RParenLoc, 5423 bool IsExecConfig) { 5424 // Bail out early if calling a builtin with custom typechecking. 5425 if (FDecl) 5426 if (unsigned ID = FDecl->getBuiltinID()) 5427 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5428 return false; 5429 5430 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5431 // assignment, to the types of the corresponding parameter, ... 5432 unsigned NumParams = Proto->getNumParams(); 5433 bool Invalid = false; 5434 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5435 unsigned FnKind = Fn->getType()->isBlockPointerType() 5436 ? 1 /* block */ 5437 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5438 : 0 /* function */); 5439 5440 // If too few arguments are available (and we don't have default 5441 // arguments for the remaining parameters), don't make the call. 5442 if (Args.size() < NumParams) { 5443 if (Args.size() < MinArgs) { 5444 TypoCorrection TC; 5445 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5446 unsigned diag_id = 5447 MinArgs == NumParams && !Proto->isVariadic() 5448 ? diag::err_typecheck_call_too_few_args_suggest 5449 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5450 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5451 << static_cast<unsigned>(Args.size()) 5452 << TC.getCorrectionRange()); 5453 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5454 Diag(RParenLoc, 5455 MinArgs == NumParams && !Proto->isVariadic() 5456 ? diag::err_typecheck_call_too_few_args_one 5457 : diag::err_typecheck_call_too_few_args_at_least_one) 5458 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5459 else 5460 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5461 ? diag::err_typecheck_call_too_few_args 5462 : diag::err_typecheck_call_too_few_args_at_least) 5463 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5464 << Fn->getSourceRange(); 5465 5466 // Emit the location of the prototype. 5467 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5468 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5469 5470 return true; 5471 } 5472 // We reserve space for the default arguments when we create 5473 // the call expression, before calling ConvertArgumentsForCall. 5474 assert((Call->getNumArgs() == NumParams) && 5475 "We should have reserved space for the default arguments before!"); 5476 } 5477 5478 // If too many are passed and not variadic, error on the extras and drop 5479 // them. 5480 if (Args.size() > NumParams) { 5481 if (!Proto->isVariadic()) { 5482 TypoCorrection TC; 5483 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5484 unsigned diag_id = 5485 MinArgs == NumParams && !Proto->isVariadic() 5486 ? diag::err_typecheck_call_too_many_args_suggest 5487 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5488 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5489 << static_cast<unsigned>(Args.size()) 5490 << TC.getCorrectionRange()); 5491 } else if (NumParams == 1 && FDecl && 5492 FDecl->getParamDecl(0)->getDeclName()) 5493 Diag(Args[NumParams]->getBeginLoc(), 5494 MinArgs == NumParams 5495 ? diag::err_typecheck_call_too_many_args_one 5496 : diag::err_typecheck_call_too_many_args_at_most_one) 5497 << FnKind << FDecl->getParamDecl(0) 5498 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5499 << SourceRange(Args[NumParams]->getBeginLoc(), 5500 Args.back()->getEndLoc()); 5501 else 5502 Diag(Args[NumParams]->getBeginLoc(), 5503 MinArgs == NumParams 5504 ? diag::err_typecheck_call_too_many_args 5505 : diag::err_typecheck_call_too_many_args_at_most) 5506 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5507 << Fn->getSourceRange() 5508 << SourceRange(Args[NumParams]->getBeginLoc(), 5509 Args.back()->getEndLoc()); 5510 5511 // Emit the location of the prototype. 5512 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5513 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5514 5515 // This deletes the extra arguments. 5516 Call->shrinkNumArgs(NumParams); 5517 return true; 5518 } 5519 } 5520 SmallVector<Expr *, 8> AllArgs; 5521 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5522 5523 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5524 AllArgs, CallType); 5525 if (Invalid) 5526 return true; 5527 unsigned TotalNumArgs = AllArgs.size(); 5528 for (unsigned i = 0; i < TotalNumArgs; ++i) 5529 Call->setArg(i, AllArgs[i]); 5530 5531 return false; 5532 } 5533 5534 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5535 const FunctionProtoType *Proto, 5536 unsigned FirstParam, ArrayRef<Expr *> Args, 5537 SmallVectorImpl<Expr *> &AllArgs, 5538 VariadicCallType CallType, bool AllowExplicit, 5539 bool IsListInitialization) { 5540 unsigned NumParams = Proto->getNumParams(); 5541 bool Invalid = false; 5542 size_t ArgIx = 0; 5543 // Continue to check argument types (even if we have too few/many args). 5544 for (unsigned i = FirstParam; i < NumParams; i++) { 5545 QualType ProtoArgType = Proto->getParamType(i); 5546 5547 Expr *Arg; 5548 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5549 if (ArgIx < Args.size()) { 5550 Arg = Args[ArgIx++]; 5551 5552 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5553 diag::err_call_incomplete_argument, Arg)) 5554 return true; 5555 5556 // Strip the unbridged-cast placeholder expression off, if applicable. 5557 bool CFAudited = false; 5558 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5559 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5560 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5561 Arg = stripARCUnbridgedCast(Arg); 5562 else if (getLangOpts().ObjCAutoRefCount && 5563 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5564 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5565 CFAudited = true; 5566 5567 if (Proto->getExtParameterInfo(i).isNoEscape()) 5568 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5569 BE->getBlockDecl()->setDoesNotEscape(); 5570 5571 InitializedEntity Entity = 5572 Param ? InitializedEntity::InitializeParameter(Context, Param, 5573 ProtoArgType) 5574 : InitializedEntity::InitializeParameter( 5575 Context, ProtoArgType, Proto->isParamConsumed(i)); 5576 5577 // Remember that parameter belongs to a CF audited API. 5578 if (CFAudited) 5579 Entity.setParameterCFAudited(); 5580 5581 ExprResult ArgE = PerformCopyInitialization( 5582 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5583 if (ArgE.isInvalid()) 5584 return true; 5585 5586 Arg = ArgE.getAs<Expr>(); 5587 } else { 5588 assert(Param && "can't use default arguments without a known callee"); 5589 5590 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5591 if (ArgExpr.isInvalid()) 5592 return true; 5593 5594 Arg = ArgExpr.getAs<Expr>(); 5595 } 5596 5597 // Check for array bounds violations for each argument to the call. This 5598 // check only triggers warnings when the argument isn't a more complex Expr 5599 // with its own checking, such as a BinaryOperator. 5600 CheckArrayAccess(Arg); 5601 5602 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5603 CheckStaticArrayArgument(CallLoc, Param, Arg); 5604 5605 AllArgs.push_back(Arg); 5606 } 5607 5608 // If this is a variadic call, handle args passed through "...". 5609 if (CallType != VariadicDoesNotApply) { 5610 // Assume that extern "C" functions with variadic arguments that 5611 // return __unknown_anytype aren't *really* variadic. 5612 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5613 FDecl->isExternC()) { 5614 for (Expr *A : Args.slice(ArgIx)) { 5615 QualType paramType; // ignored 5616 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5617 Invalid |= arg.isInvalid(); 5618 AllArgs.push_back(arg.get()); 5619 } 5620 5621 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5622 } else { 5623 for (Expr *A : Args.slice(ArgIx)) { 5624 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5625 Invalid |= Arg.isInvalid(); 5626 // Copy blocks to the heap. 5627 if (A->getType()->isBlockPointerType()) 5628 maybeExtendBlockObject(Arg); 5629 AllArgs.push_back(Arg.get()); 5630 } 5631 } 5632 5633 // Check for array bounds violations. 5634 for (Expr *A : Args.slice(ArgIx)) 5635 CheckArrayAccess(A); 5636 } 5637 return Invalid; 5638 } 5639 5640 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5641 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5642 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5643 TL = DTL.getOriginalLoc(); 5644 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5645 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5646 << ATL.getLocalSourceRange(); 5647 } 5648 5649 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5650 /// array parameter, check that it is non-null, and that if it is formed by 5651 /// array-to-pointer decay, the underlying array is sufficiently large. 5652 /// 5653 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5654 /// array type derivation, then for each call to the function, the value of the 5655 /// corresponding actual argument shall provide access to the first element of 5656 /// an array with at least as many elements as specified by the size expression. 5657 void 5658 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5659 ParmVarDecl *Param, 5660 const Expr *ArgExpr) { 5661 // Static array parameters are not supported in C++. 5662 if (!Param || getLangOpts().CPlusPlus) 5663 return; 5664 5665 QualType OrigTy = Param->getOriginalType(); 5666 5667 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5668 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5669 return; 5670 5671 if (ArgExpr->isNullPointerConstant(Context, 5672 Expr::NPC_NeverValueDependent)) { 5673 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5674 DiagnoseCalleeStaticArrayParam(*this, Param); 5675 return; 5676 } 5677 5678 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5679 if (!CAT) 5680 return; 5681 5682 const ConstantArrayType *ArgCAT = 5683 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5684 if (!ArgCAT) 5685 return; 5686 5687 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5688 ArgCAT->getElementType())) { 5689 if (ArgCAT->getSize().ult(CAT->getSize())) { 5690 Diag(CallLoc, diag::warn_static_array_too_small) 5691 << ArgExpr->getSourceRange() 5692 << (unsigned)ArgCAT->getSize().getZExtValue() 5693 << (unsigned)CAT->getSize().getZExtValue() << 0; 5694 DiagnoseCalleeStaticArrayParam(*this, Param); 5695 } 5696 return; 5697 } 5698 5699 Optional<CharUnits> ArgSize = 5700 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5701 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5702 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5703 Diag(CallLoc, diag::warn_static_array_too_small) 5704 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5705 << (unsigned)ParmSize->getQuantity() << 1; 5706 DiagnoseCalleeStaticArrayParam(*this, Param); 5707 } 5708 } 5709 5710 /// Given a function expression of unknown-any type, try to rebuild it 5711 /// to have a function type. 5712 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5713 5714 /// Is the given type a placeholder that we need to lower out 5715 /// immediately during argument processing? 5716 static bool isPlaceholderToRemoveAsArg(QualType type) { 5717 // Placeholders are never sugared. 5718 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5719 if (!placeholder) return false; 5720 5721 switch (placeholder->getKind()) { 5722 // Ignore all the non-placeholder types. 5723 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5724 case BuiltinType::Id: 5725 #include "clang/Basic/OpenCLImageTypes.def" 5726 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5727 case BuiltinType::Id: 5728 #include "clang/Basic/OpenCLExtensionTypes.def" 5729 // In practice we'll never use this, since all SVE types are sugared 5730 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5731 #define SVE_TYPE(Name, Id, SingletonId) \ 5732 case BuiltinType::Id: 5733 #include "clang/Basic/AArch64SVEACLETypes.def" 5734 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5735 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5736 #include "clang/AST/BuiltinTypes.def" 5737 return false; 5738 5739 // We cannot lower out overload sets; they might validly be resolved 5740 // by the call machinery. 5741 case BuiltinType::Overload: 5742 return false; 5743 5744 // Unbridged casts in ARC can be handled in some call positions and 5745 // should be left in place. 5746 case BuiltinType::ARCUnbridgedCast: 5747 return false; 5748 5749 // Pseudo-objects should be converted as soon as possible. 5750 case BuiltinType::PseudoObject: 5751 return true; 5752 5753 // The debugger mode could theoretically but currently does not try 5754 // to resolve unknown-typed arguments based on known parameter types. 5755 case BuiltinType::UnknownAny: 5756 return true; 5757 5758 // These are always invalid as call arguments and should be reported. 5759 case BuiltinType::BoundMember: 5760 case BuiltinType::BuiltinFn: 5761 case BuiltinType::OMPArraySection: 5762 case BuiltinType::OMPArrayShaping: 5763 case BuiltinType::OMPIterator: 5764 return true; 5765 5766 } 5767 llvm_unreachable("bad builtin type kind"); 5768 } 5769 5770 /// Check an argument list for placeholders that we won't try to 5771 /// handle later. 5772 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5773 // Apply this processing to all the arguments at once instead of 5774 // dying at the first failure. 5775 bool hasInvalid = false; 5776 for (size_t i = 0, e = args.size(); i != e; i++) { 5777 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5778 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5779 if (result.isInvalid()) hasInvalid = true; 5780 else args[i] = result.get(); 5781 } else if (hasInvalid) { 5782 (void)S.CorrectDelayedTyposInExpr(args[i]); 5783 } 5784 } 5785 return hasInvalid; 5786 } 5787 5788 /// If a builtin function has a pointer argument with no explicit address 5789 /// space, then it should be able to accept a pointer to any address 5790 /// space as input. In order to do this, we need to replace the 5791 /// standard builtin declaration with one that uses the same address space 5792 /// as the call. 5793 /// 5794 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5795 /// it does not contain any pointer arguments without 5796 /// an address space qualifer. Otherwise the rewritten 5797 /// FunctionDecl is returned. 5798 /// TODO: Handle pointer return types. 5799 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5800 FunctionDecl *FDecl, 5801 MultiExprArg ArgExprs) { 5802 5803 QualType DeclType = FDecl->getType(); 5804 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5805 5806 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5807 ArgExprs.size() < FT->getNumParams()) 5808 return nullptr; 5809 5810 bool NeedsNewDecl = false; 5811 unsigned i = 0; 5812 SmallVector<QualType, 8> OverloadParams; 5813 5814 for (QualType ParamType : FT->param_types()) { 5815 5816 // Convert array arguments to pointer to simplify type lookup. 5817 ExprResult ArgRes = 5818 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5819 if (ArgRes.isInvalid()) 5820 return nullptr; 5821 Expr *Arg = ArgRes.get(); 5822 QualType ArgType = Arg->getType(); 5823 if (!ParamType->isPointerType() || 5824 ParamType.hasAddressSpace() || 5825 !ArgType->isPointerType() || 5826 !ArgType->getPointeeType().hasAddressSpace()) { 5827 OverloadParams.push_back(ParamType); 5828 continue; 5829 } 5830 5831 QualType PointeeType = ParamType->getPointeeType(); 5832 if (PointeeType.hasAddressSpace()) 5833 continue; 5834 5835 NeedsNewDecl = true; 5836 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5837 5838 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5839 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5840 } 5841 5842 if (!NeedsNewDecl) 5843 return nullptr; 5844 5845 FunctionProtoType::ExtProtoInfo EPI; 5846 EPI.Variadic = FT->isVariadic(); 5847 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5848 OverloadParams, EPI); 5849 DeclContext *Parent = FDecl->getParent(); 5850 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5851 FDecl->getLocation(), 5852 FDecl->getLocation(), 5853 FDecl->getIdentifier(), 5854 OverloadTy, 5855 /*TInfo=*/nullptr, 5856 SC_Extern, false, 5857 /*hasPrototype=*/true); 5858 SmallVector<ParmVarDecl*, 16> Params; 5859 FT = cast<FunctionProtoType>(OverloadTy); 5860 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5861 QualType ParamType = FT->getParamType(i); 5862 ParmVarDecl *Parm = 5863 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5864 SourceLocation(), nullptr, ParamType, 5865 /*TInfo=*/nullptr, SC_None, nullptr); 5866 Parm->setScopeInfo(0, i); 5867 Params.push_back(Parm); 5868 } 5869 OverloadDecl->setParams(Params); 5870 return OverloadDecl; 5871 } 5872 5873 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5874 FunctionDecl *Callee, 5875 MultiExprArg ArgExprs) { 5876 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5877 // similar attributes) really don't like it when functions are called with an 5878 // invalid number of args. 5879 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5880 /*PartialOverloading=*/false) && 5881 !Callee->isVariadic()) 5882 return; 5883 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5884 return; 5885 5886 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5887 S.Diag(Fn->getBeginLoc(), 5888 isa<CXXMethodDecl>(Callee) 5889 ? diag::err_ovl_no_viable_member_function_in_call 5890 : diag::err_ovl_no_viable_function_in_call) 5891 << Callee << Callee->getSourceRange(); 5892 S.Diag(Callee->getLocation(), 5893 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5894 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5895 return; 5896 } 5897 } 5898 5899 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5900 const UnresolvedMemberExpr *const UME, Sema &S) { 5901 5902 const auto GetFunctionLevelDCIfCXXClass = 5903 [](Sema &S) -> const CXXRecordDecl * { 5904 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5905 if (!DC || !DC->getParent()) 5906 return nullptr; 5907 5908 // If the call to some member function was made from within a member 5909 // function body 'M' return return 'M's parent. 5910 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5911 return MD->getParent()->getCanonicalDecl(); 5912 // else the call was made from within a default member initializer of a 5913 // class, so return the class. 5914 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5915 return RD->getCanonicalDecl(); 5916 return nullptr; 5917 }; 5918 // If our DeclContext is neither a member function nor a class (in the 5919 // case of a lambda in a default member initializer), we can't have an 5920 // enclosing 'this'. 5921 5922 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5923 if (!CurParentClass) 5924 return false; 5925 5926 // The naming class for implicit member functions call is the class in which 5927 // name lookup starts. 5928 const CXXRecordDecl *const NamingClass = 5929 UME->getNamingClass()->getCanonicalDecl(); 5930 assert(NamingClass && "Must have naming class even for implicit access"); 5931 5932 // If the unresolved member functions were found in a 'naming class' that is 5933 // related (either the same or derived from) to the class that contains the 5934 // member function that itself contained the implicit member access. 5935 5936 return CurParentClass == NamingClass || 5937 CurParentClass->isDerivedFrom(NamingClass); 5938 } 5939 5940 static void 5941 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5942 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5943 5944 if (!UME) 5945 return; 5946 5947 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5948 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5949 // already been captured, or if this is an implicit member function call (if 5950 // it isn't, an attempt to capture 'this' should already have been made). 5951 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5952 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5953 return; 5954 5955 // Check if the naming class in which the unresolved members were found is 5956 // related (same as or is a base of) to the enclosing class. 5957 5958 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5959 return; 5960 5961 5962 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5963 // If the enclosing function is not dependent, then this lambda is 5964 // capture ready, so if we can capture this, do so. 5965 if (!EnclosingFunctionCtx->isDependentContext()) { 5966 // If the current lambda and all enclosing lambdas can capture 'this' - 5967 // then go ahead and capture 'this' (since our unresolved overload set 5968 // contains at least one non-static member function). 5969 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5970 S.CheckCXXThisCapture(CallLoc); 5971 } else if (S.CurContext->isDependentContext()) { 5972 // ... since this is an implicit member reference, that might potentially 5973 // involve a 'this' capture, mark 'this' for potential capture in 5974 // enclosing lambdas. 5975 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5976 CurLSI->addPotentialThisCapture(CallLoc); 5977 } 5978 } 5979 5980 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5981 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5982 Expr *ExecConfig) { 5983 ExprResult Call = 5984 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5985 if (Call.isInvalid()) 5986 return Call; 5987 5988 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5989 // language modes. 5990 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5991 if (ULE->hasExplicitTemplateArgs() && 5992 ULE->decls_begin() == ULE->decls_end()) { 5993 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5994 ? diag::warn_cxx17_compat_adl_only_template_id 5995 : diag::ext_adl_only_template_id) 5996 << ULE->getName(); 5997 } 5998 } 5999 6000 if (LangOpts.OpenMP) 6001 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6002 ExecConfig); 6003 6004 return Call; 6005 } 6006 6007 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6008 /// This provides the location of the left/right parens and a list of comma 6009 /// locations. 6010 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6011 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6012 Expr *ExecConfig, bool IsExecConfig) { 6013 // Since this might be a postfix expression, get rid of ParenListExprs. 6014 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6015 if (Result.isInvalid()) return ExprError(); 6016 Fn = Result.get(); 6017 6018 if (checkArgsForPlaceholders(*this, ArgExprs)) 6019 return ExprError(); 6020 6021 if (getLangOpts().CPlusPlus) { 6022 // If this is a pseudo-destructor expression, build the call immediately. 6023 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6024 if (!ArgExprs.empty()) { 6025 // Pseudo-destructor calls should not have any arguments. 6026 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6027 << FixItHint::CreateRemoval( 6028 SourceRange(ArgExprs.front()->getBeginLoc(), 6029 ArgExprs.back()->getEndLoc())); 6030 } 6031 6032 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6033 VK_RValue, RParenLoc); 6034 } 6035 if (Fn->getType() == Context.PseudoObjectTy) { 6036 ExprResult result = CheckPlaceholderExpr(Fn); 6037 if (result.isInvalid()) return ExprError(); 6038 Fn = result.get(); 6039 } 6040 6041 // Determine whether this is a dependent call inside a C++ template, 6042 // in which case we won't do any semantic analysis now. 6043 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6044 if (ExecConfig) { 6045 return CUDAKernelCallExpr::Create( 6046 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6047 Context.DependentTy, VK_RValue, RParenLoc); 6048 } else { 6049 6050 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6051 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6052 Fn->getBeginLoc()); 6053 6054 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6055 VK_RValue, RParenLoc); 6056 } 6057 } 6058 6059 // Determine whether this is a call to an object (C++ [over.call.object]). 6060 if (Fn->getType()->isRecordType()) 6061 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6062 RParenLoc); 6063 6064 if (Fn->getType() == Context.UnknownAnyTy) { 6065 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6066 if (result.isInvalid()) return ExprError(); 6067 Fn = result.get(); 6068 } 6069 6070 if (Fn->getType() == Context.BoundMemberTy) { 6071 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6072 RParenLoc); 6073 } 6074 } 6075 6076 // Check for overloaded calls. This can happen even in C due to extensions. 6077 if (Fn->getType() == Context.OverloadTy) { 6078 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6079 6080 // We aren't supposed to apply this logic if there's an '&' involved. 6081 if (!find.HasFormOfMemberPointer) { 6082 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6083 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6084 VK_RValue, RParenLoc); 6085 OverloadExpr *ovl = find.Expression; 6086 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6087 return BuildOverloadedCallExpr( 6088 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6089 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6090 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6091 RParenLoc); 6092 } 6093 } 6094 6095 // If we're directly calling a function, get the appropriate declaration. 6096 if (Fn->getType() == Context.UnknownAnyTy) { 6097 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6098 if (result.isInvalid()) return ExprError(); 6099 Fn = result.get(); 6100 } 6101 6102 Expr *NakedFn = Fn->IgnoreParens(); 6103 6104 bool CallingNDeclIndirectly = false; 6105 NamedDecl *NDecl = nullptr; 6106 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6107 if (UnOp->getOpcode() == UO_AddrOf) { 6108 CallingNDeclIndirectly = true; 6109 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6110 } 6111 } 6112 6113 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6114 NDecl = DRE->getDecl(); 6115 6116 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6117 if (FDecl && FDecl->getBuiltinID()) { 6118 // Rewrite the function decl for this builtin by replacing parameters 6119 // with no explicit address space with the address space of the arguments 6120 // in ArgExprs. 6121 if ((FDecl = 6122 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6123 NDecl = FDecl; 6124 Fn = DeclRefExpr::Create( 6125 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6126 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6127 nullptr, DRE->isNonOdrUse()); 6128 } 6129 } 6130 } else if (isa<MemberExpr>(NakedFn)) 6131 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6132 6133 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6134 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6135 FD, /*Complain=*/true, Fn->getBeginLoc())) 6136 return ExprError(); 6137 6138 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6139 return ExprError(); 6140 6141 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6142 } 6143 6144 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6145 ExecConfig, IsExecConfig); 6146 } 6147 6148 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6149 /// 6150 /// __builtin_astype( value, dst type ) 6151 /// 6152 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6153 SourceLocation BuiltinLoc, 6154 SourceLocation RParenLoc) { 6155 ExprValueKind VK = VK_RValue; 6156 ExprObjectKind OK = OK_Ordinary; 6157 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6158 QualType SrcTy = E->getType(); 6159 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6160 return ExprError(Diag(BuiltinLoc, 6161 diag::err_invalid_astype_of_different_size) 6162 << DstTy 6163 << SrcTy 6164 << E->getSourceRange()); 6165 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6166 } 6167 6168 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6169 /// provided arguments. 6170 /// 6171 /// __builtin_convertvector( value, dst type ) 6172 /// 6173 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6174 SourceLocation BuiltinLoc, 6175 SourceLocation RParenLoc) { 6176 TypeSourceInfo *TInfo; 6177 GetTypeFromParser(ParsedDestTy, &TInfo); 6178 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6179 } 6180 6181 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6182 /// i.e. an expression not of \p OverloadTy. The expression should 6183 /// unary-convert to an expression of function-pointer or 6184 /// block-pointer type. 6185 /// 6186 /// \param NDecl the declaration being called, if available 6187 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6188 SourceLocation LParenLoc, 6189 ArrayRef<Expr *> Args, 6190 SourceLocation RParenLoc, Expr *Config, 6191 bool IsExecConfig, ADLCallKind UsesADL) { 6192 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6193 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6194 6195 // Functions with 'interrupt' attribute cannot be called directly. 6196 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6197 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6198 return ExprError(); 6199 } 6200 6201 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6202 // so there's some risk when calling out to non-interrupt handler functions 6203 // that the callee might not preserve them. This is easy to diagnose here, 6204 // but can be very challenging to debug. 6205 if (auto *Caller = getCurFunctionDecl()) 6206 if (Caller->hasAttr<ARMInterruptAttr>()) { 6207 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6208 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6209 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6210 } 6211 6212 // Promote the function operand. 6213 // We special-case function promotion here because we only allow promoting 6214 // builtin functions to function pointers in the callee of a call. 6215 ExprResult Result; 6216 QualType ResultTy; 6217 if (BuiltinID && 6218 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6219 // Extract the return type from the (builtin) function pointer type. 6220 // FIXME Several builtins still have setType in 6221 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6222 // Builtins.def to ensure they are correct before removing setType calls. 6223 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6224 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6225 ResultTy = FDecl->getCallResultType(); 6226 } else { 6227 Result = CallExprUnaryConversions(Fn); 6228 ResultTy = Context.BoolTy; 6229 } 6230 if (Result.isInvalid()) 6231 return ExprError(); 6232 Fn = Result.get(); 6233 6234 // Check for a valid function type, but only if it is not a builtin which 6235 // requires custom type checking. These will be handled by 6236 // CheckBuiltinFunctionCall below just after creation of the call expression. 6237 const FunctionType *FuncT = nullptr; 6238 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6239 retry: 6240 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6241 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6242 // have type pointer to function". 6243 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6244 if (!FuncT) 6245 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6246 << Fn->getType() << Fn->getSourceRange()); 6247 } else if (const BlockPointerType *BPT = 6248 Fn->getType()->getAs<BlockPointerType>()) { 6249 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6250 } else { 6251 // Handle calls to expressions of unknown-any type. 6252 if (Fn->getType() == Context.UnknownAnyTy) { 6253 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6254 if (rewrite.isInvalid()) 6255 return ExprError(); 6256 Fn = rewrite.get(); 6257 goto retry; 6258 } 6259 6260 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6261 << Fn->getType() << Fn->getSourceRange()); 6262 } 6263 } 6264 6265 // Get the number of parameters in the function prototype, if any. 6266 // We will allocate space for max(Args.size(), NumParams) arguments 6267 // in the call expression. 6268 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6269 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6270 6271 CallExpr *TheCall; 6272 if (Config) { 6273 assert(UsesADL == ADLCallKind::NotADL && 6274 "CUDAKernelCallExpr should not use ADL"); 6275 TheCall = 6276 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6277 ResultTy, VK_RValue, RParenLoc, NumParams); 6278 } else { 6279 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6280 RParenLoc, NumParams, UsesADL); 6281 } 6282 6283 if (!getLangOpts().CPlusPlus) { 6284 // Forget about the nulled arguments since typo correction 6285 // do not handle them well. 6286 TheCall->shrinkNumArgs(Args.size()); 6287 // C cannot always handle TypoExpr nodes in builtin calls and direct 6288 // function calls as their argument checking don't necessarily handle 6289 // dependent types properly, so make sure any TypoExprs have been 6290 // dealt with. 6291 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6292 if (!Result.isUsable()) return ExprError(); 6293 CallExpr *TheOldCall = TheCall; 6294 TheCall = dyn_cast<CallExpr>(Result.get()); 6295 bool CorrectedTypos = TheCall != TheOldCall; 6296 if (!TheCall) return Result; 6297 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6298 6299 // A new call expression node was created if some typos were corrected. 6300 // However it may not have been constructed with enough storage. In this 6301 // case, rebuild the node with enough storage. The waste of space is 6302 // immaterial since this only happens when some typos were corrected. 6303 if (CorrectedTypos && Args.size() < NumParams) { 6304 if (Config) 6305 TheCall = CUDAKernelCallExpr::Create( 6306 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6307 RParenLoc, NumParams); 6308 else 6309 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6310 RParenLoc, NumParams, UsesADL); 6311 } 6312 // We can now handle the nulled arguments for the default arguments. 6313 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6314 } 6315 6316 // Bail out early if calling a builtin with custom type checking. 6317 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6318 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6319 6320 if (getLangOpts().CUDA) { 6321 if (Config) { 6322 // CUDA: Kernel calls must be to global functions 6323 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6324 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6325 << FDecl << Fn->getSourceRange()); 6326 6327 // CUDA: Kernel function must have 'void' return type 6328 if (!FuncT->getReturnType()->isVoidType() && 6329 !FuncT->getReturnType()->getAs<AutoType>() && 6330 !FuncT->getReturnType()->isInstantiationDependentType()) 6331 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6332 << Fn->getType() << Fn->getSourceRange()); 6333 } else { 6334 // CUDA: Calls to global functions must be configured 6335 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6336 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6337 << FDecl << Fn->getSourceRange()); 6338 } 6339 } 6340 6341 // Check for a valid return type 6342 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6343 FDecl)) 6344 return ExprError(); 6345 6346 // We know the result type of the call, set it. 6347 TheCall->setType(FuncT->getCallResultType(Context)); 6348 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6349 6350 if (Proto) { 6351 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6352 IsExecConfig)) 6353 return ExprError(); 6354 } else { 6355 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6356 6357 if (FDecl) { 6358 // Check if we have too few/too many template arguments, based 6359 // on our knowledge of the function definition. 6360 const FunctionDecl *Def = nullptr; 6361 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6362 Proto = Def->getType()->getAs<FunctionProtoType>(); 6363 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6364 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6365 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6366 } 6367 6368 // If the function we're calling isn't a function prototype, but we have 6369 // a function prototype from a prior declaratiom, use that prototype. 6370 if (!FDecl->hasPrototype()) 6371 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6372 } 6373 6374 // Promote the arguments (C99 6.5.2.2p6). 6375 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6376 Expr *Arg = Args[i]; 6377 6378 if (Proto && i < Proto->getNumParams()) { 6379 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6380 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6381 ExprResult ArgE = 6382 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6383 if (ArgE.isInvalid()) 6384 return true; 6385 6386 Arg = ArgE.getAs<Expr>(); 6387 6388 } else { 6389 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6390 6391 if (ArgE.isInvalid()) 6392 return true; 6393 6394 Arg = ArgE.getAs<Expr>(); 6395 } 6396 6397 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6398 diag::err_call_incomplete_argument, Arg)) 6399 return ExprError(); 6400 6401 TheCall->setArg(i, Arg); 6402 } 6403 } 6404 6405 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6406 if (!Method->isStatic()) 6407 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6408 << Fn->getSourceRange()); 6409 6410 // Check for sentinels 6411 if (NDecl) 6412 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6413 6414 // Do special checking on direct calls to functions. 6415 if (FDecl) { 6416 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6417 return ExprError(); 6418 6419 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6420 6421 if (BuiltinID) 6422 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6423 } else if (NDecl) { 6424 if (CheckPointerCall(NDecl, TheCall, Proto)) 6425 return ExprError(); 6426 } else { 6427 if (CheckOtherCall(TheCall, Proto)) 6428 return ExprError(); 6429 } 6430 6431 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6432 } 6433 6434 ExprResult 6435 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6436 SourceLocation RParenLoc, Expr *InitExpr) { 6437 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6438 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6439 6440 TypeSourceInfo *TInfo; 6441 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6442 if (!TInfo) 6443 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6444 6445 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6446 } 6447 6448 ExprResult 6449 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6450 SourceLocation RParenLoc, Expr *LiteralExpr) { 6451 QualType literalType = TInfo->getType(); 6452 6453 if (literalType->isArrayType()) { 6454 if (RequireCompleteSizedType( 6455 LParenLoc, Context.getBaseElementType(literalType), 6456 diag::err_array_incomplete_or_sizeless_type, 6457 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6458 return ExprError(); 6459 if (literalType->isVariableArrayType()) 6460 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6461 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6462 } else if (!literalType->isDependentType() && 6463 RequireCompleteType(LParenLoc, literalType, 6464 diag::err_typecheck_decl_incomplete_type, 6465 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6466 return ExprError(); 6467 6468 InitializedEntity Entity 6469 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6470 InitializationKind Kind 6471 = InitializationKind::CreateCStyleCast(LParenLoc, 6472 SourceRange(LParenLoc, RParenLoc), 6473 /*InitList=*/true); 6474 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6475 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6476 &literalType); 6477 if (Result.isInvalid()) 6478 return ExprError(); 6479 LiteralExpr = Result.get(); 6480 6481 bool isFileScope = !CurContext->isFunctionOrMethod(); 6482 6483 // In C, compound literals are l-values for some reason. 6484 // For GCC compatibility, in C++, file-scope array compound literals with 6485 // constant initializers are also l-values, and compound literals are 6486 // otherwise prvalues. 6487 // 6488 // (GCC also treats C++ list-initialized file-scope array prvalues with 6489 // constant initializers as l-values, but that's non-conforming, so we don't 6490 // follow it there.) 6491 // 6492 // FIXME: It would be better to handle the lvalue cases as materializing and 6493 // lifetime-extending a temporary object, but our materialized temporaries 6494 // representation only supports lifetime extension from a variable, not "out 6495 // of thin air". 6496 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6497 // is bound to the result of applying array-to-pointer decay to the compound 6498 // literal. 6499 // FIXME: GCC supports compound literals of reference type, which should 6500 // obviously have a value kind derived from the kind of reference involved. 6501 ExprValueKind VK = 6502 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6503 ? VK_RValue 6504 : VK_LValue; 6505 6506 if (isFileScope) 6507 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6508 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6509 Expr *Init = ILE->getInit(i); 6510 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6511 } 6512 6513 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6514 VK, LiteralExpr, isFileScope); 6515 if (isFileScope) { 6516 if (!LiteralExpr->isTypeDependent() && 6517 !LiteralExpr->isValueDependent() && 6518 !literalType->isDependentType()) // C99 6.5.2.5p3 6519 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6520 return ExprError(); 6521 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6522 literalType.getAddressSpace() != LangAS::Default) { 6523 // Embedded-C extensions to C99 6.5.2.5: 6524 // "If the compound literal occurs inside the body of a function, the 6525 // type name shall not be qualified by an address-space qualifier." 6526 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6527 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6528 return ExprError(); 6529 } 6530 6531 if (!isFileScope && !getLangOpts().CPlusPlus) { 6532 // Compound literals that have automatic storage duration are destroyed at 6533 // the end of the scope in C; in C++, they're just temporaries. 6534 6535 // Emit diagnostics if it is or contains a C union type that is non-trivial 6536 // to destruct. 6537 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6538 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6539 NTCUC_CompoundLiteral, NTCUK_Destruct); 6540 6541 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6542 if (literalType.isDestructedType()) { 6543 Cleanup.setExprNeedsCleanups(true); 6544 ExprCleanupObjects.push_back(E); 6545 getCurFunction()->setHasBranchProtectedScope(); 6546 } 6547 } 6548 6549 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6550 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6551 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6552 E->getInitializer()->getExprLoc()); 6553 6554 return MaybeBindToTemporary(E); 6555 } 6556 6557 ExprResult 6558 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6559 SourceLocation RBraceLoc) { 6560 // Only produce each kind of designated initialization diagnostic once. 6561 SourceLocation FirstDesignator; 6562 bool DiagnosedArrayDesignator = false; 6563 bool DiagnosedNestedDesignator = false; 6564 bool DiagnosedMixedDesignator = false; 6565 6566 // Check that any designated initializers are syntactically valid in the 6567 // current language mode. 6568 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6569 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6570 if (FirstDesignator.isInvalid()) 6571 FirstDesignator = DIE->getBeginLoc(); 6572 6573 if (!getLangOpts().CPlusPlus) 6574 break; 6575 6576 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6577 DiagnosedNestedDesignator = true; 6578 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6579 << DIE->getDesignatorsSourceRange(); 6580 } 6581 6582 for (auto &Desig : DIE->designators()) { 6583 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6584 DiagnosedArrayDesignator = true; 6585 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6586 << Desig.getSourceRange(); 6587 } 6588 } 6589 6590 if (!DiagnosedMixedDesignator && 6591 !isa<DesignatedInitExpr>(InitArgList[0])) { 6592 DiagnosedMixedDesignator = true; 6593 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6594 << DIE->getSourceRange(); 6595 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6596 << InitArgList[0]->getSourceRange(); 6597 } 6598 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6599 isa<DesignatedInitExpr>(InitArgList[0])) { 6600 DiagnosedMixedDesignator = true; 6601 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6602 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6603 << DIE->getSourceRange(); 6604 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6605 << InitArgList[I]->getSourceRange(); 6606 } 6607 } 6608 6609 if (FirstDesignator.isValid()) { 6610 // Only diagnose designated initiaization as a C++20 extension if we didn't 6611 // already diagnose use of (non-C++20) C99 designator syntax. 6612 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6613 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6614 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6615 ? diag::warn_cxx17_compat_designated_init 6616 : diag::ext_cxx_designated_init); 6617 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6618 Diag(FirstDesignator, diag::ext_designated_init); 6619 } 6620 } 6621 6622 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6623 } 6624 6625 ExprResult 6626 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6627 SourceLocation RBraceLoc) { 6628 // Semantic analysis for initializers is done by ActOnDeclarator() and 6629 // CheckInitializer() - it requires knowledge of the object being initialized. 6630 6631 // Immediately handle non-overload placeholders. Overloads can be 6632 // resolved contextually, but everything else here can't. 6633 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6634 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6635 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6636 6637 // Ignore failures; dropping the entire initializer list because 6638 // of one failure would be terrible for indexing/etc. 6639 if (result.isInvalid()) continue; 6640 6641 InitArgList[I] = result.get(); 6642 } 6643 } 6644 6645 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6646 RBraceLoc); 6647 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6648 return E; 6649 } 6650 6651 /// Do an explicit extend of the given block pointer if we're in ARC. 6652 void Sema::maybeExtendBlockObject(ExprResult &E) { 6653 assert(E.get()->getType()->isBlockPointerType()); 6654 assert(E.get()->isRValue()); 6655 6656 // Only do this in an r-value context. 6657 if (!getLangOpts().ObjCAutoRefCount) return; 6658 6659 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6660 CK_ARCExtendBlockObject, E.get(), 6661 /*base path*/ nullptr, VK_RValue); 6662 Cleanup.setExprNeedsCleanups(true); 6663 } 6664 6665 /// Prepare a conversion of the given expression to an ObjC object 6666 /// pointer type. 6667 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6668 QualType type = E.get()->getType(); 6669 if (type->isObjCObjectPointerType()) { 6670 return CK_BitCast; 6671 } else if (type->isBlockPointerType()) { 6672 maybeExtendBlockObject(E); 6673 return CK_BlockPointerToObjCPointerCast; 6674 } else { 6675 assert(type->isPointerType()); 6676 return CK_CPointerToObjCPointerCast; 6677 } 6678 } 6679 6680 /// Prepares for a scalar cast, performing all the necessary stages 6681 /// except the final cast and returning the kind required. 6682 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6683 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6684 // Also, callers should have filtered out the invalid cases with 6685 // pointers. Everything else should be possible. 6686 6687 QualType SrcTy = Src.get()->getType(); 6688 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6689 return CK_NoOp; 6690 6691 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6692 case Type::STK_MemberPointer: 6693 llvm_unreachable("member pointer type in C"); 6694 6695 case Type::STK_CPointer: 6696 case Type::STK_BlockPointer: 6697 case Type::STK_ObjCObjectPointer: 6698 switch (DestTy->getScalarTypeKind()) { 6699 case Type::STK_CPointer: { 6700 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6701 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6702 if (SrcAS != DestAS) 6703 return CK_AddressSpaceConversion; 6704 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6705 return CK_NoOp; 6706 return CK_BitCast; 6707 } 6708 case Type::STK_BlockPointer: 6709 return (SrcKind == Type::STK_BlockPointer 6710 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6711 case Type::STK_ObjCObjectPointer: 6712 if (SrcKind == Type::STK_ObjCObjectPointer) 6713 return CK_BitCast; 6714 if (SrcKind == Type::STK_CPointer) 6715 return CK_CPointerToObjCPointerCast; 6716 maybeExtendBlockObject(Src); 6717 return CK_BlockPointerToObjCPointerCast; 6718 case Type::STK_Bool: 6719 return CK_PointerToBoolean; 6720 case Type::STK_Integral: 6721 return CK_PointerToIntegral; 6722 case Type::STK_Floating: 6723 case Type::STK_FloatingComplex: 6724 case Type::STK_IntegralComplex: 6725 case Type::STK_MemberPointer: 6726 case Type::STK_FixedPoint: 6727 llvm_unreachable("illegal cast from pointer"); 6728 } 6729 llvm_unreachable("Should have returned before this"); 6730 6731 case Type::STK_FixedPoint: 6732 switch (DestTy->getScalarTypeKind()) { 6733 case Type::STK_FixedPoint: 6734 return CK_FixedPointCast; 6735 case Type::STK_Bool: 6736 return CK_FixedPointToBoolean; 6737 case Type::STK_Integral: 6738 return CK_FixedPointToIntegral; 6739 case Type::STK_Floating: 6740 case Type::STK_IntegralComplex: 6741 case Type::STK_FloatingComplex: 6742 Diag(Src.get()->getExprLoc(), 6743 diag::err_unimplemented_conversion_with_fixed_point_type) 6744 << DestTy; 6745 return CK_IntegralCast; 6746 case Type::STK_CPointer: 6747 case Type::STK_ObjCObjectPointer: 6748 case Type::STK_BlockPointer: 6749 case Type::STK_MemberPointer: 6750 llvm_unreachable("illegal cast to pointer type"); 6751 } 6752 llvm_unreachable("Should have returned before this"); 6753 6754 case Type::STK_Bool: // casting from bool is like casting from an integer 6755 case Type::STK_Integral: 6756 switch (DestTy->getScalarTypeKind()) { 6757 case Type::STK_CPointer: 6758 case Type::STK_ObjCObjectPointer: 6759 case Type::STK_BlockPointer: 6760 if (Src.get()->isNullPointerConstant(Context, 6761 Expr::NPC_ValueDependentIsNull)) 6762 return CK_NullToPointer; 6763 return CK_IntegralToPointer; 6764 case Type::STK_Bool: 6765 return CK_IntegralToBoolean; 6766 case Type::STK_Integral: 6767 return CK_IntegralCast; 6768 case Type::STK_Floating: 6769 return CK_IntegralToFloating; 6770 case Type::STK_IntegralComplex: 6771 Src = ImpCastExprToType(Src.get(), 6772 DestTy->castAs<ComplexType>()->getElementType(), 6773 CK_IntegralCast); 6774 return CK_IntegralRealToComplex; 6775 case Type::STK_FloatingComplex: 6776 Src = ImpCastExprToType(Src.get(), 6777 DestTy->castAs<ComplexType>()->getElementType(), 6778 CK_IntegralToFloating); 6779 return CK_FloatingRealToComplex; 6780 case Type::STK_MemberPointer: 6781 llvm_unreachable("member pointer type in C"); 6782 case Type::STK_FixedPoint: 6783 return CK_IntegralToFixedPoint; 6784 } 6785 llvm_unreachable("Should have returned before this"); 6786 6787 case Type::STK_Floating: 6788 switch (DestTy->getScalarTypeKind()) { 6789 case Type::STK_Floating: 6790 return CK_FloatingCast; 6791 case Type::STK_Bool: 6792 return CK_FloatingToBoolean; 6793 case Type::STK_Integral: 6794 return CK_FloatingToIntegral; 6795 case Type::STK_FloatingComplex: 6796 Src = ImpCastExprToType(Src.get(), 6797 DestTy->castAs<ComplexType>()->getElementType(), 6798 CK_FloatingCast); 6799 return CK_FloatingRealToComplex; 6800 case Type::STK_IntegralComplex: 6801 Src = ImpCastExprToType(Src.get(), 6802 DestTy->castAs<ComplexType>()->getElementType(), 6803 CK_FloatingToIntegral); 6804 return CK_IntegralRealToComplex; 6805 case Type::STK_CPointer: 6806 case Type::STK_ObjCObjectPointer: 6807 case Type::STK_BlockPointer: 6808 llvm_unreachable("valid float->pointer cast?"); 6809 case Type::STK_MemberPointer: 6810 llvm_unreachable("member pointer type in C"); 6811 case Type::STK_FixedPoint: 6812 Diag(Src.get()->getExprLoc(), 6813 diag::err_unimplemented_conversion_with_fixed_point_type) 6814 << SrcTy; 6815 return CK_IntegralCast; 6816 } 6817 llvm_unreachable("Should have returned before this"); 6818 6819 case Type::STK_FloatingComplex: 6820 switch (DestTy->getScalarTypeKind()) { 6821 case Type::STK_FloatingComplex: 6822 return CK_FloatingComplexCast; 6823 case Type::STK_IntegralComplex: 6824 return CK_FloatingComplexToIntegralComplex; 6825 case Type::STK_Floating: { 6826 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6827 if (Context.hasSameType(ET, DestTy)) 6828 return CK_FloatingComplexToReal; 6829 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6830 return CK_FloatingCast; 6831 } 6832 case Type::STK_Bool: 6833 return CK_FloatingComplexToBoolean; 6834 case Type::STK_Integral: 6835 Src = ImpCastExprToType(Src.get(), 6836 SrcTy->castAs<ComplexType>()->getElementType(), 6837 CK_FloatingComplexToReal); 6838 return CK_FloatingToIntegral; 6839 case Type::STK_CPointer: 6840 case Type::STK_ObjCObjectPointer: 6841 case Type::STK_BlockPointer: 6842 llvm_unreachable("valid complex float->pointer cast?"); 6843 case Type::STK_MemberPointer: 6844 llvm_unreachable("member pointer type in C"); 6845 case Type::STK_FixedPoint: 6846 Diag(Src.get()->getExprLoc(), 6847 diag::err_unimplemented_conversion_with_fixed_point_type) 6848 << SrcTy; 6849 return CK_IntegralCast; 6850 } 6851 llvm_unreachable("Should have returned before this"); 6852 6853 case Type::STK_IntegralComplex: 6854 switch (DestTy->getScalarTypeKind()) { 6855 case Type::STK_FloatingComplex: 6856 return CK_IntegralComplexToFloatingComplex; 6857 case Type::STK_IntegralComplex: 6858 return CK_IntegralComplexCast; 6859 case Type::STK_Integral: { 6860 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6861 if (Context.hasSameType(ET, DestTy)) 6862 return CK_IntegralComplexToReal; 6863 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6864 return CK_IntegralCast; 6865 } 6866 case Type::STK_Bool: 6867 return CK_IntegralComplexToBoolean; 6868 case Type::STK_Floating: 6869 Src = ImpCastExprToType(Src.get(), 6870 SrcTy->castAs<ComplexType>()->getElementType(), 6871 CK_IntegralComplexToReal); 6872 return CK_IntegralToFloating; 6873 case Type::STK_CPointer: 6874 case Type::STK_ObjCObjectPointer: 6875 case Type::STK_BlockPointer: 6876 llvm_unreachable("valid complex int->pointer cast?"); 6877 case Type::STK_MemberPointer: 6878 llvm_unreachable("member pointer type in C"); 6879 case Type::STK_FixedPoint: 6880 Diag(Src.get()->getExprLoc(), 6881 diag::err_unimplemented_conversion_with_fixed_point_type) 6882 << SrcTy; 6883 return CK_IntegralCast; 6884 } 6885 llvm_unreachable("Should have returned before this"); 6886 } 6887 6888 llvm_unreachable("Unhandled scalar cast"); 6889 } 6890 6891 static bool breakDownVectorType(QualType type, uint64_t &len, 6892 QualType &eltType) { 6893 // Vectors are simple. 6894 if (const VectorType *vecType = type->getAs<VectorType>()) { 6895 len = vecType->getNumElements(); 6896 eltType = vecType->getElementType(); 6897 assert(eltType->isScalarType()); 6898 return true; 6899 } 6900 6901 // We allow lax conversion to and from non-vector types, but only if 6902 // they're real types (i.e. non-complex, non-pointer scalar types). 6903 if (!type->isRealType()) return false; 6904 6905 len = 1; 6906 eltType = type; 6907 return true; 6908 } 6909 6910 /// Are the two types lax-compatible vector types? That is, given 6911 /// that one of them is a vector, do they have equal storage sizes, 6912 /// where the storage size is the number of elements times the element 6913 /// size? 6914 /// 6915 /// This will also return false if either of the types is neither a 6916 /// vector nor a real type. 6917 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6918 assert(destTy->isVectorType() || srcTy->isVectorType()); 6919 6920 // Disallow lax conversions between scalars and ExtVectors (these 6921 // conversions are allowed for other vector types because common headers 6922 // depend on them). Most scalar OP ExtVector cases are handled by the 6923 // splat path anyway, which does what we want (convert, not bitcast). 6924 // What this rules out for ExtVectors is crazy things like char4*float. 6925 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6926 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6927 6928 uint64_t srcLen, destLen; 6929 QualType srcEltTy, destEltTy; 6930 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6931 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6932 6933 // ASTContext::getTypeSize will return the size rounded up to a 6934 // power of 2, so instead of using that, we need to use the raw 6935 // element size multiplied by the element count. 6936 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6937 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6938 6939 return (srcLen * srcEltSize == destLen * destEltSize); 6940 } 6941 6942 /// Is this a legal conversion between two types, one of which is 6943 /// known to be a vector type? 6944 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6945 assert(destTy->isVectorType() || srcTy->isVectorType()); 6946 6947 switch (Context.getLangOpts().getLaxVectorConversions()) { 6948 case LangOptions::LaxVectorConversionKind::None: 6949 return false; 6950 6951 case LangOptions::LaxVectorConversionKind::Integer: 6952 if (!srcTy->isIntegralOrEnumerationType()) { 6953 auto *Vec = srcTy->getAs<VectorType>(); 6954 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6955 return false; 6956 } 6957 if (!destTy->isIntegralOrEnumerationType()) { 6958 auto *Vec = destTy->getAs<VectorType>(); 6959 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6960 return false; 6961 } 6962 // OK, integer (vector) -> integer (vector) bitcast. 6963 break; 6964 6965 case LangOptions::LaxVectorConversionKind::All: 6966 break; 6967 } 6968 6969 return areLaxCompatibleVectorTypes(srcTy, destTy); 6970 } 6971 6972 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6973 CastKind &Kind) { 6974 assert(VectorTy->isVectorType() && "Not a vector type!"); 6975 6976 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6977 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6978 return Diag(R.getBegin(), 6979 Ty->isVectorType() ? 6980 diag::err_invalid_conversion_between_vectors : 6981 diag::err_invalid_conversion_between_vector_and_integer) 6982 << VectorTy << Ty << R; 6983 } else 6984 return Diag(R.getBegin(), 6985 diag::err_invalid_conversion_between_vector_and_scalar) 6986 << VectorTy << Ty << R; 6987 6988 Kind = CK_BitCast; 6989 return false; 6990 } 6991 6992 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6993 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6994 6995 if (DestElemTy == SplattedExpr->getType()) 6996 return SplattedExpr; 6997 6998 assert(DestElemTy->isFloatingType() || 6999 DestElemTy->isIntegralOrEnumerationType()); 7000 7001 CastKind CK; 7002 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7003 // OpenCL requires that we convert `true` boolean expressions to -1, but 7004 // only when splatting vectors. 7005 if (DestElemTy->isFloatingType()) { 7006 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7007 // in two steps: boolean to signed integral, then to floating. 7008 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7009 CK_BooleanToSignedIntegral); 7010 SplattedExpr = CastExprRes.get(); 7011 CK = CK_IntegralToFloating; 7012 } else { 7013 CK = CK_BooleanToSignedIntegral; 7014 } 7015 } else { 7016 ExprResult CastExprRes = SplattedExpr; 7017 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7018 if (CastExprRes.isInvalid()) 7019 return ExprError(); 7020 SplattedExpr = CastExprRes.get(); 7021 } 7022 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7023 } 7024 7025 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7026 Expr *CastExpr, CastKind &Kind) { 7027 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7028 7029 QualType SrcTy = CastExpr->getType(); 7030 7031 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7032 // an ExtVectorType. 7033 // In OpenCL, casts between vectors of different types are not allowed. 7034 // (See OpenCL 6.2). 7035 if (SrcTy->isVectorType()) { 7036 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7037 (getLangOpts().OpenCL && 7038 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7039 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7040 << DestTy << SrcTy << R; 7041 return ExprError(); 7042 } 7043 Kind = CK_BitCast; 7044 return CastExpr; 7045 } 7046 7047 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7048 // conversion will take place first from scalar to elt type, and then 7049 // splat from elt type to vector. 7050 if (SrcTy->isPointerType()) 7051 return Diag(R.getBegin(), 7052 diag::err_invalid_conversion_between_vector_and_scalar) 7053 << DestTy << SrcTy << R; 7054 7055 Kind = CK_VectorSplat; 7056 return prepareVectorSplat(DestTy, CastExpr); 7057 } 7058 7059 ExprResult 7060 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7061 Declarator &D, ParsedType &Ty, 7062 SourceLocation RParenLoc, Expr *CastExpr) { 7063 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7064 "ActOnCastExpr(): missing type or expr"); 7065 7066 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7067 if (D.isInvalidType()) 7068 return ExprError(); 7069 7070 if (getLangOpts().CPlusPlus) { 7071 // Check that there are no default arguments (C++ only). 7072 CheckExtraCXXDefaultArguments(D); 7073 } else { 7074 // Make sure any TypoExprs have been dealt with. 7075 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7076 if (!Res.isUsable()) 7077 return ExprError(); 7078 CastExpr = Res.get(); 7079 } 7080 7081 checkUnusedDeclAttributes(D); 7082 7083 QualType castType = castTInfo->getType(); 7084 Ty = CreateParsedType(castType, castTInfo); 7085 7086 bool isVectorLiteral = false; 7087 7088 // Check for an altivec or OpenCL literal, 7089 // i.e. all the elements are integer constants. 7090 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7091 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7092 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7093 && castType->isVectorType() && (PE || PLE)) { 7094 if (PLE && PLE->getNumExprs() == 0) { 7095 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7096 return ExprError(); 7097 } 7098 if (PE || PLE->getNumExprs() == 1) { 7099 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7100 if (!E->getType()->isVectorType()) 7101 isVectorLiteral = true; 7102 } 7103 else 7104 isVectorLiteral = true; 7105 } 7106 7107 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7108 // then handle it as such. 7109 if (isVectorLiteral) 7110 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7111 7112 // If the Expr being casted is a ParenListExpr, handle it specially. 7113 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7114 // sequence of BinOp comma operators. 7115 if (isa<ParenListExpr>(CastExpr)) { 7116 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7117 if (Result.isInvalid()) return ExprError(); 7118 CastExpr = Result.get(); 7119 } 7120 7121 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7122 !getSourceManager().isInSystemMacro(LParenLoc)) 7123 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7124 7125 CheckTollFreeBridgeCast(castType, CastExpr); 7126 7127 CheckObjCBridgeRelatedCast(castType, CastExpr); 7128 7129 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7130 7131 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7132 } 7133 7134 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7135 SourceLocation RParenLoc, Expr *E, 7136 TypeSourceInfo *TInfo) { 7137 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7138 "Expected paren or paren list expression"); 7139 7140 Expr **exprs; 7141 unsigned numExprs; 7142 Expr *subExpr; 7143 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7144 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7145 LiteralLParenLoc = PE->getLParenLoc(); 7146 LiteralRParenLoc = PE->getRParenLoc(); 7147 exprs = PE->getExprs(); 7148 numExprs = PE->getNumExprs(); 7149 } else { // isa<ParenExpr> by assertion at function entrance 7150 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7151 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7152 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7153 exprs = &subExpr; 7154 numExprs = 1; 7155 } 7156 7157 QualType Ty = TInfo->getType(); 7158 assert(Ty->isVectorType() && "Expected vector type"); 7159 7160 SmallVector<Expr *, 8> initExprs; 7161 const VectorType *VTy = Ty->castAs<VectorType>(); 7162 unsigned numElems = VTy->getNumElements(); 7163 7164 // '(...)' form of vector initialization in AltiVec: the number of 7165 // initializers must be one or must match the size of the vector. 7166 // If a single value is specified in the initializer then it will be 7167 // replicated to all the components of the vector 7168 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7169 // The number of initializers must be one or must match the size of the 7170 // vector. If a single value is specified in the initializer then it will 7171 // be replicated to all the components of the vector 7172 if (numExprs == 1) { 7173 QualType ElemTy = VTy->getElementType(); 7174 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7175 if (Literal.isInvalid()) 7176 return ExprError(); 7177 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7178 PrepareScalarCast(Literal, ElemTy)); 7179 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7180 } 7181 else if (numExprs < numElems) { 7182 Diag(E->getExprLoc(), 7183 diag::err_incorrect_number_of_vector_initializers); 7184 return ExprError(); 7185 } 7186 else 7187 initExprs.append(exprs, exprs + numExprs); 7188 } 7189 else { 7190 // For OpenCL, when the number of initializers is a single value, 7191 // it will be replicated to all components of the vector. 7192 if (getLangOpts().OpenCL && 7193 VTy->getVectorKind() == VectorType::GenericVector && 7194 numExprs == 1) { 7195 QualType ElemTy = VTy->getElementType(); 7196 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7197 if (Literal.isInvalid()) 7198 return ExprError(); 7199 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7200 PrepareScalarCast(Literal, ElemTy)); 7201 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7202 } 7203 7204 initExprs.append(exprs, exprs + numExprs); 7205 } 7206 // FIXME: This means that pretty-printing the final AST will produce curly 7207 // braces instead of the original commas. 7208 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7209 initExprs, LiteralRParenLoc); 7210 initE->setType(Ty); 7211 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7212 } 7213 7214 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7215 /// the ParenListExpr into a sequence of comma binary operators. 7216 ExprResult 7217 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7218 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7219 if (!E) 7220 return OrigExpr; 7221 7222 ExprResult Result(E->getExpr(0)); 7223 7224 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7225 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7226 E->getExpr(i)); 7227 7228 if (Result.isInvalid()) return ExprError(); 7229 7230 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7231 } 7232 7233 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7234 SourceLocation R, 7235 MultiExprArg Val) { 7236 return ParenListExpr::Create(Context, L, Val, R); 7237 } 7238 7239 /// Emit a specialized diagnostic when one expression is a null pointer 7240 /// constant and the other is not a pointer. Returns true if a diagnostic is 7241 /// emitted. 7242 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7243 SourceLocation QuestionLoc) { 7244 Expr *NullExpr = LHSExpr; 7245 Expr *NonPointerExpr = RHSExpr; 7246 Expr::NullPointerConstantKind NullKind = 7247 NullExpr->isNullPointerConstant(Context, 7248 Expr::NPC_ValueDependentIsNotNull); 7249 7250 if (NullKind == Expr::NPCK_NotNull) { 7251 NullExpr = RHSExpr; 7252 NonPointerExpr = LHSExpr; 7253 NullKind = 7254 NullExpr->isNullPointerConstant(Context, 7255 Expr::NPC_ValueDependentIsNotNull); 7256 } 7257 7258 if (NullKind == Expr::NPCK_NotNull) 7259 return false; 7260 7261 if (NullKind == Expr::NPCK_ZeroExpression) 7262 return false; 7263 7264 if (NullKind == Expr::NPCK_ZeroLiteral) { 7265 // In this case, check to make sure that we got here from a "NULL" 7266 // string in the source code. 7267 NullExpr = NullExpr->IgnoreParenImpCasts(); 7268 SourceLocation loc = NullExpr->getExprLoc(); 7269 if (!findMacroSpelling(loc, "NULL")) 7270 return false; 7271 } 7272 7273 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7274 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7275 << NonPointerExpr->getType() << DiagType 7276 << NonPointerExpr->getSourceRange(); 7277 return true; 7278 } 7279 7280 /// Return false if the condition expression is valid, true otherwise. 7281 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7282 QualType CondTy = Cond->getType(); 7283 7284 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7285 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7286 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7287 << CondTy << Cond->getSourceRange(); 7288 return true; 7289 } 7290 7291 // C99 6.5.15p2 7292 if (CondTy->isScalarType()) return false; 7293 7294 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7295 << CondTy << Cond->getSourceRange(); 7296 return true; 7297 } 7298 7299 /// Handle when one or both operands are void type. 7300 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7301 ExprResult &RHS) { 7302 Expr *LHSExpr = LHS.get(); 7303 Expr *RHSExpr = RHS.get(); 7304 7305 if (!LHSExpr->getType()->isVoidType()) 7306 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7307 << RHSExpr->getSourceRange(); 7308 if (!RHSExpr->getType()->isVoidType()) 7309 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7310 << LHSExpr->getSourceRange(); 7311 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7312 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7313 return S.Context.VoidTy; 7314 } 7315 7316 /// Return false if the NullExpr can be promoted to PointerTy, 7317 /// true otherwise. 7318 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7319 QualType PointerTy) { 7320 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7321 !NullExpr.get()->isNullPointerConstant(S.Context, 7322 Expr::NPC_ValueDependentIsNull)) 7323 return true; 7324 7325 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7326 return false; 7327 } 7328 7329 /// Checks compatibility between two pointers and return the resulting 7330 /// type. 7331 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7332 ExprResult &RHS, 7333 SourceLocation Loc) { 7334 QualType LHSTy = LHS.get()->getType(); 7335 QualType RHSTy = RHS.get()->getType(); 7336 7337 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7338 // Two identical pointers types are always compatible. 7339 return LHSTy; 7340 } 7341 7342 QualType lhptee, rhptee; 7343 7344 // Get the pointee types. 7345 bool IsBlockPointer = false; 7346 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7347 lhptee = LHSBTy->getPointeeType(); 7348 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7349 IsBlockPointer = true; 7350 } else { 7351 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7352 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7353 } 7354 7355 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7356 // differently qualified versions of compatible types, the result type is 7357 // a pointer to an appropriately qualified version of the composite 7358 // type. 7359 7360 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7361 // clause doesn't make sense for our extensions. E.g. address space 2 should 7362 // be incompatible with address space 3: they may live on different devices or 7363 // anything. 7364 Qualifiers lhQual = lhptee.getQualifiers(); 7365 Qualifiers rhQual = rhptee.getQualifiers(); 7366 7367 LangAS ResultAddrSpace = LangAS::Default; 7368 LangAS LAddrSpace = lhQual.getAddressSpace(); 7369 LangAS RAddrSpace = rhQual.getAddressSpace(); 7370 7371 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7372 // spaces is disallowed. 7373 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7374 ResultAddrSpace = LAddrSpace; 7375 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7376 ResultAddrSpace = RAddrSpace; 7377 else { 7378 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7379 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7380 << RHS.get()->getSourceRange(); 7381 return QualType(); 7382 } 7383 7384 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7385 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7386 lhQual.removeCVRQualifiers(); 7387 rhQual.removeCVRQualifiers(); 7388 7389 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7390 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7391 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7392 // qual types are compatible iff 7393 // * corresponded types are compatible 7394 // * CVR qualifiers are equal 7395 // * address spaces are equal 7396 // Thus for conditional operator we merge CVR and address space unqualified 7397 // pointees and if there is a composite type we return a pointer to it with 7398 // merged qualifiers. 7399 LHSCastKind = 7400 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7401 RHSCastKind = 7402 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7403 lhQual.removeAddressSpace(); 7404 rhQual.removeAddressSpace(); 7405 7406 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7407 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7408 7409 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7410 7411 if (CompositeTy.isNull()) { 7412 // In this situation, we assume void* type. No especially good 7413 // reason, but this is what gcc does, and we do have to pick 7414 // to get a consistent AST. 7415 QualType incompatTy; 7416 incompatTy = S.Context.getPointerType( 7417 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7418 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7419 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7420 7421 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7422 // for casts between types with incompatible address space qualifiers. 7423 // For the following code the compiler produces casts between global and 7424 // local address spaces of the corresponded innermost pointees: 7425 // local int *global *a; 7426 // global int *global *b; 7427 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7428 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7429 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7430 << RHS.get()->getSourceRange(); 7431 7432 return incompatTy; 7433 } 7434 7435 // The pointer types are compatible. 7436 // In case of OpenCL ResultTy should have the address space qualifier 7437 // which is a superset of address spaces of both the 2nd and the 3rd 7438 // operands of the conditional operator. 7439 QualType ResultTy = [&, ResultAddrSpace]() { 7440 if (S.getLangOpts().OpenCL) { 7441 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7442 CompositeQuals.setAddressSpace(ResultAddrSpace); 7443 return S.Context 7444 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7445 .withCVRQualifiers(MergedCVRQual); 7446 } 7447 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7448 }(); 7449 if (IsBlockPointer) 7450 ResultTy = S.Context.getBlockPointerType(ResultTy); 7451 else 7452 ResultTy = S.Context.getPointerType(ResultTy); 7453 7454 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7455 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7456 return ResultTy; 7457 } 7458 7459 /// Return the resulting type when the operands are both block pointers. 7460 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7461 ExprResult &LHS, 7462 ExprResult &RHS, 7463 SourceLocation Loc) { 7464 QualType LHSTy = LHS.get()->getType(); 7465 QualType RHSTy = RHS.get()->getType(); 7466 7467 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7468 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7469 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7470 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7471 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7472 return destType; 7473 } 7474 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7475 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7476 << RHS.get()->getSourceRange(); 7477 return QualType(); 7478 } 7479 7480 // We have 2 block pointer types. 7481 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7482 } 7483 7484 /// Return the resulting type when the operands are both pointers. 7485 static QualType 7486 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7487 ExprResult &RHS, 7488 SourceLocation Loc) { 7489 // get the pointer types 7490 QualType LHSTy = LHS.get()->getType(); 7491 QualType RHSTy = RHS.get()->getType(); 7492 7493 // get the "pointed to" types 7494 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7495 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7496 7497 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7498 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7499 // Figure out necessary qualifiers (C99 6.5.15p6) 7500 QualType destPointee 7501 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7502 QualType destType = S.Context.getPointerType(destPointee); 7503 // Add qualifiers if necessary. 7504 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7505 // Promote to void*. 7506 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7507 return destType; 7508 } 7509 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7510 QualType destPointee 7511 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7512 QualType destType = S.Context.getPointerType(destPointee); 7513 // Add qualifiers if necessary. 7514 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7515 // Promote to void*. 7516 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7517 return destType; 7518 } 7519 7520 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7521 } 7522 7523 /// Return false if the first expression is not an integer and the second 7524 /// expression is not a pointer, true otherwise. 7525 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7526 Expr* PointerExpr, SourceLocation Loc, 7527 bool IsIntFirstExpr) { 7528 if (!PointerExpr->getType()->isPointerType() || 7529 !Int.get()->getType()->isIntegerType()) 7530 return false; 7531 7532 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7533 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7534 7535 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7536 << Expr1->getType() << Expr2->getType() 7537 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7538 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7539 CK_IntegralToPointer); 7540 return true; 7541 } 7542 7543 /// Simple conversion between integer and floating point types. 7544 /// 7545 /// Used when handling the OpenCL conditional operator where the 7546 /// condition is a vector while the other operands are scalar. 7547 /// 7548 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7549 /// types are either integer or floating type. Between the two 7550 /// operands, the type with the higher rank is defined as the "result 7551 /// type". The other operand needs to be promoted to the same type. No 7552 /// other type promotion is allowed. We cannot use 7553 /// UsualArithmeticConversions() for this purpose, since it always 7554 /// promotes promotable types. 7555 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7556 ExprResult &RHS, 7557 SourceLocation QuestionLoc) { 7558 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7559 if (LHS.isInvalid()) 7560 return QualType(); 7561 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7562 if (RHS.isInvalid()) 7563 return QualType(); 7564 7565 // For conversion purposes, we ignore any qualifiers. 7566 // For example, "const float" and "float" are equivalent. 7567 QualType LHSType = 7568 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7569 QualType RHSType = 7570 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7571 7572 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7573 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7574 << LHSType << LHS.get()->getSourceRange(); 7575 return QualType(); 7576 } 7577 7578 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7579 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7580 << RHSType << RHS.get()->getSourceRange(); 7581 return QualType(); 7582 } 7583 7584 // If both types are identical, no conversion is needed. 7585 if (LHSType == RHSType) 7586 return LHSType; 7587 7588 // Now handle "real" floating types (i.e. float, double, long double). 7589 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7590 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7591 /*IsCompAssign = */ false); 7592 7593 // Finally, we have two differing integer types. 7594 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7595 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7596 } 7597 7598 /// Convert scalar operands to a vector that matches the 7599 /// condition in length. 7600 /// 7601 /// Used when handling the OpenCL conditional operator where the 7602 /// condition is a vector while the other operands are scalar. 7603 /// 7604 /// We first compute the "result type" for the scalar operands 7605 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7606 /// into a vector of that type where the length matches the condition 7607 /// vector type. s6.11.6 requires that the element types of the result 7608 /// and the condition must have the same number of bits. 7609 static QualType 7610 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7611 QualType CondTy, SourceLocation QuestionLoc) { 7612 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7613 if (ResTy.isNull()) return QualType(); 7614 7615 const VectorType *CV = CondTy->getAs<VectorType>(); 7616 assert(CV); 7617 7618 // Determine the vector result type 7619 unsigned NumElements = CV->getNumElements(); 7620 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7621 7622 // Ensure that all types have the same number of bits 7623 if (S.Context.getTypeSize(CV->getElementType()) 7624 != S.Context.getTypeSize(ResTy)) { 7625 // Since VectorTy is created internally, it does not pretty print 7626 // with an OpenCL name. Instead, we just print a description. 7627 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7628 SmallString<64> Str; 7629 llvm::raw_svector_ostream OS(Str); 7630 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7631 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7632 << CondTy << OS.str(); 7633 return QualType(); 7634 } 7635 7636 // Convert operands to the vector result type 7637 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7638 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7639 7640 return VectorTy; 7641 } 7642 7643 /// Return false if this is a valid OpenCL condition vector 7644 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7645 SourceLocation QuestionLoc) { 7646 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7647 // integral type. 7648 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7649 assert(CondTy); 7650 QualType EleTy = CondTy->getElementType(); 7651 if (EleTy->isIntegerType()) return false; 7652 7653 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7654 << Cond->getType() << Cond->getSourceRange(); 7655 return true; 7656 } 7657 7658 /// Return false if the vector condition type and the vector 7659 /// result type are compatible. 7660 /// 7661 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7662 /// number of elements, and their element types have the same number 7663 /// of bits. 7664 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7665 SourceLocation QuestionLoc) { 7666 const VectorType *CV = CondTy->getAs<VectorType>(); 7667 const VectorType *RV = VecResTy->getAs<VectorType>(); 7668 assert(CV && RV); 7669 7670 if (CV->getNumElements() != RV->getNumElements()) { 7671 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7672 << CondTy << VecResTy; 7673 return true; 7674 } 7675 7676 QualType CVE = CV->getElementType(); 7677 QualType RVE = RV->getElementType(); 7678 7679 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7680 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7681 << CondTy << VecResTy; 7682 return true; 7683 } 7684 7685 return false; 7686 } 7687 7688 /// Return the resulting type for the conditional operator in 7689 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7690 /// s6.3.i) when the condition is a vector type. 7691 static QualType 7692 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7693 ExprResult &LHS, ExprResult &RHS, 7694 SourceLocation QuestionLoc) { 7695 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7696 if (Cond.isInvalid()) 7697 return QualType(); 7698 QualType CondTy = Cond.get()->getType(); 7699 7700 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7701 return QualType(); 7702 7703 // If either operand is a vector then find the vector type of the 7704 // result as specified in OpenCL v1.1 s6.3.i. 7705 if (LHS.get()->getType()->isVectorType() || 7706 RHS.get()->getType()->isVectorType()) { 7707 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7708 /*isCompAssign*/false, 7709 /*AllowBothBool*/true, 7710 /*AllowBoolConversions*/false); 7711 if (VecResTy.isNull()) return QualType(); 7712 // The result type must match the condition type as specified in 7713 // OpenCL v1.1 s6.11.6. 7714 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7715 return QualType(); 7716 return VecResTy; 7717 } 7718 7719 // Both operands are scalar. 7720 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7721 } 7722 7723 /// Return true if the Expr is block type 7724 static bool checkBlockType(Sema &S, const Expr *E) { 7725 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7726 QualType Ty = CE->getCallee()->getType(); 7727 if (Ty->isBlockPointerType()) { 7728 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7729 return true; 7730 } 7731 } 7732 return false; 7733 } 7734 7735 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7736 /// In that case, LHS = cond. 7737 /// C99 6.5.15 7738 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7739 ExprResult &RHS, ExprValueKind &VK, 7740 ExprObjectKind &OK, 7741 SourceLocation QuestionLoc) { 7742 7743 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7744 if (!LHSResult.isUsable()) return QualType(); 7745 LHS = LHSResult; 7746 7747 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7748 if (!RHSResult.isUsable()) return QualType(); 7749 RHS = RHSResult; 7750 7751 // C++ is sufficiently different to merit its own checker. 7752 if (getLangOpts().CPlusPlus) 7753 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7754 7755 VK = VK_RValue; 7756 OK = OK_Ordinary; 7757 7758 // The OpenCL operator with a vector condition is sufficiently 7759 // different to merit its own checker. 7760 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7761 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7762 7763 // First, check the condition. 7764 Cond = UsualUnaryConversions(Cond.get()); 7765 if (Cond.isInvalid()) 7766 return QualType(); 7767 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7768 return QualType(); 7769 7770 // Now check the two expressions. 7771 if (LHS.get()->getType()->isVectorType() || 7772 RHS.get()->getType()->isVectorType()) 7773 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7774 /*AllowBothBool*/true, 7775 /*AllowBoolConversions*/false); 7776 7777 QualType ResTy = 7778 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7779 if (LHS.isInvalid() || RHS.isInvalid()) 7780 return QualType(); 7781 7782 QualType LHSTy = LHS.get()->getType(); 7783 QualType RHSTy = RHS.get()->getType(); 7784 7785 // Diagnose attempts to convert between __float128 and long double where 7786 // such conversions currently can't be handled. 7787 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7788 Diag(QuestionLoc, 7789 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7791 return QualType(); 7792 } 7793 7794 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7795 // selection operator (?:). 7796 if (getLangOpts().OpenCL && 7797 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7798 return QualType(); 7799 } 7800 7801 // If both operands have arithmetic type, do the usual arithmetic conversions 7802 // to find a common type: C99 6.5.15p3,5. 7803 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7804 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7805 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7806 7807 return ResTy; 7808 } 7809 7810 // If both operands are the same structure or union type, the result is that 7811 // type. 7812 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7813 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7814 if (LHSRT->getDecl() == RHSRT->getDecl()) 7815 // "If both the operands have structure or union type, the result has 7816 // that type." This implies that CV qualifiers are dropped. 7817 return LHSTy.getUnqualifiedType(); 7818 // FIXME: Type of conditional expression must be complete in C mode. 7819 } 7820 7821 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7822 // The following || allows only one side to be void (a GCC-ism). 7823 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7824 return checkConditionalVoidType(*this, LHS, RHS); 7825 } 7826 7827 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7828 // the type of the other operand." 7829 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7830 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7831 7832 // All objective-c pointer type analysis is done here. 7833 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7834 QuestionLoc); 7835 if (LHS.isInvalid() || RHS.isInvalid()) 7836 return QualType(); 7837 if (!compositeType.isNull()) 7838 return compositeType; 7839 7840 7841 // Handle block pointer types. 7842 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7843 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7844 QuestionLoc); 7845 7846 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7847 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7848 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7849 QuestionLoc); 7850 7851 // GCC compatibility: soften pointer/integer mismatch. Note that 7852 // null pointers have been filtered out by this point. 7853 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7854 /*IsIntFirstExpr=*/true)) 7855 return RHSTy; 7856 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7857 /*IsIntFirstExpr=*/false)) 7858 return LHSTy; 7859 7860 // Allow ?: operations in which both operands have the same 7861 // built-in sizeless type. 7862 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 7863 return LHSTy; 7864 7865 // Emit a better diagnostic if one of the expressions is a null pointer 7866 // constant and the other is not a pointer type. In this case, the user most 7867 // likely forgot to take the address of the other expression. 7868 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7869 return QualType(); 7870 7871 // Otherwise, the operands are not compatible. 7872 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7873 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7874 << RHS.get()->getSourceRange(); 7875 return QualType(); 7876 } 7877 7878 /// FindCompositeObjCPointerType - Helper method to find composite type of 7879 /// two objective-c pointer types of the two input expressions. 7880 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7881 SourceLocation QuestionLoc) { 7882 QualType LHSTy = LHS.get()->getType(); 7883 QualType RHSTy = RHS.get()->getType(); 7884 7885 // Handle things like Class and struct objc_class*. Here we case the result 7886 // to the pseudo-builtin, because that will be implicitly cast back to the 7887 // redefinition type if an attempt is made to access its fields. 7888 if (LHSTy->isObjCClassType() && 7889 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7890 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7891 return LHSTy; 7892 } 7893 if (RHSTy->isObjCClassType() && 7894 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7895 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7896 return RHSTy; 7897 } 7898 // And the same for struct objc_object* / id 7899 if (LHSTy->isObjCIdType() && 7900 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7901 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7902 return LHSTy; 7903 } 7904 if (RHSTy->isObjCIdType() && 7905 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7906 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7907 return RHSTy; 7908 } 7909 // And the same for struct objc_selector* / SEL 7910 if (Context.isObjCSelType(LHSTy) && 7911 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7912 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7913 return LHSTy; 7914 } 7915 if (Context.isObjCSelType(RHSTy) && 7916 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7917 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7918 return RHSTy; 7919 } 7920 // Check constraints for Objective-C object pointers types. 7921 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7922 7923 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7924 // Two identical object pointer types are always compatible. 7925 return LHSTy; 7926 } 7927 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7928 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7929 QualType compositeType = LHSTy; 7930 7931 // If both operands are interfaces and either operand can be 7932 // assigned to the other, use that type as the composite 7933 // type. This allows 7934 // xxx ? (A*) a : (B*) b 7935 // where B is a subclass of A. 7936 // 7937 // Additionally, as for assignment, if either type is 'id' 7938 // allow silent coercion. Finally, if the types are 7939 // incompatible then make sure to use 'id' as the composite 7940 // type so the result is acceptable for sending messages to. 7941 7942 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7943 // It could return the composite type. 7944 if (!(compositeType = 7945 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7946 // Nothing more to do. 7947 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7948 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7949 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7950 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7951 } else if ((LHSOPT->isObjCQualifiedIdType() || 7952 RHSOPT->isObjCQualifiedIdType()) && 7953 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7954 true)) { 7955 // Need to handle "id<xx>" explicitly. 7956 // GCC allows qualified id and any Objective-C type to devolve to 7957 // id. Currently localizing to here until clear this should be 7958 // part of ObjCQualifiedIdTypesAreCompatible. 7959 compositeType = Context.getObjCIdType(); 7960 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7961 compositeType = Context.getObjCIdType(); 7962 } else { 7963 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7964 << LHSTy << RHSTy 7965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7966 QualType incompatTy = Context.getObjCIdType(); 7967 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7968 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7969 return incompatTy; 7970 } 7971 // The object pointer types are compatible. 7972 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7973 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7974 return compositeType; 7975 } 7976 // Check Objective-C object pointer types and 'void *' 7977 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7978 if (getLangOpts().ObjCAutoRefCount) { 7979 // ARC forbids the implicit conversion of object pointers to 'void *', 7980 // so these types are not compatible. 7981 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7982 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7983 LHS = RHS = true; 7984 return QualType(); 7985 } 7986 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7987 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7988 QualType destPointee 7989 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7990 QualType destType = Context.getPointerType(destPointee); 7991 // Add qualifiers if necessary. 7992 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7993 // Promote to void*. 7994 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7995 return destType; 7996 } 7997 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7998 if (getLangOpts().ObjCAutoRefCount) { 7999 // ARC forbids the implicit conversion of object pointers to 'void *', 8000 // so these types are not compatible. 8001 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8002 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8003 LHS = RHS = true; 8004 return QualType(); 8005 } 8006 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8007 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8008 QualType destPointee 8009 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8010 QualType destType = Context.getPointerType(destPointee); 8011 // Add qualifiers if necessary. 8012 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8013 // Promote to void*. 8014 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8015 return destType; 8016 } 8017 return QualType(); 8018 } 8019 8020 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8021 /// ParenRange in parentheses. 8022 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8023 const PartialDiagnostic &Note, 8024 SourceRange ParenRange) { 8025 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8026 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8027 EndLoc.isValid()) { 8028 Self.Diag(Loc, Note) 8029 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8030 << FixItHint::CreateInsertion(EndLoc, ")"); 8031 } else { 8032 // We can't display the parentheses, so just show the bare note. 8033 Self.Diag(Loc, Note) << ParenRange; 8034 } 8035 } 8036 8037 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8038 return BinaryOperator::isAdditiveOp(Opc) || 8039 BinaryOperator::isMultiplicativeOp(Opc) || 8040 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8041 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8042 // not any of the logical operators. Bitwise-xor is commonly used as a 8043 // logical-xor because there is no logical-xor operator. The logical 8044 // operators, including uses of xor, have a high false positive rate for 8045 // precedence warnings. 8046 } 8047 8048 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8049 /// expression, either using a built-in or overloaded operator, 8050 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8051 /// expression. 8052 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8053 Expr **RHSExprs) { 8054 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8055 E = E->IgnoreImpCasts(); 8056 E = E->IgnoreConversionOperator(); 8057 E = E->IgnoreImpCasts(); 8058 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8059 E = MTE->getSubExpr(); 8060 E = E->IgnoreImpCasts(); 8061 } 8062 8063 // Built-in binary operator. 8064 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8065 if (IsArithmeticOp(OP->getOpcode())) { 8066 *Opcode = OP->getOpcode(); 8067 *RHSExprs = OP->getRHS(); 8068 return true; 8069 } 8070 } 8071 8072 // Overloaded operator. 8073 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8074 if (Call->getNumArgs() != 2) 8075 return false; 8076 8077 // Make sure this is really a binary operator that is safe to pass into 8078 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8079 OverloadedOperatorKind OO = Call->getOperator(); 8080 if (OO < OO_Plus || OO > OO_Arrow || 8081 OO == OO_PlusPlus || OO == OO_MinusMinus) 8082 return false; 8083 8084 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8085 if (IsArithmeticOp(OpKind)) { 8086 *Opcode = OpKind; 8087 *RHSExprs = Call->getArg(1); 8088 return true; 8089 } 8090 } 8091 8092 return false; 8093 } 8094 8095 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8096 /// or is a logical expression such as (x==y) which has int type, but is 8097 /// commonly interpreted as boolean. 8098 static bool ExprLooksBoolean(Expr *E) { 8099 E = E->IgnoreParenImpCasts(); 8100 8101 if (E->getType()->isBooleanType()) 8102 return true; 8103 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8104 return OP->isComparisonOp() || OP->isLogicalOp(); 8105 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8106 return OP->getOpcode() == UO_LNot; 8107 if (E->getType()->isPointerType()) 8108 return true; 8109 // FIXME: What about overloaded operator calls returning "unspecified boolean 8110 // type"s (commonly pointer-to-members)? 8111 8112 return false; 8113 } 8114 8115 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8116 /// and binary operator are mixed in a way that suggests the programmer assumed 8117 /// the conditional operator has higher precedence, for example: 8118 /// "int x = a + someBinaryCondition ? 1 : 2". 8119 static void DiagnoseConditionalPrecedence(Sema &Self, 8120 SourceLocation OpLoc, 8121 Expr *Condition, 8122 Expr *LHSExpr, 8123 Expr *RHSExpr) { 8124 BinaryOperatorKind CondOpcode; 8125 Expr *CondRHS; 8126 8127 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8128 return; 8129 if (!ExprLooksBoolean(CondRHS)) 8130 return; 8131 8132 // The condition is an arithmetic binary expression, with a right- 8133 // hand side that looks boolean, so warn. 8134 8135 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8136 ? diag::warn_precedence_bitwise_conditional 8137 : diag::warn_precedence_conditional; 8138 8139 Self.Diag(OpLoc, DiagID) 8140 << Condition->getSourceRange() 8141 << BinaryOperator::getOpcodeStr(CondOpcode); 8142 8143 SuggestParentheses( 8144 Self, OpLoc, 8145 Self.PDiag(diag::note_precedence_silence) 8146 << BinaryOperator::getOpcodeStr(CondOpcode), 8147 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8148 8149 SuggestParentheses(Self, OpLoc, 8150 Self.PDiag(diag::note_precedence_conditional_first), 8151 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8152 } 8153 8154 /// Compute the nullability of a conditional expression. 8155 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8156 QualType LHSTy, QualType RHSTy, 8157 ASTContext &Ctx) { 8158 if (!ResTy->isAnyPointerType()) 8159 return ResTy; 8160 8161 auto GetNullability = [&Ctx](QualType Ty) { 8162 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8163 if (Kind) 8164 return *Kind; 8165 return NullabilityKind::Unspecified; 8166 }; 8167 8168 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8169 NullabilityKind MergedKind; 8170 8171 // Compute nullability of a binary conditional expression. 8172 if (IsBin) { 8173 if (LHSKind == NullabilityKind::NonNull) 8174 MergedKind = NullabilityKind::NonNull; 8175 else 8176 MergedKind = RHSKind; 8177 // Compute nullability of a normal conditional expression. 8178 } else { 8179 if (LHSKind == NullabilityKind::Nullable || 8180 RHSKind == NullabilityKind::Nullable) 8181 MergedKind = NullabilityKind::Nullable; 8182 else if (LHSKind == NullabilityKind::NonNull) 8183 MergedKind = RHSKind; 8184 else if (RHSKind == NullabilityKind::NonNull) 8185 MergedKind = LHSKind; 8186 else 8187 MergedKind = NullabilityKind::Unspecified; 8188 } 8189 8190 // Return if ResTy already has the correct nullability. 8191 if (GetNullability(ResTy) == MergedKind) 8192 return ResTy; 8193 8194 // Strip all nullability from ResTy. 8195 while (ResTy->getNullability(Ctx)) 8196 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8197 8198 // Create a new AttributedType with the new nullability kind. 8199 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8200 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8201 } 8202 8203 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8204 /// in the case of a the GNU conditional expr extension. 8205 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8206 SourceLocation ColonLoc, 8207 Expr *CondExpr, Expr *LHSExpr, 8208 Expr *RHSExpr) { 8209 if (!getLangOpts().CPlusPlus) { 8210 // C cannot handle TypoExpr nodes in the condition because it 8211 // doesn't handle dependent types properly, so make sure any TypoExprs have 8212 // been dealt with before checking the operands. 8213 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8214 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8215 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8216 8217 if (!CondResult.isUsable()) 8218 return ExprError(); 8219 8220 if (LHSExpr) { 8221 if (!LHSResult.isUsable()) 8222 return ExprError(); 8223 } 8224 8225 if (!RHSResult.isUsable()) 8226 return ExprError(); 8227 8228 CondExpr = CondResult.get(); 8229 LHSExpr = LHSResult.get(); 8230 RHSExpr = RHSResult.get(); 8231 } 8232 8233 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8234 // was the condition. 8235 OpaqueValueExpr *opaqueValue = nullptr; 8236 Expr *commonExpr = nullptr; 8237 if (!LHSExpr) { 8238 commonExpr = CondExpr; 8239 // Lower out placeholder types first. This is important so that we don't 8240 // try to capture a placeholder. This happens in few cases in C++; such 8241 // as Objective-C++'s dictionary subscripting syntax. 8242 if (commonExpr->hasPlaceholderType()) { 8243 ExprResult result = CheckPlaceholderExpr(commonExpr); 8244 if (!result.isUsable()) return ExprError(); 8245 commonExpr = result.get(); 8246 } 8247 // We usually want to apply unary conversions *before* saving, except 8248 // in the special case of a C++ l-value conditional. 8249 if (!(getLangOpts().CPlusPlus 8250 && !commonExpr->isTypeDependent() 8251 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8252 && commonExpr->isGLValue() 8253 && commonExpr->isOrdinaryOrBitFieldObject() 8254 && RHSExpr->isOrdinaryOrBitFieldObject() 8255 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8256 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8257 if (commonRes.isInvalid()) 8258 return ExprError(); 8259 commonExpr = commonRes.get(); 8260 } 8261 8262 // If the common expression is a class or array prvalue, materialize it 8263 // so that we can safely refer to it multiple times. 8264 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8265 commonExpr->getType()->isArrayType())) { 8266 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8267 if (MatExpr.isInvalid()) 8268 return ExprError(); 8269 commonExpr = MatExpr.get(); 8270 } 8271 8272 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8273 commonExpr->getType(), 8274 commonExpr->getValueKind(), 8275 commonExpr->getObjectKind(), 8276 commonExpr); 8277 LHSExpr = CondExpr = opaqueValue; 8278 } 8279 8280 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8281 ExprValueKind VK = VK_RValue; 8282 ExprObjectKind OK = OK_Ordinary; 8283 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8284 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8285 VK, OK, QuestionLoc); 8286 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8287 RHS.isInvalid()) 8288 return ExprError(); 8289 8290 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8291 RHS.get()); 8292 8293 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8294 8295 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8296 Context); 8297 8298 if (!commonExpr) 8299 return new (Context) 8300 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8301 RHS.get(), result, VK, OK); 8302 8303 return new (Context) BinaryConditionalOperator( 8304 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8305 ColonLoc, result, VK, OK); 8306 } 8307 8308 // Check if we have a conversion between incompatible cmse function pointer 8309 // types, that is, a conversion between a function pointer with the 8310 // cmse_nonsecure_call attribute and one without. 8311 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8312 QualType ToType) { 8313 if (const auto *ToFn = 8314 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8315 if (const auto *FromFn = 8316 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8317 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8318 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8319 8320 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8321 } 8322 } 8323 return false; 8324 } 8325 8326 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8327 // being closely modeled after the C99 spec:-). The odd characteristic of this 8328 // routine is it effectively iqnores the qualifiers on the top level pointee. 8329 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8330 // FIXME: add a couple examples in this comment. 8331 static Sema::AssignConvertType 8332 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8333 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8334 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8335 8336 // get the "pointed to" type (ignoring qualifiers at the top level) 8337 const Type *lhptee, *rhptee; 8338 Qualifiers lhq, rhq; 8339 std::tie(lhptee, lhq) = 8340 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8341 std::tie(rhptee, rhq) = 8342 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8343 8344 Sema::AssignConvertType ConvTy = Sema::Compatible; 8345 8346 // C99 6.5.16.1p1: This following citation is common to constraints 8347 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8348 // qualifiers of the type *pointed to* by the right; 8349 8350 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8351 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8352 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8353 // Ignore lifetime for further calculation. 8354 lhq.removeObjCLifetime(); 8355 rhq.removeObjCLifetime(); 8356 } 8357 8358 if (!lhq.compatiblyIncludes(rhq)) { 8359 // Treat address-space mismatches as fatal. 8360 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8361 return Sema::IncompatiblePointerDiscardsQualifiers; 8362 8363 // It's okay to add or remove GC or lifetime qualifiers when converting to 8364 // and from void*. 8365 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8366 .compatiblyIncludes( 8367 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8368 && (lhptee->isVoidType() || rhptee->isVoidType())) 8369 ; // keep old 8370 8371 // Treat lifetime mismatches as fatal. 8372 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8373 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8374 8375 // For GCC/MS compatibility, other qualifier mismatches are treated 8376 // as still compatible in C. 8377 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8378 } 8379 8380 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8381 // incomplete type and the other is a pointer to a qualified or unqualified 8382 // version of void... 8383 if (lhptee->isVoidType()) { 8384 if (rhptee->isIncompleteOrObjectType()) 8385 return ConvTy; 8386 8387 // As an extension, we allow cast to/from void* to function pointer. 8388 assert(rhptee->isFunctionType()); 8389 return Sema::FunctionVoidPointer; 8390 } 8391 8392 if (rhptee->isVoidType()) { 8393 if (lhptee->isIncompleteOrObjectType()) 8394 return ConvTy; 8395 8396 // As an extension, we allow cast to/from void* to function pointer. 8397 assert(lhptee->isFunctionType()); 8398 return Sema::FunctionVoidPointer; 8399 } 8400 8401 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8402 // unqualified versions of compatible types, ... 8403 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8404 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8405 // Check if the pointee types are compatible ignoring the sign. 8406 // We explicitly check for char so that we catch "char" vs 8407 // "unsigned char" on systems where "char" is unsigned. 8408 if (lhptee->isCharType()) 8409 ltrans = S.Context.UnsignedCharTy; 8410 else if (lhptee->hasSignedIntegerRepresentation()) 8411 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8412 8413 if (rhptee->isCharType()) 8414 rtrans = S.Context.UnsignedCharTy; 8415 else if (rhptee->hasSignedIntegerRepresentation()) 8416 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8417 8418 if (ltrans == rtrans) { 8419 // Types are compatible ignoring the sign. Qualifier incompatibility 8420 // takes priority over sign incompatibility because the sign 8421 // warning can be disabled. 8422 if (ConvTy != Sema::Compatible) 8423 return ConvTy; 8424 8425 return Sema::IncompatiblePointerSign; 8426 } 8427 8428 // If we are a multi-level pointer, it's possible that our issue is simply 8429 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8430 // the eventual target type is the same and the pointers have the same 8431 // level of indirection, this must be the issue. 8432 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8433 do { 8434 std::tie(lhptee, lhq) = 8435 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8436 std::tie(rhptee, rhq) = 8437 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8438 8439 // Inconsistent address spaces at this point is invalid, even if the 8440 // address spaces would be compatible. 8441 // FIXME: This doesn't catch address space mismatches for pointers of 8442 // different nesting levels, like: 8443 // __local int *** a; 8444 // int ** b = a; 8445 // It's not clear how to actually determine when such pointers are 8446 // invalidly incompatible. 8447 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8448 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8449 8450 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8451 8452 if (lhptee == rhptee) 8453 return Sema::IncompatibleNestedPointerQualifiers; 8454 } 8455 8456 // General pointer incompatibility takes priority over qualifiers. 8457 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8458 return Sema::IncompatibleFunctionPointer; 8459 return Sema::IncompatiblePointer; 8460 } 8461 if (!S.getLangOpts().CPlusPlus && 8462 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8463 return Sema::IncompatibleFunctionPointer; 8464 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8465 return Sema::IncompatibleFunctionPointer; 8466 return ConvTy; 8467 } 8468 8469 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8470 /// block pointer types are compatible or whether a block and normal pointer 8471 /// are compatible. It is more restrict than comparing two function pointer 8472 // types. 8473 static Sema::AssignConvertType 8474 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8475 QualType RHSType) { 8476 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8477 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8478 8479 QualType lhptee, rhptee; 8480 8481 // get the "pointed to" type (ignoring qualifiers at the top level) 8482 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8483 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8484 8485 // In C++, the types have to match exactly. 8486 if (S.getLangOpts().CPlusPlus) 8487 return Sema::IncompatibleBlockPointer; 8488 8489 Sema::AssignConvertType ConvTy = Sema::Compatible; 8490 8491 // For blocks we enforce that qualifiers are identical. 8492 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8493 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8494 if (S.getLangOpts().OpenCL) { 8495 LQuals.removeAddressSpace(); 8496 RQuals.removeAddressSpace(); 8497 } 8498 if (LQuals != RQuals) 8499 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8500 8501 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8502 // assignment. 8503 // The current behavior is similar to C++ lambdas. A block might be 8504 // assigned to a variable iff its return type and parameters are compatible 8505 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8506 // an assignment. Presumably it should behave in way that a function pointer 8507 // assignment does in C, so for each parameter and return type: 8508 // * CVR and address space of LHS should be a superset of CVR and address 8509 // space of RHS. 8510 // * unqualified types should be compatible. 8511 if (S.getLangOpts().OpenCL) { 8512 if (!S.Context.typesAreBlockPointerCompatible( 8513 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8514 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8515 return Sema::IncompatibleBlockPointer; 8516 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8517 return Sema::IncompatibleBlockPointer; 8518 8519 return ConvTy; 8520 } 8521 8522 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8523 /// for assignment compatibility. 8524 static Sema::AssignConvertType 8525 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8526 QualType RHSType) { 8527 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8528 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8529 8530 if (LHSType->isObjCBuiltinType()) { 8531 // Class is not compatible with ObjC object pointers. 8532 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8533 !RHSType->isObjCQualifiedClassType()) 8534 return Sema::IncompatiblePointer; 8535 return Sema::Compatible; 8536 } 8537 if (RHSType->isObjCBuiltinType()) { 8538 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8539 !LHSType->isObjCQualifiedClassType()) 8540 return Sema::IncompatiblePointer; 8541 return Sema::Compatible; 8542 } 8543 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8544 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8545 8546 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8547 // make an exception for id<P> 8548 !LHSType->isObjCQualifiedIdType()) 8549 return Sema::CompatiblePointerDiscardsQualifiers; 8550 8551 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8552 return Sema::Compatible; 8553 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8554 return Sema::IncompatibleObjCQualifiedId; 8555 return Sema::IncompatiblePointer; 8556 } 8557 8558 Sema::AssignConvertType 8559 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8560 QualType LHSType, QualType RHSType) { 8561 // Fake up an opaque expression. We don't actually care about what 8562 // cast operations are required, so if CheckAssignmentConstraints 8563 // adds casts to this they'll be wasted, but fortunately that doesn't 8564 // usually happen on valid code. 8565 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8566 ExprResult RHSPtr = &RHSExpr; 8567 CastKind K; 8568 8569 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8570 } 8571 8572 /// This helper function returns true if QT is a vector type that has element 8573 /// type ElementType. 8574 static bool isVector(QualType QT, QualType ElementType) { 8575 if (const VectorType *VT = QT->getAs<VectorType>()) 8576 return VT->getElementType().getCanonicalType() == ElementType; 8577 return false; 8578 } 8579 8580 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8581 /// has code to accommodate several GCC extensions when type checking 8582 /// pointers. Here are some objectionable examples that GCC considers warnings: 8583 /// 8584 /// int a, *pint; 8585 /// short *pshort; 8586 /// struct foo *pfoo; 8587 /// 8588 /// pint = pshort; // warning: assignment from incompatible pointer type 8589 /// a = pint; // warning: assignment makes integer from pointer without a cast 8590 /// pint = a; // warning: assignment makes pointer from integer without a cast 8591 /// pint = pfoo; // warning: assignment from incompatible pointer type 8592 /// 8593 /// As a result, the code for dealing with pointers is more complex than the 8594 /// C99 spec dictates. 8595 /// 8596 /// Sets 'Kind' for any result kind except Incompatible. 8597 Sema::AssignConvertType 8598 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8599 CastKind &Kind, bool ConvertRHS) { 8600 QualType RHSType = RHS.get()->getType(); 8601 QualType OrigLHSType = LHSType; 8602 8603 // Get canonical types. We're not formatting these types, just comparing 8604 // them. 8605 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8606 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8607 8608 // Common case: no conversion required. 8609 if (LHSType == RHSType) { 8610 Kind = CK_NoOp; 8611 return Compatible; 8612 } 8613 8614 // If we have an atomic type, try a non-atomic assignment, then just add an 8615 // atomic qualification step. 8616 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8617 Sema::AssignConvertType result = 8618 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8619 if (result != Compatible) 8620 return result; 8621 if (Kind != CK_NoOp && ConvertRHS) 8622 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8623 Kind = CK_NonAtomicToAtomic; 8624 return Compatible; 8625 } 8626 8627 // If the left-hand side is a reference type, then we are in a 8628 // (rare!) case where we've allowed the use of references in C, 8629 // e.g., as a parameter type in a built-in function. In this case, 8630 // just make sure that the type referenced is compatible with the 8631 // right-hand side type. The caller is responsible for adjusting 8632 // LHSType so that the resulting expression does not have reference 8633 // type. 8634 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8635 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8636 Kind = CK_LValueBitCast; 8637 return Compatible; 8638 } 8639 return Incompatible; 8640 } 8641 8642 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8643 // to the same ExtVector type. 8644 if (LHSType->isExtVectorType()) { 8645 if (RHSType->isExtVectorType()) 8646 return Incompatible; 8647 if (RHSType->isArithmeticType()) { 8648 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8649 if (ConvertRHS) 8650 RHS = prepareVectorSplat(LHSType, RHS.get()); 8651 Kind = CK_VectorSplat; 8652 return Compatible; 8653 } 8654 } 8655 8656 // Conversions to or from vector type. 8657 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8658 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8659 // Allow assignments of an AltiVec vector type to an equivalent GCC 8660 // vector type and vice versa 8661 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8662 Kind = CK_BitCast; 8663 return Compatible; 8664 } 8665 8666 // If we are allowing lax vector conversions, and LHS and RHS are both 8667 // vectors, the total size only needs to be the same. This is a bitcast; 8668 // no bits are changed but the result type is different. 8669 if (isLaxVectorConversion(RHSType, LHSType)) { 8670 Kind = CK_BitCast; 8671 return IncompatibleVectors; 8672 } 8673 } 8674 8675 // When the RHS comes from another lax conversion (e.g. binops between 8676 // scalars and vectors) the result is canonicalized as a vector. When the 8677 // LHS is also a vector, the lax is allowed by the condition above. Handle 8678 // the case where LHS is a scalar. 8679 if (LHSType->isScalarType()) { 8680 const VectorType *VecType = RHSType->getAs<VectorType>(); 8681 if (VecType && VecType->getNumElements() == 1 && 8682 isLaxVectorConversion(RHSType, LHSType)) { 8683 ExprResult *VecExpr = &RHS; 8684 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8685 Kind = CK_BitCast; 8686 return Compatible; 8687 } 8688 } 8689 8690 return Incompatible; 8691 } 8692 8693 // Diagnose attempts to convert between __float128 and long double where 8694 // such conversions currently can't be handled. 8695 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8696 return Incompatible; 8697 8698 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8699 // discards the imaginary part. 8700 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8701 !LHSType->getAs<ComplexType>()) 8702 return Incompatible; 8703 8704 // Arithmetic conversions. 8705 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8706 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8707 if (ConvertRHS) 8708 Kind = PrepareScalarCast(RHS, LHSType); 8709 return Compatible; 8710 } 8711 8712 // Conversions to normal pointers. 8713 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8714 // U* -> T* 8715 if (isa<PointerType>(RHSType)) { 8716 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8717 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8718 if (AddrSpaceL != AddrSpaceR) 8719 Kind = CK_AddressSpaceConversion; 8720 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8721 Kind = CK_NoOp; 8722 else 8723 Kind = CK_BitCast; 8724 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8725 } 8726 8727 // int -> T* 8728 if (RHSType->isIntegerType()) { 8729 Kind = CK_IntegralToPointer; // FIXME: null? 8730 return IntToPointer; 8731 } 8732 8733 // C pointers are not compatible with ObjC object pointers, 8734 // with two exceptions: 8735 if (isa<ObjCObjectPointerType>(RHSType)) { 8736 // - conversions to void* 8737 if (LHSPointer->getPointeeType()->isVoidType()) { 8738 Kind = CK_BitCast; 8739 return Compatible; 8740 } 8741 8742 // - conversions from 'Class' to the redefinition type 8743 if (RHSType->isObjCClassType() && 8744 Context.hasSameType(LHSType, 8745 Context.getObjCClassRedefinitionType())) { 8746 Kind = CK_BitCast; 8747 return Compatible; 8748 } 8749 8750 Kind = CK_BitCast; 8751 return IncompatiblePointer; 8752 } 8753 8754 // U^ -> void* 8755 if (RHSType->getAs<BlockPointerType>()) { 8756 if (LHSPointer->getPointeeType()->isVoidType()) { 8757 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8758 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8759 ->getPointeeType() 8760 .getAddressSpace(); 8761 Kind = 8762 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8763 return Compatible; 8764 } 8765 } 8766 8767 return Incompatible; 8768 } 8769 8770 // Conversions to block pointers. 8771 if (isa<BlockPointerType>(LHSType)) { 8772 // U^ -> T^ 8773 if (RHSType->isBlockPointerType()) { 8774 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8775 ->getPointeeType() 8776 .getAddressSpace(); 8777 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8778 ->getPointeeType() 8779 .getAddressSpace(); 8780 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8781 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8782 } 8783 8784 // int or null -> T^ 8785 if (RHSType->isIntegerType()) { 8786 Kind = CK_IntegralToPointer; // FIXME: null 8787 return IntToBlockPointer; 8788 } 8789 8790 // id -> T^ 8791 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8792 Kind = CK_AnyPointerToBlockPointerCast; 8793 return Compatible; 8794 } 8795 8796 // void* -> T^ 8797 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8798 if (RHSPT->getPointeeType()->isVoidType()) { 8799 Kind = CK_AnyPointerToBlockPointerCast; 8800 return Compatible; 8801 } 8802 8803 return Incompatible; 8804 } 8805 8806 // Conversions to Objective-C pointers. 8807 if (isa<ObjCObjectPointerType>(LHSType)) { 8808 // A* -> B* 8809 if (RHSType->isObjCObjectPointerType()) { 8810 Kind = CK_BitCast; 8811 Sema::AssignConvertType result = 8812 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8813 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8814 result == Compatible && 8815 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8816 result = IncompatibleObjCWeakRef; 8817 return result; 8818 } 8819 8820 // int or null -> A* 8821 if (RHSType->isIntegerType()) { 8822 Kind = CK_IntegralToPointer; // FIXME: null 8823 return IntToPointer; 8824 } 8825 8826 // In general, C pointers are not compatible with ObjC object pointers, 8827 // with two exceptions: 8828 if (isa<PointerType>(RHSType)) { 8829 Kind = CK_CPointerToObjCPointerCast; 8830 8831 // - conversions from 'void*' 8832 if (RHSType->isVoidPointerType()) { 8833 return Compatible; 8834 } 8835 8836 // - conversions to 'Class' from its redefinition type 8837 if (LHSType->isObjCClassType() && 8838 Context.hasSameType(RHSType, 8839 Context.getObjCClassRedefinitionType())) { 8840 return Compatible; 8841 } 8842 8843 return IncompatiblePointer; 8844 } 8845 8846 // Only under strict condition T^ is compatible with an Objective-C pointer. 8847 if (RHSType->isBlockPointerType() && 8848 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8849 if (ConvertRHS) 8850 maybeExtendBlockObject(RHS); 8851 Kind = CK_BlockPointerToObjCPointerCast; 8852 return Compatible; 8853 } 8854 8855 return Incompatible; 8856 } 8857 8858 // Conversions from pointers that are not covered by the above. 8859 if (isa<PointerType>(RHSType)) { 8860 // T* -> _Bool 8861 if (LHSType == Context.BoolTy) { 8862 Kind = CK_PointerToBoolean; 8863 return Compatible; 8864 } 8865 8866 // T* -> int 8867 if (LHSType->isIntegerType()) { 8868 Kind = CK_PointerToIntegral; 8869 return PointerToInt; 8870 } 8871 8872 return Incompatible; 8873 } 8874 8875 // Conversions from Objective-C pointers that are not covered by the above. 8876 if (isa<ObjCObjectPointerType>(RHSType)) { 8877 // T* -> _Bool 8878 if (LHSType == Context.BoolTy) { 8879 Kind = CK_PointerToBoolean; 8880 return Compatible; 8881 } 8882 8883 // T* -> int 8884 if (LHSType->isIntegerType()) { 8885 Kind = CK_PointerToIntegral; 8886 return PointerToInt; 8887 } 8888 8889 return Incompatible; 8890 } 8891 8892 // struct A -> struct B 8893 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8894 if (Context.typesAreCompatible(LHSType, RHSType)) { 8895 Kind = CK_NoOp; 8896 return Compatible; 8897 } 8898 } 8899 8900 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8901 Kind = CK_IntToOCLSampler; 8902 return Compatible; 8903 } 8904 8905 return Incompatible; 8906 } 8907 8908 /// Constructs a transparent union from an expression that is 8909 /// used to initialize the transparent union. 8910 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8911 ExprResult &EResult, QualType UnionType, 8912 FieldDecl *Field) { 8913 // Build an initializer list that designates the appropriate member 8914 // of the transparent union. 8915 Expr *E = EResult.get(); 8916 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8917 E, SourceLocation()); 8918 Initializer->setType(UnionType); 8919 Initializer->setInitializedFieldInUnion(Field); 8920 8921 // Build a compound literal constructing a value of the transparent 8922 // union type from this initializer list. 8923 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8924 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8925 VK_RValue, Initializer, false); 8926 } 8927 8928 Sema::AssignConvertType 8929 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8930 ExprResult &RHS) { 8931 QualType RHSType = RHS.get()->getType(); 8932 8933 // If the ArgType is a Union type, we want to handle a potential 8934 // transparent_union GCC extension. 8935 const RecordType *UT = ArgType->getAsUnionType(); 8936 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8937 return Incompatible; 8938 8939 // The field to initialize within the transparent union. 8940 RecordDecl *UD = UT->getDecl(); 8941 FieldDecl *InitField = nullptr; 8942 // It's compatible if the expression matches any of the fields. 8943 for (auto *it : UD->fields()) { 8944 if (it->getType()->isPointerType()) { 8945 // If the transparent union contains a pointer type, we allow: 8946 // 1) void pointer 8947 // 2) null pointer constant 8948 if (RHSType->isPointerType()) 8949 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8950 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8951 InitField = it; 8952 break; 8953 } 8954 8955 if (RHS.get()->isNullPointerConstant(Context, 8956 Expr::NPC_ValueDependentIsNull)) { 8957 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8958 CK_NullToPointer); 8959 InitField = it; 8960 break; 8961 } 8962 } 8963 8964 CastKind Kind; 8965 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8966 == Compatible) { 8967 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8968 InitField = it; 8969 break; 8970 } 8971 } 8972 8973 if (!InitField) 8974 return Incompatible; 8975 8976 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8977 return Compatible; 8978 } 8979 8980 Sema::AssignConvertType 8981 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8982 bool Diagnose, 8983 bool DiagnoseCFAudited, 8984 bool ConvertRHS) { 8985 // We need to be able to tell the caller whether we diagnosed a problem, if 8986 // they ask us to issue diagnostics. 8987 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8988 8989 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8990 // we can't avoid *all* modifications at the moment, so we need some somewhere 8991 // to put the updated value. 8992 ExprResult LocalRHS = CallerRHS; 8993 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8994 8995 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8996 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8997 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8998 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8999 Diag(RHS.get()->getExprLoc(), 9000 diag::warn_noderef_to_dereferenceable_pointer) 9001 << RHS.get()->getSourceRange(); 9002 } 9003 } 9004 } 9005 9006 if (getLangOpts().CPlusPlus) { 9007 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9008 // C++ 5.17p3: If the left operand is not of class type, the 9009 // expression is implicitly converted (C++ 4) to the 9010 // cv-unqualified type of the left operand. 9011 QualType RHSType = RHS.get()->getType(); 9012 if (Diagnose) { 9013 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9014 AA_Assigning); 9015 } else { 9016 ImplicitConversionSequence ICS = 9017 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9018 /*SuppressUserConversions=*/false, 9019 AllowedExplicit::None, 9020 /*InOverloadResolution=*/false, 9021 /*CStyle=*/false, 9022 /*AllowObjCWritebackConversion=*/false); 9023 if (ICS.isFailure()) 9024 return Incompatible; 9025 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9026 ICS, AA_Assigning); 9027 } 9028 if (RHS.isInvalid()) 9029 return Incompatible; 9030 Sema::AssignConvertType result = Compatible; 9031 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9032 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9033 result = IncompatibleObjCWeakRef; 9034 return result; 9035 } 9036 9037 // FIXME: Currently, we fall through and treat C++ classes like C 9038 // structures. 9039 // FIXME: We also fall through for atomics; not sure what should 9040 // happen there, though. 9041 } else if (RHS.get()->getType() == Context.OverloadTy) { 9042 // As a set of extensions to C, we support overloading on functions. These 9043 // functions need to be resolved here. 9044 DeclAccessPair DAP; 9045 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9046 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9047 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9048 else 9049 return Incompatible; 9050 } 9051 9052 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9053 // a null pointer constant. 9054 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9055 LHSType->isBlockPointerType()) && 9056 RHS.get()->isNullPointerConstant(Context, 9057 Expr::NPC_ValueDependentIsNull)) { 9058 if (Diagnose || ConvertRHS) { 9059 CastKind Kind; 9060 CXXCastPath Path; 9061 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9062 /*IgnoreBaseAccess=*/false, Diagnose); 9063 if (ConvertRHS) 9064 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9065 } 9066 return Compatible; 9067 } 9068 9069 // OpenCL queue_t type assignment. 9070 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9071 Context, Expr::NPC_ValueDependentIsNull)) { 9072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9073 return Compatible; 9074 } 9075 9076 // This check seems unnatural, however it is necessary to ensure the proper 9077 // conversion of functions/arrays. If the conversion were done for all 9078 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9079 // expressions that suppress this implicit conversion (&, sizeof). 9080 // 9081 // Suppress this for references: C++ 8.5.3p5. 9082 if (!LHSType->isReferenceType()) { 9083 // FIXME: We potentially allocate here even if ConvertRHS is false. 9084 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9085 if (RHS.isInvalid()) 9086 return Incompatible; 9087 } 9088 CastKind Kind; 9089 Sema::AssignConvertType result = 9090 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9091 9092 // C99 6.5.16.1p2: The value of the right operand is converted to the 9093 // type of the assignment expression. 9094 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9095 // so that we can use references in built-in functions even in C. 9096 // The getNonReferenceType() call makes sure that the resulting expression 9097 // does not have reference type. 9098 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9099 QualType Ty = LHSType.getNonLValueExprType(Context); 9100 Expr *E = RHS.get(); 9101 9102 // Check for various Objective-C errors. If we are not reporting 9103 // diagnostics and just checking for errors, e.g., during overload 9104 // resolution, return Incompatible to indicate the failure. 9105 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9106 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9107 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9108 if (!Diagnose) 9109 return Incompatible; 9110 } 9111 if (getLangOpts().ObjC && 9112 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9113 E->getType(), E, Diagnose) || 9114 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 9115 if (!Diagnose) 9116 return Incompatible; 9117 // Replace the expression with a corrected version and continue so we 9118 // can find further errors. 9119 RHS = E; 9120 return Compatible; 9121 } 9122 9123 if (ConvertRHS) 9124 RHS = ImpCastExprToType(E, Ty, Kind); 9125 } 9126 9127 return result; 9128 } 9129 9130 namespace { 9131 /// The original operand to an operator, prior to the application of the usual 9132 /// arithmetic conversions and converting the arguments of a builtin operator 9133 /// candidate. 9134 struct OriginalOperand { 9135 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9136 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9137 Op = MTE->getSubExpr(); 9138 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9139 Op = BTE->getSubExpr(); 9140 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9141 Orig = ICE->getSubExprAsWritten(); 9142 Conversion = ICE->getConversionFunction(); 9143 } 9144 } 9145 9146 QualType getType() const { return Orig->getType(); } 9147 9148 Expr *Orig; 9149 NamedDecl *Conversion; 9150 }; 9151 } 9152 9153 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9154 ExprResult &RHS) { 9155 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9156 9157 Diag(Loc, diag::err_typecheck_invalid_operands) 9158 << OrigLHS.getType() << OrigRHS.getType() 9159 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9160 9161 // If a user-defined conversion was applied to either of the operands prior 9162 // to applying the built-in operator rules, tell the user about it. 9163 if (OrigLHS.Conversion) { 9164 Diag(OrigLHS.Conversion->getLocation(), 9165 diag::note_typecheck_invalid_operands_converted) 9166 << 0 << LHS.get()->getType(); 9167 } 9168 if (OrigRHS.Conversion) { 9169 Diag(OrigRHS.Conversion->getLocation(), 9170 diag::note_typecheck_invalid_operands_converted) 9171 << 1 << RHS.get()->getType(); 9172 } 9173 9174 return QualType(); 9175 } 9176 9177 // Diagnose cases where a scalar was implicitly converted to a vector and 9178 // diagnose the underlying types. Otherwise, diagnose the error 9179 // as invalid vector logical operands for non-C++ cases. 9180 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9181 ExprResult &RHS) { 9182 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9183 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9184 9185 bool LHSNatVec = LHSType->isVectorType(); 9186 bool RHSNatVec = RHSType->isVectorType(); 9187 9188 if (!(LHSNatVec && RHSNatVec)) { 9189 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9190 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9191 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9192 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9193 << Vector->getSourceRange(); 9194 return QualType(); 9195 } 9196 9197 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9198 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9199 << RHS.get()->getSourceRange(); 9200 9201 return QualType(); 9202 } 9203 9204 /// Try to convert a value of non-vector type to a vector type by converting 9205 /// the type to the element type of the vector and then performing a splat. 9206 /// If the language is OpenCL, we only use conversions that promote scalar 9207 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9208 /// for float->int. 9209 /// 9210 /// OpenCL V2.0 6.2.6.p2: 9211 /// An error shall occur if any scalar operand type has greater rank 9212 /// than the type of the vector element. 9213 /// 9214 /// \param scalar - if non-null, actually perform the conversions 9215 /// \return true if the operation fails (but without diagnosing the failure) 9216 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9217 QualType scalarTy, 9218 QualType vectorEltTy, 9219 QualType vectorTy, 9220 unsigned &DiagID) { 9221 // The conversion to apply to the scalar before splatting it, 9222 // if necessary. 9223 CastKind scalarCast = CK_NoOp; 9224 9225 if (vectorEltTy->isIntegralType(S.Context)) { 9226 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9227 (scalarTy->isIntegerType() && 9228 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9229 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9230 return true; 9231 } 9232 if (!scalarTy->isIntegralType(S.Context)) 9233 return true; 9234 scalarCast = CK_IntegralCast; 9235 } else if (vectorEltTy->isRealFloatingType()) { 9236 if (scalarTy->isRealFloatingType()) { 9237 if (S.getLangOpts().OpenCL && 9238 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9239 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9240 return true; 9241 } 9242 scalarCast = CK_FloatingCast; 9243 } 9244 else if (scalarTy->isIntegralType(S.Context)) 9245 scalarCast = CK_IntegralToFloating; 9246 else 9247 return true; 9248 } else { 9249 return true; 9250 } 9251 9252 // Adjust scalar if desired. 9253 if (scalar) { 9254 if (scalarCast != CK_NoOp) 9255 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9256 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9257 } 9258 return false; 9259 } 9260 9261 /// Convert vector E to a vector with the same number of elements but different 9262 /// element type. 9263 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9264 const auto *VecTy = E->getType()->getAs<VectorType>(); 9265 assert(VecTy && "Expression E must be a vector"); 9266 QualType NewVecTy = S.Context.getVectorType(ElementType, 9267 VecTy->getNumElements(), 9268 VecTy->getVectorKind()); 9269 9270 // Look through the implicit cast. Return the subexpression if its type is 9271 // NewVecTy. 9272 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9273 if (ICE->getSubExpr()->getType() == NewVecTy) 9274 return ICE->getSubExpr(); 9275 9276 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9277 return S.ImpCastExprToType(E, NewVecTy, Cast); 9278 } 9279 9280 /// Test if a (constant) integer Int can be casted to another integer type 9281 /// IntTy without losing precision. 9282 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9283 QualType OtherIntTy) { 9284 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9285 9286 // Reject cases where the value of the Int is unknown as that would 9287 // possibly cause truncation, but accept cases where the scalar can be 9288 // demoted without loss of precision. 9289 Expr::EvalResult EVResult; 9290 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9291 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9292 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9293 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9294 9295 if (CstInt) { 9296 // If the scalar is constant and is of a higher order and has more active 9297 // bits that the vector element type, reject it. 9298 llvm::APSInt Result = EVResult.Val.getInt(); 9299 unsigned NumBits = IntSigned 9300 ? (Result.isNegative() ? Result.getMinSignedBits() 9301 : Result.getActiveBits()) 9302 : Result.getActiveBits(); 9303 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9304 return true; 9305 9306 // If the signedness of the scalar type and the vector element type 9307 // differs and the number of bits is greater than that of the vector 9308 // element reject it. 9309 return (IntSigned != OtherIntSigned && 9310 NumBits > S.Context.getIntWidth(OtherIntTy)); 9311 } 9312 9313 // Reject cases where the value of the scalar is not constant and it's 9314 // order is greater than that of the vector element type. 9315 return (Order < 0); 9316 } 9317 9318 /// Test if a (constant) integer Int can be casted to floating point type 9319 /// FloatTy without losing precision. 9320 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9321 QualType FloatTy) { 9322 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9323 9324 // Determine if the integer constant can be expressed as a floating point 9325 // number of the appropriate type. 9326 Expr::EvalResult EVResult; 9327 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9328 9329 uint64_t Bits = 0; 9330 if (CstInt) { 9331 // Reject constants that would be truncated if they were converted to 9332 // the floating point type. Test by simple to/from conversion. 9333 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9334 // could be avoided if there was a convertFromAPInt method 9335 // which could signal back if implicit truncation occurred. 9336 llvm::APSInt Result = EVResult.Val.getInt(); 9337 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9338 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9339 llvm::APFloat::rmTowardZero); 9340 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9341 !IntTy->hasSignedIntegerRepresentation()); 9342 bool Ignored = false; 9343 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9344 &Ignored); 9345 if (Result != ConvertBack) 9346 return true; 9347 } else { 9348 // Reject types that cannot be fully encoded into the mantissa of 9349 // the float. 9350 Bits = S.Context.getTypeSize(IntTy); 9351 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9352 S.Context.getFloatTypeSemantics(FloatTy)); 9353 if (Bits > FloatPrec) 9354 return true; 9355 } 9356 9357 return false; 9358 } 9359 9360 /// Attempt to convert and splat Scalar into a vector whose types matches 9361 /// Vector following GCC conversion rules. The rule is that implicit 9362 /// conversion can occur when Scalar can be casted to match Vector's element 9363 /// type without causing truncation of Scalar. 9364 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9365 ExprResult *Vector) { 9366 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9367 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9368 const VectorType *VT = VectorTy->getAs<VectorType>(); 9369 9370 assert(!isa<ExtVectorType>(VT) && 9371 "ExtVectorTypes should not be handled here!"); 9372 9373 QualType VectorEltTy = VT->getElementType(); 9374 9375 // Reject cases where the vector element type or the scalar element type are 9376 // not integral or floating point types. 9377 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9378 return true; 9379 9380 // The conversion to apply to the scalar before splatting it, 9381 // if necessary. 9382 CastKind ScalarCast = CK_NoOp; 9383 9384 // Accept cases where the vector elements are integers and the scalar is 9385 // an integer. 9386 // FIXME: Notionally if the scalar was a floating point value with a precise 9387 // integral representation, we could cast it to an appropriate integer 9388 // type and then perform the rest of the checks here. GCC will perform 9389 // this conversion in some cases as determined by the input language. 9390 // We should accept it on a language independent basis. 9391 if (VectorEltTy->isIntegralType(S.Context) && 9392 ScalarTy->isIntegralType(S.Context) && 9393 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9394 9395 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9396 return true; 9397 9398 ScalarCast = CK_IntegralCast; 9399 } else if (VectorEltTy->isIntegralType(S.Context) && 9400 ScalarTy->isRealFloatingType()) { 9401 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9402 ScalarCast = CK_FloatingToIntegral; 9403 else 9404 return true; 9405 } else if (VectorEltTy->isRealFloatingType()) { 9406 if (ScalarTy->isRealFloatingType()) { 9407 9408 // Reject cases where the scalar type is not a constant and has a higher 9409 // Order than the vector element type. 9410 llvm::APFloat Result(0.0); 9411 9412 // Determine whether this is a constant scalar. In the event that the 9413 // value is dependent (and thus cannot be evaluated by the constant 9414 // evaluator), skip the evaluation. This will then diagnose once the 9415 // expression is instantiated. 9416 bool CstScalar = Scalar->get()->isValueDependent() || 9417 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9418 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9419 if (!CstScalar && Order < 0) 9420 return true; 9421 9422 // If the scalar cannot be safely casted to the vector element type, 9423 // reject it. 9424 if (CstScalar) { 9425 bool Truncated = false; 9426 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9427 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9428 if (Truncated) 9429 return true; 9430 } 9431 9432 ScalarCast = CK_FloatingCast; 9433 } else if (ScalarTy->isIntegralType(S.Context)) { 9434 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9435 return true; 9436 9437 ScalarCast = CK_IntegralToFloating; 9438 } else 9439 return true; 9440 } 9441 9442 // Adjust scalar if desired. 9443 if (Scalar) { 9444 if (ScalarCast != CK_NoOp) 9445 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9446 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9447 } 9448 return false; 9449 } 9450 9451 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9452 SourceLocation Loc, bool IsCompAssign, 9453 bool AllowBothBool, 9454 bool AllowBoolConversions) { 9455 if (!IsCompAssign) { 9456 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9457 if (LHS.isInvalid()) 9458 return QualType(); 9459 } 9460 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9461 if (RHS.isInvalid()) 9462 return QualType(); 9463 9464 // For conversion purposes, we ignore any qualifiers. 9465 // For example, "const float" and "float" are equivalent. 9466 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9467 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9468 9469 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9470 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9471 assert(LHSVecType || RHSVecType); 9472 9473 // AltiVec-style "vector bool op vector bool" combinations are allowed 9474 // for some operators but not others. 9475 if (!AllowBothBool && 9476 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9477 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9478 return InvalidOperands(Loc, LHS, RHS); 9479 9480 // If the vector types are identical, return. 9481 if (Context.hasSameType(LHSType, RHSType)) 9482 return LHSType; 9483 9484 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9485 if (LHSVecType && RHSVecType && 9486 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9487 if (isa<ExtVectorType>(LHSVecType)) { 9488 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9489 return LHSType; 9490 } 9491 9492 if (!IsCompAssign) 9493 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9494 return RHSType; 9495 } 9496 9497 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9498 // can be mixed, with the result being the non-bool type. The non-bool 9499 // operand must have integer element type. 9500 if (AllowBoolConversions && LHSVecType && RHSVecType && 9501 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9502 (Context.getTypeSize(LHSVecType->getElementType()) == 9503 Context.getTypeSize(RHSVecType->getElementType()))) { 9504 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9505 LHSVecType->getElementType()->isIntegerType() && 9506 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9508 return LHSType; 9509 } 9510 if (!IsCompAssign && 9511 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9512 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9513 RHSVecType->getElementType()->isIntegerType()) { 9514 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9515 return RHSType; 9516 } 9517 } 9518 9519 // If there's a vector type and a scalar, try to convert the scalar to 9520 // the vector element type and splat. 9521 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9522 if (!RHSVecType) { 9523 if (isa<ExtVectorType>(LHSVecType)) { 9524 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9525 LHSVecType->getElementType(), LHSType, 9526 DiagID)) 9527 return LHSType; 9528 } else { 9529 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9530 return LHSType; 9531 } 9532 } 9533 if (!LHSVecType) { 9534 if (isa<ExtVectorType>(RHSVecType)) { 9535 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9536 LHSType, RHSVecType->getElementType(), 9537 RHSType, DiagID)) 9538 return RHSType; 9539 } else { 9540 if (LHS.get()->getValueKind() == VK_LValue || 9541 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9542 return RHSType; 9543 } 9544 } 9545 9546 // FIXME: The code below also handles conversion between vectors and 9547 // non-scalars, we should break this down into fine grained specific checks 9548 // and emit proper diagnostics. 9549 QualType VecType = LHSVecType ? LHSType : RHSType; 9550 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9551 QualType OtherType = LHSVecType ? RHSType : LHSType; 9552 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9553 if (isLaxVectorConversion(OtherType, VecType)) { 9554 // If we're allowing lax vector conversions, only the total (data) size 9555 // needs to be the same. For non compound assignment, if one of the types is 9556 // scalar, the result is always the vector type. 9557 if (!IsCompAssign) { 9558 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9559 return VecType; 9560 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9561 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9562 // type. Note that this is already done by non-compound assignments in 9563 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9564 // <1 x T> -> T. The result is also a vector type. 9565 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9566 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9567 ExprResult *RHSExpr = &RHS; 9568 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9569 return VecType; 9570 } 9571 } 9572 9573 // Okay, the expression is invalid. 9574 9575 // If there's a non-vector, non-real operand, diagnose that. 9576 if ((!RHSVecType && !RHSType->isRealType()) || 9577 (!LHSVecType && !LHSType->isRealType())) { 9578 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9579 << LHSType << RHSType 9580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9581 return QualType(); 9582 } 9583 9584 // OpenCL V1.1 6.2.6.p1: 9585 // If the operands are of more than one vector type, then an error shall 9586 // occur. Implicit conversions between vector types are not permitted, per 9587 // section 6.2.1. 9588 if (getLangOpts().OpenCL && 9589 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9590 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9591 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9592 << RHSType; 9593 return QualType(); 9594 } 9595 9596 9597 // If there is a vector type that is not a ExtVector and a scalar, we reach 9598 // this point if scalar could not be converted to the vector's element type 9599 // without truncation. 9600 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9601 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9602 QualType Scalar = LHSVecType ? RHSType : LHSType; 9603 QualType Vector = LHSVecType ? LHSType : RHSType; 9604 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9605 Diag(Loc, 9606 diag::err_typecheck_vector_not_convertable_implict_truncation) 9607 << ScalarOrVector << Scalar << Vector; 9608 9609 return QualType(); 9610 } 9611 9612 // Otherwise, use the generic diagnostic. 9613 Diag(Loc, DiagID) 9614 << LHSType << RHSType 9615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9616 return QualType(); 9617 } 9618 9619 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9620 // expression. These are mainly cases where the null pointer is used as an 9621 // integer instead of a pointer. 9622 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9623 SourceLocation Loc, bool IsCompare) { 9624 // The canonical way to check for a GNU null is with isNullPointerConstant, 9625 // but we use a bit of a hack here for speed; this is a relatively 9626 // hot path, and isNullPointerConstant is slow. 9627 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9628 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9629 9630 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9631 9632 // Avoid analyzing cases where the result will either be invalid (and 9633 // diagnosed as such) or entirely valid and not something to warn about. 9634 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9635 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9636 return; 9637 9638 // Comparison operations would not make sense with a null pointer no matter 9639 // what the other expression is. 9640 if (!IsCompare) { 9641 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9642 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9643 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9644 return; 9645 } 9646 9647 // The rest of the operations only make sense with a null pointer 9648 // if the other expression is a pointer. 9649 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9650 NonNullType->canDecayToPointerType()) 9651 return; 9652 9653 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9654 << LHSNull /* LHS is NULL */ << NonNullType 9655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9656 } 9657 9658 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9659 SourceLocation Loc) { 9660 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9661 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9662 if (!LUE || !RUE) 9663 return; 9664 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9665 RUE->getKind() != UETT_SizeOf) 9666 return; 9667 9668 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9669 QualType LHSTy = LHSArg->getType(); 9670 QualType RHSTy; 9671 9672 if (RUE->isArgumentType()) 9673 RHSTy = RUE->getArgumentType(); 9674 else 9675 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9676 9677 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9678 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9679 return; 9680 9681 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9682 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9683 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9684 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9685 << LHSArgDecl; 9686 } 9687 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9688 QualType ArrayElemTy = ArrayTy->getElementType(); 9689 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9690 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9691 ArrayElemTy->isCharType() || 9692 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9693 return; 9694 S.Diag(Loc, diag::warn_division_sizeof_array) 9695 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9696 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9697 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9698 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9699 << LHSArgDecl; 9700 } 9701 9702 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9703 } 9704 } 9705 9706 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9707 ExprResult &RHS, 9708 SourceLocation Loc, bool IsDiv) { 9709 // Check for division/remainder by zero. 9710 Expr::EvalResult RHSValue; 9711 if (!RHS.get()->isValueDependent() && 9712 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9713 RHSValue.Val.getInt() == 0) 9714 S.DiagRuntimeBehavior(Loc, RHS.get(), 9715 S.PDiag(diag::warn_remainder_division_by_zero) 9716 << IsDiv << RHS.get()->getSourceRange()); 9717 } 9718 9719 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9720 SourceLocation Loc, 9721 bool IsCompAssign, bool IsDiv) { 9722 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9723 9724 if (LHS.get()->getType()->isVectorType() || 9725 RHS.get()->getType()->isVectorType()) 9726 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9727 /*AllowBothBool*/getLangOpts().AltiVec, 9728 /*AllowBoolConversions*/false); 9729 9730 QualType compType = UsualArithmeticConversions( 9731 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9732 if (LHS.isInvalid() || RHS.isInvalid()) 9733 return QualType(); 9734 9735 9736 if (compType.isNull() || !compType->isArithmeticType()) 9737 return InvalidOperands(Loc, LHS, RHS); 9738 if (IsDiv) { 9739 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9740 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9741 } 9742 return compType; 9743 } 9744 9745 QualType Sema::CheckRemainderOperands( 9746 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9747 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9748 9749 if (LHS.get()->getType()->isVectorType() || 9750 RHS.get()->getType()->isVectorType()) { 9751 if (LHS.get()->getType()->hasIntegerRepresentation() && 9752 RHS.get()->getType()->hasIntegerRepresentation()) 9753 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9754 /*AllowBothBool*/getLangOpts().AltiVec, 9755 /*AllowBoolConversions*/false); 9756 return InvalidOperands(Loc, LHS, RHS); 9757 } 9758 9759 QualType compType = UsualArithmeticConversions( 9760 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9761 if (LHS.isInvalid() || RHS.isInvalid()) 9762 return QualType(); 9763 9764 if (compType.isNull() || !compType->isIntegerType()) 9765 return InvalidOperands(Loc, LHS, RHS); 9766 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9767 return compType; 9768 } 9769 9770 /// Diagnose invalid arithmetic on two void pointers. 9771 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9772 Expr *LHSExpr, Expr *RHSExpr) { 9773 S.Diag(Loc, S.getLangOpts().CPlusPlus 9774 ? diag::err_typecheck_pointer_arith_void_type 9775 : diag::ext_gnu_void_ptr) 9776 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9777 << RHSExpr->getSourceRange(); 9778 } 9779 9780 /// Diagnose invalid arithmetic on a void pointer. 9781 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9782 Expr *Pointer) { 9783 S.Diag(Loc, S.getLangOpts().CPlusPlus 9784 ? diag::err_typecheck_pointer_arith_void_type 9785 : diag::ext_gnu_void_ptr) 9786 << 0 /* one pointer */ << Pointer->getSourceRange(); 9787 } 9788 9789 /// Diagnose invalid arithmetic on a null pointer. 9790 /// 9791 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9792 /// idiom, which we recognize as a GNU extension. 9793 /// 9794 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9795 Expr *Pointer, bool IsGNUIdiom) { 9796 if (IsGNUIdiom) 9797 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9798 << Pointer->getSourceRange(); 9799 else 9800 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9801 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9802 } 9803 9804 /// Diagnose invalid arithmetic on two function pointers. 9805 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9806 Expr *LHS, Expr *RHS) { 9807 assert(LHS->getType()->isAnyPointerType()); 9808 assert(RHS->getType()->isAnyPointerType()); 9809 S.Diag(Loc, S.getLangOpts().CPlusPlus 9810 ? diag::err_typecheck_pointer_arith_function_type 9811 : diag::ext_gnu_ptr_func_arith) 9812 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9813 // We only show the second type if it differs from the first. 9814 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9815 RHS->getType()) 9816 << RHS->getType()->getPointeeType() 9817 << LHS->getSourceRange() << RHS->getSourceRange(); 9818 } 9819 9820 /// Diagnose invalid arithmetic on a function pointer. 9821 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9822 Expr *Pointer) { 9823 assert(Pointer->getType()->isAnyPointerType()); 9824 S.Diag(Loc, S.getLangOpts().CPlusPlus 9825 ? diag::err_typecheck_pointer_arith_function_type 9826 : diag::ext_gnu_ptr_func_arith) 9827 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9828 << 0 /* one pointer, so only one type */ 9829 << Pointer->getSourceRange(); 9830 } 9831 9832 /// Emit error if Operand is incomplete pointer type 9833 /// 9834 /// \returns True if pointer has incomplete type 9835 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9836 Expr *Operand) { 9837 QualType ResType = Operand->getType(); 9838 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9839 ResType = ResAtomicType->getValueType(); 9840 9841 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9842 QualType PointeeTy = ResType->getPointeeType(); 9843 return S.RequireCompleteSizedType( 9844 Loc, PointeeTy, 9845 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 9846 Operand->getSourceRange()); 9847 } 9848 9849 /// Check the validity of an arithmetic pointer operand. 9850 /// 9851 /// If the operand has pointer type, this code will check for pointer types 9852 /// which are invalid in arithmetic operations. These will be diagnosed 9853 /// appropriately, including whether or not the use is supported as an 9854 /// extension. 9855 /// 9856 /// \returns True when the operand is valid to use (even if as an extension). 9857 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9858 Expr *Operand) { 9859 QualType ResType = Operand->getType(); 9860 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9861 ResType = ResAtomicType->getValueType(); 9862 9863 if (!ResType->isAnyPointerType()) return true; 9864 9865 QualType PointeeTy = ResType->getPointeeType(); 9866 if (PointeeTy->isVoidType()) { 9867 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9868 return !S.getLangOpts().CPlusPlus; 9869 } 9870 if (PointeeTy->isFunctionType()) { 9871 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9872 return !S.getLangOpts().CPlusPlus; 9873 } 9874 9875 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9876 9877 return true; 9878 } 9879 9880 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9881 /// operands. 9882 /// 9883 /// This routine will diagnose any invalid arithmetic on pointer operands much 9884 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9885 /// for emitting a single diagnostic even for operations where both LHS and RHS 9886 /// are (potentially problematic) pointers. 9887 /// 9888 /// \returns True when the operand is valid to use (even if as an extension). 9889 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9890 Expr *LHSExpr, Expr *RHSExpr) { 9891 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9892 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9893 if (!isLHSPointer && !isRHSPointer) return true; 9894 9895 QualType LHSPointeeTy, RHSPointeeTy; 9896 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9897 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9898 9899 // if both are pointers check if operation is valid wrt address spaces 9900 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9901 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9902 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9903 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9904 S.Diag(Loc, 9905 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9906 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9907 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9908 return false; 9909 } 9910 } 9911 9912 // Check for arithmetic on pointers to incomplete types. 9913 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9914 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9915 if (isLHSVoidPtr || isRHSVoidPtr) { 9916 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9917 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9918 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9919 9920 return !S.getLangOpts().CPlusPlus; 9921 } 9922 9923 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9924 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9925 if (isLHSFuncPtr || isRHSFuncPtr) { 9926 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9927 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9928 RHSExpr); 9929 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9930 9931 return !S.getLangOpts().CPlusPlus; 9932 } 9933 9934 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9935 return false; 9936 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9937 return false; 9938 9939 return true; 9940 } 9941 9942 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9943 /// literal. 9944 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9945 Expr *LHSExpr, Expr *RHSExpr) { 9946 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9947 Expr* IndexExpr = RHSExpr; 9948 if (!StrExpr) { 9949 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9950 IndexExpr = LHSExpr; 9951 } 9952 9953 bool IsStringPlusInt = StrExpr && 9954 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9955 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9956 return; 9957 9958 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9959 Self.Diag(OpLoc, diag::warn_string_plus_int) 9960 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9961 9962 // Only print a fixit for "str" + int, not for int + "str". 9963 if (IndexExpr == RHSExpr) { 9964 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9965 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9966 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9967 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9968 << FixItHint::CreateInsertion(EndLoc, "]"); 9969 } else 9970 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9971 } 9972 9973 /// Emit a warning when adding a char literal to a string. 9974 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9975 Expr *LHSExpr, Expr *RHSExpr) { 9976 const Expr *StringRefExpr = LHSExpr; 9977 const CharacterLiteral *CharExpr = 9978 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9979 9980 if (!CharExpr) { 9981 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9982 StringRefExpr = RHSExpr; 9983 } 9984 9985 if (!CharExpr || !StringRefExpr) 9986 return; 9987 9988 const QualType StringType = StringRefExpr->getType(); 9989 9990 // Return if not a PointerType. 9991 if (!StringType->isAnyPointerType()) 9992 return; 9993 9994 // Return if not a CharacterType. 9995 if (!StringType->getPointeeType()->isAnyCharacterType()) 9996 return; 9997 9998 ASTContext &Ctx = Self.getASTContext(); 9999 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10000 10001 const QualType CharType = CharExpr->getType(); 10002 if (!CharType->isAnyCharacterType() && 10003 CharType->isIntegerType() && 10004 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10005 Self.Diag(OpLoc, diag::warn_string_plus_char) 10006 << DiagRange << Ctx.CharTy; 10007 } else { 10008 Self.Diag(OpLoc, diag::warn_string_plus_char) 10009 << DiagRange << CharExpr->getType(); 10010 } 10011 10012 // Only print a fixit for str + char, not for char + str. 10013 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10014 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10015 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10016 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10017 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10018 << FixItHint::CreateInsertion(EndLoc, "]"); 10019 } else { 10020 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10021 } 10022 } 10023 10024 /// Emit error when two pointers are incompatible. 10025 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10026 Expr *LHSExpr, Expr *RHSExpr) { 10027 assert(LHSExpr->getType()->isAnyPointerType()); 10028 assert(RHSExpr->getType()->isAnyPointerType()); 10029 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10030 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10031 << RHSExpr->getSourceRange(); 10032 } 10033 10034 // C99 6.5.6 10035 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10036 SourceLocation Loc, BinaryOperatorKind Opc, 10037 QualType* CompLHSTy) { 10038 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10039 10040 if (LHS.get()->getType()->isVectorType() || 10041 RHS.get()->getType()->isVectorType()) { 10042 QualType compType = CheckVectorOperands( 10043 LHS, RHS, Loc, CompLHSTy, 10044 /*AllowBothBool*/getLangOpts().AltiVec, 10045 /*AllowBoolConversions*/getLangOpts().ZVector); 10046 if (CompLHSTy) *CompLHSTy = compType; 10047 return compType; 10048 } 10049 10050 QualType compType = UsualArithmeticConversions( 10051 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10052 if (LHS.isInvalid() || RHS.isInvalid()) 10053 return QualType(); 10054 10055 // Diagnose "string literal" '+' int and string '+' "char literal". 10056 if (Opc == BO_Add) { 10057 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10058 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10059 } 10060 10061 // handle the common case first (both operands are arithmetic). 10062 if (!compType.isNull() && compType->isArithmeticType()) { 10063 if (CompLHSTy) *CompLHSTy = compType; 10064 return compType; 10065 } 10066 10067 // Type-checking. Ultimately the pointer's going to be in PExp; 10068 // note that we bias towards the LHS being the pointer. 10069 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10070 10071 bool isObjCPointer; 10072 if (PExp->getType()->isPointerType()) { 10073 isObjCPointer = false; 10074 } else if (PExp->getType()->isObjCObjectPointerType()) { 10075 isObjCPointer = true; 10076 } else { 10077 std::swap(PExp, IExp); 10078 if (PExp->getType()->isPointerType()) { 10079 isObjCPointer = false; 10080 } else if (PExp->getType()->isObjCObjectPointerType()) { 10081 isObjCPointer = true; 10082 } else { 10083 return InvalidOperands(Loc, LHS, RHS); 10084 } 10085 } 10086 assert(PExp->getType()->isAnyPointerType()); 10087 10088 if (!IExp->getType()->isIntegerType()) 10089 return InvalidOperands(Loc, LHS, RHS); 10090 10091 // Adding to a null pointer results in undefined behavior. 10092 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10093 Context, Expr::NPC_ValueDependentIsNotNull)) { 10094 // In C++ adding zero to a null pointer is defined. 10095 Expr::EvalResult KnownVal; 10096 if (!getLangOpts().CPlusPlus || 10097 (!IExp->isValueDependent() && 10098 (!IExp->EvaluateAsInt(KnownVal, Context) || 10099 KnownVal.Val.getInt() != 0))) { 10100 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10101 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10102 Context, BO_Add, PExp, IExp); 10103 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10104 } 10105 } 10106 10107 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10108 return QualType(); 10109 10110 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10111 return QualType(); 10112 10113 // Check array bounds for pointer arithemtic 10114 CheckArrayAccess(PExp, IExp); 10115 10116 if (CompLHSTy) { 10117 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10118 if (LHSTy.isNull()) { 10119 LHSTy = LHS.get()->getType(); 10120 if (LHSTy->isPromotableIntegerType()) 10121 LHSTy = Context.getPromotedIntegerType(LHSTy); 10122 } 10123 *CompLHSTy = LHSTy; 10124 } 10125 10126 return PExp->getType(); 10127 } 10128 10129 // C99 6.5.6 10130 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10131 SourceLocation Loc, 10132 QualType* CompLHSTy) { 10133 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10134 10135 if (LHS.get()->getType()->isVectorType() || 10136 RHS.get()->getType()->isVectorType()) { 10137 QualType compType = CheckVectorOperands( 10138 LHS, RHS, Loc, CompLHSTy, 10139 /*AllowBothBool*/getLangOpts().AltiVec, 10140 /*AllowBoolConversions*/getLangOpts().ZVector); 10141 if (CompLHSTy) *CompLHSTy = compType; 10142 return compType; 10143 } 10144 10145 QualType compType = UsualArithmeticConversions( 10146 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10147 if (LHS.isInvalid() || RHS.isInvalid()) 10148 return QualType(); 10149 10150 // Enforce type constraints: C99 6.5.6p3. 10151 10152 // Handle the common case first (both operands are arithmetic). 10153 if (!compType.isNull() && compType->isArithmeticType()) { 10154 if (CompLHSTy) *CompLHSTy = compType; 10155 return compType; 10156 } 10157 10158 // Either ptr - int or ptr - ptr. 10159 if (LHS.get()->getType()->isAnyPointerType()) { 10160 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10161 10162 // Diagnose bad cases where we step over interface counts. 10163 if (LHS.get()->getType()->isObjCObjectPointerType() && 10164 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10165 return QualType(); 10166 10167 // The result type of a pointer-int computation is the pointer type. 10168 if (RHS.get()->getType()->isIntegerType()) { 10169 // Subtracting from a null pointer should produce a warning. 10170 // The last argument to the diagnose call says this doesn't match the 10171 // GNU int-to-pointer idiom. 10172 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10173 Expr::NPC_ValueDependentIsNotNull)) { 10174 // In C++ adding zero to a null pointer is defined. 10175 Expr::EvalResult KnownVal; 10176 if (!getLangOpts().CPlusPlus || 10177 (!RHS.get()->isValueDependent() && 10178 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10179 KnownVal.Val.getInt() != 0))) { 10180 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10181 } 10182 } 10183 10184 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10185 return QualType(); 10186 10187 // Check array bounds for pointer arithemtic 10188 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10189 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10190 10191 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10192 return LHS.get()->getType(); 10193 } 10194 10195 // Handle pointer-pointer subtractions. 10196 if (const PointerType *RHSPTy 10197 = RHS.get()->getType()->getAs<PointerType>()) { 10198 QualType rpointee = RHSPTy->getPointeeType(); 10199 10200 if (getLangOpts().CPlusPlus) { 10201 // Pointee types must be the same: C++ [expr.add] 10202 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10203 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10204 } 10205 } else { 10206 // Pointee types must be compatible C99 6.5.6p3 10207 if (!Context.typesAreCompatible( 10208 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10209 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10210 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10211 return QualType(); 10212 } 10213 } 10214 10215 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10216 LHS.get(), RHS.get())) 10217 return QualType(); 10218 10219 // FIXME: Add warnings for nullptr - ptr. 10220 10221 // The pointee type may have zero size. As an extension, a structure or 10222 // union may have zero size or an array may have zero length. In this 10223 // case subtraction does not make sense. 10224 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10225 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10226 if (ElementSize.isZero()) { 10227 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10228 << rpointee.getUnqualifiedType() 10229 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10230 } 10231 } 10232 10233 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10234 return Context.getPointerDiffType(); 10235 } 10236 } 10237 10238 return InvalidOperands(Loc, LHS, RHS); 10239 } 10240 10241 static bool isScopedEnumerationType(QualType T) { 10242 if (const EnumType *ET = T->getAs<EnumType>()) 10243 return ET->getDecl()->isScoped(); 10244 return false; 10245 } 10246 10247 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10248 SourceLocation Loc, BinaryOperatorKind Opc, 10249 QualType LHSType) { 10250 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10251 // so skip remaining warnings as we don't want to modify values within Sema. 10252 if (S.getLangOpts().OpenCL) 10253 return; 10254 10255 // Check right/shifter operand 10256 Expr::EvalResult RHSResult; 10257 if (RHS.get()->isValueDependent() || 10258 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10259 return; 10260 llvm::APSInt Right = RHSResult.Val.getInt(); 10261 10262 if (Right.isNegative()) { 10263 S.DiagRuntimeBehavior(Loc, RHS.get(), 10264 S.PDiag(diag::warn_shift_negative) 10265 << RHS.get()->getSourceRange()); 10266 return; 10267 } 10268 llvm::APInt LeftBits(Right.getBitWidth(), 10269 S.Context.getTypeSize(LHS.get()->getType())); 10270 if (Right.uge(LeftBits)) { 10271 S.DiagRuntimeBehavior(Loc, RHS.get(), 10272 S.PDiag(diag::warn_shift_gt_typewidth) 10273 << RHS.get()->getSourceRange()); 10274 return; 10275 } 10276 if (Opc != BO_Shl) 10277 return; 10278 10279 // When left shifting an ICE which is signed, we can check for overflow which 10280 // according to C++ standards prior to C++2a has undefined behavior 10281 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10282 // more than the maximum value representable in the result type, so never 10283 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10284 // expression is still probably a bug.) 10285 Expr::EvalResult LHSResult; 10286 if (LHS.get()->isValueDependent() || 10287 LHSType->hasUnsignedIntegerRepresentation() || 10288 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10289 return; 10290 llvm::APSInt Left = LHSResult.Val.getInt(); 10291 10292 // If LHS does not have a signed type and non-negative value 10293 // then, the behavior is undefined before C++2a. Warn about it. 10294 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10295 !S.getLangOpts().CPlusPlus2a) { 10296 S.DiagRuntimeBehavior(Loc, LHS.get(), 10297 S.PDiag(diag::warn_shift_lhs_negative) 10298 << LHS.get()->getSourceRange()); 10299 return; 10300 } 10301 10302 llvm::APInt ResultBits = 10303 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10304 if (LeftBits.uge(ResultBits)) 10305 return; 10306 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10307 Result = Result.shl(Right); 10308 10309 // Print the bit representation of the signed integer as an unsigned 10310 // hexadecimal number. 10311 SmallString<40> HexResult; 10312 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10313 10314 // If we are only missing a sign bit, this is less likely to result in actual 10315 // bugs -- if the result is cast back to an unsigned type, it will have the 10316 // expected value. Thus we place this behind a different warning that can be 10317 // turned off separately if needed. 10318 if (LeftBits == ResultBits - 1) { 10319 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10320 << HexResult << LHSType 10321 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10322 return; 10323 } 10324 10325 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10326 << HexResult.str() << Result.getMinSignedBits() << LHSType 10327 << Left.getBitWidth() << LHS.get()->getSourceRange() 10328 << RHS.get()->getSourceRange(); 10329 } 10330 10331 /// Return the resulting type when a vector is shifted 10332 /// by a scalar or vector shift amount. 10333 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10334 SourceLocation Loc, bool IsCompAssign) { 10335 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10336 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10337 !LHS.get()->getType()->isVectorType()) { 10338 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10339 << RHS.get()->getType() << LHS.get()->getType() 10340 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10341 return QualType(); 10342 } 10343 10344 if (!IsCompAssign) { 10345 LHS = S.UsualUnaryConversions(LHS.get()); 10346 if (LHS.isInvalid()) return QualType(); 10347 } 10348 10349 RHS = S.UsualUnaryConversions(RHS.get()); 10350 if (RHS.isInvalid()) return QualType(); 10351 10352 QualType LHSType = LHS.get()->getType(); 10353 // Note that LHS might be a scalar because the routine calls not only in 10354 // OpenCL case. 10355 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10356 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10357 10358 // Note that RHS might not be a vector. 10359 QualType RHSType = RHS.get()->getType(); 10360 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10361 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10362 10363 // The operands need to be integers. 10364 if (!LHSEleType->isIntegerType()) { 10365 S.Diag(Loc, diag::err_typecheck_expect_int) 10366 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10367 return QualType(); 10368 } 10369 10370 if (!RHSEleType->isIntegerType()) { 10371 S.Diag(Loc, diag::err_typecheck_expect_int) 10372 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10373 return QualType(); 10374 } 10375 10376 if (!LHSVecTy) { 10377 assert(RHSVecTy); 10378 if (IsCompAssign) 10379 return RHSType; 10380 if (LHSEleType != RHSEleType) { 10381 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10382 LHSEleType = RHSEleType; 10383 } 10384 QualType VecTy = 10385 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10386 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10387 LHSType = VecTy; 10388 } else if (RHSVecTy) { 10389 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10390 // are applied component-wise. So if RHS is a vector, then ensure 10391 // that the number of elements is the same as LHS... 10392 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10393 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10394 << LHS.get()->getType() << RHS.get()->getType() 10395 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10396 return QualType(); 10397 } 10398 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10399 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10400 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10401 if (LHSBT != RHSBT && 10402 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10403 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10404 << LHS.get()->getType() << RHS.get()->getType() 10405 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10406 } 10407 } 10408 } else { 10409 // ...else expand RHS to match the number of elements in LHS. 10410 QualType VecTy = 10411 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10412 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10413 } 10414 10415 return LHSType; 10416 } 10417 10418 // C99 6.5.7 10419 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10420 SourceLocation Loc, BinaryOperatorKind Opc, 10421 bool IsCompAssign) { 10422 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10423 10424 // Vector shifts promote their scalar inputs to vector type. 10425 if (LHS.get()->getType()->isVectorType() || 10426 RHS.get()->getType()->isVectorType()) { 10427 if (LangOpts.ZVector) { 10428 // The shift operators for the z vector extensions work basically 10429 // like general shifts, except that neither the LHS nor the RHS is 10430 // allowed to be a "vector bool". 10431 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10432 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10433 return InvalidOperands(Loc, LHS, RHS); 10434 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10435 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10436 return InvalidOperands(Loc, LHS, RHS); 10437 } 10438 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10439 } 10440 10441 // Shifts don't perform usual arithmetic conversions, they just do integer 10442 // promotions on each operand. C99 6.5.7p3 10443 10444 // For the LHS, do usual unary conversions, but then reset them away 10445 // if this is a compound assignment. 10446 ExprResult OldLHS = LHS; 10447 LHS = UsualUnaryConversions(LHS.get()); 10448 if (LHS.isInvalid()) 10449 return QualType(); 10450 QualType LHSType = LHS.get()->getType(); 10451 if (IsCompAssign) LHS = OldLHS; 10452 10453 // The RHS is simpler. 10454 RHS = UsualUnaryConversions(RHS.get()); 10455 if (RHS.isInvalid()) 10456 return QualType(); 10457 QualType RHSType = RHS.get()->getType(); 10458 10459 // C99 6.5.7p2: Each of the operands shall have integer type. 10460 if (!LHSType->hasIntegerRepresentation() || 10461 !RHSType->hasIntegerRepresentation()) 10462 return InvalidOperands(Loc, LHS, RHS); 10463 10464 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10465 // hasIntegerRepresentation() above instead of this. 10466 if (isScopedEnumerationType(LHSType) || 10467 isScopedEnumerationType(RHSType)) { 10468 return InvalidOperands(Loc, LHS, RHS); 10469 } 10470 // Sanity-check shift operands 10471 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10472 10473 // "The type of the result is that of the promoted left operand." 10474 return LHSType; 10475 } 10476 10477 /// Diagnose bad pointer comparisons. 10478 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10479 ExprResult &LHS, ExprResult &RHS, 10480 bool IsError) { 10481 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10482 : diag::ext_typecheck_comparison_of_distinct_pointers) 10483 << LHS.get()->getType() << RHS.get()->getType() 10484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10485 } 10486 10487 /// Returns false if the pointers are converted to a composite type, 10488 /// true otherwise. 10489 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10490 ExprResult &LHS, ExprResult &RHS) { 10491 // C++ [expr.rel]p2: 10492 // [...] Pointer conversions (4.10) and qualification 10493 // conversions (4.4) are performed on pointer operands (or on 10494 // a pointer operand and a null pointer constant) to bring 10495 // them to their composite pointer type. [...] 10496 // 10497 // C++ [expr.eq]p1 uses the same notion for (in)equality 10498 // comparisons of pointers. 10499 10500 QualType LHSType = LHS.get()->getType(); 10501 QualType RHSType = RHS.get()->getType(); 10502 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10503 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10504 10505 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10506 if (T.isNull()) { 10507 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10508 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10509 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10510 else 10511 S.InvalidOperands(Loc, LHS, RHS); 10512 return true; 10513 } 10514 10515 return false; 10516 } 10517 10518 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10519 ExprResult &LHS, 10520 ExprResult &RHS, 10521 bool IsError) { 10522 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10523 : diag::ext_typecheck_comparison_of_fptr_to_void) 10524 << LHS.get()->getType() << RHS.get()->getType() 10525 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10526 } 10527 10528 static bool isObjCObjectLiteral(ExprResult &E) { 10529 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10530 case Stmt::ObjCArrayLiteralClass: 10531 case Stmt::ObjCDictionaryLiteralClass: 10532 case Stmt::ObjCStringLiteralClass: 10533 case Stmt::ObjCBoxedExprClass: 10534 return true; 10535 default: 10536 // Note that ObjCBoolLiteral is NOT an object literal! 10537 return false; 10538 } 10539 } 10540 10541 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10542 const ObjCObjectPointerType *Type = 10543 LHS->getType()->getAs<ObjCObjectPointerType>(); 10544 10545 // If this is not actually an Objective-C object, bail out. 10546 if (!Type) 10547 return false; 10548 10549 // Get the LHS object's interface type. 10550 QualType InterfaceType = Type->getPointeeType(); 10551 10552 // If the RHS isn't an Objective-C object, bail out. 10553 if (!RHS->getType()->isObjCObjectPointerType()) 10554 return false; 10555 10556 // Try to find the -isEqual: method. 10557 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10558 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10559 InterfaceType, 10560 /*IsInstance=*/true); 10561 if (!Method) { 10562 if (Type->isObjCIdType()) { 10563 // For 'id', just check the global pool. 10564 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10565 /*receiverId=*/true); 10566 } else { 10567 // Check protocols. 10568 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10569 /*IsInstance=*/true); 10570 } 10571 } 10572 10573 if (!Method) 10574 return false; 10575 10576 QualType T = Method->parameters()[0]->getType(); 10577 if (!T->isObjCObjectPointerType()) 10578 return false; 10579 10580 QualType R = Method->getReturnType(); 10581 if (!R->isScalarType()) 10582 return false; 10583 10584 return true; 10585 } 10586 10587 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10588 FromE = FromE->IgnoreParenImpCasts(); 10589 switch (FromE->getStmtClass()) { 10590 default: 10591 break; 10592 case Stmt::ObjCStringLiteralClass: 10593 // "string literal" 10594 return LK_String; 10595 case Stmt::ObjCArrayLiteralClass: 10596 // "array literal" 10597 return LK_Array; 10598 case Stmt::ObjCDictionaryLiteralClass: 10599 // "dictionary literal" 10600 return LK_Dictionary; 10601 case Stmt::BlockExprClass: 10602 return LK_Block; 10603 case Stmt::ObjCBoxedExprClass: { 10604 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10605 switch (Inner->getStmtClass()) { 10606 case Stmt::IntegerLiteralClass: 10607 case Stmt::FloatingLiteralClass: 10608 case Stmt::CharacterLiteralClass: 10609 case Stmt::ObjCBoolLiteralExprClass: 10610 case Stmt::CXXBoolLiteralExprClass: 10611 // "numeric literal" 10612 return LK_Numeric; 10613 case Stmt::ImplicitCastExprClass: { 10614 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10615 // Boolean literals can be represented by implicit casts. 10616 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10617 return LK_Numeric; 10618 break; 10619 } 10620 default: 10621 break; 10622 } 10623 return LK_Boxed; 10624 } 10625 } 10626 return LK_None; 10627 } 10628 10629 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10630 ExprResult &LHS, ExprResult &RHS, 10631 BinaryOperator::Opcode Opc){ 10632 Expr *Literal; 10633 Expr *Other; 10634 if (isObjCObjectLiteral(LHS)) { 10635 Literal = LHS.get(); 10636 Other = RHS.get(); 10637 } else { 10638 Literal = RHS.get(); 10639 Other = LHS.get(); 10640 } 10641 10642 // Don't warn on comparisons against nil. 10643 Other = Other->IgnoreParenCasts(); 10644 if (Other->isNullPointerConstant(S.getASTContext(), 10645 Expr::NPC_ValueDependentIsNotNull)) 10646 return; 10647 10648 // This should be kept in sync with warn_objc_literal_comparison. 10649 // LK_String should always be after the other literals, since it has its own 10650 // warning flag. 10651 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10652 assert(LiteralKind != Sema::LK_Block); 10653 if (LiteralKind == Sema::LK_None) { 10654 llvm_unreachable("Unknown Objective-C object literal kind"); 10655 } 10656 10657 if (LiteralKind == Sema::LK_String) 10658 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10659 << Literal->getSourceRange(); 10660 else 10661 S.Diag(Loc, diag::warn_objc_literal_comparison) 10662 << LiteralKind << Literal->getSourceRange(); 10663 10664 if (BinaryOperator::isEqualityOp(Opc) && 10665 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10666 SourceLocation Start = LHS.get()->getBeginLoc(); 10667 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10668 CharSourceRange OpRange = 10669 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10670 10671 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10672 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10673 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10674 << FixItHint::CreateInsertion(End, "]"); 10675 } 10676 } 10677 10678 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10679 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10680 ExprResult &RHS, SourceLocation Loc, 10681 BinaryOperatorKind Opc) { 10682 // Check that left hand side is !something. 10683 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10684 if (!UO || UO->getOpcode() != UO_LNot) return; 10685 10686 // Only check if the right hand side is non-bool arithmetic type. 10687 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10688 10689 // Make sure that the something in !something is not bool. 10690 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10691 if (SubExpr->isKnownToHaveBooleanValue()) return; 10692 10693 // Emit warning. 10694 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10695 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10696 << Loc << IsBitwiseOp; 10697 10698 // First note suggest !(x < y) 10699 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10700 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10701 FirstClose = S.getLocForEndOfToken(FirstClose); 10702 if (FirstClose.isInvalid()) 10703 FirstOpen = SourceLocation(); 10704 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10705 << IsBitwiseOp 10706 << FixItHint::CreateInsertion(FirstOpen, "(") 10707 << FixItHint::CreateInsertion(FirstClose, ")"); 10708 10709 // Second note suggests (!x) < y 10710 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10711 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10712 SecondClose = S.getLocForEndOfToken(SecondClose); 10713 if (SecondClose.isInvalid()) 10714 SecondOpen = SourceLocation(); 10715 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10716 << FixItHint::CreateInsertion(SecondOpen, "(") 10717 << FixItHint::CreateInsertion(SecondClose, ")"); 10718 } 10719 10720 // Returns true if E refers to a non-weak array. 10721 static bool checkForArray(const Expr *E) { 10722 const ValueDecl *D = nullptr; 10723 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10724 D = DR->getDecl(); 10725 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10726 if (Mem->isImplicitAccess()) 10727 D = Mem->getMemberDecl(); 10728 } 10729 if (!D) 10730 return false; 10731 return D->getType()->isArrayType() && !D->isWeak(); 10732 } 10733 10734 /// Diagnose some forms of syntactically-obvious tautological comparison. 10735 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10736 Expr *LHS, Expr *RHS, 10737 BinaryOperatorKind Opc) { 10738 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10739 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10740 10741 QualType LHSType = LHS->getType(); 10742 QualType RHSType = RHS->getType(); 10743 if (LHSType->hasFloatingRepresentation() || 10744 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10745 S.inTemplateInstantiation()) 10746 return; 10747 10748 // Comparisons between two array types are ill-formed for operator<=>, so 10749 // we shouldn't emit any additional warnings about it. 10750 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10751 return; 10752 10753 // For non-floating point types, check for self-comparisons of the form 10754 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10755 // often indicate logic errors in the program. 10756 // 10757 // NOTE: Don't warn about comparison expressions resulting from macro 10758 // expansion. Also don't warn about comparisons which are only self 10759 // comparisons within a template instantiation. The warnings should catch 10760 // obvious cases in the definition of the template anyways. The idea is to 10761 // warn when the typed comparison operator will always evaluate to the same 10762 // result. 10763 10764 // Used for indexing into %select in warn_comparison_always 10765 enum { 10766 AlwaysConstant, 10767 AlwaysTrue, 10768 AlwaysFalse, 10769 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10770 }; 10771 10772 // C++2a [depr.array.comp]: 10773 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10774 // operands of array type are deprecated. 10775 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10776 RHSStripped->getType()->isArrayType()) { 10777 S.Diag(Loc, diag::warn_depr_array_comparison) 10778 << LHS->getSourceRange() << RHS->getSourceRange() 10779 << LHSStripped->getType() << RHSStripped->getType(); 10780 // Carry on to produce the tautological comparison warning, if this 10781 // expression is potentially-evaluated, we can resolve the array to a 10782 // non-weak declaration, and so on. 10783 } 10784 10785 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10786 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10787 unsigned Result; 10788 switch (Opc) { 10789 case BO_EQ: 10790 case BO_LE: 10791 case BO_GE: 10792 Result = AlwaysTrue; 10793 break; 10794 case BO_NE: 10795 case BO_LT: 10796 case BO_GT: 10797 Result = AlwaysFalse; 10798 break; 10799 case BO_Cmp: 10800 Result = AlwaysEqual; 10801 break; 10802 default: 10803 Result = AlwaysConstant; 10804 break; 10805 } 10806 S.DiagRuntimeBehavior(Loc, nullptr, 10807 S.PDiag(diag::warn_comparison_always) 10808 << 0 /*self-comparison*/ 10809 << Result); 10810 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10811 // What is it always going to evaluate to? 10812 unsigned Result; 10813 switch (Opc) { 10814 case BO_EQ: // e.g. array1 == array2 10815 Result = AlwaysFalse; 10816 break; 10817 case BO_NE: // e.g. array1 != array2 10818 Result = AlwaysTrue; 10819 break; 10820 default: // e.g. array1 <= array2 10821 // The best we can say is 'a constant' 10822 Result = AlwaysConstant; 10823 break; 10824 } 10825 S.DiagRuntimeBehavior(Loc, nullptr, 10826 S.PDiag(diag::warn_comparison_always) 10827 << 1 /*array comparison*/ 10828 << Result); 10829 } 10830 } 10831 10832 if (isa<CastExpr>(LHSStripped)) 10833 LHSStripped = LHSStripped->IgnoreParenCasts(); 10834 if (isa<CastExpr>(RHSStripped)) 10835 RHSStripped = RHSStripped->IgnoreParenCasts(); 10836 10837 // Warn about comparisons against a string constant (unless the other 10838 // operand is null); the user probably wants string comparison function. 10839 Expr *LiteralString = nullptr; 10840 Expr *LiteralStringStripped = nullptr; 10841 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10842 !RHSStripped->isNullPointerConstant(S.Context, 10843 Expr::NPC_ValueDependentIsNull)) { 10844 LiteralString = LHS; 10845 LiteralStringStripped = LHSStripped; 10846 } else if ((isa<StringLiteral>(RHSStripped) || 10847 isa<ObjCEncodeExpr>(RHSStripped)) && 10848 !LHSStripped->isNullPointerConstant(S.Context, 10849 Expr::NPC_ValueDependentIsNull)) { 10850 LiteralString = RHS; 10851 LiteralStringStripped = RHSStripped; 10852 } 10853 10854 if (LiteralString) { 10855 S.DiagRuntimeBehavior(Loc, nullptr, 10856 S.PDiag(diag::warn_stringcompare) 10857 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10858 << LiteralString->getSourceRange()); 10859 } 10860 } 10861 10862 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10863 switch (CK) { 10864 default: { 10865 #ifndef NDEBUG 10866 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10867 << "\n"; 10868 #endif 10869 llvm_unreachable("unhandled cast kind"); 10870 } 10871 case CK_UserDefinedConversion: 10872 return ICK_Identity; 10873 case CK_LValueToRValue: 10874 return ICK_Lvalue_To_Rvalue; 10875 case CK_ArrayToPointerDecay: 10876 return ICK_Array_To_Pointer; 10877 case CK_FunctionToPointerDecay: 10878 return ICK_Function_To_Pointer; 10879 case CK_IntegralCast: 10880 return ICK_Integral_Conversion; 10881 case CK_FloatingCast: 10882 return ICK_Floating_Conversion; 10883 case CK_IntegralToFloating: 10884 case CK_FloatingToIntegral: 10885 return ICK_Floating_Integral; 10886 case CK_IntegralComplexCast: 10887 case CK_FloatingComplexCast: 10888 case CK_FloatingComplexToIntegralComplex: 10889 case CK_IntegralComplexToFloatingComplex: 10890 return ICK_Complex_Conversion; 10891 case CK_FloatingComplexToReal: 10892 case CK_FloatingRealToComplex: 10893 case CK_IntegralComplexToReal: 10894 case CK_IntegralRealToComplex: 10895 return ICK_Complex_Real; 10896 } 10897 } 10898 10899 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10900 QualType FromType, 10901 SourceLocation Loc) { 10902 // Check for a narrowing implicit conversion. 10903 StandardConversionSequence SCS; 10904 SCS.setAsIdentityConversion(); 10905 SCS.setToType(0, FromType); 10906 SCS.setToType(1, ToType); 10907 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10908 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10909 10910 APValue PreNarrowingValue; 10911 QualType PreNarrowingType; 10912 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10913 PreNarrowingType, 10914 /*IgnoreFloatToIntegralConversion*/ true)) { 10915 case NK_Dependent_Narrowing: 10916 // Implicit conversion to a narrower type, but the expression is 10917 // value-dependent so we can't tell whether it's actually narrowing. 10918 case NK_Not_Narrowing: 10919 return false; 10920 10921 case NK_Constant_Narrowing: 10922 // Implicit conversion to a narrower type, and the value is not a constant 10923 // expression. 10924 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10925 << /*Constant*/ 1 10926 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10927 return true; 10928 10929 case NK_Variable_Narrowing: 10930 // Implicit conversion to a narrower type, and the value is not a constant 10931 // expression. 10932 case NK_Type_Narrowing: 10933 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10934 << /*Constant*/ 0 << FromType << ToType; 10935 // TODO: It's not a constant expression, but what if the user intended it 10936 // to be? Can we produce notes to help them figure out why it isn't? 10937 return true; 10938 } 10939 llvm_unreachable("unhandled case in switch"); 10940 } 10941 10942 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10943 ExprResult &LHS, 10944 ExprResult &RHS, 10945 SourceLocation Loc) { 10946 QualType LHSType = LHS.get()->getType(); 10947 QualType RHSType = RHS.get()->getType(); 10948 // Dig out the original argument type and expression before implicit casts 10949 // were applied. These are the types/expressions we need to check the 10950 // [expr.spaceship] requirements against. 10951 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10952 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10953 QualType LHSStrippedType = LHSStripped.get()->getType(); 10954 QualType RHSStrippedType = RHSStripped.get()->getType(); 10955 10956 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10957 // other is not, the program is ill-formed. 10958 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10959 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10960 return QualType(); 10961 } 10962 10963 // FIXME: Consider combining this with checkEnumArithmeticConversions. 10964 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10965 RHSStrippedType->isEnumeralType(); 10966 if (NumEnumArgs == 1) { 10967 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10968 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10969 if (OtherTy->hasFloatingRepresentation()) { 10970 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10971 return QualType(); 10972 } 10973 } 10974 if (NumEnumArgs == 2) { 10975 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10976 // type E, the operator yields the result of converting the operands 10977 // to the underlying type of E and applying <=> to the converted operands. 10978 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10979 S.InvalidOperands(Loc, LHS, RHS); 10980 return QualType(); 10981 } 10982 QualType IntType = 10983 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10984 assert(IntType->isArithmeticType()); 10985 10986 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10987 // promote the boolean type, and all other promotable integer types, to 10988 // avoid this. 10989 if (IntType->isPromotableIntegerType()) 10990 IntType = S.Context.getPromotedIntegerType(IntType); 10991 10992 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10993 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10994 LHSType = RHSType = IntType; 10995 } 10996 10997 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10998 // usual arithmetic conversions are applied to the operands. 10999 QualType Type = 11000 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11001 if (LHS.isInvalid() || RHS.isInvalid()) 11002 return QualType(); 11003 if (Type.isNull()) 11004 return S.InvalidOperands(Loc, LHS, RHS); 11005 11006 Optional<ComparisonCategoryType> CCT = 11007 getComparisonCategoryForBuiltinCmp(Type); 11008 if (!CCT) 11009 return S.InvalidOperands(Loc, LHS, RHS); 11010 11011 bool HasNarrowing = checkThreeWayNarrowingConversion( 11012 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11013 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11014 RHS.get()->getBeginLoc()); 11015 if (HasNarrowing) 11016 return QualType(); 11017 11018 assert(!Type.isNull() && "composite type for <=> has not been set"); 11019 11020 return S.CheckComparisonCategoryType( 11021 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11022 } 11023 11024 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11025 ExprResult &RHS, 11026 SourceLocation Loc, 11027 BinaryOperatorKind Opc) { 11028 if (Opc == BO_Cmp) 11029 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11030 11031 // C99 6.5.8p3 / C99 6.5.9p4 11032 QualType Type = 11033 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11034 if (LHS.isInvalid() || RHS.isInvalid()) 11035 return QualType(); 11036 if (Type.isNull()) 11037 return S.InvalidOperands(Loc, LHS, RHS); 11038 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11039 11040 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11041 return S.InvalidOperands(Loc, LHS, RHS); 11042 11043 // Check for comparisons of floating point operands using != and ==. 11044 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11045 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11046 11047 // The result of comparisons is 'bool' in C++, 'int' in C. 11048 return S.Context.getLogicalOperationType(); 11049 } 11050 11051 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11052 if (!NullE.get()->getType()->isAnyPointerType()) 11053 return; 11054 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11055 if (!E.get()->getType()->isAnyPointerType() && 11056 E.get()->isNullPointerConstant(Context, 11057 Expr::NPC_ValueDependentIsNotNull) == 11058 Expr::NPCK_ZeroExpression) { 11059 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11060 if (CL->getValue() == 0) 11061 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11062 << NullValue 11063 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11064 NullValue ? "NULL" : "(void *)0"); 11065 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11066 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11067 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11068 if (T == Context.CharTy) 11069 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11070 << NullValue 11071 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11072 NullValue ? "NULL" : "(void *)0"); 11073 } 11074 } 11075 } 11076 11077 // C99 6.5.8, C++ [expr.rel] 11078 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11079 SourceLocation Loc, 11080 BinaryOperatorKind Opc) { 11081 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11082 bool IsThreeWay = Opc == BO_Cmp; 11083 bool IsOrdered = IsRelational || IsThreeWay; 11084 auto IsAnyPointerType = [](ExprResult E) { 11085 QualType Ty = E.get()->getType(); 11086 return Ty->isPointerType() || Ty->isMemberPointerType(); 11087 }; 11088 11089 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11090 // type, array-to-pointer, ..., conversions are performed on both operands to 11091 // bring them to their composite type. 11092 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11093 // any type-related checks. 11094 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11095 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11096 if (LHS.isInvalid()) 11097 return QualType(); 11098 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11099 if (RHS.isInvalid()) 11100 return QualType(); 11101 } else { 11102 LHS = DefaultLvalueConversion(LHS.get()); 11103 if (LHS.isInvalid()) 11104 return QualType(); 11105 RHS = DefaultLvalueConversion(RHS.get()); 11106 if (RHS.isInvalid()) 11107 return QualType(); 11108 } 11109 11110 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11111 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11112 CheckPtrComparisonWithNullChar(LHS, RHS); 11113 CheckPtrComparisonWithNullChar(RHS, LHS); 11114 } 11115 11116 // Handle vector comparisons separately. 11117 if (LHS.get()->getType()->isVectorType() || 11118 RHS.get()->getType()->isVectorType()) 11119 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11120 11121 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11122 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11123 11124 QualType LHSType = LHS.get()->getType(); 11125 QualType RHSType = RHS.get()->getType(); 11126 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11127 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11128 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11129 11130 const Expr::NullPointerConstantKind LHSNullKind = 11131 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11132 const Expr::NullPointerConstantKind RHSNullKind = 11133 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11134 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11135 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11136 11137 auto computeResultTy = [&]() { 11138 if (Opc != BO_Cmp) 11139 return Context.getLogicalOperationType(); 11140 assert(getLangOpts().CPlusPlus); 11141 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11142 11143 QualType CompositeTy = LHS.get()->getType(); 11144 assert(!CompositeTy->isReferenceType()); 11145 11146 Optional<ComparisonCategoryType> CCT = 11147 getComparisonCategoryForBuiltinCmp(CompositeTy); 11148 if (!CCT) 11149 return InvalidOperands(Loc, LHS, RHS); 11150 11151 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11152 // P0946R0: Comparisons between a null pointer constant and an object 11153 // pointer result in std::strong_equality, which is ill-formed under 11154 // P1959R0. 11155 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11156 << (LHSIsNull ? LHS.get()->getSourceRange() 11157 : RHS.get()->getSourceRange()); 11158 return QualType(); 11159 } 11160 11161 return CheckComparisonCategoryType( 11162 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11163 }; 11164 11165 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11166 bool IsEquality = Opc == BO_EQ; 11167 if (RHSIsNull) 11168 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11169 RHS.get()->getSourceRange()); 11170 else 11171 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11172 LHS.get()->getSourceRange()); 11173 } 11174 11175 if ((LHSType->isIntegerType() && !LHSIsNull) || 11176 (RHSType->isIntegerType() && !RHSIsNull)) { 11177 // Skip normal pointer conversion checks in this case; we have better 11178 // diagnostics for this below. 11179 } else if (getLangOpts().CPlusPlus) { 11180 // Equality comparison of a function pointer to a void pointer is invalid, 11181 // but we allow it as an extension. 11182 // FIXME: If we really want to allow this, should it be part of composite 11183 // pointer type computation so it works in conditionals too? 11184 if (!IsOrdered && 11185 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11186 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11187 // This is a gcc extension compatibility comparison. 11188 // In a SFINAE context, we treat this as a hard error to maintain 11189 // conformance with the C++ standard. 11190 diagnoseFunctionPointerToVoidComparison( 11191 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11192 11193 if (isSFINAEContext()) 11194 return QualType(); 11195 11196 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11197 return computeResultTy(); 11198 } 11199 11200 // C++ [expr.eq]p2: 11201 // If at least one operand is a pointer [...] bring them to their 11202 // composite pointer type. 11203 // C++ [expr.spaceship]p6 11204 // If at least one of the operands is of pointer type, [...] bring them 11205 // to their composite pointer type. 11206 // C++ [expr.rel]p2: 11207 // If both operands are pointers, [...] bring them to their composite 11208 // pointer type. 11209 // For <=>, the only valid non-pointer types are arrays and functions, and 11210 // we already decayed those, so this is really the same as the relational 11211 // comparison rule. 11212 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11213 (IsOrdered ? 2 : 1) && 11214 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11215 RHSType->isObjCObjectPointerType()))) { 11216 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11217 return QualType(); 11218 return computeResultTy(); 11219 } 11220 } else if (LHSType->isPointerType() && 11221 RHSType->isPointerType()) { // C99 6.5.8p2 11222 // All of the following pointer-related warnings are GCC extensions, except 11223 // when handling null pointer constants. 11224 QualType LCanPointeeTy = 11225 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11226 QualType RCanPointeeTy = 11227 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11228 11229 // C99 6.5.9p2 and C99 6.5.8p2 11230 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11231 RCanPointeeTy.getUnqualifiedType())) { 11232 // Valid unless a relational comparison of function pointers 11233 if (IsRelational && LCanPointeeTy->isFunctionType()) { 11234 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11235 << LHSType << RHSType << LHS.get()->getSourceRange() 11236 << RHS.get()->getSourceRange(); 11237 } 11238 } else if (!IsRelational && 11239 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11240 // Valid unless comparison between non-null pointer and function pointer 11241 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11242 && !LHSIsNull && !RHSIsNull) 11243 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11244 /*isError*/false); 11245 } else { 11246 // Invalid 11247 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11248 } 11249 if (LCanPointeeTy != RCanPointeeTy) { 11250 // Treat NULL constant as a special case in OpenCL. 11251 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11252 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 11253 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 11254 Diag(Loc, 11255 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11256 << LHSType << RHSType << 0 /* comparison */ 11257 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11258 } 11259 } 11260 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11261 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11262 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11263 : CK_BitCast; 11264 if (LHSIsNull && !RHSIsNull) 11265 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11266 else 11267 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11268 } 11269 return computeResultTy(); 11270 } 11271 11272 if (getLangOpts().CPlusPlus) { 11273 // C++ [expr.eq]p4: 11274 // Two operands of type std::nullptr_t or one operand of type 11275 // std::nullptr_t and the other a null pointer constant compare equal. 11276 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11277 if (LHSType->isNullPtrType()) { 11278 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11279 return computeResultTy(); 11280 } 11281 if (RHSType->isNullPtrType()) { 11282 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11283 return computeResultTy(); 11284 } 11285 } 11286 11287 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11288 // These aren't covered by the composite pointer type rules. 11289 if (!IsOrdered && RHSType->isNullPtrType() && 11290 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11291 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11292 return computeResultTy(); 11293 } 11294 if (!IsOrdered && LHSType->isNullPtrType() && 11295 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11296 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11297 return computeResultTy(); 11298 } 11299 11300 if (IsRelational && 11301 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11302 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11303 // HACK: Relational comparison of nullptr_t against a pointer type is 11304 // invalid per DR583, but we allow it within std::less<> and friends, 11305 // since otherwise common uses of it break. 11306 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11307 // friends to have std::nullptr_t overload candidates. 11308 DeclContext *DC = CurContext; 11309 if (isa<FunctionDecl>(DC)) 11310 DC = DC->getParent(); 11311 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11312 if (CTSD->isInStdNamespace() && 11313 llvm::StringSwitch<bool>(CTSD->getName()) 11314 .Cases("less", "less_equal", "greater", "greater_equal", true) 11315 .Default(false)) { 11316 if (RHSType->isNullPtrType()) 11317 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11318 else 11319 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11320 return computeResultTy(); 11321 } 11322 } 11323 } 11324 11325 // C++ [expr.eq]p2: 11326 // If at least one operand is a pointer to member, [...] bring them to 11327 // their composite pointer type. 11328 if (!IsOrdered && 11329 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11330 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11331 return QualType(); 11332 else 11333 return computeResultTy(); 11334 } 11335 } 11336 11337 // Handle block pointer types. 11338 if (!IsOrdered && LHSType->isBlockPointerType() && 11339 RHSType->isBlockPointerType()) { 11340 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11341 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11342 11343 if (!LHSIsNull && !RHSIsNull && 11344 !Context.typesAreCompatible(lpointee, rpointee)) { 11345 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11346 << LHSType << RHSType << LHS.get()->getSourceRange() 11347 << RHS.get()->getSourceRange(); 11348 } 11349 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11350 return computeResultTy(); 11351 } 11352 11353 // Allow block pointers to be compared with null pointer constants. 11354 if (!IsOrdered 11355 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11356 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11357 if (!LHSIsNull && !RHSIsNull) { 11358 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11359 ->getPointeeType()->isVoidType()) 11360 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11361 ->getPointeeType()->isVoidType()))) 11362 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11363 << LHSType << RHSType << LHS.get()->getSourceRange() 11364 << RHS.get()->getSourceRange(); 11365 } 11366 if (LHSIsNull && !RHSIsNull) 11367 LHS = ImpCastExprToType(LHS.get(), RHSType, 11368 RHSType->isPointerType() ? CK_BitCast 11369 : CK_AnyPointerToBlockPointerCast); 11370 else 11371 RHS = ImpCastExprToType(RHS.get(), LHSType, 11372 LHSType->isPointerType() ? CK_BitCast 11373 : CK_AnyPointerToBlockPointerCast); 11374 return computeResultTy(); 11375 } 11376 11377 if (LHSType->isObjCObjectPointerType() || 11378 RHSType->isObjCObjectPointerType()) { 11379 const PointerType *LPT = LHSType->getAs<PointerType>(); 11380 const PointerType *RPT = RHSType->getAs<PointerType>(); 11381 if (LPT || RPT) { 11382 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11383 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11384 11385 if (!LPtrToVoid && !RPtrToVoid && 11386 !Context.typesAreCompatible(LHSType, RHSType)) { 11387 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11388 /*isError*/false); 11389 } 11390 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11391 // the RHS, but we have test coverage for this behavior. 11392 // FIXME: Consider using convertPointersToCompositeType in C++. 11393 if (LHSIsNull && !RHSIsNull) { 11394 Expr *E = LHS.get(); 11395 if (getLangOpts().ObjCAutoRefCount) 11396 CheckObjCConversion(SourceRange(), RHSType, E, 11397 CCK_ImplicitConversion); 11398 LHS = ImpCastExprToType(E, RHSType, 11399 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11400 } 11401 else { 11402 Expr *E = RHS.get(); 11403 if (getLangOpts().ObjCAutoRefCount) 11404 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11405 /*Diagnose=*/true, 11406 /*DiagnoseCFAudited=*/false, Opc); 11407 RHS = ImpCastExprToType(E, LHSType, 11408 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11409 } 11410 return computeResultTy(); 11411 } 11412 if (LHSType->isObjCObjectPointerType() && 11413 RHSType->isObjCObjectPointerType()) { 11414 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11415 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11416 /*isError*/false); 11417 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11418 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11419 11420 if (LHSIsNull && !RHSIsNull) 11421 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11422 else 11423 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11424 return computeResultTy(); 11425 } 11426 11427 if (!IsOrdered && LHSType->isBlockPointerType() && 11428 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11429 LHS = ImpCastExprToType(LHS.get(), RHSType, 11430 CK_BlockPointerToObjCPointerCast); 11431 return computeResultTy(); 11432 } else if (!IsOrdered && 11433 LHSType->isBlockCompatibleObjCPointerType(Context) && 11434 RHSType->isBlockPointerType()) { 11435 RHS = ImpCastExprToType(RHS.get(), LHSType, 11436 CK_BlockPointerToObjCPointerCast); 11437 return computeResultTy(); 11438 } 11439 } 11440 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11441 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11442 unsigned DiagID = 0; 11443 bool isError = false; 11444 if (LangOpts.DebuggerSupport) { 11445 // Under a debugger, allow the comparison of pointers to integers, 11446 // since users tend to want to compare addresses. 11447 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11448 (RHSIsNull && RHSType->isIntegerType())) { 11449 if (IsOrdered) { 11450 isError = getLangOpts().CPlusPlus; 11451 DiagID = 11452 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11453 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11454 } 11455 } else if (getLangOpts().CPlusPlus) { 11456 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11457 isError = true; 11458 } else if (IsOrdered) 11459 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11460 else 11461 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11462 11463 if (DiagID) { 11464 Diag(Loc, DiagID) 11465 << LHSType << RHSType << LHS.get()->getSourceRange() 11466 << RHS.get()->getSourceRange(); 11467 if (isError) 11468 return QualType(); 11469 } 11470 11471 if (LHSType->isIntegerType()) 11472 LHS = ImpCastExprToType(LHS.get(), RHSType, 11473 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11474 else 11475 RHS = ImpCastExprToType(RHS.get(), LHSType, 11476 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11477 return computeResultTy(); 11478 } 11479 11480 // Handle block pointers. 11481 if (!IsOrdered && RHSIsNull 11482 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11483 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11484 return computeResultTy(); 11485 } 11486 if (!IsOrdered && LHSIsNull 11487 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11488 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11489 return computeResultTy(); 11490 } 11491 11492 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11493 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11494 return computeResultTy(); 11495 } 11496 11497 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11498 return computeResultTy(); 11499 } 11500 11501 if (LHSIsNull && RHSType->isQueueT()) { 11502 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11503 return computeResultTy(); 11504 } 11505 11506 if (LHSType->isQueueT() && RHSIsNull) { 11507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11508 return computeResultTy(); 11509 } 11510 } 11511 11512 return InvalidOperands(Loc, LHS, RHS); 11513 } 11514 11515 // Return a signed ext_vector_type that is of identical size and number of 11516 // elements. For floating point vectors, return an integer type of identical 11517 // size and number of elements. In the non ext_vector_type case, search from 11518 // the largest type to the smallest type to avoid cases where long long == long, 11519 // where long gets picked over long long. 11520 QualType Sema::GetSignedVectorType(QualType V) { 11521 const VectorType *VTy = V->castAs<VectorType>(); 11522 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11523 11524 if (isa<ExtVectorType>(VTy)) { 11525 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11526 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11527 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11528 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11529 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11530 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11531 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11532 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11533 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11534 "Unhandled vector element size in vector compare"); 11535 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11536 } 11537 11538 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11539 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11540 VectorType::GenericVector); 11541 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11542 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11543 VectorType::GenericVector); 11544 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11545 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11546 VectorType::GenericVector); 11547 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11548 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11549 VectorType::GenericVector); 11550 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11551 "Unhandled vector element size in vector compare"); 11552 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11553 VectorType::GenericVector); 11554 } 11555 11556 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11557 /// operates on extended vector types. Instead of producing an IntTy result, 11558 /// like a scalar comparison, a vector comparison produces a vector of integer 11559 /// types. 11560 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11561 SourceLocation Loc, 11562 BinaryOperatorKind Opc) { 11563 if (Opc == BO_Cmp) { 11564 Diag(Loc, diag::err_three_way_vector_comparison); 11565 return QualType(); 11566 } 11567 11568 // Check to make sure we're operating on vectors of the same type and width, 11569 // Allowing one side to be a scalar of element type. 11570 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11571 /*AllowBothBool*/true, 11572 /*AllowBoolConversions*/getLangOpts().ZVector); 11573 if (vType.isNull()) 11574 return vType; 11575 11576 QualType LHSType = LHS.get()->getType(); 11577 11578 // If AltiVec, the comparison results in a numeric type, i.e. 11579 // bool for C++, int for C 11580 if (getLangOpts().AltiVec && 11581 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11582 return Context.getLogicalOperationType(); 11583 11584 // For non-floating point types, check for self-comparisons of the form 11585 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11586 // often indicate logic errors in the program. 11587 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11588 11589 // Check for comparisons of floating point operands using != and ==. 11590 if (BinaryOperator::isEqualityOp(Opc) && 11591 LHSType->hasFloatingRepresentation()) { 11592 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11593 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11594 } 11595 11596 // Return a signed type for the vector. 11597 return GetSignedVectorType(vType); 11598 } 11599 11600 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11601 const ExprResult &XorRHS, 11602 const SourceLocation Loc) { 11603 // Do not diagnose macros. 11604 if (Loc.isMacroID()) 11605 return; 11606 11607 bool Negative = false; 11608 bool ExplicitPlus = false; 11609 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11610 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11611 11612 if (!LHSInt) 11613 return; 11614 if (!RHSInt) { 11615 // Check negative literals. 11616 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11617 UnaryOperatorKind Opc = UO->getOpcode(); 11618 if (Opc != UO_Minus && Opc != UO_Plus) 11619 return; 11620 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11621 if (!RHSInt) 11622 return; 11623 Negative = (Opc == UO_Minus); 11624 ExplicitPlus = !Negative; 11625 } else { 11626 return; 11627 } 11628 } 11629 11630 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11631 llvm::APInt RightSideValue = RHSInt->getValue(); 11632 if (LeftSideValue != 2 && LeftSideValue != 10) 11633 return; 11634 11635 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11636 return; 11637 11638 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11639 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11640 llvm::StringRef ExprStr = 11641 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11642 11643 CharSourceRange XorRange = 11644 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11645 llvm::StringRef XorStr = 11646 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11647 // Do not diagnose if xor keyword/macro is used. 11648 if (XorStr == "xor") 11649 return; 11650 11651 std::string LHSStr = std::string(Lexer::getSourceText( 11652 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11653 S.getSourceManager(), S.getLangOpts())); 11654 std::string RHSStr = std::string(Lexer::getSourceText( 11655 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11656 S.getSourceManager(), S.getLangOpts())); 11657 11658 if (Negative) { 11659 RightSideValue = -RightSideValue; 11660 RHSStr = "-" + RHSStr; 11661 } else if (ExplicitPlus) { 11662 RHSStr = "+" + RHSStr; 11663 } 11664 11665 StringRef LHSStrRef = LHSStr; 11666 StringRef RHSStrRef = RHSStr; 11667 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11668 // literals. 11669 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11670 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11671 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11672 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11673 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11674 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11675 LHSStrRef.find('\'') != StringRef::npos || 11676 RHSStrRef.find('\'') != StringRef::npos) 11677 return; 11678 11679 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11680 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11681 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11682 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11683 std::string SuggestedExpr = "1 << " + RHSStr; 11684 bool Overflow = false; 11685 llvm::APInt One = (LeftSideValue - 1); 11686 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11687 if (Overflow) { 11688 if (RightSideIntValue < 64) 11689 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11690 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11691 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11692 else if (RightSideIntValue == 64) 11693 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11694 else 11695 return; 11696 } else { 11697 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11698 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11699 << PowValue.toString(10, true) 11700 << FixItHint::CreateReplacement( 11701 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11702 } 11703 11704 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11705 } else if (LeftSideValue == 10) { 11706 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11707 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11708 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11709 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11710 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11711 } 11712 } 11713 11714 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11715 SourceLocation Loc) { 11716 // Ensure that either both operands are of the same vector type, or 11717 // one operand is of a vector type and the other is of its element type. 11718 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11719 /*AllowBothBool*/true, 11720 /*AllowBoolConversions*/false); 11721 if (vType.isNull()) 11722 return InvalidOperands(Loc, LHS, RHS); 11723 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11724 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11725 return InvalidOperands(Loc, LHS, RHS); 11726 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11727 // usage of the logical operators && and || with vectors in C. This 11728 // check could be notionally dropped. 11729 if (!getLangOpts().CPlusPlus && 11730 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11731 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11732 11733 return GetSignedVectorType(LHS.get()->getType()); 11734 } 11735 11736 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11737 SourceLocation Loc, 11738 BinaryOperatorKind Opc) { 11739 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11740 11741 bool IsCompAssign = 11742 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11743 11744 if (LHS.get()->getType()->isVectorType() || 11745 RHS.get()->getType()->isVectorType()) { 11746 if (LHS.get()->getType()->hasIntegerRepresentation() && 11747 RHS.get()->getType()->hasIntegerRepresentation()) 11748 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11749 /*AllowBothBool*/true, 11750 /*AllowBoolConversions*/getLangOpts().ZVector); 11751 return InvalidOperands(Loc, LHS, RHS); 11752 } 11753 11754 if (Opc == BO_And) 11755 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11756 11757 if (LHS.get()->getType()->hasFloatingRepresentation() || 11758 RHS.get()->getType()->hasFloatingRepresentation()) 11759 return InvalidOperands(Loc, LHS, RHS); 11760 11761 ExprResult LHSResult = LHS, RHSResult = RHS; 11762 QualType compType = UsualArithmeticConversions( 11763 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11764 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11765 return QualType(); 11766 LHS = LHSResult.get(); 11767 RHS = RHSResult.get(); 11768 11769 if (Opc == BO_Xor) 11770 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11771 11772 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11773 return compType; 11774 return InvalidOperands(Loc, LHS, RHS); 11775 } 11776 11777 // C99 6.5.[13,14] 11778 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11779 SourceLocation Loc, 11780 BinaryOperatorKind Opc) { 11781 // Check vector operands differently. 11782 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11783 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11784 11785 bool EnumConstantInBoolContext = false; 11786 for (const ExprResult &HS : {LHS, RHS}) { 11787 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11788 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11789 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11790 EnumConstantInBoolContext = true; 11791 } 11792 } 11793 11794 if (EnumConstantInBoolContext) 11795 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11796 11797 // Diagnose cases where the user write a logical and/or but probably meant a 11798 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11799 // is a constant. 11800 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11801 !LHS.get()->getType()->isBooleanType() && 11802 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11803 // Don't warn in macros or template instantiations. 11804 !Loc.isMacroID() && !inTemplateInstantiation()) { 11805 // If the RHS can be constant folded, and if it constant folds to something 11806 // that isn't 0 or 1 (which indicate a potential logical operation that 11807 // happened to fold to true/false) then warn. 11808 // Parens on the RHS are ignored. 11809 Expr::EvalResult EVResult; 11810 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11811 llvm::APSInt Result = EVResult.Val.getInt(); 11812 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11813 !RHS.get()->getExprLoc().isMacroID()) || 11814 (Result != 0 && Result != 1)) { 11815 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11816 << RHS.get()->getSourceRange() 11817 << (Opc == BO_LAnd ? "&&" : "||"); 11818 // Suggest replacing the logical operator with the bitwise version 11819 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11820 << (Opc == BO_LAnd ? "&" : "|") 11821 << FixItHint::CreateReplacement(SourceRange( 11822 Loc, getLocForEndOfToken(Loc)), 11823 Opc == BO_LAnd ? "&" : "|"); 11824 if (Opc == BO_LAnd) 11825 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11826 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11827 << FixItHint::CreateRemoval( 11828 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11829 RHS.get()->getEndLoc())); 11830 } 11831 } 11832 } 11833 11834 if (!Context.getLangOpts().CPlusPlus) { 11835 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11836 // not operate on the built-in scalar and vector float types. 11837 if (Context.getLangOpts().OpenCL && 11838 Context.getLangOpts().OpenCLVersion < 120) { 11839 if (LHS.get()->getType()->isFloatingType() || 11840 RHS.get()->getType()->isFloatingType()) 11841 return InvalidOperands(Loc, LHS, RHS); 11842 } 11843 11844 LHS = UsualUnaryConversions(LHS.get()); 11845 if (LHS.isInvalid()) 11846 return QualType(); 11847 11848 RHS = UsualUnaryConversions(RHS.get()); 11849 if (RHS.isInvalid()) 11850 return QualType(); 11851 11852 if (!LHS.get()->getType()->isScalarType() || 11853 !RHS.get()->getType()->isScalarType()) 11854 return InvalidOperands(Loc, LHS, RHS); 11855 11856 return Context.IntTy; 11857 } 11858 11859 // The following is safe because we only use this method for 11860 // non-overloadable operands. 11861 11862 // C++ [expr.log.and]p1 11863 // C++ [expr.log.or]p1 11864 // The operands are both contextually converted to type bool. 11865 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11866 if (LHSRes.isInvalid()) 11867 return InvalidOperands(Loc, LHS, RHS); 11868 LHS = LHSRes; 11869 11870 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11871 if (RHSRes.isInvalid()) 11872 return InvalidOperands(Loc, LHS, RHS); 11873 RHS = RHSRes; 11874 11875 // C++ [expr.log.and]p2 11876 // C++ [expr.log.or]p2 11877 // The result is a bool. 11878 return Context.BoolTy; 11879 } 11880 11881 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11882 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11883 if (!ME) return false; 11884 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11885 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11886 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11887 if (!Base) return false; 11888 return Base->getMethodDecl() != nullptr; 11889 } 11890 11891 /// Is the given expression (which must be 'const') a reference to a 11892 /// variable which was originally non-const, but which has become 11893 /// 'const' due to being captured within a block? 11894 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11895 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11896 assert(E->isLValue() && E->getType().isConstQualified()); 11897 E = E->IgnoreParens(); 11898 11899 // Must be a reference to a declaration from an enclosing scope. 11900 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11901 if (!DRE) return NCCK_None; 11902 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11903 11904 // The declaration must be a variable which is not declared 'const'. 11905 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11906 if (!var) return NCCK_None; 11907 if (var->getType().isConstQualified()) return NCCK_None; 11908 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11909 11910 // Decide whether the first capture was for a block or a lambda. 11911 DeclContext *DC = S.CurContext, *Prev = nullptr; 11912 // Decide whether the first capture was for a block or a lambda. 11913 while (DC) { 11914 // For init-capture, it is possible that the variable belongs to the 11915 // template pattern of the current context. 11916 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11917 if (var->isInitCapture() && 11918 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11919 break; 11920 if (DC == var->getDeclContext()) 11921 break; 11922 Prev = DC; 11923 DC = DC->getParent(); 11924 } 11925 // Unless we have an init-capture, we've gone one step too far. 11926 if (!var->isInitCapture()) 11927 DC = Prev; 11928 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11929 } 11930 11931 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11932 Ty = Ty.getNonReferenceType(); 11933 if (IsDereference && Ty->isPointerType()) 11934 Ty = Ty->getPointeeType(); 11935 return !Ty.isConstQualified(); 11936 } 11937 11938 // Update err_typecheck_assign_const and note_typecheck_assign_const 11939 // when this enum is changed. 11940 enum { 11941 ConstFunction, 11942 ConstVariable, 11943 ConstMember, 11944 ConstMethod, 11945 NestedConstMember, 11946 ConstUnknown, // Keep as last element 11947 }; 11948 11949 /// Emit the "read-only variable not assignable" error and print notes to give 11950 /// more information about why the variable is not assignable, such as pointing 11951 /// to the declaration of a const variable, showing that a method is const, or 11952 /// that the function is returning a const reference. 11953 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11954 SourceLocation Loc) { 11955 SourceRange ExprRange = E->getSourceRange(); 11956 11957 // Only emit one error on the first const found. All other consts will emit 11958 // a note to the error. 11959 bool DiagnosticEmitted = false; 11960 11961 // Track if the current expression is the result of a dereference, and if the 11962 // next checked expression is the result of a dereference. 11963 bool IsDereference = false; 11964 bool NextIsDereference = false; 11965 11966 // Loop to process MemberExpr chains. 11967 while (true) { 11968 IsDereference = NextIsDereference; 11969 11970 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11971 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11972 NextIsDereference = ME->isArrow(); 11973 const ValueDecl *VD = ME->getMemberDecl(); 11974 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11975 // Mutable fields can be modified even if the class is const. 11976 if (Field->isMutable()) { 11977 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11978 break; 11979 } 11980 11981 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11982 if (!DiagnosticEmitted) { 11983 S.Diag(Loc, diag::err_typecheck_assign_const) 11984 << ExprRange << ConstMember << false /*static*/ << Field 11985 << Field->getType(); 11986 DiagnosticEmitted = true; 11987 } 11988 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11989 << ConstMember << false /*static*/ << Field << Field->getType() 11990 << Field->getSourceRange(); 11991 } 11992 E = ME->getBase(); 11993 continue; 11994 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11995 if (VDecl->getType().isConstQualified()) { 11996 if (!DiagnosticEmitted) { 11997 S.Diag(Loc, diag::err_typecheck_assign_const) 11998 << ExprRange << ConstMember << true /*static*/ << VDecl 11999 << VDecl->getType(); 12000 DiagnosticEmitted = true; 12001 } 12002 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12003 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12004 << VDecl->getSourceRange(); 12005 } 12006 // Static fields do not inherit constness from parents. 12007 break; 12008 } 12009 break; // End MemberExpr 12010 } else if (const ArraySubscriptExpr *ASE = 12011 dyn_cast<ArraySubscriptExpr>(E)) { 12012 E = ASE->getBase()->IgnoreParenImpCasts(); 12013 continue; 12014 } else if (const ExtVectorElementExpr *EVE = 12015 dyn_cast<ExtVectorElementExpr>(E)) { 12016 E = EVE->getBase()->IgnoreParenImpCasts(); 12017 continue; 12018 } 12019 break; 12020 } 12021 12022 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12023 // Function calls 12024 const FunctionDecl *FD = CE->getDirectCallee(); 12025 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12026 if (!DiagnosticEmitted) { 12027 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12028 << ConstFunction << FD; 12029 DiagnosticEmitted = true; 12030 } 12031 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12032 diag::note_typecheck_assign_const) 12033 << ConstFunction << FD << FD->getReturnType() 12034 << FD->getReturnTypeSourceRange(); 12035 } 12036 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12037 // Point to variable declaration. 12038 if (const ValueDecl *VD = DRE->getDecl()) { 12039 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12040 if (!DiagnosticEmitted) { 12041 S.Diag(Loc, diag::err_typecheck_assign_const) 12042 << ExprRange << ConstVariable << VD << VD->getType(); 12043 DiagnosticEmitted = true; 12044 } 12045 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12046 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12047 } 12048 } 12049 } else if (isa<CXXThisExpr>(E)) { 12050 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12051 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12052 if (MD->isConst()) { 12053 if (!DiagnosticEmitted) { 12054 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12055 << ConstMethod << MD; 12056 DiagnosticEmitted = true; 12057 } 12058 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12059 << ConstMethod << MD << MD->getSourceRange(); 12060 } 12061 } 12062 } 12063 } 12064 12065 if (DiagnosticEmitted) 12066 return; 12067 12068 // Can't determine a more specific message, so display the generic error. 12069 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12070 } 12071 12072 enum OriginalExprKind { 12073 OEK_Variable, 12074 OEK_Member, 12075 OEK_LValue 12076 }; 12077 12078 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12079 const RecordType *Ty, 12080 SourceLocation Loc, SourceRange Range, 12081 OriginalExprKind OEK, 12082 bool &DiagnosticEmitted) { 12083 std::vector<const RecordType *> RecordTypeList; 12084 RecordTypeList.push_back(Ty); 12085 unsigned NextToCheckIndex = 0; 12086 // We walk the record hierarchy breadth-first to ensure that we print 12087 // diagnostics in field nesting order. 12088 while (RecordTypeList.size() > NextToCheckIndex) { 12089 bool IsNested = NextToCheckIndex > 0; 12090 for (const FieldDecl *Field : 12091 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12092 // First, check every field for constness. 12093 QualType FieldTy = Field->getType(); 12094 if (FieldTy.isConstQualified()) { 12095 if (!DiagnosticEmitted) { 12096 S.Diag(Loc, diag::err_typecheck_assign_const) 12097 << Range << NestedConstMember << OEK << VD 12098 << IsNested << Field; 12099 DiagnosticEmitted = true; 12100 } 12101 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12102 << NestedConstMember << IsNested << Field 12103 << FieldTy << Field->getSourceRange(); 12104 } 12105 12106 // Then we append it to the list to check next in order. 12107 FieldTy = FieldTy.getCanonicalType(); 12108 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12109 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12110 RecordTypeList.push_back(FieldRecTy); 12111 } 12112 } 12113 ++NextToCheckIndex; 12114 } 12115 } 12116 12117 /// Emit an error for the case where a record we are trying to assign to has a 12118 /// const-qualified field somewhere in its hierarchy. 12119 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12120 SourceLocation Loc) { 12121 QualType Ty = E->getType(); 12122 assert(Ty->isRecordType() && "lvalue was not record?"); 12123 SourceRange Range = E->getSourceRange(); 12124 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12125 bool DiagEmitted = false; 12126 12127 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12128 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12129 Range, OEK_Member, DiagEmitted); 12130 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12131 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12132 Range, OEK_Variable, DiagEmitted); 12133 else 12134 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12135 Range, OEK_LValue, DiagEmitted); 12136 if (!DiagEmitted) 12137 DiagnoseConstAssignment(S, E, Loc); 12138 } 12139 12140 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12141 /// emit an error and return true. If so, return false. 12142 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12143 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12144 12145 S.CheckShadowingDeclModification(E, Loc); 12146 12147 SourceLocation OrigLoc = Loc; 12148 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12149 &Loc); 12150 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12151 IsLV = Expr::MLV_InvalidMessageExpression; 12152 if (IsLV == Expr::MLV_Valid) 12153 return false; 12154 12155 unsigned DiagID = 0; 12156 bool NeedType = false; 12157 switch (IsLV) { // C99 6.5.16p2 12158 case Expr::MLV_ConstQualified: 12159 // Use a specialized diagnostic when we're assigning to an object 12160 // from an enclosing function or block. 12161 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12162 if (NCCK == NCCK_Block) 12163 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12164 else 12165 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12166 break; 12167 } 12168 12169 // In ARC, use some specialized diagnostics for occasions where we 12170 // infer 'const'. These are always pseudo-strong variables. 12171 if (S.getLangOpts().ObjCAutoRefCount) { 12172 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12173 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12174 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12175 12176 // Use the normal diagnostic if it's pseudo-__strong but the 12177 // user actually wrote 'const'. 12178 if (var->isARCPseudoStrong() && 12179 (!var->getTypeSourceInfo() || 12180 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12181 // There are three pseudo-strong cases: 12182 // - self 12183 ObjCMethodDecl *method = S.getCurMethodDecl(); 12184 if (method && var == method->getSelfDecl()) { 12185 DiagID = method->isClassMethod() 12186 ? diag::err_typecheck_arc_assign_self_class_method 12187 : diag::err_typecheck_arc_assign_self; 12188 12189 // - Objective-C externally_retained attribute. 12190 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12191 isa<ParmVarDecl>(var)) { 12192 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12193 12194 // - fast enumeration variables 12195 } else { 12196 DiagID = diag::err_typecheck_arr_assign_enumeration; 12197 } 12198 12199 SourceRange Assign; 12200 if (Loc != OrigLoc) 12201 Assign = SourceRange(OrigLoc, OrigLoc); 12202 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12203 // We need to preserve the AST regardless, so migration tool 12204 // can do its job. 12205 return false; 12206 } 12207 } 12208 } 12209 12210 // If none of the special cases above are triggered, then this is a 12211 // simple const assignment. 12212 if (DiagID == 0) { 12213 DiagnoseConstAssignment(S, E, Loc); 12214 return true; 12215 } 12216 12217 break; 12218 case Expr::MLV_ConstAddrSpace: 12219 DiagnoseConstAssignment(S, E, Loc); 12220 return true; 12221 case Expr::MLV_ConstQualifiedField: 12222 DiagnoseRecursiveConstFields(S, E, Loc); 12223 return true; 12224 case Expr::MLV_ArrayType: 12225 case Expr::MLV_ArrayTemporary: 12226 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12227 NeedType = true; 12228 break; 12229 case Expr::MLV_NotObjectType: 12230 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12231 NeedType = true; 12232 break; 12233 case Expr::MLV_LValueCast: 12234 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12235 break; 12236 case Expr::MLV_Valid: 12237 llvm_unreachable("did not take early return for MLV_Valid"); 12238 case Expr::MLV_InvalidExpression: 12239 case Expr::MLV_MemberFunction: 12240 case Expr::MLV_ClassTemporary: 12241 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12242 break; 12243 case Expr::MLV_IncompleteType: 12244 case Expr::MLV_IncompleteVoidType: 12245 return S.RequireCompleteType(Loc, E->getType(), 12246 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12247 case Expr::MLV_DuplicateVectorComponents: 12248 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12249 break; 12250 case Expr::MLV_NoSetterProperty: 12251 llvm_unreachable("readonly properties should be processed differently"); 12252 case Expr::MLV_InvalidMessageExpression: 12253 DiagID = diag::err_readonly_message_assignment; 12254 break; 12255 case Expr::MLV_SubObjCPropertySetting: 12256 DiagID = diag::err_no_subobject_property_setting; 12257 break; 12258 } 12259 12260 SourceRange Assign; 12261 if (Loc != OrigLoc) 12262 Assign = SourceRange(OrigLoc, OrigLoc); 12263 if (NeedType) 12264 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12265 else 12266 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12267 return true; 12268 } 12269 12270 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12271 SourceLocation Loc, 12272 Sema &Sema) { 12273 if (Sema.inTemplateInstantiation()) 12274 return; 12275 if (Sema.isUnevaluatedContext()) 12276 return; 12277 if (Loc.isInvalid() || Loc.isMacroID()) 12278 return; 12279 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12280 return; 12281 12282 // C / C++ fields 12283 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12284 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12285 if (ML && MR) { 12286 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12287 return; 12288 const ValueDecl *LHSDecl = 12289 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12290 const ValueDecl *RHSDecl = 12291 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12292 if (LHSDecl != RHSDecl) 12293 return; 12294 if (LHSDecl->getType().isVolatileQualified()) 12295 return; 12296 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12297 if (RefTy->getPointeeType().isVolatileQualified()) 12298 return; 12299 12300 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12301 } 12302 12303 // Objective-C instance variables 12304 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12305 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12306 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12307 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12308 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12309 if (RL && RR && RL->getDecl() == RR->getDecl()) 12310 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12311 } 12312 } 12313 12314 // C99 6.5.16.1 12315 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12316 SourceLocation Loc, 12317 QualType CompoundType) { 12318 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12319 12320 // Verify that LHS is a modifiable lvalue, and emit error if not. 12321 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12322 return QualType(); 12323 12324 QualType LHSType = LHSExpr->getType(); 12325 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12326 CompoundType; 12327 // OpenCL v1.2 s6.1.1.1 p2: 12328 // The half data type can only be used to declare a pointer to a buffer that 12329 // contains half values 12330 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12331 LHSType->isHalfType()) { 12332 Diag(Loc, diag::err_opencl_half_load_store) << 1 12333 << LHSType.getUnqualifiedType(); 12334 return QualType(); 12335 } 12336 12337 AssignConvertType ConvTy; 12338 if (CompoundType.isNull()) { 12339 Expr *RHSCheck = RHS.get(); 12340 12341 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12342 12343 QualType LHSTy(LHSType); 12344 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12345 if (RHS.isInvalid()) 12346 return QualType(); 12347 // Special case of NSObject attributes on c-style pointer types. 12348 if (ConvTy == IncompatiblePointer && 12349 ((Context.isObjCNSObjectType(LHSType) && 12350 RHSType->isObjCObjectPointerType()) || 12351 (Context.isObjCNSObjectType(RHSType) && 12352 LHSType->isObjCObjectPointerType()))) 12353 ConvTy = Compatible; 12354 12355 if (ConvTy == Compatible && 12356 LHSType->isObjCObjectType()) 12357 Diag(Loc, diag::err_objc_object_assignment) 12358 << LHSType; 12359 12360 // If the RHS is a unary plus or minus, check to see if they = and + are 12361 // right next to each other. If so, the user may have typo'd "x =+ 4" 12362 // instead of "x += 4". 12363 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12364 RHSCheck = ICE->getSubExpr(); 12365 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12366 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12367 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12368 // Only if the two operators are exactly adjacent. 12369 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12370 // And there is a space or other character before the subexpr of the 12371 // unary +/-. We don't want to warn on "x=-1". 12372 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12373 UO->getSubExpr()->getBeginLoc().isFileID()) { 12374 Diag(Loc, diag::warn_not_compound_assign) 12375 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12376 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12377 } 12378 } 12379 12380 if (ConvTy == Compatible) { 12381 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12382 // Warn about retain cycles where a block captures the LHS, but 12383 // not if the LHS is a simple variable into which the block is 12384 // being stored...unless that variable can be captured by reference! 12385 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12386 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12387 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12388 checkRetainCycles(LHSExpr, RHS.get()); 12389 } 12390 12391 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12392 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12393 // It is safe to assign a weak reference into a strong variable. 12394 // Although this code can still have problems: 12395 // id x = self.weakProp; 12396 // id y = self.weakProp; 12397 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12398 // paths through the function. This should be revisited if 12399 // -Wrepeated-use-of-weak is made flow-sensitive. 12400 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12401 // variable, which will be valid for the current autorelease scope. 12402 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12403 RHS.get()->getBeginLoc())) 12404 getCurFunction()->markSafeWeakUse(RHS.get()); 12405 12406 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12407 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12408 } 12409 } 12410 } else { 12411 // Compound assignment "x += y" 12412 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12413 } 12414 12415 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12416 RHS.get(), AA_Assigning)) 12417 return QualType(); 12418 12419 CheckForNullPointerDereference(*this, LHSExpr); 12420 12421 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12422 if (CompoundType.isNull()) { 12423 // C++2a [expr.ass]p5: 12424 // A simple-assignment whose left operand is of a volatile-qualified 12425 // type is deprecated unless the assignment is either a discarded-value 12426 // expression or an unevaluated operand 12427 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12428 } else { 12429 // C++2a [expr.ass]p6: 12430 // [Compound-assignment] expressions are deprecated if E1 has 12431 // volatile-qualified type 12432 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12433 } 12434 } 12435 12436 // C99 6.5.16p3: The type of an assignment expression is the type of the 12437 // left operand unless the left operand has qualified type, in which case 12438 // it is the unqualified version of the type of the left operand. 12439 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12440 // is converted to the type of the assignment expression (above). 12441 // C++ 5.17p1: the type of the assignment expression is that of its left 12442 // operand. 12443 return (getLangOpts().CPlusPlus 12444 ? LHSType : LHSType.getUnqualifiedType()); 12445 } 12446 12447 // Only ignore explicit casts to void. 12448 static bool IgnoreCommaOperand(const Expr *E) { 12449 E = E->IgnoreParens(); 12450 12451 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12452 if (CE->getCastKind() == CK_ToVoid) { 12453 return true; 12454 } 12455 12456 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12457 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12458 CE->getSubExpr()->getType()->isDependentType()) { 12459 return true; 12460 } 12461 } 12462 12463 return false; 12464 } 12465 12466 // Look for instances where it is likely the comma operator is confused with 12467 // another operator. There is a whitelist of acceptable expressions for the 12468 // left hand side of the comma operator, otherwise emit a warning. 12469 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12470 // No warnings in macros 12471 if (Loc.isMacroID()) 12472 return; 12473 12474 // Don't warn in template instantiations. 12475 if (inTemplateInstantiation()) 12476 return; 12477 12478 // Scope isn't fine-grained enough to whitelist the specific cases, so 12479 // instead, skip more than needed, then call back into here with the 12480 // CommaVisitor in SemaStmt.cpp. 12481 // The whitelisted locations are the initialization and increment portions 12482 // of a for loop. The additional checks are on the condition of 12483 // if statements, do/while loops, and for loops. 12484 // Differences in scope flags for C89 mode requires the extra logic. 12485 const unsigned ForIncrementFlags = 12486 getLangOpts().C99 || getLangOpts().CPlusPlus 12487 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12488 : Scope::ContinueScope | Scope::BreakScope; 12489 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12490 const unsigned ScopeFlags = getCurScope()->getFlags(); 12491 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12492 (ScopeFlags & ForInitFlags) == ForInitFlags) 12493 return; 12494 12495 // If there are multiple comma operators used together, get the RHS of the 12496 // of the comma operator as the LHS. 12497 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12498 if (BO->getOpcode() != BO_Comma) 12499 break; 12500 LHS = BO->getRHS(); 12501 } 12502 12503 // Only allow some expressions on LHS to not warn. 12504 if (IgnoreCommaOperand(LHS)) 12505 return; 12506 12507 Diag(Loc, diag::warn_comma_operator); 12508 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12509 << LHS->getSourceRange() 12510 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12511 LangOpts.CPlusPlus ? "static_cast<void>(" 12512 : "(void)(") 12513 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12514 ")"); 12515 } 12516 12517 // C99 6.5.17 12518 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12519 SourceLocation Loc) { 12520 LHS = S.CheckPlaceholderExpr(LHS.get()); 12521 RHS = S.CheckPlaceholderExpr(RHS.get()); 12522 if (LHS.isInvalid() || RHS.isInvalid()) 12523 return QualType(); 12524 12525 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12526 // operands, but not unary promotions. 12527 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12528 12529 // So we treat the LHS as a ignored value, and in C++ we allow the 12530 // containing site to determine what should be done with the RHS. 12531 LHS = S.IgnoredValueConversions(LHS.get()); 12532 if (LHS.isInvalid()) 12533 return QualType(); 12534 12535 S.DiagnoseUnusedExprResult(LHS.get()); 12536 12537 if (!S.getLangOpts().CPlusPlus) { 12538 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12539 if (RHS.isInvalid()) 12540 return QualType(); 12541 if (!RHS.get()->getType()->isVoidType()) 12542 S.RequireCompleteType(Loc, RHS.get()->getType(), 12543 diag::err_incomplete_type); 12544 } 12545 12546 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12547 S.DiagnoseCommaOperator(LHS.get(), Loc); 12548 12549 return RHS.get()->getType(); 12550 } 12551 12552 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12553 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12554 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12555 ExprValueKind &VK, 12556 ExprObjectKind &OK, 12557 SourceLocation OpLoc, 12558 bool IsInc, bool IsPrefix) { 12559 if (Op->isTypeDependent()) 12560 return S.Context.DependentTy; 12561 12562 QualType ResType = Op->getType(); 12563 // Atomic types can be used for increment / decrement where the non-atomic 12564 // versions can, so ignore the _Atomic() specifier for the purpose of 12565 // checking. 12566 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12567 ResType = ResAtomicType->getValueType(); 12568 12569 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12570 12571 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12572 // Decrement of bool is not allowed. 12573 if (!IsInc) { 12574 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12575 return QualType(); 12576 } 12577 // Increment of bool sets it to true, but is deprecated. 12578 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12579 : diag::warn_increment_bool) 12580 << Op->getSourceRange(); 12581 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12582 // Error on enum increments and decrements in C++ mode 12583 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12584 return QualType(); 12585 } else if (ResType->isRealType()) { 12586 // OK! 12587 } else if (ResType->isPointerType()) { 12588 // C99 6.5.2.4p2, 6.5.6p2 12589 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12590 return QualType(); 12591 } else if (ResType->isObjCObjectPointerType()) { 12592 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12593 // Otherwise, we just need a complete type. 12594 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12595 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12596 return QualType(); 12597 } else if (ResType->isAnyComplexType()) { 12598 // C99 does not support ++/-- on complex types, we allow as an extension. 12599 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12600 << ResType << Op->getSourceRange(); 12601 } else if (ResType->isPlaceholderType()) { 12602 ExprResult PR = S.CheckPlaceholderExpr(Op); 12603 if (PR.isInvalid()) return QualType(); 12604 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12605 IsInc, IsPrefix); 12606 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12607 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12608 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12609 (ResType->castAs<VectorType>()->getVectorKind() != 12610 VectorType::AltiVecBool)) { 12611 // The z vector extensions allow ++ and -- for non-bool vectors. 12612 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12613 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12614 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12615 } else { 12616 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12617 << ResType << int(IsInc) << Op->getSourceRange(); 12618 return QualType(); 12619 } 12620 // At this point, we know we have a real, complex or pointer type. 12621 // Now make sure the operand is a modifiable lvalue. 12622 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12623 return QualType(); 12624 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12625 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12626 // An operand with volatile-qualified type is deprecated 12627 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12628 << IsInc << ResType; 12629 } 12630 // In C++, a prefix increment is the same type as the operand. Otherwise 12631 // (in C or with postfix), the increment is the unqualified type of the 12632 // operand. 12633 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12634 VK = VK_LValue; 12635 OK = Op->getObjectKind(); 12636 return ResType; 12637 } else { 12638 VK = VK_RValue; 12639 return ResType.getUnqualifiedType(); 12640 } 12641 } 12642 12643 12644 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12645 /// This routine allows us to typecheck complex/recursive expressions 12646 /// where the declaration is needed for type checking. We only need to 12647 /// handle cases when the expression references a function designator 12648 /// or is an lvalue. Here are some examples: 12649 /// - &(x) => x 12650 /// - &*****f => f for f a function designator. 12651 /// - &s.xx => s 12652 /// - &s.zz[1].yy -> s, if zz is an array 12653 /// - *(x + 1) -> x, if x is an array 12654 /// - &"123"[2] -> 0 12655 /// - & __real__ x -> x 12656 static ValueDecl *getPrimaryDecl(Expr *E) { 12657 switch (E->getStmtClass()) { 12658 case Stmt::DeclRefExprClass: 12659 return cast<DeclRefExpr>(E)->getDecl(); 12660 case Stmt::MemberExprClass: 12661 // If this is an arrow operator, the address is an offset from 12662 // the base's value, so the object the base refers to is 12663 // irrelevant. 12664 if (cast<MemberExpr>(E)->isArrow()) 12665 return nullptr; 12666 // Otherwise, the expression refers to a part of the base 12667 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12668 case Stmt::ArraySubscriptExprClass: { 12669 // FIXME: This code shouldn't be necessary! We should catch the implicit 12670 // promotion of register arrays earlier. 12671 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12672 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12673 if (ICE->getSubExpr()->getType()->isArrayType()) 12674 return getPrimaryDecl(ICE->getSubExpr()); 12675 } 12676 return nullptr; 12677 } 12678 case Stmt::UnaryOperatorClass: { 12679 UnaryOperator *UO = cast<UnaryOperator>(E); 12680 12681 switch(UO->getOpcode()) { 12682 case UO_Real: 12683 case UO_Imag: 12684 case UO_Extension: 12685 return getPrimaryDecl(UO->getSubExpr()); 12686 default: 12687 return nullptr; 12688 } 12689 } 12690 case Stmt::ParenExprClass: 12691 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12692 case Stmt::ImplicitCastExprClass: 12693 // If the result of an implicit cast is an l-value, we care about 12694 // the sub-expression; otherwise, the result here doesn't matter. 12695 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12696 default: 12697 return nullptr; 12698 } 12699 } 12700 12701 namespace { 12702 enum { 12703 AO_Bit_Field = 0, 12704 AO_Vector_Element = 1, 12705 AO_Property_Expansion = 2, 12706 AO_Register_Variable = 3, 12707 AO_No_Error = 4 12708 }; 12709 } 12710 /// Diagnose invalid operand for address of operations. 12711 /// 12712 /// \param Type The type of operand which cannot have its address taken. 12713 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12714 Expr *E, unsigned Type) { 12715 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12716 } 12717 12718 /// CheckAddressOfOperand - The operand of & must be either a function 12719 /// designator or an lvalue designating an object. If it is an lvalue, the 12720 /// object cannot be declared with storage class register or be a bit field. 12721 /// Note: The usual conversions are *not* applied to the operand of the & 12722 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12723 /// In C++, the operand might be an overloaded function name, in which case 12724 /// we allow the '&' but retain the overloaded-function type. 12725 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12726 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12727 if (PTy->getKind() == BuiltinType::Overload) { 12728 Expr *E = OrigOp.get()->IgnoreParens(); 12729 if (!isa<OverloadExpr>(E)) { 12730 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12731 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12732 << OrigOp.get()->getSourceRange(); 12733 return QualType(); 12734 } 12735 12736 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12737 if (isa<UnresolvedMemberExpr>(Ovl)) 12738 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12739 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12740 << OrigOp.get()->getSourceRange(); 12741 return QualType(); 12742 } 12743 12744 return Context.OverloadTy; 12745 } 12746 12747 if (PTy->getKind() == BuiltinType::UnknownAny) 12748 return Context.UnknownAnyTy; 12749 12750 if (PTy->getKind() == BuiltinType::BoundMember) { 12751 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12752 << OrigOp.get()->getSourceRange(); 12753 return QualType(); 12754 } 12755 12756 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12757 if (OrigOp.isInvalid()) return QualType(); 12758 } 12759 12760 if (OrigOp.get()->isTypeDependent()) 12761 return Context.DependentTy; 12762 12763 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12764 12765 // Make sure to ignore parentheses in subsequent checks 12766 Expr *op = OrigOp.get()->IgnoreParens(); 12767 12768 // In OpenCL captures for blocks called as lambda functions 12769 // are located in the private address space. Blocks used in 12770 // enqueue_kernel can be located in a different address space 12771 // depending on a vendor implementation. Thus preventing 12772 // taking an address of the capture to avoid invalid AS casts. 12773 if (LangOpts.OpenCL) { 12774 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12775 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12776 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12777 return QualType(); 12778 } 12779 } 12780 12781 if (getLangOpts().C99) { 12782 // Implement C99-only parts of addressof rules. 12783 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12784 if (uOp->getOpcode() == UO_Deref) 12785 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12786 // (assuming the deref expression is valid). 12787 return uOp->getSubExpr()->getType(); 12788 } 12789 // Technically, there should be a check for array subscript 12790 // expressions here, but the result of one is always an lvalue anyway. 12791 } 12792 ValueDecl *dcl = getPrimaryDecl(op); 12793 12794 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12795 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12796 op->getBeginLoc())) 12797 return QualType(); 12798 12799 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12800 unsigned AddressOfError = AO_No_Error; 12801 12802 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12803 bool sfinae = (bool)isSFINAEContext(); 12804 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12805 : diag::ext_typecheck_addrof_temporary) 12806 << op->getType() << op->getSourceRange(); 12807 if (sfinae) 12808 return QualType(); 12809 // Materialize the temporary as an lvalue so that we can take its address. 12810 OrigOp = op = 12811 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12812 } else if (isa<ObjCSelectorExpr>(op)) { 12813 return Context.getPointerType(op->getType()); 12814 } else if (lval == Expr::LV_MemberFunction) { 12815 // If it's an instance method, make a member pointer. 12816 // The expression must have exactly the form &A::foo. 12817 12818 // If the underlying expression isn't a decl ref, give up. 12819 if (!isa<DeclRefExpr>(op)) { 12820 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12821 << OrigOp.get()->getSourceRange(); 12822 return QualType(); 12823 } 12824 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12825 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12826 12827 // The id-expression was parenthesized. 12828 if (OrigOp.get() != DRE) { 12829 Diag(OpLoc, diag::err_parens_pointer_member_function) 12830 << OrigOp.get()->getSourceRange(); 12831 12832 // The method was named without a qualifier. 12833 } else if (!DRE->getQualifier()) { 12834 if (MD->getParent()->getName().empty()) 12835 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12836 << op->getSourceRange(); 12837 else { 12838 SmallString<32> Str; 12839 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12840 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12841 << op->getSourceRange() 12842 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12843 } 12844 } 12845 12846 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12847 if (isa<CXXDestructorDecl>(MD)) 12848 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12849 12850 QualType MPTy = Context.getMemberPointerType( 12851 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12852 // Under the MS ABI, lock down the inheritance model now. 12853 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12854 (void)isCompleteType(OpLoc, MPTy); 12855 return MPTy; 12856 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12857 // C99 6.5.3.2p1 12858 // The operand must be either an l-value or a function designator 12859 if (!op->getType()->isFunctionType()) { 12860 // Use a special diagnostic for loads from property references. 12861 if (isa<PseudoObjectExpr>(op)) { 12862 AddressOfError = AO_Property_Expansion; 12863 } else { 12864 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12865 << op->getType() << op->getSourceRange(); 12866 return QualType(); 12867 } 12868 } 12869 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12870 // The operand cannot be a bit-field 12871 AddressOfError = AO_Bit_Field; 12872 } else if (op->getObjectKind() == OK_VectorComponent) { 12873 // The operand cannot be an element of a vector 12874 AddressOfError = AO_Vector_Element; 12875 } else if (dcl) { // C99 6.5.3.2p1 12876 // We have an lvalue with a decl. Make sure the decl is not declared 12877 // with the register storage-class specifier. 12878 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12879 // in C++ it is not error to take address of a register 12880 // variable (c++03 7.1.1P3) 12881 if (vd->getStorageClass() == SC_Register && 12882 !getLangOpts().CPlusPlus) { 12883 AddressOfError = AO_Register_Variable; 12884 } 12885 } else if (isa<MSPropertyDecl>(dcl)) { 12886 AddressOfError = AO_Property_Expansion; 12887 } else if (isa<FunctionTemplateDecl>(dcl)) { 12888 return Context.OverloadTy; 12889 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12890 // Okay: we can take the address of a field. 12891 // Could be a pointer to member, though, if there is an explicit 12892 // scope qualifier for the class. 12893 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12894 DeclContext *Ctx = dcl->getDeclContext(); 12895 if (Ctx && Ctx->isRecord()) { 12896 if (dcl->getType()->isReferenceType()) { 12897 Diag(OpLoc, 12898 diag::err_cannot_form_pointer_to_member_of_reference_type) 12899 << dcl->getDeclName() << dcl->getType(); 12900 return QualType(); 12901 } 12902 12903 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12904 Ctx = Ctx->getParent(); 12905 12906 QualType MPTy = Context.getMemberPointerType( 12907 op->getType(), 12908 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12909 // Under the MS ABI, lock down the inheritance model now. 12910 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12911 (void)isCompleteType(OpLoc, MPTy); 12912 return MPTy; 12913 } 12914 } 12915 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12916 !isa<BindingDecl>(dcl)) 12917 llvm_unreachable("Unknown/unexpected decl type"); 12918 } 12919 12920 if (AddressOfError != AO_No_Error) { 12921 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12922 return QualType(); 12923 } 12924 12925 if (lval == Expr::LV_IncompleteVoidType) { 12926 // Taking the address of a void variable is technically illegal, but we 12927 // allow it in cases which are otherwise valid. 12928 // Example: "extern void x; void* y = &x;". 12929 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12930 } 12931 12932 // If the operand has type "type", the result has type "pointer to type". 12933 if (op->getType()->isObjCObjectType()) 12934 return Context.getObjCObjectPointerType(op->getType()); 12935 12936 CheckAddressOfPackedMember(op); 12937 12938 return Context.getPointerType(op->getType()); 12939 } 12940 12941 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12942 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12943 if (!DRE) 12944 return; 12945 const Decl *D = DRE->getDecl(); 12946 if (!D) 12947 return; 12948 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12949 if (!Param) 12950 return; 12951 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12952 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12953 return; 12954 if (FunctionScopeInfo *FD = S.getCurFunction()) 12955 if (!FD->ModifiedNonNullParams.count(Param)) 12956 FD->ModifiedNonNullParams.insert(Param); 12957 } 12958 12959 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12960 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12961 SourceLocation OpLoc) { 12962 if (Op->isTypeDependent()) 12963 return S.Context.DependentTy; 12964 12965 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12966 if (ConvResult.isInvalid()) 12967 return QualType(); 12968 Op = ConvResult.get(); 12969 QualType OpTy = Op->getType(); 12970 QualType Result; 12971 12972 if (isa<CXXReinterpretCastExpr>(Op)) { 12973 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12974 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12975 Op->getSourceRange()); 12976 } 12977 12978 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12979 { 12980 Result = PT->getPointeeType(); 12981 } 12982 else if (const ObjCObjectPointerType *OPT = 12983 OpTy->getAs<ObjCObjectPointerType>()) 12984 Result = OPT->getPointeeType(); 12985 else { 12986 ExprResult PR = S.CheckPlaceholderExpr(Op); 12987 if (PR.isInvalid()) return QualType(); 12988 if (PR.get() != Op) 12989 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12990 } 12991 12992 if (Result.isNull()) { 12993 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12994 << OpTy << Op->getSourceRange(); 12995 return QualType(); 12996 } 12997 12998 // Note that per both C89 and C99, indirection is always legal, even if Result 12999 // is an incomplete type or void. It would be possible to warn about 13000 // dereferencing a void pointer, but it's completely well-defined, and such a 13001 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13002 // for pointers to 'void' but is fine for any other pointer type: 13003 // 13004 // C++ [expr.unary.op]p1: 13005 // [...] the expression to which [the unary * operator] is applied shall 13006 // be a pointer to an object type, or a pointer to a function type 13007 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13008 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13009 << OpTy << Op->getSourceRange(); 13010 13011 // Dereferences are usually l-values... 13012 VK = VK_LValue; 13013 13014 // ...except that certain expressions are never l-values in C. 13015 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13016 VK = VK_RValue; 13017 13018 return Result; 13019 } 13020 13021 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13022 BinaryOperatorKind Opc; 13023 switch (Kind) { 13024 default: llvm_unreachable("Unknown binop!"); 13025 case tok::periodstar: Opc = BO_PtrMemD; break; 13026 case tok::arrowstar: Opc = BO_PtrMemI; break; 13027 case tok::star: Opc = BO_Mul; break; 13028 case tok::slash: Opc = BO_Div; break; 13029 case tok::percent: Opc = BO_Rem; break; 13030 case tok::plus: Opc = BO_Add; break; 13031 case tok::minus: Opc = BO_Sub; break; 13032 case tok::lessless: Opc = BO_Shl; break; 13033 case tok::greatergreater: Opc = BO_Shr; break; 13034 case tok::lessequal: Opc = BO_LE; break; 13035 case tok::less: Opc = BO_LT; break; 13036 case tok::greaterequal: Opc = BO_GE; break; 13037 case tok::greater: Opc = BO_GT; break; 13038 case tok::exclaimequal: Opc = BO_NE; break; 13039 case tok::equalequal: Opc = BO_EQ; break; 13040 case tok::spaceship: Opc = BO_Cmp; break; 13041 case tok::amp: Opc = BO_And; break; 13042 case tok::caret: Opc = BO_Xor; break; 13043 case tok::pipe: Opc = BO_Or; break; 13044 case tok::ampamp: Opc = BO_LAnd; break; 13045 case tok::pipepipe: Opc = BO_LOr; break; 13046 case tok::equal: Opc = BO_Assign; break; 13047 case tok::starequal: Opc = BO_MulAssign; break; 13048 case tok::slashequal: Opc = BO_DivAssign; break; 13049 case tok::percentequal: Opc = BO_RemAssign; break; 13050 case tok::plusequal: Opc = BO_AddAssign; break; 13051 case tok::minusequal: Opc = BO_SubAssign; break; 13052 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13053 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13054 case tok::ampequal: Opc = BO_AndAssign; break; 13055 case tok::caretequal: Opc = BO_XorAssign; break; 13056 case tok::pipeequal: Opc = BO_OrAssign; break; 13057 case tok::comma: Opc = BO_Comma; break; 13058 } 13059 return Opc; 13060 } 13061 13062 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13063 tok::TokenKind Kind) { 13064 UnaryOperatorKind Opc; 13065 switch (Kind) { 13066 default: llvm_unreachable("Unknown unary op!"); 13067 case tok::plusplus: Opc = UO_PreInc; break; 13068 case tok::minusminus: Opc = UO_PreDec; break; 13069 case tok::amp: Opc = UO_AddrOf; break; 13070 case tok::star: Opc = UO_Deref; break; 13071 case tok::plus: Opc = UO_Plus; break; 13072 case tok::minus: Opc = UO_Minus; break; 13073 case tok::tilde: Opc = UO_Not; break; 13074 case tok::exclaim: Opc = UO_LNot; break; 13075 case tok::kw___real: Opc = UO_Real; break; 13076 case tok::kw___imag: Opc = UO_Imag; break; 13077 case tok::kw___extension__: Opc = UO_Extension; break; 13078 } 13079 return Opc; 13080 } 13081 13082 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13083 /// This warning suppressed in the event of macro expansions. 13084 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13085 SourceLocation OpLoc, bool IsBuiltin) { 13086 if (S.inTemplateInstantiation()) 13087 return; 13088 if (S.isUnevaluatedContext()) 13089 return; 13090 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13091 return; 13092 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13093 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13094 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13095 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13096 if (!LHSDeclRef || !RHSDeclRef || 13097 LHSDeclRef->getLocation().isMacroID() || 13098 RHSDeclRef->getLocation().isMacroID()) 13099 return; 13100 const ValueDecl *LHSDecl = 13101 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13102 const ValueDecl *RHSDecl = 13103 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13104 if (LHSDecl != RHSDecl) 13105 return; 13106 if (LHSDecl->getType().isVolatileQualified()) 13107 return; 13108 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13109 if (RefTy->getPointeeType().isVolatileQualified()) 13110 return; 13111 13112 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13113 : diag::warn_self_assignment_overloaded) 13114 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13115 << RHSExpr->getSourceRange(); 13116 } 13117 13118 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13119 /// is usually indicative of introspection within the Objective-C pointer. 13120 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13121 SourceLocation OpLoc) { 13122 if (!S.getLangOpts().ObjC) 13123 return; 13124 13125 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13126 const Expr *LHS = L.get(); 13127 const Expr *RHS = R.get(); 13128 13129 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13130 ObjCPointerExpr = LHS; 13131 OtherExpr = RHS; 13132 } 13133 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13134 ObjCPointerExpr = RHS; 13135 OtherExpr = LHS; 13136 } 13137 13138 // This warning is deliberately made very specific to reduce false 13139 // positives with logic that uses '&' for hashing. This logic mainly 13140 // looks for code trying to introspect into tagged pointers, which 13141 // code should generally never do. 13142 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13143 unsigned Diag = diag::warn_objc_pointer_masking; 13144 // Determine if we are introspecting the result of performSelectorXXX. 13145 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13146 // Special case messages to -performSelector and friends, which 13147 // can return non-pointer values boxed in a pointer value. 13148 // Some clients may wish to silence warnings in this subcase. 13149 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13150 Selector S = ME->getSelector(); 13151 StringRef SelArg0 = S.getNameForSlot(0); 13152 if (SelArg0.startswith("performSelector")) 13153 Diag = diag::warn_objc_pointer_masking_performSelector; 13154 } 13155 13156 S.Diag(OpLoc, Diag) 13157 << ObjCPointerExpr->getSourceRange(); 13158 } 13159 } 13160 13161 static NamedDecl *getDeclFromExpr(Expr *E) { 13162 if (!E) 13163 return nullptr; 13164 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13165 return DRE->getDecl(); 13166 if (auto *ME = dyn_cast<MemberExpr>(E)) 13167 return ME->getMemberDecl(); 13168 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13169 return IRE->getDecl(); 13170 return nullptr; 13171 } 13172 13173 // This helper function promotes a binary operator's operands (which are of a 13174 // half vector type) to a vector of floats and then truncates the result to 13175 // a vector of either half or short. 13176 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13177 BinaryOperatorKind Opc, QualType ResultTy, 13178 ExprValueKind VK, ExprObjectKind OK, 13179 bool IsCompAssign, SourceLocation OpLoc, 13180 FPOptions FPFeatures) { 13181 auto &Context = S.getASTContext(); 13182 assert((isVector(ResultTy, Context.HalfTy) || 13183 isVector(ResultTy, Context.ShortTy)) && 13184 "Result must be a vector of half or short"); 13185 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13186 isVector(RHS.get()->getType(), Context.HalfTy) && 13187 "both operands expected to be a half vector"); 13188 13189 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13190 QualType BinOpResTy = RHS.get()->getType(); 13191 13192 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13193 // change BinOpResTy to a vector of ints. 13194 if (isVector(ResultTy, Context.ShortTy)) 13195 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13196 13197 if (IsCompAssign) 13198 return new (Context) CompoundAssignOperator( 13199 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 13200 OpLoc, FPFeatures); 13201 13202 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13203 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 13204 VK, OK, OpLoc, FPFeatures); 13205 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13206 } 13207 13208 static std::pair<ExprResult, ExprResult> 13209 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13210 Expr *RHSExpr) { 13211 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13212 if (!S.getLangOpts().CPlusPlus) { 13213 // C cannot handle TypoExpr nodes on either side of a binop because it 13214 // doesn't handle dependent types properly, so make sure any TypoExprs have 13215 // been dealt with before checking the operands. 13216 LHS = S.CorrectDelayedTyposInExpr(LHS); 13217 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 13218 if (Opc != BO_Assign) 13219 return ExprResult(E); 13220 // Avoid correcting the RHS to the same Expr as the LHS. 13221 Decl *D = getDeclFromExpr(E); 13222 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13223 }); 13224 } 13225 return std::make_pair(LHS, RHS); 13226 } 13227 13228 /// Returns true if conversion between vectors of halfs and vectors of floats 13229 /// is needed. 13230 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13231 Expr *E0, Expr *E1 = nullptr) { 13232 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13233 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13234 return false; 13235 13236 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13237 QualType Ty = E->IgnoreImplicit()->getType(); 13238 13239 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13240 // to vectors of floats. Although the element type of the vectors is __fp16, 13241 // the vectors shouldn't be treated as storage-only types. See the 13242 // discussion here: https://reviews.llvm.org/rG825235c140e7 13243 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13244 if (VT->getVectorKind() == VectorType::NeonVector) 13245 return false; 13246 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13247 } 13248 return false; 13249 }; 13250 13251 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13252 } 13253 13254 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13255 /// operator @p Opc at location @c TokLoc. This routine only supports 13256 /// built-in operations; ActOnBinOp handles overloaded operators. 13257 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13258 BinaryOperatorKind Opc, 13259 Expr *LHSExpr, Expr *RHSExpr) { 13260 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13261 // The syntax only allows initializer lists on the RHS of assignment, 13262 // so we don't need to worry about accepting invalid code for 13263 // non-assignment operators. 13264 // C++11 5.17p9: 13265 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13266 // of x = {} is x = T(). 13267 InitializationKind Kind = InitializationKind::CreateDirectList( 13268 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13269 InitializedEntity Entity = 13270 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13271 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13272 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13273 if (Init.isInvalid()) 13274 return Init; 13275 RHSExpr = Init.get(); 13276 } 13277 13278 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13279 QualType ResultTy; // Result type of the binary operator. 13280 // The following two variables are used for compound assignment operators 13281 QualType CompLHSTy; // Type of LHS after promotions for computation 13282 QualType CompResultTy; // Type of computation result 13283 ExprValueKind VK = VK_RValue; 13284 ExprObjectKind OK = OK_Ordinary; 13285 bool ConvertHalfVec = false; 13286 13287 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13288 if (!LHS.isUsable() || !RHS.isUsable()) 13289 return ExprError(); 13290 13291 if (getLangOpts().OpenCL) { 13292 QualType LHSTy = LHSExpr->getType(); 13293 QualType RHSTy = RHSExpr->getType(); 13294 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13295 // the ATOMIC_VAR_INIT macro. 13296 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13297 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13298 if (BO_Assign == Opc) 13299 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13300 else 13301 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13302 return ExprError(); 13303 } 13304 13305 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13306 // only with a builtin functions and therefore should be disallowed here. 13307 if (LHSTy->isImageType() || RHSTy->isImageType() || 13308 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13309 LHSTy->isPipeType() || RHSTy->isPipeType() || 13310 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13311 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13312 return ExprError(); 13313 } 13314 } 13315 13316 // Diagnose operations on the unsupported types for OpenMP device compilation. 13317 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13318 if (Opc != BO_Assign && Opc != BO_Comma) { 13319 checkOpenMPDeviceExpr(LHSExpr); 13320 checkOpenMPDeviceExpr(RHSExpr); 13321 } 13322 } 13323 13324 switch (Opc) { 13325 case BO_Assign: 13326 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13327 if (getLangOpts().CPlusPlus && 13328 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13329 VK = LHS.get()->getValueKind(); 13330 OK = LHS.get()->getObjectKind(); 13331 } 13332 if (!ResultTy.isNull()) { 13333 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13334 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13335 13336 // Avoid copying a block to the heap if the block is assigned to a local 13337 // auto variable that is declared in the same scope as the block. This 13338 // optimization is unsafe if the local variable is declared in an outer 13339 // scope. For example: 13340 // 13341 // BlockTy b; 13342 // { 13343 // b = ^{...}; 13344 // } 13345 // // It is unsafe to invoke the block here if it wasn't copied to the 13346 // // heap. 13347 // b(); 13348 13349 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13350 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13351 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13352 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13353 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13354 13355 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13356 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13357 NTCUC_Assignment, NTCUK_Copy); 13358 } 13359 RecordModifiableNonNullParam(*this, LHS.get()); 13360 break; 13361 case BO_PtrMemD: 13362 case BO_PtrMemI: 13363 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13364 Opc == BO_PtrMemI); 13365 break; 13366 case BO_Mul: 13367 case BO_Div: 13368 ConvertHalfVec = true; 13369 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13370 Opc == BO_Div); 13371 break; 13372 case BO_Rem: 13373 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13374 break; 13375 case BO_Add: 13376 ConvertHalfVec = true; 13377 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13378 break; 13379 case BO_Sub: 13380 ConvertHalfVec = true; 13381 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13382 break; 13383 case BO_Shl: 13384 case BO_Shr: 13385 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13386 break; 13387 case BO_LE: 13388 case BO_LT: 13389 case BO_GE: 13390 case BO_GT: 13391 ConvertHalfVec = true; 13392 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13393 break; 13394 case BO_EQ: 13395 case BO_NE: 13396 ConvertHalfVec = true; 13397 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13398 break; 13399 case BO_Cmp: 13400 ConvertHalfVec = true; 13401 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13402 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13403 break; 13404 case BO_And: 13405 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13406 LLVM_FALLTHROUGH; 13407 case BO_Xor: 13408 case BO_Or: 13409 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13410 break; 13411 case BO_LAnd: 13412 case BO_LOr: 13413 ConvertHalfVec = true; 13414 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13415 break; 13416 case BO_MulAssign: 13417 case BO_DivAssign: 13418 ConvertHalfVec = true; 13419 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13420 Opc == BO_DivAssign); 13421 CompLHSTy = CompResultTy; 13422 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13423 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13424 break; 13425 case BO_RemAssign: 13426 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13427 CompLHSTy = CompResultTy; 13428 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13429 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13430 break; 13431 case BO_AddAssign: 13432 ConvertHalfVec = true; 13433 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13434 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13435 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13436 break; 13437 case BO_SubAssign: 13438 ConvertHalfVec = true; 13439 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13440 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13441 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13442 break; 13443 case BO_ShlAssign: 13444 case BO_ShrAssign: 13445 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13446 CompLHSTy = CompResultTy; 13447 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13448 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13449 break; 13450 case BO_AndAssign: 13451 case BO_OrAssign: // fallthrough 13452 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13453 LLVM_FALLTHROUGH; 13454 case BO_XorAssign: 13455 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13456 CompLHSTy = CompResultTy; 13457 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13458 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13459 break; 13460 case BO_Comma: 13461 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13462 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13463 VK = RHS.get()->getValueKind(); 13464 OK = RHS.get()->getObjectKind(); 13465 } 13466 break; 13467 } 13468 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13469 return ExprError(); 13470 13471 if (ResultTy->isRealFloatingType() && 13472 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13473 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13474 // Mark the current function as usng floating point constrained intrinsics 13475 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13476 F->setUsesFPIntrin(true); 13477 } 13478 13479 // Some of the binary operations require promoting operands of half vector to 13480 // float vectors and truncating the result back to half vector. For now, we do 13481 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13482 // arm64). 13483 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13484 isVector(LHS.get()->getType(), Context.HalfTy) && 13485 "both sides are half vectors or neither sides are"); 13486 ConvertHalfVec = 13487 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13488 13489 // Check for array bounds violations for both sides of the BinaryOperator 13490 CheckArrayAccess(LHS.get()); 13491 CheckArrayAccess(RHS.get()); 13492 13493 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13494 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13495 &Context.Idents.get("object_setClass"), 13496 SourceLocation(), LookupOrdinaryName); 13497 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13498 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13499 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13500 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13501 "object_setClass(") 13502 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13503 ",") 13504 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13505 } 13506 else 13507 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13508 } 13509 else if (const ObjCIvarRefExpr *OIRE = 13510 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13511 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13512 13513 // Opc is not a compound assignment if CompResultTy is null. 13514 if (CompResultTy.isNull()) { 13515 if (ConvertHalfVec) 13516 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13517 OpLoc, FPFeatures); 13518 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13519 OK, OpLoc, FPFeatures); 13520 } 13521 13522 // Handle compound assignments. 13523 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13524 OK_ObjCProperty) { 13525 VK = VK_LValue; 13526 OK = LHS.get()->getObjectKind(); 13527 } 13528 13529 if (ConvertHalfVec) 13530 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13531 OpLoc, FPFeatures); 13532 13533 return new (Context) CompoundAssignOperator( 13534 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13535 OpLoc, FPFeatures); 13536 } 13537 13538 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13539 /// operators are mixed in a way that suggests that the programmer forgot that 13540 /// comparison operators have higher precedence. The most typical example of 13541 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13542 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13543 SourceLocation OpLoc, Expr *LHSExpr, 13544 Expr *RHSExpr) { 13545 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13546 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13547 13548 // Check that one of the sides is a comparison operator and the other isn't. 13549 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13550 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13551 if (isLeftComp == isRightComp) 13552 return; 13553 13554 // Bitwise operations are sometimes used as eager logical ops. 13555 // Don't diagnose this. 13556 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13557 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13558 if (isLeftBitwise || isRightBitwise) 13559 return; 13560 13561 SourceRange DiagRange = isLeftComp 13562 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13563 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13564 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13565 SourceRange ParensRange = 13566 isLeftComp 13567 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13568 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13569 13570 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13571 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13572 SuggestParentheses(Self, OpLoc, 13573 Self.PDiag(diag::note_precedence_silence) << OpStr, 13574 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13575 SuggestParentheses(Self, OpLoc, 13576 Self.PDiag(diag::note_precedence_bitwise_first) 13577 << BinaryOperator::getOpcodeStr(Opc), 13578 ParensRange); 13579 } 13580 13581 /// It accepts a '&&' expr that is inside a '||' one. 13582 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13583 /// in parentheses. 13584 static void 13585 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13586 BinaryOperator *Bop) { 13587 assert(Bop->getOpcode() == BO_LAnd); 13588 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13589 << Bop->getSourceRange() << OpLoc; 13590 SuggestParentheses(Self, Bop->getOperatorLoc(), 13591 Self.PDiag(diag::note_precedence_silence) 13592 << Bop->getOpcodeStr(), 13593 Bop->getSourceRange()); 13594 } 13595 13596 /// Returns true if the given expression can be evaluated as a constant 13597 /// 'true'. 13598 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13599 bool Res; 13600 return !E->isValueDependent() && 13601 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13602 } 13603 13604 /// Returns true if the given expression can be evaluated as a constant 13605 /// 'false'. 13606 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13607 bool Res; 13608 return !E->isValueDependent() && 13609 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13610 } 13611 13612 /// Look for '&&' in the left hand of a '||' expr. 13613 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13614 Expr *LHSExpr, Expr *RHSExpr) { 13615 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13616 if (Bop->getOpcode() == BO_LAnd) { 13617 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13618 if (EvaluatesAsFalse(S, RHSExpr)) 13619 return; 13620 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13621 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13622 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13623 } else if (Bop->getOpcode() == BO_LOr) { 13624 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13625 // If it's "a || b && 1 || c" we didn't warn earlier for 13626 // "a || b && 1", but warn now. 13627 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13628 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13629 } 13630 } 13631 } 13632 } 13633 13634 /// Look for '&&' in the right hand of a '||' expr. 13635 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13636 Expr *LHSExpr, Expr *RHSExpr) { 13637 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13638 if (Bop->getOpcode() == BO_LAnd) { 13639 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13640 if (EvaluatesAsFalse(S, LHSExpr)) 13641 return; 13642 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13643 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13644 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13645 } 13646 } 13647 } 13648 13649 /// Look for bitwise op in the left or right hand of a bitwise op with 13650 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13651 /// the '&' expression in parentheses. 13652 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13653 SourceLocation OpLoc, Expr *SubExpr) { 13654 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13655 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13656 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13657 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13658 << Bop->getSourceRange() << OpLoc; 13659 SuggestParentheses(S, Bop->getOperatorLoc(), 13660 S.PDiag(diag::note_precedence_silence) 13661 << Bop->getOpcodeStr(), 13662 Bop->getSourceRange()); 13663 } 13664 } 13665 } 13666 13667 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13668 Expr *SubExpr, StringRef Shift) { 13669 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13670 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13671 StringRef Op = Bop->getOpcodeStr(); 13672 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13673 << Bop->getSourceRange() << OpLoc << Shift << Op; 13674 SuggestParentheses(S, Bop->getOperatorLoc(), 13675 S.PDiag(diag::note_precedence_silence) << Op, 13676 Bop->getSourceRange()); 13677 } 13678 } 13679 } 13680 13681 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13682 Expr *LHSExpr, Expr *RHSExpr) { 13683 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13684 if (!OCE) 13685 return; 13686 13687 FunctionDecl *FD = OCE->getDirectCallee(); 13688 if (!FD || !FD->isOverloadedOperator()) 13689 return; 13690 13691 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13692 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13693 return; 13694 13695 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13696 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13697 << (Kind == OO_LessLess); 13698 SuggestParentheses(S, OCE->getOperatorLoc(), 13699 S.PDiag(diag::note_precedence_silence) 13700 << (Kind == OO_LessLess ? "<<" : ">>"), 13701 OCE->getSourceRange()); 13702 SuggestParentheses( 13703 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13704 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13705 } 13706 13707 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13708 /// precedence. 13709 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13710 SourceLocation OpLoc, Expr *LHSExpr, 13711 Expr *RHSExpr){ 13712 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13713 if (BinaryOperator::isBitwiseOp(Opc)) 13714 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13715 13716 // Diagnose "arg1 & arg2 | arg3" 13717 if ((Opc == BO_Or || Opc == BO_Xor) && 13718 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13719 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13720 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13721 } 13722 13723 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13724 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13725 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13726 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13727 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13728 } 13729 13730 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13731 || Opc == BO_Shr) { 13732 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13733 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13734 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13735 } 13736 13737 // Warn on overloaded shift operators and comparisons, such as: 13738 // cout << 5 == 4; 13739 if (BinaryOperator::isComparisonOp(Opc)) 13740 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13741 } 13742 13743 // Binary Operators. 'Tok' is the token for the operator. 13744 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13745 tok::TokenKind Kind, 13746 Expr *LHSExpr, Expr *RHSExpr) { 13747 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13748 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13749 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13750 13751 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13752 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13753 13754 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13755 } 13756 13757 /// Build an overloaded binary operator expression in the given scope. 13758 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13759 BinaryOperatorKind Opc, 13760 Expr *LHS, Expr *RHS) { 13761 switch (Opc) { 13762 case BO_Assign: 13763 case BO_DivAssign: 13764 case BO_RemAssign: 13765 case BO_SubAssign: 13766 case BO_AndAssign: 13767 case BO_OrAssign: 13768 case BO_XorAssign: 13769 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13770 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13771 break; 13772 default: 13773 break; 13774 } 13775 13776 // Find all of the overloaded operators visible from this 13777 // point. We perform both an operator-name lookup from the local 13778 // scope and an argument-dependent lookup based on the types of 13779 // the arguments. 13780 UnresolvedSet<16> Functions; 13781 OverloadedOperatorKind OverOp 13782 = BinaryOperator::getOverloadedOperator(Opc); 13783 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13784 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13785 RHS->getType(), Functions); 13786 13787 // In C++20 onwards, we may have a second operator to look up. 13788 if (S.getLangOpts().CPlusPlus2a) { 13789 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13790 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13791 RHS->getType(), Functions); 13792 } 13793 13794 // Build the (potentially-overloaded, potentially-dependent) 13795 // binary operation. 13796 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13797 } 13798 13799 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13800 BinaryOperatorKind Opc, 13801 Expr *LHSExpr, Expr *RHSExpr) { 13802 ExprResult LHS, RHS; 13803 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13804 if (!LHS.isUsable() || !RHS.isUsable()) 13805 return ExprError(); 13806 LHSExpr = LHS.get(); 13807 RHSExpr = RHS.get(); 13808 13809 // We want to end up calling one of checkPseudoObjectAssignment 13810 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13811 // both expressions are overloadable or either is type-dependent), 13812 // or CreateBuiltinBinOp (in any other case). We also want to get 13813 // any placeholder types out of the way. 13814 13815 // Handle pseudo-objects in the LHS. 13816 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13817 // Assignments with a pseudo-object l-value need special analysis. 13818 if (pty->getKind() == BuiltinType::PseudoObject && 13819 BinaryOperator::isAssignmentOp(Opc)) 13820 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13821 13822 // Don't resolve overloads if the other type is overloadable. 13823 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13824 // We can't actually test that if we still have a placeholder, 13825 // though. Fortunately, none of the exceptions we see in that 13826 // code below are valid when the LHS is an overload set. Note 13827 // that an overload set can be dependently-typed, but it never 13828 // instantiates to having an overloadable type. 13829 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13830 if (resolvedRHS.isInvalid()) return ExprError(); 13831 RHSExpr = resolvedRHS.get(); 13832 13833 if (RHSExpr->isTypeDependent() || 13834 RHSExpr->getType()->isOverloadableType()) 13835 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13836 } 13837 13838 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13839 // template, diagnose the missing 'template' keyword instead of diagnosing 13840 // an invalid use of a bound member function. 13841 // 13842 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13843 // to C++1z [over.over]/1.4, but we already checked for that case above. 13844 if (Opc == BO_LT && inTemplateInstantiation() && 13845 (pty->getKind() == BuiltinType::BoundMember || 13846 pty->getKind() == BuiltinType::Overload)) { 13847 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13848 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13849 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13850 return isa<FunctionTemplateDecl>(ND); 13851 })) { 13852 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13853 : OE->getNameLoc(), 13854 diag::err_template_kw_missing) 13855 << OE->getName().getAsString() << ""; 13856 return ExprError(); 13857 } 13858 } 13859 13860 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13861 if (LHS.isInvalid()) return ExprError(); 13862 LHSExpr = LHS.get(); 13863 } 13864 13865 // Handle pseudo-objects in the RHS. 13866 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13867 // An overload in the RHS can potentially be resolved by the type 13868 // being assigned to. 13869 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13870 if (getLangOpts().CPlusPlus && 13871 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13872 LHSExpr->getType()->isOverloadableType())) 13873 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13874 13875 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13876 } 13877 13878 // Don't resolve overloads if the other type is overloadable. 13879 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13880 LHSExpr->getType()->isOverloadableType()) 13881 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13882 13883 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13884 if (!resolvedRHS.isUsable()) return ExprError(); 13885 RHSExpr = resolvedRHS.get(); 13886 } 13887 13888 if (getLangOpts().CPlusPlus) { 13889 // If either expression is type-dependent, always build an 13890 // overloaded op. 13891 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13892 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13893 13894 // Otherwise, build an overloaded op if either expression has an 13895 // overloadable type. 13896 if (LHSExpr->getType()->isOverloadableType() || 13897 RHSExpr->getType()->isOverloadableType()) 13898 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13899 } 13900 13901 // Build a built-in binary operation. 13902 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13903 } 13904 13905 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13906 if (T.isNull() || T->isDependentType()) 13907 return false; 13908 13909 if (!T->isPromotableIntegerType()) 13910 return true; 13911 13912 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13913 } 13914 13915 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13916 UnaryOperatorKind Opc, 13917 Expr *InputExpr) { 13918 ExprResult Input = InputExpr; 13919 ExprValueKind VK = VK_RValue; 13920 ExprObjectKind OK = OK_Ordinary; 13921 QualType resultType; 13922 bool CanOverflow = false; 13923 13924 bool ConvertHalfVec = false; 13925 if (getLangOpts().OpenCL) { 13926 QualType Ty = InputExpr->getType(); 13927 // The only legal unary operation for atomics is '&'. 13928 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13929 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13930 // only with a builtin functions and therefore should be disallowed here. 13931 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13932 || Ty->isBlockPointerType())) { 13933 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13934 << InputExpr->getType() 13935 << Input.get()->getSourceRange()); 13936 } 13937 } 13938 // Diagnose operations on the unsupported types for OpenMP device compilation. 13939 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13940 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13941 UnaryOperator::isArithmeticOp(Opc)) 13942 checkOpenMPDeviceExpr(InputExpr); 13943 } 13944 13945 switch (Opc) { 13946 case UO_PreInc: 13947 case UO_PreDec: 13948 case UO_PostInc: 13949 case UO_PostDec: 13950 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13951 OpLoc, 13952 Opc == UO_PreInc || 13953 Opc == UO_PostInc, 13954 Opc == UO_PreInc || 13955 Opc == UO_PreDec); 13956 CanOverflow = isOverflowingIntegerType(Context, resultType); 13957 break; 13958 case UO_AddrOf: 13959 resultType = CheckAddressOfOperand(Input, OpLoc); 13960 CheckAddressOfNoDeref(InputExpr); 13961 RecordModifiableNonNullParam(*this, InputExpr); 13962 break; 13963 case UO_Deref: { 13964 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13965 if (Input.isInvalid()) return ExprError(); 13966 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13967 break; 13968 } 13969 case UO_Plus: 13970 case UO_Minus: 13971 CanOverflow = Opc == UO_Minus && 13972 isOverflowingIntegerType(Context, Input.get()->getType()); 13973 Input = UsualUnaryConversions(Input.get()); 13974 if (Input.isInvalid()) return ExprError(); 13975 // Unary plus and minus require promoting an operand of half vector to a 13976 // float vector and truncating the result back to a half vector. For now, we 13977 // do this only when HalfArgsAndReturns is set (that is, when the target is 13978 // arm or arm64). 13979 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 13980 13981 // If the operand is a half vector, promote it to a float vector. 13982 if (ConvertHalfVec) 13983 Input = convertVector(Input.get(), Context.FloatTy, *this); 13984 resultType = Input.get()->getType(); 13985 if (resultType->isDependentType()) 13986 break; 13987 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13988 break; 13989 else if (resultType->isVectorType() && 13990 // The z vector extensions don't allow + or - with bool vectors. 13991 (!Context.getLangOpts().ZVector || 13992 resultType->castAs<VectorType>()->getVectorKind() != 13993 VectorType::AltiVecBool)) 13994 break; 13995 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13996 Opc == UO_Plus && 13997 resultType->isPointerType()) 13998 break; 13999 14000 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14001 << resultType << Input.get()->getSourceRange()); 14002 14003 case UO_Not: // bitwise complement 14004 Input = UsualUnaryConversions(Input.get()); 14005 if (Input.isInvalid()) 14006 return ExprError(); 14007 resultType = Input.get()->getType(); 14008 if (resultType->isDependentType()) 14009 break; 14010 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14011 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14012 // C99 does not support '~' for complex conjugation. 14013 Diag(OpLoc, diag::ext_integer_complement_complex) 14014 << resultType << Input.get()->getSourceRange(); 14015 else if (resultType->hasIntegerRepresentation()) 14016 break; 14017 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14018 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14019 // on vector float types. 14020 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14021 if (!T->isIntegerType()) 14022 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14023 << resultType << Input.get()->getSourceRange()); 14024 } else { 14025 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14026 << resultType << Input.get()->getSourceRange()); 14027 } 14028 break; 14029 14030 case UO_LNot: // logical negation 14031 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14032 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14033 if (Input.isInvalid()) return ExprError(); 14034 resultType = Input.get()->getType(); 14035 14036 // Though we still have to promote half FP to float... 14037 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14038 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14039 resultType = Context.FloatTy; 14040 } 14041 14042 if (resultType->isDependentType()) 14043 break; 14044 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14045 // C99 6.5.3.3p1: ok, fallthrough; 14046 if (Context.getLangOpts().CPlusPlus) { 14047 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14048 // operand contextually converted to bool. 14049 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14050 ScalarTypeToBooleanCastKind(resultType)); 14051 } else if (Context.getLangOpts().OpenCL && 14052 Context.getLangOpts().OpenCLVersion < 120) { 14053 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14054 // operate on scalar float types. 14055 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14056 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14057 << resultType << Input.get()->getSourceRange()); 14058 } 14059 } else if (resultType->isExtVectorType()) { 14060 if (Context.getLangOpts().OpenCL && 14061 Context.getLangOpts().OpenCLVersion < 120 && 14062 !Context.getLangOpts().OpenCLCPlusPlus) { 14063 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14064 // operate on vector float types. 14065 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14066 if (!T->isIntegerType()) 14067 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14068 << resultType << Input.get()->getSourceRange()); 14069 } 14070 // Vector logical not returns the signed variant of the operand type. 14071 resultType = GetSignedVectorType(resultType); 14072 break; 14073 } else { 14074 // FIXME: GCC's vector extension permits the usage of '!' with a vector 14075 // type in C++. We should allow that here too. 14076 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14077 << resultType << Input.get()->getSourceRange()); 14078 } 14079 14080 // LNot always has type int. C99 6.5.3.3p5. 14081 // In C++, it's bool. C++ 5.3.1p8 14082 resultType = Context.getLogicalOperationType(); 14083 break; 14084 case UO_Real: 14085 case UO_Imag: 14086 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14087 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14088 // complex l-values to ordinary l-values and all other values to r-values. 14089 if (Input.isInvalid()) return ExprError(); 14090 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14091 if (Input.get()->getValueKind() != VK_RValue && 14092 Input.get()->getObjectKind() == OK_Ordinary) 14093 VK = Input.get()->getValueKind(); 14094 } else if (!getLangOpts().CPlusPlus) { 14095 // In C, a volatile scalar is read by __imag. In C++, it is not. 14096 Input = DefaultLvalueConversion(Input.get()); 14097 } 14098 break; 14099 case UO_Extension: 14100 resultType = Input.get()->getType(); 14101 VK = Input.get()->getValueKind(); 14102 OK = Input.get()->getObjectKind(); 14103 break; 14104 case UO_Coawait: 14105 // It's unnecessary to represent the pass-through operator co_await in the 14106 // AST; just return the input expression instead. 14107 assert(!Input.get()->getType()->isDependentType() && 14108 "the co_await expression must be non-dependant before " 14109 "building operator co_await"); 14110 return Input; 14111 } 14112 if (resultType.isNull() || Input.isInvalid()) 14113 return ExprError(); 14114 14115 // Check for array bounds violations in the operand of the UnaryOperator, 14116 // except for the '*' and '&' operators that have to be handled specially 14117 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14118 // that are explicitly defined as valid by the standard). 14119 if (Opc != UO_AddrOf && Opc != UO_Deref) 14120 CheckArrayAccess(Input.get()); 14121 14122 auto *UO = new (Context) 14123 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 14124 14125 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14126 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14127 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14128 14129 // Convert the result back to a half vector. 14130 if (ConvertHalfVec) 14131 return convertVector(UO, Context.HalfTy, *this); 14132 return UO; 14133 } 14134 14135 /// Determine whether the given expression is a qualified member 14136 /// access expression, of a form that could be turned into a pointer to member 14137 /// with the address-of operator. 14138 bool Sema::isQualifiedMemberAccess(Expr *E) { 14139 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14140 if (!DRE->getQualifier()) 14141 return false; 14142 14143 ValueDecl *VD = DRE->getDecl(); 14144 if (!VD->isCXXClassMember()) 14145 return false; 14146 14147 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14148 return true; 14149 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14150 return Method->isInstance(); 14151 14152 return false; 14153 } 14154 14155 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14156 if (!ULE->getQualifier()) 14157 return false; 14158 14159 for (NamedDecl *D : ULE->decls()) { 14160 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14161 if (Method->isInstance()) 14162 return true; 14163 } else { 14164 // Overload set does not contain methods. 14165 break; 14166 } 14167 } 14168 14169 return false; 14170 } 14171 14172 return false; 14173 } 14174 14175 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14176 UnaryOperatorKind Opc, Expr *Input) { 14177 // First things first: handle placeholders so that the 14178 // overloaded-operator check considers the right type. 14179 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14180 // Increment and decrement of pseudo-object references. 14181 if (pty->getKind() == BuiltinType::PseudoObject && 14182 UnaryOperator::isIncrementDecrementOp(Opc)) 14183 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14184 14185 // extension is always a builtin operator. 14186 if (Opc == UO_Extension) 14187 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14188 14189 // & gets special logic for several kinds of placeholder. 14190 // The builtin code knows what to do. 14191 if (Opc == UO_AddrOf && 14192 (pty->getKind() == BuiltinType::Overload || 14193 pty->getKind() == BuiltinType::UnknownAny || 14194 pty->getKind() == BuiltinType::BoundMember)) 14195 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14196 14197 // Anything else needs to be handled now. 14198 ExprResult Result = CheckPlaceholderExpr(Input); 14199 if (Result.isInvalid()) return ExprError(); 14200 Input = Result.get(); 14201 } 14202 14203 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14204 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14205 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14206 // Find all of the overloaded operators visible from this 14207 // point. We perform both an operator-name lookup from the local 14208 // scope and an argument-dependent lookup based on the types of 14209 // the arguments. 14210 UnresolvedSet<16> Functions; 14211 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14212 if (S && OverOp != OO_None) 14213 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14214 Functions); 14215 14216 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14217 } 14218 14219 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14220 } 14221 14222 // Unary Operators. 'Tok' is the token for the operator. 14223 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14224 tok::TokenKind Op, Expr *Input) { 14225 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14226 } 14227 14228 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14229 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14230 LabelDecl *TheDecl) { 14231 TheDecl->markUsed(Context); 14232 // Create the AST node. The address of a label always has type 'void*'. 14233 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14234 Context.getPointerType(Context.VoidTy)); 14235 } 14236 14237 void Sema::ActOnStartStmtExpr() { 14238 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14239 } 14240 14241 void Sema::ActOnStmtExprError() { 14242 // Note that function is also called by TreeTransform when leaving a 14243 // StmtExpr scope without rebuilding anything. 14244 14245 DiscardCleanupsInEvaluationContext(); 14246 PopExpressionEvaluationContext(); 14247 } 14248 14249 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14250 SourceLocation RPLoc) { 14251 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14252 } 14253 14254 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14255 SourceLocation RPLoc, unsigned TemplateDepth) { 14256 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14257 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14258 14259 if (hasAnyUnrecoverableErrorsInThisFunction()) 14260 DiscardCleanupsInEvaluationContext(); 14261 assert(!Cleanup.exprNeedsCleanups() && 14262 "cleanups within StmtExpr not correctly bound!"); 14263 PopExpressionEvaluationContext(); 14264 14265 // FIXME: there are a variety of strange constraints to enforce here, for 14266 // example, it is not possible to goto into a stmt expression apparently. 14267 // More semantic analysis is needed. 14268 14269 // If there are sub-stmts in the compound stmt, take the type of the last one 14270 // as the type of the stmtexpr. 14271 QualType Ty = Context.VoidTy; 14272 bool StmtExprMayBindToTemp = false; 14273 if (!Compound->body_empty()) { 14274 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14275 if (const auto *LastStmt = 14276 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14277 if (const Expr *Value = LastStmt->getExprStmt()) { 14278 StmtExprMayBindToTemp = true; 14279 Ty = Value->getType(); 14280 } 14281 } 14282 } 14283 14284 // FIXME: Check that expression type is complete/non-abstract; statement 14285 // expressions are not lvalues. 14286 Expr *ResStmtExpr = 14287 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14288 if (StmtExprMayBindToTemp) 14289 return MaybeBindToTemporary(ResStmtExpr); 14290 return ResStmtExpr; 14291 } 14292 14293 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14294 if (ER.isInvalid()) 14295 return ExprError(); 14296 14297 // Do function/array conversion on the last expression, but not 14298 // lvalue-to-rvalue. However, initialize an unqualified type. 14299 ER = DefaultFunctionArrayConversion(ER.get()); 14300 if (ER.isInvalid()) 14301 return ExprError(); 14302 Expr *E = ER.get(); 14303 14304 if (E->isTypeDependent()) 14305 return E; 14306 14307 // In ARC, if the final expression ends in a consume, splice 14308 // the consume out and bind it later. In the alternate case 14309 // (when dealing with a retainable type), the result 14310 // initialization will create a produce. In both cases the 14311 // result will be +1, and we'll need to balance that out with 14312 // a bind. 14313 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14314 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14315 return Cast->getSubExpr(); 14316 14317 // FIXME: Provide a better location for the initialization. 14318 return PerformCopyInitialization( 14319 InitializedEntity::InitializeStmtExprResult( 14320 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14321 SourceLocation(), E); 14322 } 14323 14324 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14325 TypeSourceInfo *TInfo, 14326 ArrayRef<OffsetOfComponent> Components, 14327 SourceLocation RParenLoc) { 14328 QualType ArgTy = TInfo->getType(); 14329 bool Dependent = ArgTy->isDependentType(); 14330 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14331 14332 // We must have at least one component that refers to the type, and the first 14333 // one is known to be a field designator. Verify that the ArgTy represents 14334 // a struct/union/class. 14335 if (!Dependent && !ArgTy->isRecordType()) 14336 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14337 << ArgTy << TypeRange); 14338 14339 // Type must be complete per C99 7.17p3 because a declaring a variable 14340 // with an incomplete type would be ill-formed. 14341 if (!Dependent 14342 && RequireCompleteType(BuiltinLoc, ArgTy, 14343 diag::err_offsetof_incomplete_type, TypeRange)) 14344 return ExprError(); 14345 14346 bool DidWarnAboutNonPOD = false; 14347 QualType CurrentType = ArgTy; 14348 SmallVector<OffsetOfNode, 4> Comps; 14349 SmallVector<Expr*, 4> Exprs; 14350 for (const OffsetOfComponent &OC : Components) { 14351 if (OC.isBrackets) { 14352 // Offset of an array sub-field. TODO: Should we allow vector elements? 14353 if (!CurrentType->isDependentType()) { 14354 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14355 if(!AT) 14356 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14357 << CurrentType); 14358 CurrentType = AT->getElementType(); 14359 } else 14360 CurrentType = Context.DependentTy; 14361 14362 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14363 if (IdxRval.isInvalid()) 14364 return ExprError(); 14365 Expr *Idx = IdxRval.get(); 14366 14367 // The expression must be an integral expression. 14368 // FIXME: An integral constant expression? 14369 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14370 !Idx->getType()->isIntegerType()) 14371 return ExprError( 14372 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14373 << Idx->getSourceRange()); 14374 14375 // Record this array index. 14376 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14377 Exprs.push_back(Idx); 14378 continue; 14379 } 14380 14381 // Offset of a field. 14382 if (CurrentType->isDependentType()) { 14383 // We have the offset of a field, but we can't look into the dependent 14384 // type. Just record the identifier of the field. 14385 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14386 CurrentType = Context.DependentTy; 14387 continue; 14388 } 14389 14390 // We need to have a complete type to look into. 14391 if (RequireCompleteType(OC.LocStart, CurrentType, 14392 diag::err_offsetof_incomplete_type)) 14393 return ExprError(); 14394 14395 // Look for the designated field. 14396 const RecordType *RC = CurrentType->getAs<RecordType>(); 14397 if (!RC) 14398 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14399 << CurrentType); 14400 RecordDecl *RD = RC->getDecl(); 14401 14402 // C++ [lib.support.types]p5: 14403 // The macro offsetof accepts a restricted set of type arguments in this 14404 // International Standard. type shall be a POD structure or a POD union 14405 // (clause 9). 14406 // C++11 [support.types]p4: 14407 // If type is not a standard-layout class (Clause 9), the results are 14408 // undefined. 14409 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14410 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14411 unsigned DiagID = 14412 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14413 : diag::ext_offsetof_non_pod_type; 14414 14415 if (!IsSafe && !DidWarnAboutNonPOD && 14416 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14417 PDiag(DiagID) 14418 << SourceRange(Components[0].LocStart, OC.LocEnd) 14419 << CurrentType)) 14420 DidWarnAboutNonPOD = true; 14421 } 14422 14423 // Look for the field. 14424 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14425 LookupQualifiedName(R, RD); 14426 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14427 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14428 if (!MemberDecl) { 14429 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14430 MemberDecl = IndirectMemberDecl->getAnonField(); 14431 } 14432 14433 if (!MemberDecl) 14434 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14435 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14436 OC.LocEnd)); 14437 14438 // C99 7.17p3: 14439 // (If the specified member is a bit-field, the behavior is undefined.) 14440 // 14441 // We diagnose this as an error. 14442 if (MemberDecl->isBitField()) { 14443 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14444 << MemberDecl->getDeclName() 14445 << SourceRange(BuiltinLoc, RParenLoc); 14446 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14447 return ExprError(); 14448 } 14449 14450 RecordDecl *Parent = MemberDecl->getParent(); 14451 if (IndirectMemberDecl) 14452 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14453 14454 // If the member was found in a base class, introduce OffsetOfNodes for 14455 // the base class indirections. 14456 CXXBasePaths Paths; 14457 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14458 Paths)) { 14459 if (Paths.getDetectedVirtual()) { 14460 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14461 << MemberDecl->getDeclName() 14462 << SourceRange(BuiltinLoc, RParenLoc); 14463 return ExprError(); 14464 } 14465 14466 CXXBasePath &Path = Paths.front(); 14467 for (const CXXBasePathElement &B : Path) 14468 Comps.push_back(OffsetOfNode(B.Base)); 14469 } 14470 14471 if (IndirectMemberDecl) { 14472 for (auto *FI : IndirectMemberDecl->chain()) { 14473 assert(isa<FieldDecl>(FI)); 14474 Comps.push_back(OffsetOfNode(OC.LocStart, 14475 cast<FieldDecl>(FI), OC.LocEnd)); 14476 } 14477 } else 14478 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14479 14480 CurrentType = MemberDecl->getType().getNonReferenceType(); 14481 } 14482 14483 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14484 Comps, Exprs, RParenLoc); 14485 } 14486 14487 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14488 SourceLocation BuiltinLoc, 14489 SourceLocation TypeLoc, 14490 ParsedType ParsedArgTy, 14491 ArrayRef<OffsetOfComponent> Components, 14492 SourceLocation RParenLoc) { 14493 14494 TypeSourceInfo *ArgTInfo; 14495 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14496 if (ArgTy.isNull()) 14497 return ExprError(); 14498 14499 if (!ArgTInfo) 14500 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14501 14502 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14503 } 14504 14505 14506 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14507 Expr *CondExpr, 14508 Expr *LHSExpr, Expr *RHSExpr, 14509 SourceLocation RPLoc) { 14510 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14511 14512 ExprValueKind VK = VK_RValue; 14513 ExprObjectKind OK = OK_Ordinary; 14514 QualType resType; 14515 bool CondIsTrue = false; 14516 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14517 resType = Context.DependentTy; 14518 } else { 14519 // The conditional expression is required to be a constant expression. 14520 llvm::APSInt condEval(32); 14521 ExprResult CondICE 14522 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14523 diag::err_typecheck_choose_expr_requires_constant, false); 14524 if (CondICE.isInvalid()) 14525 return ExprError(); 14526 CondExpr = CondICE.get(); 14527 CondIsTrue = condEval.getZExtValue(); 14528 14529 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14530 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14531 14532 resType = ActiveExpr->getType(); 14533 VK = ActiveExpr->getValueKind(); 14534 OK = ActiveExpr->getObjectKind(); 14535 } 14536 14537 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14538 resType, VK, OK, RPLoc, CondIsTrue); 14539 } 14540 14541 //===----------------------------------------------------------------------===// 14542 // Clang Extensions. 14543 //===----------------------------------------------------------------------===// 14544 14545 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14546 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14547 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14548 14549 if (LangOpts.CPlusPlus) { 14550 MangleNumberingContext *MCtx; 14551 Decl *ManglingContextDecl; 14552 std::tie(MCtx, ManglingContextDecl) = 14553 getCurrentMangleNumberContext(Block->getDeclContext()); 14554 if (MCtx) { 14555 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14556 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14557 } 14558 } 14559 14560 PushBlockScope(CurScope, Block); 14561 CurContext->addDecl(Block); 14562 if (CurScope) 14563 PushDeclContext(CurScope, Block); 14564 else 14565 CurContext = Block; 14566 14567 getCurBlock()->HasImplicitReturnType = true; 14568 14569 // Enter a new evaluation context to insulate the block from any 14570 // cleanups from the enclosing full-expression. 14571 PushExpressionEvaluationContext( 14572 ExpressionEvaluationContext::PotentiallyEvaluated); 14573 } 14574 14575 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14576 Scope *CurScope) { 14577 assert(ParamInfo.getIdentifier() == nullptr && 14578 "block-id should have no identifier!"); 14579 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14580 BlockScopeInfo *CurBlock = getCurBlock(); 14581 14582 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14583 QualType T = Sig->getType(); 14584 14585 // FIXME: We should allow unexpanded parameter packs here, but that would, 14586 // in turn, make the block expression contain unexpanded parameter packs. 14587 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14588 // Drop the parameters. 14589 FunctionProtoType::ExtProtoInfo EPI; 14590 EPI.HasTrailingReturn = false; 14591 EPI.TypeQuals.addConst(); 14592 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14593 Sig = Context.getTrivialTypeSourceInfo(T); 14594 } 14595 14596 // GetTypeForDeclarator always produces a function type for a block 14597 // literal signature. Furthermore, it is always a FunctionProtoType 14598 // unless the function was written with a typedef. 14599 assert(T->isFunctionType() && 14600 "GetTypeForDeclarator made a non-function block signature"); 14601 14602 // Look for an explicit signature in that function type. 14603 FunctionProtoTypeLoc ExplicitSignature; 14604 14605 if ((ExplicitSignature = Sig->getTypeLoc() 14606 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14607 14608 // Check whether that explicit signature was synthesized by 14609 // GetTypeForDeclarator. If so, don't save that as part of the 14610 // written signature. 14611 if (ExplicitSignature.getLocalRangeBegin() == 14612 ExplicitSignature.getLocalRangeEnd()) { 14613 // This would be much cheaper if we stored TypeLocs instead of 14614 // TypeSourceInfos. 14615 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14616 unsigned Size = Result.getFullDataSize(); 14617 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14618 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14619 14620 ExplicitSignature = FunctionProtoTypeLoc(); 14621 } 14622 } 14623 14624 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14625 CurBlock->FunctionType = T; 14626 14627 const FunctionType *Fn = T->getAs<FunctionType>(); 14628 QualType RetTy = Fn->getReturnType(); 14629 bool isVariadic = 14630 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14631 14632 CurBlock->TheDecl->setIsVariadic(isVariadic); 14633 14634 // Context.DependentTy is used as a placeholder for a missing block 14635 // return type. TODO: what should we do with declarators like: 14636 // ^ * { ... } 14637 // If the answer is "apply template argument deduction".... 14638 if (RetTy != Context.DependentTy) { 14639 CurBlock->ReturnType = RetTy; 14640 CurBlock->TheDecl->setBlockMissingReturnType(false); 14641 CurBlock->HasImplicitReturnType = false; 14642 } 14643 14644 // Push block parameters from the declarator if we had them. 14645 SmallVector<ParmVarDecl*, 8> Params; 14646 if (ExplicitSignature) { 14647 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14648 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14649 if (Param->getIdentifier() == nullptr && 14650 !Param->isImplicit() && 14651 !Param->isInvalidDecl() && 14652 !getLangOpts().CPlusPlus) 14653 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14654 Params.push_back(Param); 14655 } 14656 14657 // Fake up parameter variables if we have a typedef, like 14658 // ^ fntype { ... } 14659 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14660 for (const auto &I : Fn->param_types()) { 14661 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14662 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14663 Params.push_back(Param); 14664 } 14665 } 14666 14667 // Set the parameters on the block decl. 14668 if (!Params.empty()) { 14669 CurBlock->TheDecl->setParams(Params); 14670 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14671 /*CheckParameterNames=*/false); 14672 } 14673 14674 // Finally we can process decl attributes. 14675 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14676 14677 // Put the parameter variables in scope. 14678 for (auto AI : CurBlock->TheDecl->parameters()) { 14679 AI->setOwningFunction(CurBlock->TheDecl); 14680 14681 // If this has an identifier, add it to the scope stack. 14682 if (AI->getIdentifier()) { 14683 CheckShadow(CurBlock->TheScope, AI); 14684 14685 PushOnScopeChains(AI, CurBlock->TheScope); 14686 } 14687 } 14688 } 14689 14690 /// ActOnBlockError - If there is an error parsing a block, this callback 14691 /// is invoked to pop the information about the block from the action impl. 14692 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14693 // Leave the expression-evaluation context. 14694 DiscardCleanupsInEvaluationContext(); 14695 PopExpressionEvaluationContext(); 14696 14697 // Pop off CurBlock, handle nested blocks. 14698 PopDeclContext(); 14699 PopFunctionScopeInfo(); 14700 } 14701 14702 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14703 /// literal was successfully completed. ^(int x){...} 14704 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14705 Stmt *Body, Scope *CurScope) { 14706 // If blocks are disabled, emit an error. 14707 if (!LangOpts.Blocks) 14708 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14709 14710 // Leave the expression-evaluation context. 14711 if (hasAnyUnrecoverableErrorsInThisFunction()) 14712 DiscardCleanupsInEvaluationContext(); 14713 assert(!Cleanup.exprNeedsCleanups() && 14714 "cleanups within block not correctly bound!"); 14715 PopExpressionEvaluationContext(); 14716 14717 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14718 BlockDecl *BD = BSI->TheDecl; 14719 14720 if (BSI->HasImplicitReturnType) 14721 deduceClosureReturnType(*BSI); 14722 14723 QualType RetTy = Context.VoidTy; 14724 if (!BSI->ReturnType.isNull()) 14725 RetTy = BSI->ReturnType; 14726 14727 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14728 QualType BlockTy; 14729 14730 // If the user wrote a function type in some form, try to use that. 14731 if (!BSI->FunctionType.isNull()) { 14732 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14733 14734 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14735 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14736 14737 // Turn protoless block types into nullary block types. 14738 if (isa<FunctionNoProtoType>(FTy)) { 14739 FunctionProtoType::ExtProtoInfo EPI; 14740 EPI.ExtInfo = Ext; 14741 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14742 14743 // Otherwise, if we don't need to change anything about the function type, 14744 // preserve its sugar structure. 14745 } else if (FTy->getReturnType() == RetTy && 14746 (!NoReturn || FTy->getNoReturnAttr())) { 14747 BlockTy = BSI->FunctionType; 14748 14749 // Otherwise, make the minimal modifications to the function type. 14750 } else { 14751 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14752 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14753 EPI.TypeQuals = Qualifiers(); 14754 EPI.ExtInfo = Ext; 14755 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14756 } 14757 14758 // If we don't have a function type, just build one from nothing. 14759 } else { 14760 FunctionProtoType::ExtProtoInfo EPI; 14761 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14762 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14763 } 14764 14765 DiagnoseUnusedParameters(BD->parameters()); 14766 BlockTy = Context.getBlockPointerType(BlockTy); 14767 14768 // If needed, diagnose invalid gotos and switches in the block. 14769 if (getCurFunction()->NeedsScopeChecking() && 14770 !PP.isCodeCompletionEnabled()) 14771 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14772 14773 BD->setBody(cast<CompoundStmt>(Body)); 14774 14775 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14776 DiagnoseUnguardedAvailabilityViolations(BD); 14777 14778 // Try to apply the named return value optimization. We have to check again 14779 // if we can do this, though, because blocks keep return statements around 14780 // to deduce an implicit return type. 14781 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14782 !BD->isDependentContext()) 14783 computeNRVO(Body, BSI); 14784 14785 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14786 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14787 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14788 NTCUK_Destruct|NTCUK_Copy); 14789 14790 PopDeclContext(); 14791 14792 // Pop the block scope now but keep it alive to the end of this function. 14793 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14794 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14795 14796 // Set the captured variables on the block. 14797 SmallVector<BlockDecl::Capture, 4> Captures; 14798 for (Capture &Cap : BSI->Captures) { 14799 if (Cap.isInvalid() || Cap.isThisCapture()) 14800 continue; 14801 14802 VarDecl *Var = Cap.getVariable(); 14803 Expr *CopyExpr = nullptr; 14804 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14805 if (const RecordType *Record = 14806 Cap.getCaptureType()->getAs<RecordType>()) { 14807 // The capture logic needs the destructor, so make sure we mark it. 14808 // Usually this is unnecessary because most local variables have 14809 // their destructors marked at declaration time, but parameters are 14810 // an exception because it's technically only the call site that 14811 // actually requires the destructor. 14812 if (isa<ParmVarDecl>(Var)) 14813 FinalizeVarWithDestructor(Var, Record); 14814 14815 // Enter a separate potentially-evaluated context while building block 14816 // initializers to isolate their cleanups from those of the block 14817 // itself. 14818 // FIXME: Is this appropriate even when the block itself occurs in an 14819 // unevaluated operand? 14820 EnterExpressionEvaluationContext EvalContext( 14821 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14822 14823 SourceLocation Loc = Cap.getLocation(); 14824 14825 ExprResult Result = BuildDeclarationNameExpr( 14826 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14827 14828 // According to the blocks spec, the capture of a variable from 14829 // the stack requires a const copy constructor. This is not true 14830 // of the copy/move done to move a __block variable to the heap. 14831 if (!Result.isInvalid() && 14832 !Result.get()->getType().isConstQualified()) { 14833 Result = ImpCastExprToType(Result.get(), 14834 Result.get()->getType().withConst(), 14835 CK_NoOp, VK_LValue); 14836 } 14837 14838 if (!Result.isInvalid()) { 14839 Result = PerformCopyInitialization( 14840 InitializedEntity::InitializeBlock(Var->getLocation(), 14841 Cap.getCaptureType(), false), 14842 Loc, Result.get()); 14843 } 14844 14845 // Build a full-expression copy expression if initialization 14846 // succeeded and used a non-trivial constructor. Recover from 14847 // errors by pretending that the copy isn't necessary. 14848 if (!Result.isInvalid() && 14849 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14850 ->isTrivial()) { 14851 Result = MaybeCreateExprWithCleanups(Result); 14852 CopyExpr = Result.get(); 14853 } 14854 } 14855 } 14856 14857 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14858 CopyExpr); 14859 Captures.push_back(NewCap); 14860 } 14861 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14862 14863 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14864 14865 // If the block isn't obviously global, i.e. it captures anything at 14866 // all, then we need to do a few things in the surrounding context: 14867 if (Result->getBlockDecl()->hasCaptures()) { 14868 // First, this expression has a new cleanup object. 14869 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14870 Cleanup.setExprNeedsCleanups(true); 14871 14872 // It also gets a branch-protected scope if any of the captured 14873 // variables needs destruction. 14874 for (const auto &CI : Result->getBlockDecl()->captures()) { 14875 const VarDecl *var = CI.getVariable(); 14876 if (var->getType().isDestructedType() != QualType::DK_none) { 14877 setFunctionHasBranchProtectedScope(); 14878 break; 14879 } 14880 } 14881 } 14882 14883 if (getCurFunction()) 14884 getCurFunction()->addBlock(BD); 14885 14886 return Result; 14887 } 14888 14889 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14890 SourceLocation RPLoc) { 14891 TypeSourceInfo *TInfo; 14892 GetTypeFromParser(Ty, &TInfo); 14893 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14894 } 14895 14896 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14897 Expr *E, TypeSourceInfo *TInfo, 14898 SourceLocation RPLoc) { 14899 Expr *OrigExpr = E; 14900 bool IsMS = false; 14901 14902 // CUDA device code does not support varargs. 14903 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14904 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14905 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14906 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14907 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14908 } 14909 } 14910 14911 // NVPTX does not support va_arg expression. 14912 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14913 Context.getTargetInfo().getTriple().isNVPTX()) 14914 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14915 14916 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14917 // as Microsoft ABI on an actual Microsoft platform, where 14918 // __builtin_ms_va_list and __builtin_va_list are the same.) 14919 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14920 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14921 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14922 if (Context.hasSameType(MSVaListType, E->getType())) { 14923 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14924 return ExprError(); 14925 IsMS = true; 14926 } 14927 } 14928 14929 // Get the va_list type 14930 QualType VaListType = Context.getBuiltinVaListType(); 14931 if (!IsMS) { 14932 if (VaListType->isArrayType()) { 14933 // Deal with implicit array decay; for example, on x86-64, 14934 // va_list is an array, but it's supposed to decay to 14935 // a pointer for va_arg. 14936 VaListType = Context.getArrayDecayedType(VaListType); 14937 // Make sure the input expression also decays appropriately. 14938 ExprResult Result = UsualUnaryConversions(E); 14939 if (Result.isInvalid()) 14940 return ExprError(); 14941 E = Result.get(); 14942 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14943 // If va_list is a record type and we are compiling in C++ mode, 14944 // check the argument using reference binding. 14945 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14946 Context, Context.getLValueReferenceType(VaListType), false); 14947 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14948 if (Init.isInvalid()) 14949 return ExprError(); 14950 E = Init.getAs<Expr>(); 14951 } else { 14952 // Otherwise, the va_list argument must be an l-value because 14953 // it is modified by va_arg. 14954 if (!E->isTypeDependent() && 14955 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14956 return ExprError(); 14957 } 14958 } 14959 14960 if (!IsMS && !E->isTypeDependent() && 14961 !Context.hasSameType(VaListType, E->getType())) 14962 return ExprError( 14963 Diag(E->getBeginLoc(), 14964 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14965 << OrigExpr->getType() << E->getSourceRange()); 14966 14967 if (!TInfo->getType()->isDependentType()) { 14968 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14969 diag::err_second_parameter_to_va_arg_incomplete, 14970 TInfo->getTypeLoc())) 14971 return ExprError(); 14972 14973 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14974 TInfo->getType(), 14975 diag::err_second_parameter_to_va_arg_abstract, 14976 TInfo->getTypeLoc())) 14977 return ExprError(); 14978 14979 if (!TInfo->getType().isPODType(Context)) { 14980 Diag(TInfo->getTypeLoc().getBeginLoc(), 14981 TInfo->getType()->isObjCLifetimeType() 14982 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14983 : diag::warn_second_parameter_to_va_arg_not_pod) 14984 << TInfo->getType() 14985 << TInfo->getTypeLoc().getSourceRange(); 14986 } 14987 14988 // Check for va_arg where arguments of the given type will be promoted 14989 // (i.e. this va_arg is guaranteed to have undefined behavior). 14990 QualType PromoteType; 14991 if (TInfo->getType()->isPromotableIntegerType()) { 14992 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14993 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14994 PromoteType = QualType(); 14995 } 14996 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14997 PromoteType = Context.DoubleTy; 14998 if (!PromoteType.isNull()) 14999 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15000 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15001 << TInfo->getType() 15002 << PromoteType 15003 << TInfo->getTypeLoc().getSourceRange()); 15004 } 15005 15006 QualType T = TInfo->getType().getNonLValueExprType(Context); 15007 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15008 } 15009 15010 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15011 // The type of __null will be int or long, depending on the size of 15012 // pointers on the target. 15013 QualType Ty; 15014 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15015 if (pw == Context.getTargetInfo().getIntWidth()) 15016 Ty = Context.IntTy; 15017 else if (pw == Context.getTargetInfo().getLongWidth()) 15018 Ty = Context.LongTy; 15019 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15020 Ty = Context.LongLongTy; 15021 else { 15022 llvm_unreachable("I don't know size of pointer!"); 15023 } 15024 15025 return new (Context) GNUNullExpr(Ty, TokenLoc); 15026 } 15027 15028 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15029 SourceLocation BuiltinLoc, 15030 SourceLocation RPLoc) { 15031 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15032 } 15033 15034 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15035 SourceLocation BuiltinLoc, 15036 SourceLocation RPLoc, 15037 DeclContext *ParentContext) { 15038 return new (Context) 15039 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15040 } 15041 15042 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 15043 bool Diagnose) { 15044 if (!getLangOpts().ObjC) 15045 return false; 15046 15047 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15048 if (!PT) 15049 return false; 15050 15051 if (!PT->isObjCIdType()) { 15052 // Check if the destination is the 'NSString' interface. 15053 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15054 if (!ID || !ID->getIdentifier()->isStr("NSString")) 15055 return false; 15056 } 15057 15058 // Ignore any parens, implicit casts (should only be 15059 // array-to-pointer decays), and not-so-opaque values. The last is 15060 // important for making this trigger for property assignments. 15061 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15062 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15063 if (OV->getSourceExpr()) 15064 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15065 15066 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 15067 if (!SL || !SL->isAscii()) 15068 return false; 15069 if (Diagnose) { 15070 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15071 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15072 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15073 } 15074 return true; 15075 } 15076 15077 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15078 const Expr *SrcExpr) { 15079 if (!DstType->isFunctionPointerType() || 15080 !SrcExpr->getType()->isFunctionType()) 15081 return false; 15082 15083 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15084 if (!DRE) 15085 return false; 15086 15087 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15088 if (!FD) 15089 return false; 15090 15091 return !S.checkAddressOfFunctionIsAvailable(FD, 15092 /*Complain=*/true, 15093 SrcExpr->getBeginLoc()); 15094 } 15095 15096 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15097 SourceLocation Loc, 15098 QualType DstType, QualType SrcType, 15099 Expr *SrcExpr, AssignmentAction Action, 15100 bool *Complained) { 15101 if (Complained) 15102 *Complained = false; 15103 15104 // Decode the result (notice that AST's are still created for extensions). 15105 bool CheckInferredResultType = false; 15106 bool isInvalid = false; 15107 unsigned DiagKind = 0; 15108 FixItHint Hint; 15109 ConversionFixItGenerator ConvHints; 15110 bool MayHaveConvFixit = false; 15111 bool MayHaveFunctionDiff = false; 15112 const ObjCInterfaceDecl *IFace = nullptr; 15113 const ObjCProtocolDecl *PDecl = nullptr; 15114 15115 switch (ConvTy) { 15116 case Compatible: 15117 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15118 return false; 15119 15120 case PointerToInt: 15121 if (getLangOpts().CPlusPlus) { 15122 DiagKind = diag::err_typecheck_convert_pointer_int; 15123 isInvalid = true; 15124 } else { 15125 DiagKind = diag::ext_typecheck_convert_pointer_int; 15126 } 15127 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15128 MayHaveConvFixit = true; 15129 break; 15130 case IntToPointer: 15131 if (getLangOpts().CPlusPlus) { 15132 DiagKind = diag::err_typecheck_convert_int_pointer; 15133 isInvalid = true; 15134 } else { 15135 DiagKind = diag::ext_typecheck_convert_int_pointer; 15136 } 15137 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15138 MayHaveConvFixit = true; 15139 break; 15140 case IncompatibleFunctionPointer: 15141 if (getLangOpts().CPlusPlus) { 15142 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15143 isInvalid = true; 15144 } else { 15145 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15146 } 15147 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15148 MayHaveConvFixit = true; 15149 break; 15150 case IncompatiblePointer: 15151 if (Action == AA_Passing_CFAudited) { 15152 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15153 } else if (getLangOpts().CPlusPlus) { 15154 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15155 isInvalid = true; 15156 } else { 15157 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15158 } 15159 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15160 SrcType->isObjCObjectPointerType(); 15161 if (Hint.isNull() && !CheckInferredResultType) { 15162 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15163 } 15164 else if (CheckInferredResultType) { 15165 SrcType = SrcType.getUnqualifiedType(); 15166 DstType = DstType.getUnqualifiedType(); 15167 } 15168 MayHaveConvFixit = true; 15169 break; 15170 case IncompatiblePointerSign: 15171 if (getLangOpts().CPlusPlus) { 15172 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15173 isInvalid = true; 15174 } else { 15175 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15176 } 15177 break; 15178 case FunctionVoidPointer: 15179 if (getLangOpts().CPlusPlus) { 15180 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15181 isInvalid = true; 15182 } else { 15183 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15184 } 15185 break; 15186 case IncompatiblePointerDiscardsQualifiers: { 15187 // Perform array-to-pointer decay if necessary. 15188 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15189 15190 isInvalid = true; 15191 15192 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15193 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15194 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15195 DiagKind = diag::err_typecheck_incompatible_address_space; 15196 break; 15197 15198 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15199 DiagKind = diag::err_typecheck_incompatible_ownership; 15200 break; 15201 } 15202 15203 llvm_unreachable("unknown error case for discarding qualifiers!"); 15204 // fallthrough 15205 } 15206 case CompatiblePointerDiscardsQualifiers: 15207 // If the qualifiers lost were because we were applying the 15208 // (deprecated) C++ conversion from a string literal to a char* 15209 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15210 // Ideally, this check would be performed in 15211 // checkPointerTypesForAssignment. However, that would require a 15212 // bit of refactoring (so that the second argument is an 15213 // expression, rather than a type), which should be done as part 15214 // of a larger effort to fix checkPointerTypesForAssignment for 15215 // C++ semantics. 15216 if (getLangOpts().CPlusPlus && 15217 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15218 return false; 15219 if (getLangOpts().CPlusPlus) { 15220 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15221 isInvalid = true; 15222 } else { 15223 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15224 } 15225 15226 break; 15227 case IncompatibleNestedPointerQualifiers: 15228 if (getLangOpts().CPlusPlus) { 15229 isInvalid = true; 15230 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15231 } else { 15232 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15233 } 15234 break; 15235 case IncompatibleNestedPointerAddressSpaceMismatch: 15236 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15237 isInvalid = true; 15238 break; 15239 case IntToBlockPointer: 15240 DiagKind = diag::err_int_to_block_pointer; 15241 isInvalid = true; 15242 break; 15243 case IncompatibleBlockPointer: 15244 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15245 isInvalid = true; 15246 break; 15247 case IncompatibleObjCQualifiedId: { 15248 if (SrcType->isObjCQualifiedIdType()) { 15249 const ObjCObjectPointerType *srcOPT = 15250 SrcType->castAs<ObjCObjectPointerType>(); 15251 for (auto *srcProto : srcOPT->quals()) { 15252 PDecl = srcProto; 15253 break; 15254 } 15255 if (const ObjCInterfaceType *IFaceT = 15256 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15257 IFace = IFaceT->getDecl(); 15258 } 15259 else if (DstType->isObjCQualifiedIdType()) { 15260 const ObjCObjectPointerType *dstOPT = 15261 DstType->castAs<ObjCObjectPointerType>(); 15262 for (auto *dstProto : dstOPT->quals()) { 15263 PDecl = dstProto; 15264 break; 15265 } 15266 if (const ObjCInterfaceType *IFaceT = 15267 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15268 IFace = IFaceT->getDecl(); 15269 } 15270 if (getLangOpts().CPlusPlus) { 15271 DiagKind = diag::err_incompatible_qualified_id; 15272 isInvalid = true; 15273 } else { 15274 DiagKind = diag::warn_incompatible_qualified_id; 15275 } 15276 break; 15277 } 15278 case IncompatibleVectors: 15279 if (getLangOpts().CPlusPlus) { 15280 DiagKind = diag::err_incompatible_vectors; 15281 isInvalid = true; 15282 } else { 15283 DiagKind = diag::warn_incompatible_vectors; 15284 } 15285 break; 15286 case IncompatibleObjCWeakRef: 15287 DiagKind = diag::err_arc_weak_unavailable_assign; 15288 isInvalid = true; 15289 break; 15290 case Incompatible: 15291 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15292 if (Complained) 15293 *Complained = true; 15294 return true; 15295 } 15296 15297 DiagKind = diag::err_typecheck_convert_incompatible; 15298 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15299 MayHaveConvFixit = true; 15300 isInvalid = true; 15301 MayHaveFunctionDiff = true; 15302 break; 15303 } 15304 15305 QualType FirstType, SecondType; 15306 switch (Action) { 15307 case AA_Assigning: 15308 case AA_Initializing: 15309 // The destination type comes first. 15310 FirstType = DstType; 15311 SecondType = SrcType; 15312 break; 15313 15314 case AA_Returning: 15315 case AA_Passing: 15316 case AA_Passing_CFAudited: 15317 case AA_Converting: 15318 case AA_Sending: 15319 case AA_Casting: 15320 // The source type comes first. 15321 FirstType = SrcType; 15322 SecondType = DstType; 15323 break; 15324 } 15325 15326 PartialDiagnostic FDiag = PDiag(DiagKind); 15327 if (Action == AA_Passing_CFAudited) 15328 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15329 else 15330 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15331 15332 // If we can fix the conversion, suggest the FixIts. 15333 assert(ConvHints.isNull() || Hint.isNull()); 15334 if (!ConvHints.isNull()) { 15335 for (FixItHint &H : ConvHints.Hints) 15336 FDiag << H; 15337 } else { 15338 FDiag << Hint; 15339 } 15340 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15341 15342 if (MayHaveFunctionDiff) 15343 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15344 15345 Diag(Loc, FDiag); 15346 if ((DiagKind == diag::warn_incompatible_qualified_id || 15347 DiagKind == diag::err_incompatible_qualified_id) && 15348 PDecl && IFace && !IFace->hasDefinition()) 15349 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15350 << IFace << PDecl; 15351 15352 if (SecondType == Context.OverloadTy) 15353 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15354 FirstType, /*TakingAddress=*/true); 15355 15356 if (CheckInferredResultType) 15357 EmitRelatedResultTypeNote(SrcExpr); 15358 15359 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15360 EmitRelatedResultTypeNoteForReturn(DstType); 15361 15362 if (Complained) 15363 *Complained = true; 15364 return isInvalid; 15365 } 15366 15367 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15368 llvm::APSInt *Result) { 15369 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15370 public: 15371 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15372 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15373 } 15374 } Diagnoser; 15375 15376 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15377 } 15378 15379 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15380 llvm::APSInt *Result, 15381 unsigned DiagID, 15382 bool AllowFold) { 15383 class IDDiagnoser : public VerifyICEDiagnoser { 15384 unsigned DiagID; 15385 15386 public: 15387 IDDiagnoser(unsigned DiagID) 15388 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15389 15390 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15391 S.Diag(Loc, DiagID) << SR; 15392 } 15393 } Diagnoser(DiagID); 15394 15395 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15396 } 15397 15398 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15399 SourceRange SR) { 15400 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15401 } 15402 15403 ExprResult 15404 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15405 VerifyICEDiagnoser &Diagnoser, 15406 bool AllowFold) { 15407 SourceLocation DiagLoc = E->getBeginLoc(); 15408 15409 if (getLangOpts().CPlusPlus11) { 15410 // C++11 [expr.const]p5: 15411 // If an expression of literal class type is used in a context where an 15412 // integral constant expression is required, then that class type shall 15413 // have a single non-explicit conversion function to an integral or 15414 // unscoped enumeration type 15415 ExprResult Converted; 15416 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15417 public: 15418 CXX11ConvertDiagnoser(bool Silent) 15419 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15420 Silent, true) {} 15421 15422 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15423 QualType T) override { 15424 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15425 } 15426 15427 SemaDiagnosticBuilder diagnoseIncomplete( 15428 Sema &S, SourceLocation Loc, QualType T) override { 15429 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15430 } 15431 15432 SemaDiagnosticBuilder diagnoseExplicitConv( 15433 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15434 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15435 } 15436 15437 SemaDiagnosticBuilder noteExplicitConv( 15438 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15439 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15440 << ConvTy->isEnumeralType() << ConvTy; 15441 } 15442 15443 SemaDiagnosticBuilder diagnoseAmbiguous( 15444 Sema &S, SourceLocation Loc, QualType T) override { 15445 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15446 } 15447 15448 SemaDiagnosticBuilder noteAmbiguous( 15449 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15450 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15451 << ConvTy->isEnumeralType() << ConvTy; 15452 } 15453 15454 SemaDiagnosticBuilder diagnoseConversion( 15455 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15456 llvm_unreachable("conversion functions are permitted"); 15457 } 15458 } ConvertDiagnoser(Diagnoser.Suppress); 15459 15460 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15461 ConvertDiagnoser); 15462 if (Converted.isInvalid()) 15463 return Converted; 15464 E = Converted.get(); 15465 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15466 return ExprError(); 15467 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15468 // An ICE must be of integral or unscoped enumeration type. 15469 if (!Diagnoser.Suppress) 15470 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15471 return ExprError(); 15472 } 15473 15474 ExprResult RValueExpr = DefaultLvalueConversion(E); 15475 if (RValueExpr.isInvalid()) 15476 return ExprError(); 15477 15478 E = RValueExpr.get(); 15479 15480 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15481 // in the non-ICE case. 15482 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15483 if (Result) 15484 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15485 if (!isa<ConstantExpr>(E)) 15486 E = ConstantExpr::Create(Context, E); 15487 return E; 15488 } 15489 15490 Expr::EvalResult EvalResult; 15491 SmallVector<PartialDiagnosticAt, 8> Notes; 15492 EvalResult.Diag = &Notes; 15493 15494 // Try to evaluate the expression, and produce diagnostics explaining why it's 15495 // not a constant expression as a side-effect. 15496 bool Folded = 15497 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15498 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15499 15500 if (!isa<ConstantExpr>(E)) 15501 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15502 15503 // In C++11, we can rely on diagnostics being produced for any expression 15504 // which is not a constant expression. If no diagnostics were produced, then 15505 // this is a constant expression. 15506 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15507 if (Result) 15508 *Result = EvalResult.Val.getInt(); 15509 return E; 15510 } 15511 15512 // If our only note is the usual "invalid subexpression" note, just point 15513 // the caret at its location rather than producing an essentially 15514 // redundant note. 15515 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15516 diag::note_invalid_subexpr_in_const_expr) { 15517 DiagLoc = Notes[0].first; 15518 Notes.clear(); 15519 } 15520 15521 if (!Folded || !AllowFold) { 15522 if (!Diagnoser.Suppress) { 15523 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15524 for (const PartialDiagnosticAt &Note : Notes) 15525 Diag(Note.first, Note.second); 15526 } 15527 15528 return ExprError(); 15529 } 15530 15531 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15532 for (const PartialDiagnosticAt &Note : Notes) 15533 Diag(Note.first, Note.second); 15534 15535 if (Result) 15536 *Result = EvalResult.Val.getInt(); 15537 return E; 15538 } 15539 15540 namespace { 15541 // Handle the case where we conclude a expression which we speculatively 15542 // considered to be unevaluated is actually evaluated. 15543 class TransformToPE : public TreeTransform<TransformToPE> { 15544 typedef TreeTransform<TransformToPE> BaseTransform; 15545 15546 public: 15547 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15548 15549 // Make sure we redo semantic analysis 15550 bool AlwaysRebuild() { return true; } 15551 bool ReplacingOriginal() { return true; } 15552 15553 // We need to special-case DeclRefExprs referring to FieldDecls which 15554 // are not part of a member pointer formation; normal TreeTransforming 15555 // doesn't catch this case because of the way we represent them in the AST. 15556 // FIXME: This is a bit ugly; is it really the best way to handle this 15557 // case? 15558 // 15559 // Error on DeclRefExprs referring to FieldDecls. 15560 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15561 if (isa<FieldDecl>(E->getDecl()) && 15562 !SemaRef.isUnevaluatedContext()) 15563 return SemaRef.Diag(E->getLocation(), 15564 diag::err_invalid_non_static_member_use) 15565 << E->getDecl() << E->getSourceRange(); 15566 15567 return BaseTransform::TransformDeclRefExpr(E); 15568 } 15569 15570 // Exception: filter out member pointer formation 15571 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15572 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15573 return E; 15574 15575 return BaseTransform::TransformUnaryOperator(E); 15576 } 15577 15578 // The body of a lambda-expression is in a separate expression evaluation 15579 // context so never needs to be transformed. 15580 // FIXME: Ideally we wouldn't transform the closure type either, and would 15581 // just recreate the capture expressions and lambda expression. 15582 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15583 return SkipLambdaBody(E, Body); 15584 } 15585 }; 15586 } 15587 15588 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15589 assert(isUnevaluatedContext() && 15590 "Should only transform unevaluated expressions"); 15591 ExprEvalContexts.back().Context = 15592 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15593 if (isUnevaluatedContext()) 15594 return E; 15595 return TransformToPE(*this).TransformExpr(E); 15596 } 15597 15598 void 15599 Sema::PushExpressionEvaluationContext( 15600 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15601 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15602 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15603 LambdaContextDecl, ExprContext); 15604 Cleanup.reset(); 15605 if (!MaybeODRUseExprs.empty()) 15606 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15607 } 15608 15609 void 15610 Sema::PushExpressionEvaluationContext( 15611 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15612 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15613 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15614 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15615 } 15616 15617 namespace { 15618 15619 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15620 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15621 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15622 if (E->getOpcode() == UO_Deref) 15623 return CheckPossibleDeref(S, E->getSubExpr()); 15624 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15625 return CheckPossibleDeref(S, E->getBase()); 15626 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15627 return CheckPossibleDeref(S, E->getBase()); 15628 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15629 QualType Inner; 15630 QualType Ty = E->getType(); 15631 if (const auto *Ptr = Ty->getAs<PointerType>()) 15632 Inner = Ptr->getPointeeType(); 15633 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15634 Inner = Arr->getElementType(); 15635 else 15636 return nullptr; 15637 15638 if (Inner->hasAttr(attr::NoDeref)) 15639 return E; 15640 } 15641 return nullptr; 15642 } 15643 15644 } // namespace 15645 15646 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15647 for (const Expr *E : Rec.PossibleDerefs) { 15648 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15649 if (DeclRef) { 15650 const ValueDecl *Decl = DeclRef->getDecl(); 15651 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15652 << Decl->getName() << E->getSourceRange(); 15653 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15654 } else { 15655 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15656 << E->getSourceRange(); 15657 } 15658 } 15659 Rec.PossibleDerefs.clear(); 15660 } 15661 15662 /// Check whether E, which is either a discarded-value expression or an 15663 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15664 /// and if so, remove it from the list of volatile-qualified assignments that 15665 /// we are going to warn are deprecated. 15666 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15667 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15668 return; 15669 15670 // Note: ignoring parens here is not justified by the standard rules, but 15671 // ignoring parentheses seems like a more reasonable approach, and this only 15672 // drives a deprecation warning so doesn't affect conformance. 15673 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15674 if (BO->getOpcode() == BO_Assign) { 15675 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15676 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15677 LHSs.end()); 15678 } 15679 } 15680 } 15681 15682 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15683 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15684 RebuildingImmediateInvocation) 15685 return E; 15686 15687 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15688 /// It's OK if this fails; we'll also remove this in 15689 /// HandleImmediateInvocations, but catching it here allows us to avoid 15690 /// walking the AST looking for it in simple cases. 15691 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15692 if (auto *DeclRef = 15693 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15694 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15695 15696 E = MaybeCreateExprWithCleanups(E); 15697 15698 ConstantExpr *Res = ConstantExpr::Create( 15699 getASTContext(), E.get(), 15700 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15701 getASTContext()), 15702 /*IsImmediateInvocation*/ true); 15703 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15704 return Res; 15705 } 15706 15707 static void EvaluateAndDiagnoseImmediateInvocation( 15708 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15709 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15710 Expr::EvalResult Eval; 15711 Eval.Diag = &Notes; 15712 ConstantExpr *CE = Candidate.getPointer(); 15713 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15714 SemaRef.getASTContext(), true); 15715 if (!Result || !Notes.empty()) { 15716 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15717 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 15718 InnerExpr = FunctionalCast->getSubExpr(); 15719 FunctionDecl *FD = nullptr; 15720 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15721 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15722 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15723 FD = Call->getConstructor(); 15724 else 15725 llvm_unreachable("unhandled decl kind"); 15726 assert(FD->isConsteval()); 15727 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15728 for (auto &Note : Notes) 15729 SemaRef.Diag(Note.first, Note.second); 15730 return; 15731 } 15732 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15733 } 15734 15735 static void RemoveNestedImmediateInvocation( 15736 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15737 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15738 struct ComplexRemove : TreeTransform<ComplexRemove> { 15739 using Base = TreeTransform<ComplexRemove>; 15740 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15741 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15742 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15743 CurrentII; 15744 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15745 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15746 SmallVector<Sema::ImmediateInvocationCandidate, 15747 4>::reverse_iterator Current) 15748 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15749 void RemoveImmediateInvocation(ConstantExpr* E) { 15750 auto It = std::find_if(CurrentII, IISet.rend(), 15751 [E](Sema::ImmediateInvocationCandidate Elem) { 15752 return Elem.getPointer() == E; 15753 }); 15754 assert(It != IISet.rend() && 15755 "ConstantExpr marked IsImmediateInvocation should " 15756 "be present"); 15757 It->setInt(1); // Mark as deleted 15758 } 15759 ExprResult TransformConstantExpr(ConstantExpr *E) { 15760 if (!E->isImmediateInvocation()) 15761 return Base::TransformConstantExpr(E); 15762 RemoveImmediateInvocation(E); 15763 return Base::TransformExpr(E->getSubExpr()); 15764 } 15765 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15766 /// we need to remove its DeclRefExpr from the DRSet. 15767 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15768 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15769 return Base::TransformCXXOperatorCallExpr(E); 15770 } 15771 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15772 /// here. 15773 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15774 if (!Init) 15775 return Init; 15776 /// ConstantExpr are the first layer of implicit node to be removed so if 15777 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15778 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 15779 if (CE->isImmediateInvocation()) 15780 RemoveImmediateInvocation(CE); 15781 return Base::TransformInitializer(Init, NotCopyInit); 15782 } 15783 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15784 DRSet.erase(E); 15785 return E; 15786 } 15787 bool AlwaysRebuild() { return false; } 15788 bool ReplacingOriginal() { return true; } 15789 bool AllowSkippingCXXConstructExpr() { 15790 bool Res = AllowSkippingFirstCXXConstructExpr; 15791 AllowSkippingFirstCXXConstructExpr = true; 15792 return Res; 15793 } 15794 bool AllowSkippingFirstCXXConstructExpr = true; 15795 } Transformer(SemaRef, Rec.ReferenceToConsteval, 15796 Rec.ImmediateInvocationCandidates, It); 15797 15798 /// CXXConstructExpr with a single argument are getting skipped by 15799 /// TreeTransform in some situtation because they could be implicit. This 15800 /// can only occur for the top-level CXXConstructExpr because it is used 15801 /// nowhere in the expression being transformed therefore will not be rebuilt. 15802 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 15803 /// skipping the first CXXConstructExpr. 15804 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 15805 Transformer.AllowSkippingFirstCXXConstructExpr = false; 15806 15807 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 15808 assert(Res.isUsable()); 15809 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 15810 It->getPointer()->setSubExpr(Res.get()); 15811 } 15812 15813 static void 15814 HandleImmediateInvocations(Sema &SemaRef, 15815 Sema::ExpressionEvaluationContextRecord &Rec) { 15816 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 15817 Rec.ReferenceToConsteval.size() == 0) || 15818 SemaRef.RebuildingImmediateInvocation) 15819 return; 15820 15821 /// When we have more then 1 ImmediateInvocationCandidates we need to check 15822 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 15823 /// need to remove ReferenceToConsteval in the immediate invocation. 15824 if (Rec.ImmediateInvocationCandidates.size() > 1) { 15825 15826 /// Prevent sema calls during the tree transform from adding pointers that 15827 /// are already in the sets. 15828 llvm::SaveAndRestore<bool> DisableIITracking( 15829 SemaRef.RebuildingImmediateInvocation, true); 15830 15831 /// Prevent diagnostic during tree transfrom as they are duplicates 15832 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 15833 15834 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 15835 It != Rec.ImmediateInvocationCandidates.rend(); It++) 15836 if (!It->getInt()) 15837 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 15838 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 15839 Rec.ReferenceToConsteval.size()) { 15840 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 15841 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15842 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 15843 bool VisitDeclRefExpr(DeclRefExpr *E) { 15844 DRSet.erase(E); 15845 return DRSet.size(); 15846 } 15847 } Visitor(Rec.ReferenceToConsteval); 15848 Visitor.TraverseStmt( 15849 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 15850 } 15851 for (auto CE : Rec.ImmediateInvocationCandidates) 15852 if (!CE.getInt()) 15853 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 15854 for (auto DR : Rec.ReferenceToConsteval) { 15855 auto *FD = cast<FunctionDecl>(DR->getDecl()); 15856 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 15857 << FD; 15858 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 15859 } 15860 } 15861 15862 void Sema::PopExpressionEvaluationContext() { 15863 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15864 unsigned NumTypos = Rec.NumTypos; 15865 15866 if (!Rec.Lambdas.empty()) { 15867 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15868 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15869 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15870 unsigned D; 15871 if (Rec.isUnevaluated()) { 15872 // C++11 [expr.prim.lambda]p2: 15873 // A lambda-expression shall not appear in an unevaluated operand 15874 // (Clause 5). 15875 D = diag::err_lambda_unevaluated_operand; 15876 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15877 // C++1y [expr.const]p2: 15878 // A conditional-expression e is a core constant expression unless the 15879 // evaluation of e, following the rules of the abstract machine, would 15880 // evaluate [...] a lambda-expression. 15881 D = diag::err_lambda_in_constant_expression; 15882 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15883 // C++17 [expr.prim.lamda]p2: 15884 // A lambda-expression shall not appear [...] in a template-argument. 15885 D = diag::err_lambda_in_invalid_context; 15886 } else 15887 llvm_unreachable("Couldn't infer lambda error message."); 15888 15889 for (const auto *L : Rec.Lambdas) 15890 Diag(L->getBeginLoc(), D); 15891 } 15892 } 15893 15894 WarnOnPendingNoDerefs(Rec); 15895 HandleImmediateInvocations(*this, Rec); 15896 15897 // Warn on any volatile-qualified simple-assignments that are not discarded- 15898 // value expressions nor unevaluated operands (those cases get removed from 15899 // this list by CheckUnusedVolatileAssignment). 15900 for (auto *BO : Rec.VolatileAssignmentLHSs) 15901 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15902 << BO->getType(); 15903 15904 // When are coming out of an unevaluated context, clear out any 15905 // temporaries that we may have created as part of the evaluation of 15906 // the expression in that context: they aren't relevant because they 15907 // will never be constructed. 15908 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15909 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15910 ExprCleanupObjects.end()); 15911 Cleanup = Rec.ParentCleanup; 15912 CleanupVarDeclMarking(); 15913 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15914 // Otherwise, merge the contexts together. 15915 } else { 15916 Cleanup.mergeFrom(Rec.ParentCleanup); 15917 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15918 Rec.SavedMaybeODRUseExprs.end()); 15919 } 15920 15921 // Pop the current expression evaluation context off the stack. 15922 ExprEvalContexts.pop_back(); 15923 15924 // The global expression evaluation context record is never popped. 15925 ExprEvalContexts.back().NumTypos += NumTypos; 15926 } 15927 15928 void Sema::DiscardCleanupsInEvaluationContext() { 15929 ExprCleanupObjects.erase( 15930 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15931 ExprCleanupObjects.end()); 15932 Cleanup.reset(); 15933 MaybeODRUseExprs.clear(); 15934 } 15935 15936 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15937 ExprResult Result = CheckPlaceholderExpr(E); 15938 if (Result.isInvalid()) 15939 return ExprError(); 15940 E = Result.get(); 15941 if (!E->getType()->isVariablyModifiedType()) 15942 return E; 15943 return TransformToPotentiallyEvaluated(E); 15944 } 15945 15946 /// Are we in a context that is potentially constant evaluated per C++20 15947 /// [expr.const]p12? 15948 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15949 /// C++2a [expr.const]p12: 15950 // An expression or conversion is potentially constant evaluated if it is 15951 switch (SemaRef.ExprEvalContexts.back().Context) { 15952 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15953 // -- a manifestly constant-evaluated expression, 15954 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15955 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15956 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15957 // -- a potentially-evaluated expression, 15958 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15959 // -- an immediate subexpression of a braced-init-list, 15960 15961 // -- [FIXME] an expression of the form & cast-expression that occurs 15962 // within a templated entity 15963 // -- a subexpression of one of the above that is not a subexpression of 15964 // a nested unevaluated operand. 15965 return true; 15966 15967 case Sema::ExpressionEvaluationContext::Unevaluated: 15968 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15969 // Expressions in this context are never evaluated. 15970 return false; 15971 } 15972 llvm_unreachable("Invalid context"); 15973 } 15974 15975 /// Return true if this function has a calling convention that requires mangling 15976 /// in the size of the parameter pack. 15977 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15978 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15979 // we don't need parameter type sizes. 15980 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15981 if (!TT.isOSWindows() || !TT.isX86()) 15982 return false; 15983 15984 // If this is C++ and this isn't an extern "C" function, parameters do not 15985 // need to be complete. In this case, C++ mangling will apply, which doesn't 15986 // use the size of the parameters. 15987 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15988 return false; 15989 15990 // Stdcall, fastcall, and vectorcall need this special treatment. 15991 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15992 switch (CC) { 15993 case CC_X86StdCall: 15994 case CC_X86FastCall: 15995 case CC_X86VectorCall: 15996 return true; 15997 default: 15998 break; 15999 } 16000 return false; 16001 } 16002 16003 /// Require that all of the parameter types of function be complete. Normally, 16004 /// parameter types are only required to be complete when a function is called 16005 /// or defined, but to mangle functions with certain calling conventions, the 16006 /// mangler needs to know the size of the parameter list. In this situation, 16007 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16008 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16009 /// result in a linker error. Clang doesn't implement this behavior, and instead 16010 /// attempts to error at compile time. 16011 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16012 SourceLocation Loc) { 16013 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16014 FunctionDecl *FD; 16015 ParmVarDecl *Param; 16016 16017 public: 16018 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16019 : FD(FD), Param(Param) {} 16020 16021 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16022 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16023 StringRef CCName; 16024 switch (CC) { 16025 case CC_X86StdCall: 16026 CCName = "stdcall"; 16027 break; 16028 case CC_X86FastCall: 16029 CCName = "fastcall"; 16030 break; 16031 case CC_X86VectorCall: 16032 CCName = "vectorcall"; 16033 break; 16034 default: 16035 llvm_unreachable("CC does not need mangling"); 16036 } 16037 16038 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16039 << Param->getDeclName() << FD->getDeclName() << CCName; 16040 } 16041 }; 16042 16043 for (ParmVarDecl *Param : FD->parameters()) { 16044 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16045 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16046 } 16047 } 16048 16049 namespace { 16050 enum class OdrUseContext { 16051 /// Declarations in this context are not odr-used. 16052 None, 16053 /// Declarations in this context are formally odr-used, but this is a 16054 /// dependent context. 16055 Dependent, 16056 /// Declarations in this context are odr-used but not actually used (yet). 16057 FormallyOdrUsed, 16058 /// Declarations in this context are used. 16059 Used 16060 }; 16061 } 16062 16063 /// Are we within a context in which references to resolved functions or to 16064 /// variables result in odr-use? 16065 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16066 OdrUseContext Result; 16067 16068 switch (SemaRef.ExprEvalContexts.back().Context) { 16069 case Sema::ExpressionEvaluationContext::Unevaluated: 16070 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16071 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16072 return OdrUseContext::None; 16073 16074 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16075 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16076 Result = OdrUseContext::Used; 16077 break; 16078 16079 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16080 Result = OdrUseContext::FormallyOdrUsed; 16081 break; 16082 16083 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16084 // A default argument formally results in odr-use, but doesn't actually 16085 // result in a use in any real sense until it itself is used. 16086 Result = OdrUseContext::FormallyOdrUsed; 16087 break; 16088 } 16089 16090 if (SemaRef.CurContext->isDependentContext()) 16091 return OdrUseContext::Dependent; 16092 16093 return Result; 16094 } 16095 16096 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16097 return Func->isConstexpr() && 16098 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16099 } 16100 16101 /// Mark a function referenced, and check whether it is odr-used 16102 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16103 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16104 bool MightBeOdrUse) { 16105 assert(Func && "No function?"); 16106 16107 Func->setReferenced(); 16108 16109 // Recursive functions aren't really used until they're used from some other 16110 // context. 16111 bool IsRecursiveCall = CurContext == Func; 16112 16113 // C++11 [basic.def.odr]p3: 16114 // A function whose name appears as a potentially-evaluated expression is 16115 // odr-used if it is the unique lookup result or the selected member of a 16116 // set of overloaded functions [...]. 16117 // 16118 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16119 // can just check that here. 16120 OdrUseContext OdrUse = 16121 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16122 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16123 OdrUse = OdrUseContext::FormallyOdrUsed; 16124 16125 // Trivial default constructors and destructors are never actually used. 16126 // FIXME: What about other special members? 16127 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16128 OdrUse == OdrUseContext::Used) { 16129 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16130 if (Constructor->isDefaultConstructor()) 16131 OdrUse = OdrUseContext::FormallyOdrUsed; 16132 if (isa<CXXDestructorDecl>(Func)) 16133 OdrUse = OdrUseContext::FormallyOdrUsed; 16134 } 16135 16136 // C++20 [expr.const]p12: 16137 // A function [...] is needed for constant evaluation if it is [...] a 16138 // constexpr function that is named by an expression that is potentially 16139 // constant evaluated 16140 bool NeededForConstantEvaluation = 16141 isPotentiallyConstantEvaluatedContext(*this) && 16142 isImplicitlyDefinableConstexprFunction(Func); 16143 16144 // Determine whether we require a function definition to exist, per 16145 // C++11 [temp.inst]p3: 16146 // Unless a function template specialization has been explicitly 16147 // instantiated or explicitly specialized, the function template 16148 // specialization is implicitly instantiated when the specialization is 16149 // referenced in a context that requires a function definition to exist. 16150 // C++20 [temp.inst]p7: 16151 // The existence of a definition of a [...] function is considered to 16152 // affect the semantics of the program if the [...] function is needed for 16153 // constant evaluation by an expression 16154 // C++20 [basic.def.odr]p10: 16155 // Every program shall contain exactly one definition of every non-inline 16156 // function or variable that is odr-used in that program outside of a 16157 // discarded statement 16158 // C++20 [special]p1: 16159 // The implementation will implicitly define [defaulted special members] 16160 // if they are odr-used or needed for constant evaluation. 16161 // 16162 // Note that we skip the implicit instantiation of templates that are only 16163 // used in unused default arguments or by recursive calls to themselves. 16164 // This is formally non-conforming, but seems reasonable in practice. 16165 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16166 NeededForConstantEvaluation); 16167 16168 // C++14 [temp.expl.spec]p6: 16169 // If a template [...] is explicitly specialized then that specialization 16170 // shall be declared before the first use of that specialization that would 16171 // cause an implicit instantiation to take place, in every translation unit 16172 // in which such a use occurs 16173 if (NeedDefinition && 16174 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16175 Func->getMemberSpecializationInfo())) 16176 checkSpecializationVisibility(Loc, Func); 16177 16178 if (getLangOpts().CUDA) 16179 CheckCUDACall(Loc, Func); 16180 16181 // If we need a definition, try to create one. 16182 if (NeedDefinition && !Func->getBody()) { 16183 runWithSufficientStackSpace(Loc, [&] { 16184 if (CXXConstructorDecl *Constructor = 16185 dyn_cast<CXXConstructorDecl>(Func)) { 16186 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16187 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16188 if (Constructor->isDefaultConstructor()) { 16189 if (Constructor->isTrivial() && 16190 !Constructor->hasAttr<DLLExportAttr>()) 16191 return; 16192 DefineImplicitDefaultConstructor(Loc, Constructor); 16193 } else if (Constructor->isCopyConstructor()) { 16194 DefineImplicitCopyConstructor(Loc, Constructor); 16195 } else if (Constructor->isMoveConstructor()) { 16196 DefineImplicitMoveConstructor(Loc, Constructor); 16197 } 16198 } else if (Constructor->getInheritedConstructor()) { 16199 DefineInheritingConstructor(Loc, Constructor); 16200 } 16201 } else if (CXXDestructorDecl *Destructor = 16202 dyn_cast<CXXDestructorDecl>(Func)) { 16203 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16204 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16205 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16206 return; 16207 DefineImplicitDestructor(Loc, Destructor); 16208 } 16209 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16210 MarkVTableUsed(Loc, Destructor->getParent()); 16211 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16212 if (MethodDecl->isOverloadedOperator() && 16213 MethodDecl->getOverloadedOperator() == OO_Equal) { 16214 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16215 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16216 if (MethodDecl->isCopyAssignmentOperator()) 16217 DefineImplicitCopyAssignment(Loc, MethodDecl); 16218 else if (MethodDecl->isMoveAssignmentOperator()) 16219 DefineImplicitMoveAssignment(Loc, MethodDecl); 16220 } 16221 } else if (isa<CXXConversionDecl>(MethodDecl) && 16222 MethodDecl->getParent()->isLambda()) { 16223 CXXConversionDecl *Conversion = 16224 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16225 if (Conversion->isLambdaToBlockPointerConversion()) 16226 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16227 else 16228 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16229 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16230 MarkVTableUsed(Loc, MethodDecl->getParent()); 16231 } 16232 16233 if (Func->isDefaulted() && !Func->isDeleted()) { 16234 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16235 if (DCK != DefaultedComparisonKind::None) 16236 DefineDefaultedComparison(Loc, Func, DCK); 16237 } 16238 16239 // Implicit instantiation of function templates and member functions of 16240 // class templates. 16241 if (Func->isImplicitlyInstantiable()) { 16242 TemplateSpecializationKind TSK = 16243 Func->getTemplateSpecializationKindForInstantiation(); 16244 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16245 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16246 if (FirstInstantiation) { 16247 PointOfInstantiation = Loc; 16248 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16249 } else if (TSK != TSK_ImplicitInstantiation) { 16250 // Use the point of use as the point of instantiation, instead of the 16251 // point of explicit instantiation (which we track as the actual point 16252 // of instantiation). This gives better backtraces in diagnostics. 16253 PointOfInstantiation = Loc; 16254 } 16255 16256 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16257 Func->isConstexpr()) { 16258 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16259 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16260 CodeSynthesisContexts.size()) 16261 PendingLocalImplicitInstantiations.push_back( 16262 std::make_pair(Func, PointOfInstantiation)); 16263 else if (Func->isConstexpr()) 16264 // Do not defer instantiations of constexpr functions, to avoid the 16265 // expression evaluator needing to call back into Sema if it sees a 16266 // call to such a function. 16267 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16268 else { 16269 Func->setInstantiationIsPending(true); 16270 PendingInstantiations.push_back( 16271 std::make_pair(Func, PointOfInstantiation)); 16272 // Notify the consumer that a function was implicitly instantiated. 16273 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16274 } 16275 } 16276 } else { 16277 // Walk redefinitions, as some of them may be instantiable. 16278 for (auto i : Func->redecls()) { 16279 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16280 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16281 } 16282 } 16283 }); 16284 } 16285 16286 // C++14 [except.spec]p17: 16287 // An exception-specification is considered to be needed when: 16288 // - the function is odr-used or, if it appears in an unevaluated operand, 16289 // would be odr-used if the expression were potentially-evaluated; 16290 // 16291 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16292 // function is a pure virtual function we're calling, and in that case the 16293 // function was selected by overload resolution and we need to resolve its 16294 // exception specification for a different reason. 16295 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16296 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16297 ResolveExceptionSpec(Loc, FPT); 16298 16299 // If this is the first "real" use, act on that. 16300 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16301 // Keep track of used but undefined functions. 16302 if (!Func->isDefined()) { 16303 if (mightHaveNonExternalLinkage(Func)) 16304 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16305 else if (Func->getMostRecentDecl()->isInlined() && 16306 !LangOpts.GNUInline && 16307 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16308 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16309 else if (isExternalWithNoLinkageType(Func)) 16310 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16311 } 16312 16313 // Some x86 Windows calling conventions mangle the size of the parameter 16314 // pack into the name. Computing the size of the parameters requires the 16315 // parameter types to be complete. Check that now. 16316 if (funcHasParameterSizeMangling(*this, Func)) 16317 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16318 16319 Func->markUsed(Context); 16320 } 16321 } 16322 16323 /// Directly mark a variable odr-used. Given a choice, prefer to use 16324 /// MarkVariableReferenced since it does additional checks and then 16325 /// calls MarkVarDeclODRUsed. 16326 /// If the variable must be captured: 16327 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16328 /// - else capture it in the DeclContext that maps to the 16329 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16330 static void 16331 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16332 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16333 // Keep track of used but undefined variables. 16334 // FIXME: We shouldn't suppress this warning for static data members. 16335 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16336 (!Var->isExternallyVisible() || Var->isInline() || 16337 SemaRef.isExternalWithNoLinkageType(Var)) && 16338 !(Var->isStaticDataMember() && Var->hasInit())) { 16339 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16340 if (old.isInvalid()) 16341 old = Loc; 16342 } 16343 QualType CaptureType, DeclRefType; 16344 if (SemaRef.LangOpts.OpenMP) 16345 SemaRef.tryCaptureOpenMPLambdas(Var); 16346 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16347 /*EllipsisLoc*/ SourceLocation(), 16348 /*BuildAndDiagnose*/ true, 16349 CaptureType, DeclRefType, 16350 FunctionScopeIndexToStopAt); 16351 16352 Var->markUsed(SemaRef.Context); 16353 } 16354 16355 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16356 SourceLocation Loc, 16357 unsigned CapturingScopeIndex) { 16358 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16359 } 16360 16361 static void 16362 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16363 ValueDecl *var, DeclContext *DC) { 16364 DeclContext *VarDC = var->getDeclContext(); 16365 16366 // If the parameter still belongs to the translation unit, then 16367 // we're actually just using one parameter in the declaration of 16368 // the next. 16369 if (isa<ParmVarDecl>(var) && 16370 isa<TranslationUnitDecl>(VarDC)) 16371 return; 16372 16373 // For C code, don't diagnose about capture if we're not actually in code 16374 // right now; it's impossible to write a non-constant expression outside of 16375 // function context, so we'll get other (more useful) diagnostics later. 16376 // 16377 // For C++, things get a bit more nasty... it would be nice to suppress this 16378 // diagnostic for certain cases like using a local variable in an array bound 16379 // for a member of a local class, but the correct predicate is not obvious. 16380 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16381 return; 16382 16383 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16384 unsigned ContextKind = 3; // unknown 16385 if (isa<CXXMethodDecl>(VarDC) && 16386 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16387 ContextKind = 2; 16388 } else if (isa<FunctionDecl>(VarDC)) { 16389 ContextKind = 0; 16390 } else if (isa<BlockDecl>(VarDC)) { 16391 ContextKind = 1; 16392 } 16393 16394 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16395 << var << ValueKind << ContextKind << VarDC; 16396 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16397 << var; 16398 16399 // FIXME: Add additional diagnostic info about class etc. which prevents 16400 // capture. 16401 } 16402 16403 16404 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16405 bool &SubCapturesAreNested, 16406 QualType &CaptureType, 16407 QualType &DeclRefType) { 16408 // Check whether we've already captured it. 16409 if (CSI->CaptureMap.count(Var)) { 16410 // If we found a capture, any subcaptures are nested. 16411 SubCapturesAreNested = true; 16412 16413 // Retrieve the capture type for this variable. 16414 CaptureType = CSI->getCapture(Var).getCaptureType(); 16415 16416 // Compute the type of an expression that refers to this variable. 16417 DeclRefType = CaptureType.getNonReferenceType(); 16418 16419 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16420 // are mutable in the sense that user can change their value - they are 16421 // private instances of the captured declarations. 16422 const Capture &Cap = CSI->getCapture(Var); 16423 if (Cap.isCopyCapture() && 16424 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16425 !(isa<CapturedRegionScopeInfo>(CSI) && 16426 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16427 DeclRefType.addConst(); 16428 return true; 16429 } 16430 return false; 16431 } 16432 16433 // Only block literals, captured statements, and lambda expressions can 16434 // capture; other scopes don't work. 16435 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16436 SourceLocation Loc, 16437 const bool Diagnose, Sema &S) { 16438 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16439 return getLambdaAwareParentOfDeclContext(DC); 16440 else if (Var->hasLocalStorage()) { 16441 if (Diagnose) 16442 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16443 } 16444 return nullptr; 16445 } 16446 16447 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16448 // certain types of variables (unnamed, variably modified types etc.) 16449 // so check for eligibility. 16450 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16451 SourceLocation Loc, 16452 const bool Diagnose, Sema &S) { 16453 16454 bool IsBlock = isa<BlockScopeInfo>(CSI); 16455 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16456 16457 // Lambdas are not allowed to capture unnamed variables 16458 // (e.g. anonymous unions). 16459 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16460 // assuming that's the intent. 16461 if (IsLambda && !Var->getDeclName()) { 16462 if (Diagnose) { 16463 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16464 S.Diag(Var->getLocation(), diag::note_declared_at); 16465 } 16466 return false; 16467 } 16468 16469 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16470 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16471 if (Diagnose) { 16472 S.Diag(Loc, diag::err_ref_vm_type); 16473 S.Diag(Var->getLocation(), diag::note_previous_decl) 16474 << Var->getDeclName(); 16475 } 16476 return false; 16477 } 16478 // Prohibit structs with flexible array members too. 16479 // We cannot capture what is in the tail end of the struct. 16480 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16481 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16482 if (Diagnose) { 16483 if (IsBlock) 16484 S.Diag(Loc, diag::err_ref_flexarray_type); 16485 else 16486 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16487 << Var->getDeclName(); 16488 S.Diag(Var->getLocation(), diag::note_previous_decl) 16489 << Var->getDeclName(); 16490 } 16491 return false; 16492 } 16493 } 16494 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16495 // Lambdas and captured statements are not allowed to capture __block 16496 // variables; they don't support the expected semantics. 16497 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16498 if (Diagnose) { 16499 S.Diag(Loc, diag::err_capture_block_variable) 16500 << Var->getDeclName() << !IsLambda; 16501 S.Diag(Var->getLocation(), diag::note_previous_decl) 16502 << Var->getDeclName(); 16503 } 16504 return false; 16505 } 16506 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16507 if (S.getLangOpts().OpenCL && IsBlock && 16508 Var->getType()->isBlockPointerType()) { 16509 if (Diagnose) 16510 S.Diag(Loc, diag::err_opencl_block_ref_block); 16511 return false; 16512 } 16513 16514 return true; 16515 } 16516 16517 // Returns true if the capture by block was successful. 16518 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16519 SourceLocation Loc, 16520 const bool BuildAndDiagnose, 16521 QualType &CaptureType, 16522 QualType &DeclRefType, 16523 const bool Nested, 16524 Sema &S, bool Invalid) { 16525 bool ByRef = false; 16526 16527 // Blocks are not allowed to capture arrays, excepting OpenCL. 16528 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16529 // (decayed to pointers). 16530 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16531 if (BuildAndDiagnose) { 16532 S.Diag(Loc, diag::err_ref_array_type); 16533 S.Diag(Var->getLocation(), diag::note_previous_decl) 16534 << Var->getDeclName(); 16535 Invalid = true; 16536 } else { 16537 return false; 16538 } 16539 } 16540 16541 // Forbid the block-capture of autoreleasing variables. 16542 if (!Invalid && 16543 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16544 if (BuildAndDiagnose) { 16545 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16546 << /*block*/ 0; 16547 S.Diag(Var->getLocation(), diag::note_previous_decl) 16548 << Var->getDeclName(); 16549 Invalid = true; 16550 } else { 16551 return false; 16552 } 16553 } 16554 16555 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16556 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16557 QualType PointeeTy = PT->getPointeeType(); 16558 16559 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16560 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16561 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16562 if (BuildAndDiagnose) { 16563 SourceLocation VarLoc = Var->getLocation(); 16564 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16565 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16566 } 16567 } 16568 } 16569 16570 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16571 if (HasBlocksAttr || CaptureType->isReferenceType() || 16572 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16573 // Block capture by reference does not change the capture or 16574 // declaration reference types. 16575 ByRef = true; 16576 } else { 16577 // Block capture by copy introduces 'const'. 16578 CaptureType = CaptureType.getNonReferenceType().withConst(); 16579 DeclRefType = CaptureType; 16580 } 16581 16582 // Actually capture the variable. 16583 if (BuildAndDiagnose) 16584 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16585 CaptureType, Invalid); 16586 16587 return !Invalid; 16588 } 16589 16590 16591 /// Capture the given variable in the captured region. 16592 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16593 VarDecl *Var, 16594 SourceLocation Loc, 16595 const bool BuildAndDiagnose, 16596 QualType &CaptureType, 16597 QualType &DeclRefType, 16598 const bool RefersToCapturedVariable, 16599 Sema &S, bool Invalid) { 16600 // By default, capture variables by reference. 16601 bool ByRef = true; 16602 // Using an LValue reference type is consistent with Lambdas (see below). 16603 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16604 if (S.isOpenMPCapturedDecl(Var)) { 16605 bool HasConst = DeclRefType.isConstQualified(); 16606 DeclRefType = DeclRefType.getUnqualifiedType(); 16607 // Don't lose diagnostics about assignments to const. 16608 if (HasConst) 16609 DeclRefType.addConst(); 16610 } 16611 // Do not capture firstprivates in tasks. 16612 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 16613 OMPC_unknown) 16614 return true; 16615 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16616 RSI->OpenMPCaptureLevel); 16617 } 16618 16619 if (ByRef) 16620 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16621 else 16622 CaptureType = DeclRefType; 16623 16624 // Actually capture the variable. 16625 if (BuildAndDiagnose) 16626 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16627 Loc, SourceLocation(), CaptureType, Invalid); 16628 16629 return !Invalid; 16630 } 16631 16632 /// Capture the given variable in the lambda. 16633 static bool captureInLambda(LambdaScopeInfo *LSI, 16634 VarDecl *Var, 16635 SourceLocation Loc, 16636 const bool BuildAndDiagnose, 16637 QualType &CaptureType, 16638 QualType &DeclRefType, 16639 const bool RefersToCapturedVariable, 16640 const Sema::TryCaptureKind Kind, 16641 SourceLocation EllipsisLoc, 16642 const bool IsTopScope, 16643 Sema &S, bool Invalid) { 16644 // Determine whether we are capturing by reference or by value. 16645 bool ByRef = false; 16646 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16647 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16648 } else { 16649 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16650 } 16651 16652 // Compute the type of the field that will capture this variable. 16653 if (ByRef) { 16654 // C++11 [expr.prim.lambda]p15: 16655 // An entity is captured by reference if it is implicitly or 16656 // explicitly captured but not captured by copy. It is 16657 // unspecified whether additional unnamed non-static data 16658 // members are declared in the closure type for entities 16659 // captured by reference. 16660 // 16661 // FIXME: It is not clear whether we want to build an lvalue reference 16662 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16663 // to do the former, while EDG does the latter. Core issue 1249 will 16664 // clarify, but for now we follow GCC because it's a more permissive and 16665 // easily defensible position. 16666 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16667 } else { 16668 // C++11 [expr.prim.lambda]p14: 16669 // For each entity captured by copy, an unnamed non-static 16670 // data member is declared in the closure type. The 16671 // declaration order of these members is unspecified. The type 16672 // of such a data member is the type of the corresponding 16673 // captured entity if the entity is not a reference to an 16674 // object, or the referenced type otherwise. [Note: If the 16675 // captured entity is a reference to a function, the 16676 // corresponding data member is also a reference to a 16677 // function. - end note ] 16678 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16679 if (!RefType->getPointeeType()->isFunctionType()) 16680 CaptureType = RefType->getPointeeType(); 16681 } 16682 16683 // Forbid the lambda copy-capture of autoreleasing variables. 16684 if (!Invalid && 16685 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16686 if (BuildAndDiagnose) { 16687 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16688 S.Diag(Var->getLocation(), diag::note_previous_decl) 16689 << Var->getDeclName(); 16690 Invalid = true; 16691 } else { 16692 return false; 16693 } 16694 } 16695 16696 // Make sure that by-copy captures are of a complete and non-abstract type. 16697 if (!Invalid && BuildAndDiagnose) { 16698 if (!CaptureType->isDependentType() && 16699 S.RequireCompleteSizedType( 16700 Loc, CaptureType, 16701 diag::err_capture_of_incomplete_or_sizeless_type, 16702 Var->getDeclName())) 16703 Invalid = true; 16704 else if (S.RequireNonAbstractType(Loc, CaptureType, 16705 diag::err_capture_of_abstract_type)) 16706 Invalid = true; 16707 } 16708 } 16709 16710 // Compute the type of a reference to this captured variable. 16711 if (ByRef) 16712 DeclRefType = CaptureType.getNonReferenceType(); 16713 else { 16714 // C++ [expr.prim.lambda]p5: 16715 // The closure type for a lambda-expression has a public inline 16716 // function call operator [...]. This function call operator is 16717 // declared const (9.3.1) if and only if the lambda-expression's 16718 // parameter-declaration-clause is not followed by mutable. 16719 DeclRefType = CaptureType.getNonReferenceType(); 16720 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16721 DeclRefType.addConst(); 16722 } 16723 16724 // Add the capture. 16725 if (BuildAndDiagnose) 16726 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16727 Loc, EllipsisLoc, CaptureType, Invalid); 16728 16729 return !Invalid; 16730 } 16731 16732 bool Sema::tryCaptureVariable( 16733 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16734 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16735 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16736 // An init-capture is notionally from the context surrounding its 16737 // declaration, but its parent DC is the lambda class. 16738 DeclContext *VarDC = Var->getDeclContext(); 16739 if (Var->isInitCapture()) 16740 VarDC = VarDC->getParent(); 16741 16742 DeclContext *DC = CurContext; 16743 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16744 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16745 // We need to sync up the Declaration Context with the 16746 // FunctionScopeIndexToStopAt 16747 if (FunctionScopeIndexToStopAt) { 16748 unsigned FSIndex = FunctionScopes.size() - 1; 16749 while (FSIndex != MaxFunctionScopesIndex) { 16750 DC = getLambdaAwareParentOfDeclContext(DC); 16751 --FSIndex; 16752 } 16753 } 16754 16755 16756 // If the variable is declared in the current context, there is no need to 16757 // capture it. 16758 if (VarDC == DC) return true; 16759 16760 // Capture global variables if it is required to use private copy of this 16761 // variable. 16762 bool IsGlobal = !Var->hasLocalStorage(); 16763 if (IsGlobal && 16764 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16765 MaxFunctionScopesIndex))) 16766 return true; 16767 Var = Var->getCanonicalDecl(); 16768 16769 // Walk up the stack to determine whether we can capture the variable, 16770 // performing the "simple" checks that don't depend on type. We stop when 16771 // we've either hit the declared scope of the variable or find an existing 16772 // capture of that variable. We start from the innermost capturing-entity 16773 // (the DC) and ensure that all intervening capturing-entities 16774 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16775 // declcontext can either capture the variable or have already captured 16776 // the variable. 16777 CaptureType = Var->getType(); 16778 DeclRefType = CaptureType.getNonReferenceType(); 16779 bool Nested = false; 16780 bool Explicit = (Kind != TryCapture_Implicit); 16781 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16782 do { 16783 // Only block literals, captured statements, and lambda expressions can 16784 // capture; other scopes don't work. 16785 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16786 ExprLoc, 16787 BuildAndDiagnose, 16788 *this); 16789 // We need to check for the parent *first* because, if we *have* 16790 // private-captured a global variable, we need to recursively capture it in 16791 // intermediate blocks, lambdas, etc. 16792 if (!ParentDC) { 16793 if (IsGlobal) { 16794 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16795 break; 16796 } 16797 return true; 16798 } 16799 16800 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16801 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16802 16803 16804 // Check whether we've already captured it. 16805 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16806 DeclRefType)) { 16807 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16808 break; 16809 } 16810 // If we are instantiating a generic lambda call operator body, 16811 // we do not want to capture new variables. What was captured 16812 // during either a lambdas transformation or initial parsing 16813 // should be used. 16814 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16815 if (BuildAndDiagnose) { 16816 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16817 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16818 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16819 Diag(Var->getLocation(), diag::note_previous_decl) 16820 << Var->getDeclName(); 16821 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16822 } else 16823 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16824 } 16825 return true; 16826 } 16827 16828 // Try to capture variable-length arrays types. 16829 if (Var->getType()->isVariablyModifiedType()) { 16830 // We're going to walk down into the type and look for VLA 16831 // expressions. 16832 QualType QTy = Var->getType(); 16833 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16834 QTy = PVD->getOriginalType(); 16835 captureVariablyModifiedType(Context, QTy, CSI); 16836 } 16837 16838 if (getLangOpts().OpenMP) { 16839 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16840 // OpenMP private variables should not be captured in outer scope, so 16841 // just break here. Similarly, global variables that are captured in a 16842 // target region should not be captured outside the scope of the region. 16843 if (RSI->CapRegionKind == CR_OpenMP) { 16844 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 16845 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 16846 // If the variable is private (i.e. not captured) and has variably 16847 // modified type, we still need to capture the type for correct 16848 // codegen in all regions, associated with the construct. Currently, 16849 // it is captured in the innermost captured region only. 16850 if (IsOpenMPPrivateDecl != OMPC_unknown && 16851 Var->getType()->isVariablyModifiedType()) { 16852 QualType QTy = Var->getType(); 16853 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16854 QTy = PVD->getOriginalType(); 16855 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16856 I < E; ++I) { 16857 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16858 FunctionScopes[FunctionScopesIndex - I]); 16859 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16860 "Wrong number of captured regions associated with the " 16861 "OpenMP construct."); 16862 captureVariablyModifiedType(Context, QTy, OuterRSI); 16863 } 16864 } 16865 bool IsTargetCap = 16866 IsOpenMPPrivateDecl != OMPC_private && 16867 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 16868 RSI->OpenMPCaptureLevel); 16869 // Do not capture global if it is not privatized in outer regions. 16870 bool IsGlobalCap = 16871 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 16872 RSI->OpenMPCaptureLevel); 16873 16874 // When we detect target captures we are looking from inside the 16875 // target region, therefore we need to propagate the capture from the 16876 // enclosing region. Therefore, the capture is not initially nested. 16877 if (IsTargetCap) 16878 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16879 16880 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 16881 (IsGlobal && !IsGlobalCap)) { 16882 Nested = !IsTargetCap; 16883 DeclRefType = DeclRefType.getUnqualifiedType(); 16884 CaptureType = Context.getLValueReferenceType(DeclRefType); 16885 break; 16886 } 16887 } 16888 } 16889 } 16890 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16891 // No capture-default, and this is not an explicit capture 16892 // so cannot capture this variable. 16893 if (BuildAndDiagnose) { 16894 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16895 Diag(Var->getLocation(), diag::note_previous_decl) 16896 << Var->getDeclName(); 16897 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16898 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16899 diag::note_lambda_decl); 16900 // FIXME: If we error out because an outer lambda can not implicitly 16901 // capture a variable that an inner lambda explicitly captures, we 16902 // should have the inner lambda do the explicit capture - because 16903 // it makes for cleaner diagnostics later. This would purely be done 16904 // so that the diagnostic does not misleadingly claim that a variable 16905 // can not be captured by a lambda implicitly even though it is captured 16906 // explicitly. Suggestion: 16907 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16908 // at the function head 16909 // - cache the StartingDeclContext - this must be a lambda 16910 // - captureInLambda in the innermost lambda the variable. 16911 } 16912 return true; 16913 } 16914 16915 FunctionScopesIndex--; 16916 DC = ParentDC; 16917 Explicit = false; 16918 } while (!VarDC->Equals(DC)); 16919 16920 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16921 // computing the type of the capture at each step, checking type-specific 16922 // requirements, and adding captures if requested. 16923 // If the variable had already been captured previously, we start capturing 16924 // at the lambda nested within that one. 16925 bool Invalid = false; 16926 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16927 ++I) { 16928 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16929 16930 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16931 // certain types of variables (unnamed, variably modified types etc.) 16932 // so check for eligibility. 16933 if (!Invalid) 16934 Invalid = 16935 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16936 16937 // After encountering an error, if we're actually supposed to capture, keep 16938 // capturing in nested contexts to suppress any follow-on diagnostics. 16939 if (Invalid && !BuildAndDiagnose) 16940 return true; 16941 16942 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16943 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16944 DeclRefType, Nested, *this, Invalid); 16945 Nested = true; 16946 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16947 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16948 CaptureType, DeclRefType, Nested, 16949 *this, Invalid); 16950 Nested = true; 16951 } else { 16952 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16953 Invalid = 16954 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16955 DeclRefType, Nested, Kind, EllipsisLoc, 16956 /*IsTopScope*/ I == N - 1, *this, Invalid); 16957 Nested = true; 16958 } 16959 16960 if (Invalid && !BuildAndDiagnose) 16961 return true; 16962 } 16963 return Invalid; 16964 } 16965 16966 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16967 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16968 QualType CaptureType; 16969 QualType DeclRefType; 16970 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16971 /*BuildAndDiagnose=*/true, CaptureType, 16972 DeclRefType, nullptr); 16973 } 16974 16975 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16976 QualType CaptureType; 16977 QualType DeclRefType; 16978 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16979 /*BuildAndDiagnose=*/false, CaptureType, 16980 DeclRefType, nullptr); 16981 } 16982 16983 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16984 QualType CaptureType; 16985 QualType DeclRefType; 16986 16987 // Determine whether we can capture this variable. 16988 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16989 /*BuildAndDiagnose=*/false, CaptureType, 16990 DeclRefType, nullptr)) 16991 return QualType(); 16992 16993 return DeclRefType; 16994 } 16995 16996 namespace { 16997 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16998 // The produced TemplateArgumentListInfo* points to data stored within this 16999 // object, so should only be used in contexts where the pointer will not be 17000 // used after the CopiedTemplateArgs object is destroyed. 17001 class CopiedTemplateArgs { 17002 bool HasArgs; 17003 TemplateArgumentListInfo TemplateArgStorage; 17004 public: 17005 template<typename RefExpr> 17006 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17007 if (HasArgs) 17008 E->copyTemplateArgumentsInto(TemplateArgStorage); 17009 } 17010 operator TemplateArgumentListInfo*() 17011 #ifdef __has_cpp_attribute 17012 #if __has_cpp_attribute(clang::lifetimebound) 17013 [[clang::lifetimebound]] 17014 #endif 17015 #endif 17016 { 17017 return HasArgs ? &TemplateArgStorage : nullptr; 17018 } 17019 }; 17020 } 17021 17022 /// Walk the set of potential results of an expression and mark them all as 17023 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17024 /// 17025 /// \return A new expression if we found any potential results, ExprEmpty() if 17026 /// not, and ExprError() if we diagnosed an error. 17027 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17028 NonOdrUseReason NOUR) { 17029 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17030 // an object that satisfies the requirements for appearing in a 17031 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17032 // is immediately applied." This function handles the lvalue-to-rvalue 17033 // conversion part. 17034 // 17035 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17036 // transform it into the relevant kind of non-odr-use node and rebuild the 17037 // tree of nodes leading to it. 17038 // 17039 // This is a mini-TreeTransform that only transforms a restricted subset of 17040 // nodes (and only certain operands of them). 17041 17042 // Rebuild a subexpression. 17043 auto Rebuild = [&](Expr *Sub) { 17044 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17045 }; 17046 17047 // Check whether a potential result satisfies the requirements of NOUR. 17048 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17049 // Any entity other than a VarDecl is always odr-used whenever it's named 17050 // in a potentially-evaluated expression. 17051 auto *VD = dyn_cast<VarDecl>(D); 17052 if (!VD) 17053 return true; 17054 17055 // C++2a [basic.def.odr]p4: 17056 // A variable x whose name appears as a potentially-evalauted expression 17057 // e is odr-used by e unless 17058 // -- x is a reference that is usable in constant expressions, or 17059 // -- x is a variable of non-reference type that is usable in constant 17060 // expressions and has no mutable subobjects, and e is an element of 17061 // the set of potential results of an expression of 17062 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17063 // conversion is applied, or 17064 // -- x is a variable of non-reference type, and e is an element of the 17065 // set of potential results of a discarded-value expression to which 17066 // the lvalue-to-rvalue conversion is not applied 17067 // 17068 // We check the first bullet and the "potentially-evaluated" condition in 17069 // BuildDeclRefExpr. We check the type requirements in the second bullet 17070 // in CheckLValueToRValueConversionOperand below. 17071 switch (NOUR) { 17072 case NOUR_None: 17073 case NOUR_Unevaluated: 17074 llvm_unreachable("unexpected non-odr-use-reason"); 17075 17076 case NOUR_Constant: 17077 // Constant references were handled when they were built. 17078 if (VD->getType()->isReferenceType()) 17079 return true; 17080 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17081 if (RD->hasMutableFields()) 17082 return true; 17083 if (!VD->isUsableInConstantExpressions(S.Context)) 17084 return true; 17085 break; 17086 17087 case NOUR_Discarded: 17088 if (VD->getType()->isReferenceType()) 17089 return true; 17090 break; 17091 } 17092 return false; 17093 }; 17094 17095 // Mark that this expression does not constitute an odr-use. 17096 auto MarkNotOdrUsed = [&] { 17097 S.MaybeODRUseExprs.erase(E); 17098 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17099 LSI->markVariableExprAsNonODRUsed(E); 17100 }; 17101 17102 // C++2a [basic.def.odr]p2: 17103 // The set of potential results of an expression e is defined as follows: 17104 switch (E->getStmtClass()) { 17105 // -- If e is an id-expression, ... 17106 case Expr::DeclRefExprClass: { 17107 auto *DRE = cast<DeclRefExpr>(E); 17108 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17109 break; 17110 17111 // Rebuild as a non-odr-use DeclRefExpr. 17112 MarkNotOdrUsed(); 17113 return DeclRefExpr::Create( 17114 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17115 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17116 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17117 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17118 } 17119 17120 case Expr::FunctionParmPackExprClass: { 17121 auto *FPPE = cast<FunctionParmPackExpr>(E); 17122 // If any of the declarations in the pack is odr-used, then the expression 17123 // as a whole constitutes an odr-use. 17124 for (VarDecl *D : *FPPE) 17125 if (IsPotentialResultOdrUsed(D)) 17126 return ExprEmpty(); 17127 17128 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17129 // nothing cares about whether we marked this as an odr-use, but it might 17130 // be useful for non-compiler tools. 17131 MarkNotOdrUsed(); 17132 break; 17133 } 17134 17135 // -- If e is a subscripting operation with an array operand... 17136 case Expr::ArraySubscriptExprClass: { 17137 auto *ASE = cast<ArraySubscriptExpr>(E); 17138 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17139 if (!OldBase->getType()->isArrayType()) 17140 break; 17141 ExprResult Base = Rebuild(OldBase); 17142 if (!Base.isUsable()) 17143 return Base; 17144 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17145 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17146 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17147 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17148 ASE->getRBracketLoc()); 17149 } 17150 17151 case Expr::MemberExprClass: { 17152 auto *ME = cast<MemberExpr>(E); 17153 // -- If e is a class member access expression [...] naming a non-static 17154 // data member... 17155 if (isa<FieldDecl>(ME->getMemberDecl())) { 17156 ExprResult Base = Rebuild(ME->getBase()); 17157 if (!Base.isUsable()) 17158 return Base; 17159 return MemberExpr::Create( 17160 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17161 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17162 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17163 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17164 ME->getObjectKind(), ME->isNonOdrUse()); 17165 } 17166 17167 if (ME->getMemberDecl()->isCXXInstanceMember()) 17168 break; 17169 17170 // -- If e is a class member access expression naming a static data member, 17171 // ... 17172 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17173 break; 17174 17175 // Rebuild as a non-odr-use MemberExpr. 17176 MarkNotOdrUsed(); 17177 return MemberExpr::Create( 17178 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17179 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17180 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17181 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17182 return ExprEmpty(); 17183 } 17184 17185 case Expr::BinaryOperatorClass: { 17186 auto *BO = cast<BinaryOperator>(E); 17187 Expr *LHS = BO->getLHS(); 17188 Expr *RHS = BO->getRHS(); 17189 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17190 if (BO->getOpcode() == BO_PtrMemD) { 17191 ExprResult Sub = Rebuild(LHS); 17192 if (!Sub.isUsable()) 17193 return Sub; 17194 LHS = Sub.get(); 17195 // -- If e is a comma expression, ... 17196 } else if (BO->getOpcode() == BO_Comma) { 17197 ExprResult Sub = Rebuild(RHS); 17198 if (!Sub.isUsable()) 17199 return Sub; 17200 RHS = Sub.get(); 17201 } else { 17202 break; 17203 } 17204 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17205 LHS, RHS); 17206 } 17207 17208 // -- If e has the form (e1)... 17209 case Expr::ParenExprClass: { 17210 auto *PE = cast<ParenExpr>(E); 17211 ExprResult Sub = Rebuild(PE->getSubExpr()); 17212 if (!Sub.isUsable()) 17213 return Sub; 17214 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17215 } 17216 17217 // -- If e is a glvalue conditional expression, ... 17218 // We don't apply this to a binary conditional operator. FIXME: Should we? 17219 case Expr::ConditionalOperatorClass: { 17220 auto *CO = cast<ConditionalOperator>(E); 17221 ExprResult LHS = Rebuild(CO->getLHS()); 17222 if (LHS.isInvalid()) 17223 return ExprError(); 17224 ExprResult RHS = Rebuild(CO->getRHS()); 17225 if (RHS.isInvalid()) 17226 return ExprError(); 17227 if (!LHS.isUsable() && !RHS.isUsable()) 17228 return ExprEmpty(); 17229 if (!LHS.isUsable()) 17230 LHS = CO->getLHS(); 17231 if (!RHS.isUsable()) 17232 RHS = CO->getRHS(); 17233 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17234 CO->getCond(), LHS.get(), RHS.get()); 17235 } 17236 17237 // [Clang extension] 17238 // -- If e has the form __extension__ e1... 17239 case Expr::UnaryOperatorClass: { 17240 auto *UO = cast<UnaryOperator>(E); 17241 if (UO->getOpcode() != UO_Extension) 17242 break; 17243 ExprResult Sub = Rebuild(UO->getSubExpr()); 17244 if (!Sub.isUsable()) 17245 return Sub; 17246 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17247 Sub.get()); 17248 } 17249 17250 // [Clang extension] 17251 // -- If e has the form _Generic(...), the set of potential results is the 17252 // union of the sets of potential results of the associated expressions. 17253 case Expr::GenericSelectionExprClass: { 17254 auto *GSE = cast<GenericSelectionExpr>(E); 17255 17256 SmallVector<Expr *, 4> AssocExprs; 17257 bool AnyChanged = false; 17258 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17259 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17260 if (AssocExpr.isInvalid()) 17261 return ExprError(); 17262 if (AssocExpr.isUsable()) { 17263 AssocExprs.push_back(AssocExpr.get()); 17264 AnyChanged = true; 17265 } else { 17266 AssocExprs.push_back(OrigAssocExpr); 17267 } 17268 } 17269 17270 return AnyChanged ? S.CreateGenericSelectionExpr( 17271 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17272 GSE->getRParenLoc(), GSE->getControllingExpr(), 17273 GSE->getAssocTypeSourceInfos(), AssocExprs) 17274 : ExprEmpty(); 17275 } 17276 17277 // [Clang extension] 17278 // -- If e has the form __builtin_choose_expr(...), the set of potential 17279 // results is the union of the sets of potential results of the 17280 // second and third subexpressions. 17281 case Expr::ChooseExprClass: { 17282 auto *CE = cast<ChooseExpr>(E); 17283 17284 ExprResult LHS = Rebuild(CE->getLHS()); 17285 if (LHS.isInvalid()) 17286 return ExprError(); 17287 17288 ExprResult RHS = Rebuild(CE->getLHS()); 17289 if (RHS.isInvalid()) 17290 return ExprError(); 17291 17292 if (!LHS.get() && !RHS.get()) 17293 return ExprEmpty(); 17294 if (!LHS.isUsable()) 17295 LHS = CE->getLHS(); 17296 if (!RHS.isUsable()) 17297 RHS = CE->getRHS(); 17298 17299 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17300 RHS.get(), CE->getRParenLoc()); 17301 } 17302 17303 // Step through non-syntactic nodes. 17304 case Expr::ConstantExprClass: { 17305 auto *CE = cast<ConstantExpr>(E); 17306 ExprResult Sub = Rebuild(CE->getSubExpr()); 17307 if (!Sub.isUsable()) 17308 return Sub; 17309 return ConstantExpr::Create(S.Context, Sub.get()); 17310 } 17311 17312 // We could mostly rely on the recursive rebuilding to rebuild implicit 17313 // casts, but not at the top level, so rebuild them here. 17314 case Expr::ImplicitCastExprClass: { 17315 auto *ICE = cast<ImplicitCastExpr>(E); 17316 // Only step through the narrow set of cast kinds we expect to encounter. 17317 // Anything else suggests we've left the region in which potential results 17318 // can be found. 17319 switch (ICE->getCastKind()) { 17320 case CK_NoOp: 17321 case CK_DerivedToBase: 17322 case CK_UncheckedDerivedToBase: { 17323 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17324 if (!Sub.isUsable()) 17325 return Sub; 17326 CXXCastPath Path(ICE->path()); 17327 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17328 ICE->getValueKind(), &Path); 17329 } 17330 17331 default: 17332 break; 17333 } 17334 break; 17335 } 17336 17337 default: 17338 break; 17339 } 17340 17341 // Can't traverse through this node. Nothing to do. 17342 return ExprEmpty(); 17343 } 17344 17345 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17346 // Check whether the operand is or contains an object of non-trivial C union 17347 // type. 17348 if (E->getType().isVolatileQualified() && 17349 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17350 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17351 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17352 Sema::NTCUC_LValueToRValueVolatile, 17353 NTCUK_Destruct|NTCUK_Copy); 17354 17355 // C++2a [basic.def.odr]p4: 17356 // [...] an expression of non-volatile-qualified non-class type to which 17357 // the lvalue-to-rvalue conversion is applied [...] 17358 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17359 return E; 17360 17361 ExprResult Result = 17362 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17363 if (Result.isInvalid()) 17364 return ExprError(); 17365 return Result.get() ? Result : E; 17366 } 17367 17368 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17369 Res = CorrectDelayedTyposInExpr(Res); 17370 17371 if (!Res.isUsable()) 17372 return Res; 17373 17374 // If a constant-expression is a reference to a variable where we delay 17375 // deciding whether it is an odr-use, just assume we will apply the 17376 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17377 // (a non-type template argument), we have special handling anyway. 17378 return CheckLValueToRValueConversionOperand(Res.get()); 17379 } 17380 17381 void Sema::CleanupVarDeclMarking() { 17382 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17383 // call. 17384 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17385 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17386 17387 for (Expr *E : LocalMaybeODRUseExprs) { 17388 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17389 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17390 DRE->getLocation(), *this); 17391 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17392 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17393 *this); 17394 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17395 for (VarDecl *VD : *FP) 17396 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17397 } else { 17398 llvm_unreachable("Unexpected expression"); 17399 } 17400 } 17401 17402 assert(MaybeODRUseExprs.empty() && 17403 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17404 } 17405 17406 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17407 VarDecl *Var, Expr *E) { 17408 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17409 isa<FunctionParmPackExpr>(E)) && 17410 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17411 Var->setReferenced(); 17412 17413 if (Var->isInvalidDecl()) 17414 return; 17415 17416 auto *MSI = Var->getMemberSpecializationInfo(); 17417 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17418 : Var->getTemplateSpecializationKind(); 17419 17420 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17421 bool UsableInConstantExpr = 17422 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17423 17424 // C++20 [expr.const]p12: 17425 // A variable [...] is needed for constant evaluation if it is [...] a 17426 // variable whose name appears as a potentially constant evaluated 17427 // expression that is either a contexpr variable or is of non-volatile 17428 // const-qualified integral type or of reference type 17429 bool NeededForConstantEvaluation = 17430 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17431 17432 bool NeedDefinition = 17433 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17434 17435 VarTemplateSpecializationDecl *VarSpec = 17436 dyn_cast<VarTemplateSpecializationDecl>(Var); 17437 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17438 "Can't instantiate a partial template specialization."); 17439 17440 // If this might be a member specialization of a static data member, check 17441 // the specialization is visible. We already did the checks for variable 17442 // template specializations when we created them. 17443 if (NeedDefinition && TSK != TSK_Undeclared && 17444 !isa<VarTemplateSpecializationDecl>(Var)) 17445 SemaRef.checkSpecializationVisibility(Loc, Var); 17446 17447 // Perform implicit instantiation of static data members, static data member 17448 // templates of class templates, and variable template specializations. Delay 17449 // instantiations of variable templates, except for those that could be used 17450 // in a constant expression. 17451 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17452 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17453 // instantiation declaration if a variable is usable in a constant 17454 // expression (among other cases). 17455 bool TryInstantiating = 17456 TSK == TSK_ImplicitInstantiation || 17457 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17458 17459 if (TryInstantiating) { 17460 SourceLocation PointOfInstantiation = 17461 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17462 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17463 if (FirstInstantiation) { 17464 PointOfInstantiation = Loc; 17465 if (MSI) 17466 MSI->setPointOfInstantiation(PointOfInstantiation); 17467 else 17468 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17469 } 17470 17471 bool InstantiationDependent = false; 17472 bool IsNonDependent = 17473 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17474 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17475 : true; 17476 17477 // Do not instantiate specializations that are still type-dependent. 17478 if (IsNonDependent) { 17479 if (UsableInConstantExpr) { 17480 // Do not defer instantiations of variables that could be used in a 17481 // constant expression. 17482 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17483 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17484 }); 17485 } else if (FirstInstantiation || 17486 isa<VarTemplateSpecializationDecl>(Var)) { 17487 // FIXME: For a specialization of a variable template, we don't 17488 // distinguish between "declaration and type implicitly instantiated" 17489 // and "implicit instantiation of definition requested", so we have 17490 // no direct way to avoid enqueueing the pending instantiation 17491 // multiple times. 17492 SemaRef.PendingInstantiations 17493 .push_back(std::make_pair(Var, PointOfInstantiation)); 17494 } 17495 } 17496 } 17497 } 17498 17499 // C++2a [basic.def.odr]p4: 17500 // A variable x whose name appears as a potentially-evaluated expression e 17501 // is odr-used by e unless 17502 // -- x is a reference that is usable in constant expressions 17503 // -- x is a variable of non-reference type that is usable in constant 17504 // expressions and has no mutable subobjects [FIXME], and e is an 17505 // element of the set of potential results of an expression of 17506 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17507 // conversion is applied 17508 // -- x is a variable of non-reference type, and e is an element of the set 17509 // of potential results of a discarded-value expression to which the 17510 // lvalue-to-rvalue conversion is not applied [FIXME] 17511 // 17512 // We check the first part of the second bullet here, and 17513 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17514 // FIXME: To get the third bullet right, we need to delay this even for 17515 // variables that are not usable in constant expressions. 17516 17517 // If we already know this isn't an odr-use, there's nothing more to do. 17518 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17519 if (DRE->isNonOdrUse()) 17520 return; 17521 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17522 if (ME->isNonOdrUse()) 17523 return; 17524 17525 switch (OdrUse) { 17526 case OdrUseContext::None: 17527 assert((!E || isa<FunctionParmPackExpr>(E)) && 17528 "missing non-odr-use marking for unevaluated decl ref"); 17529 break; 17530 17531 case OdrUseContext::FormallyOdrUsed: 17532 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17533 // behavior. 17534 break; 17535 17536 case OdrUseContext::Used: 17537 // If we might later find that this expression isn't actually an odr-use, 17538 // delay the marking. 17539 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17540 SemaRef.MaybeODRUseExprs.insert(E); 17541 else 17542 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17543 break; 17544 17545 case OdrUseContext::Dependent: 17546 // If this is a dependent context, we don't need to mark variables as 17547 // odr-used, but we may still need to track them for lambda capture. 17548 // FIXME: Do we also need to do this inside dependent typeid expressions 17549 // (which are modeled as unevaluated at this point)? 17550 const bool RefersToEnclosingScope = 17551 (SemaRef.CurContext != Var->getDeclContext() && 17552 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17553 if (RefersToEnclosingScope) { 17554 LambdaScopeInfo *const LSI = 17555 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17556 if (LSI && (!LSI->CallOperator || 17557 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17558 // If a variable could potentially be odr-used, defer marking it so 17559 // until we finish analyzing the full expression for any 17560 // lvalue-to-rvalue 17561 // or discarded value conversions that would obviate odr-use. 17562 // Add it to the list of potential captures that will be analyzed 17563 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17564 // unless the variable is a reference that was initialized by a constant 17565 // expression (this will never need to be captured or odr-used). 17566 // 17567 // FIXME: We can simplify this a lot after implementing P0588R1. 17568 assert(E && "Capture variable should be used in an expression."); 17569 if (!Var->getType()->isReferenceType() || 17570 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17571 LSI->addPotentialCapture(E->IgnoreParens()); 17572 } 17573 } 17574 break; 17575 } 17576 } 17577 17578 /// Mark a variable referenced, and check whether it is odr-used 17579 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17580 /// used directly for normal expressions referring to VarDecl. 17581 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17582 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17583 } 17584 17585 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17586 Decl *D, Expr *E, bool MightBeOdrUse) { 17587 if (SemaRef.isInOpenMPDeclareTargetContext()) 17588 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17589 17590 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17591 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17592 return; 17593 } 17594 17595 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17596 17597 // If this is a call to a method via a cast, also mark the method in the 17598 // derived class used in case codegen can devirtualize the call. 17599 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17600 if (!ME) 17601 return; 17602 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17603 if (!MD) 17604 return; 17605 // Only attempt to devirtualize if this is truly a virtual call. 17606 bool IsVirtualCall = MD->isVirtual() && 17607 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17608 if (!IsVirtualCall) 17609 return; 17610 17611 // If it's possible to devirtualize the call, mark the called function 17612 // referenced. 17613 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17614 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17615 if (DM) 17616 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17617 } 17618 17619 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17620 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17621 // TODO: update this with DR# once a defect report is filed. 17622 // C++11 defect. The address of a pure member should not be an ODR use, even 17623 // if it's a qualified reference. 17624 bool OdrUse = true; 17625 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17626 if (Method->isVirtual() && 17627 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17628 OdrUse = false; 17629 17630 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17631 if (!isConstantEvaluated() && FD->isConsteval() && 17632 !RebuildingImmediateInvocation) 17633 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17634 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17635 } 17636 17637 /// Perform reference-marking and odr-use handling for a MemberExpr. 17638 void Sema::MarkMemberReferenced(MemberExpr *E) { 17639 // C++11 [basic.def.odr]p2: 17640 // A non-overloaded function whose name appears as a potentially-evaluated 17641 // expression or a member of a set of candidate functions, if selected by 17642 // overload resolution when referred to from a potentially-evaluated 17643 // expression, is odr-used, unless it is a pure virtual function and its 17644 // name is not explicitly qualified. 17645 bool MightBeOdrUse = true; 17646 if (E->performsVirtualDispatch(getLangOpts())) { 17647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17648 if (Method->isPure()) 17649 MightBeOdrUse = false; 17650 } 17651 SourceLocation Loc = 17652 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17653 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17654 } 17655 17656 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17657 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17658 for (VarDecl *VD : *E) 17659 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17660 } 17661 17662 /// Perform marking for a reference to an arbitrary declaration. It 17663 /// marks the declaration referenced, and performs odr-use checking for 17664 /// functions and variables. This method should not be used when building a 17665 /// normal expression which refers to a variable. 17666 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17667 bool MightBeOdrUse) { 17668 if (MightBeOdrUse) { 17669 if (auto *VD = dyn_cast<VarDecl>(D)) { 17670 MarkVariableReferenced(Loc, VD); 17671 return; 17672 } 17673 } 17674 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17675 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17676 return; 17677 } 17678 D->setReferenced(); 17679 } 17680 17681 namespace { 17682 // Mark all of the declarations used by a type as referenced. 17683 // FIXME: Not fully implemented yet! We need to have a better understanding 17684 // of when we're entering a context we should not recurse into. 17685 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17686 // TreeTransforms rebuilding the type in a new context. Rather than 17687 // duplicating the TreeTransform logic, we should consider reusing it here. 17688 // Currently that causes problems when rebuilding LambdaExprs. 17689 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17690 Sema &S; 17691 SourceLocation Loc; 17692 17693 public: 17694 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17695 17696 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17697 17698 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17699 }; 17700 } 17701 17702 bool MarkReferencedDecls::TraverseTemplateArgument( 17703 const TemplateArgument &Arg) { 17704 { 17705 // A non-type template argument is a constant-evaluated context. 17706 EnterExpressionEvaluationContext Evaluated( 17707 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17708 if (Arg.getKind() == TemplateArgument::Declaration) { 17709 if (Decl *D = Arg.getAsDecl()) 17710 S.MarkAnyDeclReferenced(Loc, D, true); 17711 } else if (Arg.getKind() == TemplateArgument::Expression) { 17712 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17713 } 17714 } 17715 17716 return Inherited::TraverseTemplateArgument(Arg); 17717 } 17718 17719 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17720 MarkReferencedDecls Marker(*this, Loc); 17721 Marker.TraverseType(T); 17722 } 17723 17724 namespace { 17725 /// Helper class that marks all of the declarations referenced by 17726 /// potentially-evaluated subexpressions as "referenced". 17727 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 17728 public: 17729 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 17730 bool SkipLocalVariables; 17731 17732 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17733 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 17734 17735 void visitUsedDecl(SourceLocation Loc, Decl *D) { 17736 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 17737 } 17738 17739 void VisitDeclRefExpr(DeclRefExpr *E) { 17740 // If we were asked not to visit local variables, don't. 17741 if (SkipLocalVariables) { 17742 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17743 if (VD->hasLocalStorage()) 17744 return; 17745 } 17746 S.MarkDeclRefReferenced(E); 17747 } 17748 17749 void VisitMemberExpr(MemberExpr *E) { 17750 S.MarkMemberReferenced(E); 17751 Visit(E->getBase()); 17752 } 17753 }; 17754 } // namespace 17755 17756 /// Mark any declarations that appear within this expression or any 17757 /// potentially-evaluated subexpressions as "referenced". 17758 /// 17759 /// \param SkipLocalVariables If true, don't mark local variables as 17760 /// 'referenced'. 17761 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17762 bool SkipLocalVariables) { 17763 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17764 } 17765 17766 /// Emit a diagnostic that describes an effect on the run-time behavior 17767 /// of the program being compiled. 17768 /// 17769 /// This routine emits the given diagnostic when the code currently being 17770 /// type-checked is "potentially evaluated", meaning that there is a 17771 /// possibility that the code will actually be executable. Code in sizeof() 17772 /// expressions, code used only during overload resolution, etc., are not 17773 /// potentially evaluated. This routine will suppress such diagnostics or, 17774 /// in the absolutely nutty case of potentially potentially evaluated 17775 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17776 /// later. 17777 /// 17778 /// This routine should be used for all diagnostics that describe the run-time 17779 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17780 /// Failure to do so will likely result in spurious diagnostics or failures 17781 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17782 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17783 const PartialDiagnostic &PD) { 17784 switch (ExprEvalContexts.back().Context) { 17785 case ExpressionEvaluationContext::Unevaluated: 17786 case ExpressionEvaluationContext::UnevaluatedList: 17787 case ExpressionEvaluationContext::UnevaluatedAbstract: 17788 case ExpressionEvaluationContext::DiscardedStatement: 17789 // The argument will never be evaluated, so don't complain. 17790 break; 17791 17792 case ExpressionEvaluationContext::ConstantEvaluated: 17793 // Relevant diagnostics should be produced by constant evaluation. 17794 break; 17795 17796 case ExpressionEvaluationContext::PotentiallyEvaluated: 17797 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17798 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17799 FunctionScopes.back()->PossiblyUnreachableDiags. 17800 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17801 return true; 17802 } 17803 17804 // The initializer of a constexpr variable or of the first declaration of a 17805 // static data member is not syntactically a constant evaluated constant, 17806 // but nonetheless is always required to be a constant expression, so we 17807 // can skip diagnosing. 17808 // FIXME: Using the mangling context here is a hack. 17809 if (auto *VD = dyn_cast_or_null<VarDecl>( 17810 ExprEvalContexts.back().ManglingContextDecl)) { 17811 if (VD->isConstexpr() || 17812 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17813 break; 17814 // FIXME: For any other kind of variable, we should build a CFG for its 17815 // initializer and check whether the context in question is reachable. 17816 } 17817 17818 Diag(Loc, PD); 17819 return true; 17820 } 17821 17822 return false; 17823 } 17824 17825 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17826 const PartialDiagnostic &PD) { 17827 return DiagRuntimeBehavior( 17828 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17829 } 17830 17831 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17832 CallExpr *CE, FunctionDecl *FD) { 17833 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17834 return false; 17835 17836 // If we're inside a decltype's expression, don't check for a valid return 17837 // type or construct temporaries until we know whether this is the last call. 17838 if (ExprEvalContexts.back().ExprContext == 17839 ExpressionEvaluationContextRecord::EK_Decltype) { 17840 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17841 return false; 17842 } 17843 17844 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17845 FunctionDecl *FD; 17846 CallExpr *CE; 17847 17848 public: 17849 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17850 : FD(FD), CE(CE) { } 17851 17852 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17853 if (!FD) { 17854 S.Diag(Loc, diag::err_call_incomplete_return) 17855 << T << CE->getSourceRange(); 17856 return; 17857 } 17858 17859 S.Diag(Loc, diag::err_call_function_incomplete_return) 17860 << CE->getSourceRange() << FD->getDeclName() << T; 17861 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17862 << FD->getDeclName(); 17863 } 17864 } Diagnoser(FD, CE); 17865 17866 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17867 return true; 17868 17869 return false; 17870 } 17871 17872 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17873 // will prevent this condition from triggering, which is what we want. 17874 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17875 SourceLocation Loc; 17876 17877 unsigned diagnostic = diag::warn_condition_is_assignment; 17878 bool IsOrAssign = false; 17879 17880 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17881 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17882 return; 17883 17884 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17885 17886 // Greylist some idioms by putting them into a warning subcategory. 17887 if (ObjCMessageExpr *ME 17888 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17889 Selector Sel = ME->getSelector(); 17890 17891 // self = [<foo> init...] 17892 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17893 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17894 17895 // <foo> = [<bar> nextObject] 17896 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17897 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17898 } 17899 17900 Loc = Op->getOperatorLoc(); 17901 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17902 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17903 return; 17904 17905 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17906 Loc = Op->getOperatorLoc(); 17907 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17908 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17909 else { 17910 // Not an assignment. 17911 return; 17912 } 17913 17914 Diag(Loc, diagnostic) << E->getSourceRange(); 17915 17916 SourceLocation Open = E->getBeginLoc(); 17917 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17918 Diag(Loc, diag::note_condition_assign_silence) 17919 << FixItHint::CreateInsertion(Open, "(") 17920 << FixItHint::CreateInsertion(Close, ")"); 17921 17922 if (IsOrAssign) 17923 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17924 << FixItHint::CreateReplacement(Loc, "!="); 17925 else 17926 Diag(Loc, diag::note_condition_assign_to_comparison) 17927 << FixItHint::CreateReplacement(Loc, "=="); 17928 } 17929 17930 /// Redundant parentheses over an equality comparison can indicate 17931 /// that the user intended an assignment used as condition. 17932 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17933 // Don't warn if the parens came from a macro. 17934 SourceLocation parenLoc = ParenE->getBeginLoc(); 17935 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17936 return; 17937 // Don't warn for dependent expressions. 17938 if (ParenE->isTypeDependent()) 17939 return; 17940 17941 Expr *E = ParenE->IgnoreParens(); 17942 17943 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17944 if (opE->getOpcode() == BO_EQ && 17945 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17946 == Expr::MLV_Valid) { 17947 SourceLocation Loc = opE->getOperatorLoc(); 17948 17949 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17950 SourceRange ParenERange = ParenE->getSourceRange(); 17951 Diag(Loc, diag::note_equality_comparison_silence) 17952 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17953 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17954 Diag(Loc, diag::note_equality_comparison_to_assign) 17955 << FixItHint::CreateReplacement(Loc, "="); 17956 } 17957 } 17958 17959 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17960 bool IsConstexpr) { 17961 DiagnoseAssignmentAsCondition(E); 17962 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17963 DiagnoseEqualityWithExtraParens(parenE); 17964 17965 ExprResult result = CheckPlaceholderExpr(E); 17966 if (result.isInvalid()) return ExprError(); 17967 E = result.get(); 17968 17969 if (!E->isTypeDependent()) { 17970 if (getLangOpts().CPlusPlus) 17971 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17972 17973 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17974 if (ERes.isInvalid()) 17975 return ExprError(); 17976 E = ERes.get(); 17977 17978 QualType T = E->getType(); 17979 if (!T->isScalarType()) { // C99 6.8.4.1p1 17980 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17981 << T << E->getSourceRange(); 17982 return ExprError(); 17983 } 17984 CheckBoolLikeConversion(E, Loc); 17985 } 17986 17987 return E; 17988 } 17989 17990 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17991 Expr *SubExpr, ConditionKind CK) { 17992 // Empty conditions are valid in for-statements. 17993 if (!SubExpr) 17994 return ConditionResult(); 17995 17996 ExprResult Cond; 17997 switch (CK) { 17998 case ConditionKind::Boolean: 17999 Cond = CheckBooleanCondition(Loc, SubExpr); 18000 break; 18001 18002 case ConditionKind::ConstexprIf: 18003 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18004 break; 18005 18006 case ConditionKind::Switch: 18007 Cond = CheckSwitchCondition(Loc, SubExpr); 18008 break; 18009 } 18010 if (Cond.isInvalid()) 18011 return ConditionError(); 18012 18013 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18014 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18015 if (!FullExpr.get()) 18016 return ConditionError(); 18017 18018 return ConditionResult(*this, nullptr, FullExpr, 18019 CK == ConditionKind::ConstexprIf); 18020 } 18021 18022 namespace { 18023 /// A visitor for rebuilding a call to an __unknown_any expression 18024 /// to have an appropriate type. 18025 struct RebuildUnknownAnyFunction 18026 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18027 18028 Sema &S; 18029 18030 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18031 18032 ExprResult VisitStmt(Stmt *S) { 18033 llvm_unreachable("unexpected statement!"); 18034 } 18035 18036 ExprResult VisitExpr(Expr *E) { 18037 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18038 << E->getSourceRange(); 18039 return ExprError(); 18040 } 18041 18042 /// Rebuild an expression which simply semantically wraps another 18043 /// expression which it shares the type and value kind of. 18044 template <class T> ExprResult rebuildSugarExpr(T *E) { 18045 ExprResult SubResult = Visit(E->getSubExpr()); 18046 if (SubResult.isInvalid()) return ExprError(); 18047 18048 Expr *SubExpr = SubResult.get(); 18049 E->setSubExpr(SubExpr); 18050 E->setType(SubExpr->getType()); 18051 E->setValueKind(SubExpr->getValueKind()); 18052 assert(E->getObjectKind() == OK_Ordinary); 18053 return E; 18054 } 18055 18056 ExprResult VisitParenExpr(ParenExpr *E) { 18057 return rebuildSugarExpr(E); 18058 } 18059 18060 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18061 return rebuildSugarExpr(E); 18062 } 18063 18064 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18065 ExprResult SubResult = Visit(E->getSubExpr()); 18066 if (SubResult.isInvalid()) return ExprError(); 18067 18068 Expr *SubExpr = SubResult.get(); 18069 E->setSubExpr(SubExpr); 18070 E->setType(S.Context.getPointerType(SubExpr->getType())); 18071 assert(E->getValueKind() == VK_RValue); 18072 assert(E->getObjectKind() == OK_Ordinary); 18073 return E; 18074 } 18075 18076 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18077 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18078 18079 E->setType(VD->getType()); 18080 18081 assert(E->getValueKind() == VK_RValue); 18082 if (S.getLangOpts().CPlusPlus && 18083 !(isa<CXXMethodDecl>(VD) && 18084 cast<CXXMethodDecl>(VD)->isInstance())) 18085 E->setValueKind(VK_LValue); 18086 18087 return E; 18088 } 18089 18090 ExprResult VisitMemberExpr(MemberExpr *E) { 18091 return resolveDecl(E, E->getMemberDecl()); 18092 } 18093 18094 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18095 return resolveDecl(E, E->getDecl()); 18096 } 18097 }; 18098 } 18099 18100 /// Given a function expression of unknown-any type, try to rebuild it 18101 /// to have a function type. 18102 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18103 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18104 if (Result.isInvalid()) return ExprError(); 18105 return S.DefaultFunctionArrayConversion(Result.get()); 18106 } 18107 18108 namespace { 18109 /// A visitor for rebuilding an expression of type __unknown_anytype 18110 /// into one which resolves the type directly on the referring 18111 /// expression. Strict preservation of the original source 18112 /// structure is not a goal. 18113 struct RebuildUnknownAnyExpr 18114 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18115 18116 Sema &S; 18117 18118 /// The current destination type. 18119 QualType DestType; 18120 18121 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18122 : S(S), DestType(CastType) {} 18123 18124 ExprResult VisitStmt(Stmt *S) { 18125 llvm_unreachable("unexpected statement!"); 18126 } 18127 18128 ExprResult VisitExpr(Expr *E) { 18129 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18130 << E->getSourceRange(); 18131 return ExprError(); 18132 } 18133 18134 ExprResult VisitCallExpr(CallExpr *E); 18135 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18136 18137 /// Rebuild an expression which simply semantically wraps another 18138 /// expression which it shares the type and value kind of. 18139 template <class T> ExprResult rebuildSugarExpr(T *E) { 18140 ExprResult SubResult = Visit(E->getSubExpr()); 18141 if (SubResult.isInvalid()) return ExprError(); 18142 Expr *SubExpr = SubResult.get(); 18143 E->setSubExpr(SubExpr); 18144 E->setType(SubExpr->getType()); 18145 E->setValueKind(SubExpr->getValueKind()); 18146 assert(E->getObjectKind() == OK_Ordinary); 18147 return E; 18148 } 18149 18150 ExprResult VisitParenExpr(ParenExpr *E) { 18151 return rebuildSugarExpr(E); 18152 } 18153 18154 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18155 return rebuildSugarExpr(E); 18156 } 18157 18158 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18159 const PointerType *Ptr = DestType->getAs<PointerType>(); 18160 if (!Ptr) { 18161 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18162 << E->getSourceRange(); 18163 return ExprError(); 18164 } 18165 18166 if (isa<CallExpr>(E->getSubExpr())) { 18167 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18168 << E->getSourceRange(); 18169 return ExprError(); 18170 } 18171 18172 assert(E->getValueKind() == VK_RValue); 18173 assert(E->getObjectKind() == OK_Ordinary); 18174 E->setType(DestType); 18175 18176 // Build the sub-expression as if it were an object of the pointee type. 18177 DestType = Ptr->getPointeeType(); 18178 ExprResult SubResult = Visit(E->getSubExpr()); 18179 if (SubResult.isInvalid()) return ExprError(); 18180 E->setSubExpr(SubResult.get()); 18181 return E; 18182 } 18183 18184 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18185 18186 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18187 18188 ExprResult VisitMemberExpr(MemberExpr *E) { 18189 return resolveDecl(E, E->getMemberDecl()); 18190 } 18191 18192 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18193 return resolveDecl(E, E->getDecl()); 18194 } 18195 }; 18196 } 18197 18198 /// Rebuilds a call expression which yielded __unknown_anytype. 18199 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18200 Expr *CalleeExpr = E->getCallee(); 18201 18202 enum FnKind { 18203 FK_MemberFunction, 18204 FK_FunctionPointer, 18205 FK_BlockPointer 18206 }; 18207 18208 FnKind Kind; 18209 QualType CalleeType = CalleeExpr->getType(); 18210 if (CalleeType == S.Context.BoundMemberTy) { 18211 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18212 Kind = FK_MemberFunction; 18213 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18214 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18215 CalleeType = Ptr->getPointeeType(); 18216 Kind = FK_FunctionPointer; 18217 } else { 18218 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18219 Kind = FK_BlockPointer; 18220 } 18221 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18222 18223 // Verify that this is a legal result type of a function. 18224 if (DestType->isArrayType() || DestType->isFunctionType()) { 18225 unsigned diagID = diag::err_func_returning_array_function; 18226 if (Kind == FK_BlockPointer) 18227 diagID = diag::err_block_returning_array_function; 18228 18229 S.Diag(E->getExprLoc(), diagID) 18230 << DestType->isFunctionType() << DestType; 18231 return ExprError(); 18232 } 18233 18234 // Otherwise, go ahead and set DestType as the call's result. 18235 E->setType(DestType.getNonLValueExprType(S.Context)); 18236 E->setValueKind(Expr::getValueKindForType(DestType)); 18237 assert(E->getObjectKind() == OK_Ordinary); 18238 18239 // Rebuild the function type, replacing the result type with DestType. 18240 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18241 if (Proto) { 18242 // __unknown_anytype(...) is a special case used by the debugger when 18243 // it has no idea what a function's signature is. 18244 // 18245 // We want to build this call essentially under the K&R 18246 // unprototyped rules, but making a FunctionNoProtoType in C++ 18247 // would foul up all sorts of assumptions. However, we cannot 18248 // simply pass all arguments as variadic arguments, nor can we 18249 // portably just call the function under a non-variadic type; see 18250 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18251 // However, it turns out that in practice it is generally safe to 18252 // call a function declared as "A foo(B,C,D);" under the prototype 18253 // "A foo(B,C,D,...);". The only known exception is with the 18254 // Windows ABI, where any variadic function is implicitly cdecl 18255 // regardless of its normal CC. Therefore we change the parameter 18256 // types to match the types of the arguments. 18257 // 18258 // This is a hack, but it is far superior to moving the 18259 // corresponding target-specific code from IR-gen to Sema/AST. 18260 18261 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18262 SmallVector<QualType, 8> ArgTypes; 18263 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18264 ArgTypes.reserve(E->getNumArgs()); 18265 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18266 Expr *Arg = E->getArg(i); 18267 QualType ArgType = Arg->getType(); 18268 if (E->isLValue()) { 18269 ArgType = S.Context.getLValueReferenceType(ArgType); 18270 } else if (E->isXValue()) { 18271 ArgType = S.Context.getRValueReferenceType(ArgType); 18272 } 18273 ArgTypes.push_back(ArgType); 18274 } 18275 ParamTypes = ArgTypes; 18276 } 18277 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18278 Proto->getExtProtoInfo()); 18279 } else { 18280 DestType = S.Context.getFunctionNoProtoType(DestType, 18281 FnType->getExtInfo()); 18282 } 18283 18284 // Rebuild the appropriate pointer-to-function type. 18285 switch (Kind) { 18286 case FK_MemberFunction: 18287 // Nothing to do. 18288 break; 18289 18290 case FK_FunctionPointer: 18291 DestType = S.Context.getPointerType(DestType); 18292 break; 18293 18294 case FK_BlockPointer: 18295 DestType = S.Context.getBlockPointerType(DestType); 18296 break; 18297 } 18298 18299 // Finally, we can recurse. 18300 ExprResult CalleeResult = Visit(CalleeExpr); 18301 if (!CalleeResult.isUsable()) return ExprError(); 18302 E->setCallee(CalleeResult.get()); 18303 18304 // Bind a temporary if necessary. 18305 return S.MaybeBindToTemporary(E); 18306 } 18307 18308 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18309 // Verify that this is a legal result type of a call. 18310 if (DestType->isArrayType() || DestType->isFunctionType()) { 18311 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18312 << DestType->isFunctionType() << DestType; 18313 return ExprError(); 18314 } 18315 18316 // Rewrite the method result type if available. 18317 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18318 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18319 Method->setReturnType(DestType); 18320 } 18321 18322 // Change the type of the message. 18323 E->setType(DestType.getNonReferenceType()); 18324 E->setValueKind(Expr::getValueKindForType(DestType)); 18325 18326 return S.MaybeBindToTemporary(E); 18327 } 18328 18329 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18330 // The only case we should ever see here is a function-to-pointer decay. 18331 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18332 assert(E->getValueKind() == VK_RValue); 18333 assert(E->getObjectKind() == OK_Ordinary); 18334 18335 E->setType(DestType); 18336 18337 // Rebuild the sub-expression as the pointee (function) type. 18338 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18339 18340 ExprResult Result = Visit(E->getSubExpr()); 18341 if (!Result.isUsable()) return ExprError(); 18342 18343 E->setSubExpr(Result.get()); 18344 return E; 18345 } else if (E->getCastKind() == CK_LValueToRValue) { 18346 assert(E->getValueKind() == VK_RValue); 18347 assert(E->getObjectKind() == OK_Ordinary); 18348 18349 assert(isa<BlockPointerType>(E->getType())); 18350 18351 E->setType(DestType); 18352 18353 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18354 DestType = S.Context.getLValueReferenceType(DestType); 18355 18356 ExprResult Result = Visit(E->getSubExpr()); 18357 if (!Result.isUsable()) return ExprError(); 18358 18359 E->setSubExpr(Result.get()); 18360 return E; 18361 } else { 18362 llvm_unreachable("Unhandled cast type!"); 18363 } 18364 } 18365 18366 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18367 ExprValueKind ValueKind = VK_LValue; 18368 QualType Type = DestType; 18369 18370 // We know how to make this work for certain kinds of decls: 18371 18372 // - functions 18373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18374 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18375 DestType = Ptr->getPointeeType(); 18376 ExprResult Result = resolveDecl(E, VD); 18377 if (Result.isInvalid()) return ExprError(); 18378 return S.ImpCastExprToType(Result.get(), Type, 18379 CK_FunctionToPointerDecay, VK_RValue); 18380 } 18381 18382 if (!Type->isFunctionType()) { 18383 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18384 << VD << E->getSourceRange(); 18385 return ExprError(); 18386 } 18387 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18388 // We must match the FunctionDecl's type to the hack introduced in 18389 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18390 // type. See the lengthy commentary in that routine. 18391 QualType FDT = FD->getType(); 18392 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18393 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18394 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18395 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18396 SourceLocation Loc = FD->getLocation(); 18397 FunctionDecl *NewFD = FunctionDecl::Create( 18398 S.Context, FD->getDeclContext(), Loc, Loc, 18399 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18400 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18401 /*ConstexprKind*/ CSK_unspecified); 18402 18403 if (FD->getQualifier()) 18404 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18405 18406 SmallVector<ParmVarDecl*, 16> Params; 18407 for (const auto &AI : FT->param_types()) { 18408 ParmVarDecl *Param = 18409 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18410 Param->setScopeInfo(0, Params.size()); 18411 Params.push_back(Param); 18412 } 18413 NewFD->setParams(Params); 18414 DRE->setDecl(NewFD); 18415 VD = DRE->getDecl(); 18416 } 18417 } 18418 18419 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18420 if (MD->isInstance()) { 18421 ValueKind = VK_RValue; 18422 Type = S.Context.BoundMemberTy; 18423 } 18424 18425 // Function references aren't l-values in C. 18426 if (!S.getLangOpts().CPlusPlus) 18427 ValueKind = VK_RValue; 18428 18429 // - variables 18430 } else if (isa<VarDecl>(VD)) { 18431 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18432 Type = RefTy->getPointeeType(); 18433 } else if (Type->isFunctionType()) { 18434 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18435 << VD << E->getSourceRange(); 18436 return ExprError(); 18437 } 18438 18439 // - nothing else 18440 } else { 18441 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18442 << VD << E->getSourceRange(); 18443 return ExprError(); 18444 } 18445 18446 // Modifying the declaration like this is friendly to IR-gen but 18447 // also really dangerous. 18448 VD->setType(DestType); 18449 E->setType(Type); 18450 E->setValueKind(ValueKind); 18451 return E; 18452 } 18453 18454 /// Check a cast of an unknown-any type. We intentionally only 18455 /// trigger this for C-style casts. 18456 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18457 Expr *CastExpr, CastKind &CastKind, 18458 ExprValueKind &VK, CXXCastPath &Path) { 18459 // The type we're casting to must be either void or complete. 18460 if (!CastType->isVoidType() && 18461 RequireCompleteType(TypeRange.getBegin(), CastType, 18462 diag::err_typecheck_cast_to_incomplete)) 18463 return ExprError(); 18464 18465 // Rewrite the casted expression from scratch. 18466 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18467 if (!result.isUsable()) return ExprError(); 18468 18469 CastExpr = result.get(); 18470 VK = CastExpr->getValueKind(); 18471 CastKind = CK_NoOp; 18472 18473 return CastExpr; 18474 } 18475 18476 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18477 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18478 } 18479 18480 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18481 Expr *arg, QualType ¶mType) { 18482 // If the syntactic form of the argument is not an explicit cast of 18483 // any sort, just do default argument promotion. 18484 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18485 if (!castArg) { 18486 ExprResult result = DefaultArgumentPromotion(arg); 18487 if (result.isInvalid()) return ExprError(); 18488 paramType = result.get()->getType(); 18489 return result; 18490 } 18491 18492 // Otherwise, use the type that was written in the explicit cast. 18493 assert(!arg->hasPlaceholderType()); 18494 paramType = castArg->getTypeAsWritten(); 18495 18496 // Copy-initialize a parameter of that type. 18497 InitializedEntity entity = 18498 InitializedEntity::InitializeParameter(Context, paramType, 18499 /*consumed*/ false); 18500 return PerformCopyInitialization(entity, callLoc, arg); 18501 } 18502 18503 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18504 Expr *orig = E; 18505 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18506 while (true) { 18507 E = E->IgnoreParenImpCasts(); 18508 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18509 E = call->getCallee(); 18510 diagID = diag::err_uncasted_call_of_unknown_any; 18511 } else { 18512 break; 18513 } 18514 } 18515 18516 SourceLocation loc; 18517 NamedDecl *d; 18518 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18519 loc = ref->getLocation(); 18520 d = ref->getDecl(); 18521 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18522 loc = mem->getMemberLoc(); 18523 d = mem->getMemberDecl(); 18524 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18525 diagID = diag::err_uncasted_call_of_unknown_any; 18526 loc = msg->getSelectorStartLoc(); 18527 d = msg->getMethodDecl(); 18528 if (!d) { 18529 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18530 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18531 << orig->getSourceRange(); 18532 return ExprError(); 18533 } 18534 } else { 18535 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18536 << E->getSourceRange(); 18537 return ExprError(); 18538 } 18539 18540 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18541 18542 // Never recoverable. 18543 return ExprError(); 18544 } 18545 18546 /// Check for operands with placeholder types and complain if found. 18547 /// Returns ExprError() if there was an error and no recovery was possible. 18548 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18549 if (!getLangOpts().CPlusPlus) { 18550 // C cannot handle TypoExpr nodes on either side of a binop because it 18551 // doesn't handle dependent types properly, so make sure any TypoExprs have 18552 // been dealt with before checking the operands. 18553 ExprResult Result = CorrectDelayedTyposInExpr(E); 18554 if (!Result.isUsable()) return ExprError(); 18555 E = Result.get(); 18556 } 18557 18558 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18559 if (!placeholderType) return E; 18560 18561 switch (placeholderType->getKind()) { 18562 18563 // Overloaded expressions. 18564 case BuiltinType::Overload: { 18565 // Try to resolve a single function template specialization. 18566 // This is obligatory. 18567 ExprResult Result = E; 18568 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18569 return Result; 18570 18571 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18572 // leaves Result unchanged on failure. 18573 Result = E; 18574 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18575 return Result; 18576 18577 // If that failed, try to recover with a call. 18578 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18579 /*complain*/ true); 18580 return Result; 18581 } 18582 18583 // Bound member functions. 18584 case BuiltinType::BoundMember: { 18585 ExprResult result = E; 18586 const Expr *BME = E->IgnoreParens(); 18587 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18588 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18589 if (isa<CXXPseudoDestructorExpr>(BME)) { 18590 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18591 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18592 if (ME->getMemberNameInfo().getName().getNameKind() == 18593 DeclarationName::CXXDestructorName) 18594 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18595 } 18596 tryToRecoverWithCall(result, PD, 18597 /*complain*/ true); 18598 return result; 18599 } 18600 18601 // ARC unbridged casts. 18602 case BuiltinType::ARCUnbridgedCast: { 18603 Expr *realCast = stripARCUnbridgedCast(E); 18604 diagnoseARCUnbridgedCast(realCast); 18605 return realCast; 18606 } 18607 18608 // Expressions of unknown type. 18609 case BuiltinType::UnknownAny: 18610 return diagnoseUnknownAnyExpr(*this, E); 18611 18612 // Pseudo-objects. 18613 case BuiltinType::PseudoObject: 18614 return checkPseudoObjectRValue(E); 18615 18616 case BuiltinType::BuiltinFn: { 18617 // Accept __noop without parens by implicitly converting it to a call expr. 18618 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18619 if (DRE) { 18620 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18621 if (FD->getBuiltinID() == Builtin::BI__noop) { 18622 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18623 CK_BuiltinFnToFnPtr) 18624 .get(); 18625 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18626 VK_RValue, SourceLocation()); 18627 } 18628 } 18629 18630 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18631 return ExprError(); 18632 } 18633 18634 // Expressions of unknown type. 18635 case BuiltinType::OMPArraySection: 18636 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18637 return ExprError(); 18638 18639 // Expressions of unknown type. 18640 case BuiltinType::OMPArrayShaping: 18641 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 18642 18643 case BuiltinType::OMPIterator: 18644 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 18645 18646 // Everything else should be impossible. 18647 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18648 case BuiltinType::Id: 18649 #include "clang/Basic/OpenCLImageTypes.def" 18650 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18651 case BuiltinType::Id: 18652 #include "clang/Basic/OpenCLExtensionTypes.def" 18653 #define SVE_TYPE(Name, Id, SingletonId) \ 18654 case BuiltinType::Id: 18655 #include "clang/Basic/AArch64SVEACLETypes.def" 18656 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18657 #define PLACEHOLDER_TYPE(Id, SingletonId) 18658 #include "clang/AST/BuiltinTypes.def" 18659 break; 18660 } 18661 18662 llvm_unreachable("invalid placeholder type!"); 18663 } 18664 18665 bool Sema::CheckCaseExpression(Expr *E) { 18666 if (E->isTypeDependent()) 18667 return true; 18668 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18669 return E->getType()->isIntegralOrEnumerationType(); 18670 return false; 18671 } 18672 18673 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18674 ExprResult 18675 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18676 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18677 "Unknown Objective-C Boolean value!"); 18678 QualType BoolT = Context.ObjCBuiltinBoolTy; 18679 if (!Context.getBOOLDecl()) { 18680 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18681 Sema::LookupOrdinaryName); 18682 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18683 NamedDecl *ND = Result.getFoundDecl(); 18684 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18685 Context.setBOOLDecl(TD); 18686 } 18687 } 18688 if (Context.getBOOLDecl()) 18689 BoolT = Context.getBOOLType(); 18690 return new (Context) 18691 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18692 } 18693 18694 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18695 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18696 SourceLocation RParen) { 18697 18698 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18699 18700 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18701 return Spec.getPlatform() == Platform; 18702 }); 18703 18704 VersionTuple Version; 18705 if (Spec != AvailSpecs.end()) 18706 Version = Spec->getVersion(); 18707 18708 // The use of `@available` in the enclosing function should be analyzed to 18709 // warn when it's used inappropriately (i.e. not if(@available)). 18710 if (getCurFunctionOrMethodDecl()) 18711 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18712 else if (getCurBlock() || getCurLambda()) 18713 getCurFunction()->HasPotentialAvailabilityViolations = true; 18714 18715 return new (Context) 18716 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18717 } 18718 18719 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18720 assert(E->isTypeDependent()); 18721 return isa<UnresolvedLookupExpr>(E); 18722 } 18723 18724 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 18725 ArrayRef<Expr *> SubExprs) { 18726 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 18727 // bogus diagnostics and this trick does not work in C. 18728 // FIXME: use containsErrors() to suppress unwanted diags in C. 18729 if (!Context.getLangOpts().RecoveryAST) 18730 return ExprError(); 18731 18732 if (isSFINAEContext()) 18733 return ExprError(); 18734 18735 return RecoveryExpr::Create(Context, Begin, End, SubExprs); 18736 } 18737