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 "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 #include "llvm/Support/SaveAndRestore.h" 50 using namespace clang; 51 using namespace sema; 52 53 /// Determine whether the use of this declaration is valid, without 54 /// emitting diagnostics. 55 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 56 // See if this is an auto-typed variable whose initializer we are parsing. 57 if (ParsingInitForAutoVars.count(D)) 58 return false; 59 60 // See if this is a deleted function. 61 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 62 if (FD->isDeleted()) 63 return false; 64 65 // If the function has a deduced return type, and we can't deduce it, 66 // then we can't use it either. 67 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 68 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 69 return false; 70 71 // See if this is an aligned allocation/deallocation function that is 72 // unavailable. 73 if (TreatUnavailableAsInvalid && 74 isUnavailableAlignedAllocationFunction(*FD)) 75 return false; 76 } 77 78 // See if this function is unavailable. 79 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 80 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 81 return false; 82 83 return true; 84 } 85 86 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 87 // Warn if this is used but marked unused. 88 if (const auto *A = D->getAttr<UnusedAttr>()) { 89 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 90 // should diagnose them. 91 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 92 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 93 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 94 if (DC && !DC->hasAttr<UnusedAttr>()) 95 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 96 } 97 } 98 } 99 100 /// Emit a note explaining that this function is deleted. 101 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 102 assert(Decl && Decl->isDeleted()); 103 104 if (Decl->isDefaulted()) { 105 // If the method was explicitly defaulted, point at that declaration. 106 if (!Decl->isImplicit()) 107 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 108 109 // Try to diagnose why this special member function was implicitly 110 // deleted. This might fail, if that reason no longer applies. 111 DiagnoseDeletedDefaultedFunction(Decl); 112 return; 113 } 114 115 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 116 if (Ctor && Ctor->isInheritingConstructor()) 117 return NoteDeletedInheritingConstructor(Ctor); 118 119 Diag(Decl->getLocation(), diag::note_availability_specified_here) 120 << Decl << 1; 121 } 122 123 /// Determine whether a FunctionDecl was ever declared with an 124 /// explicit storage class. 125 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 126 for (auto I : D->redecls()) { 127 if (I->getStorageClass() != SC_None) 128 return true; 129 } 130 return false; 131 } 132 133 /// Check whether we're in an extern inline function and referring to a 134 /// variable or function with internal linkage (C11 6.7.4p3). 135 /// 136 /// This is only a warning because we used to silently accept this code, but 137 /// in many cases it will not behave correctly. This is not enabled in C++ mode 138 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 139 /// and so while there may still be user mistakes, most of the time we can't 140 /// prove that there are errors. 141 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 142 const NamedDecl *D, 143 SourceLocation Loc) { 144 // This is disabled under C++; there are too many ways for this to fire in 145 // contexts where the warning is a false positive, or where it is technically 146 // correct but benign. 147 if (S.getLangOpts().CPlusPlus) 148 return; 149 150 // Check if this is an inlined function or method. 151 FunctionDecl *Current = S.getCurFunctionDecl(); 152 if (!Current) 153 return; 154 if (!Current->isInlined()) 155 return; 156 if (!Current->isExternallyVisible()) 157 return; 158 159 // Check if the decl has internal linkage. 160 if (D->getFormalLinkage() != InternalLinkage) 161 return; 162 163 // Downgrade from ExtWarn to Extension if 164 // (1) the supposedly external inline function is in the main file, 165 // and probably won't be included anywhere else. 166 // (2) the thing we're referencing is a pure function. 167 // (3) the thing we're referencing is another inline function. 168 // This last can give us false negatives, but it's better than warning on 169 // wrappers for simple C library functions. 170 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 171 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 172 if (!DowngradeWarning && UsedFn) 173 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 174 175 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 176 : diag::ext_internal_in_extern_inline) 177 << /*IsVar=*/!UsedFn << D; 178 179 S.MaybeSuggestAddingStaticToDecl(Current); 180 181 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 182 << D; 183 } 184 185 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 186 const FunctionDecl *First = Cur->getFirstDecl(); 187 188 // Suggest "static" on the function, if possible. 189 if (!hasAnyExplicitStorageClass(First)) { 190 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 191 Diag(DeclBegin, diag::note_convert_inline_to_static) 192 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 193 } 194 } 195 196 /// Determine whether the use of this declaration is valid, and 197 /// emit any corresponding diagnostics. 198 /// 199 /// This routine diagnoses various problems with referencing 200 /// declarations that can occur when using a declaration. For example, 201 /// it might warn if a deprecated or unavailable declaration is being 202 /// used, or produce an error (and return true) if a C++0x deleted 203 /// function is being used. 204 /// 205 /// \returns true if there was an error (this declaration cannot be 206 /// referenced), false otherwise. 207 /// 208 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 209 const ObjCInterfaceDecl *UnknownObjCClass, 210 bool ObjCPropertyAccess, 211 bool AvoidPartialAvailabilityChecks, 212 ObjCInterfaceDecl *ClassReceiver) { 213 SourceLocation Loc = Locs.front(); 214 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 215 // If there were any diagnostics suppressed by template argument deduction, 216 // emit them now. 217 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 218 if (Pos != SuppressedDiagnostics.end()) { 219 for (const PartialDiagnosticAt &Suppressed : Pos->second) 220 Diag(Suppressed.first, Suppressed.second); 221 222 // Clear out the list of suppressed diagnostics, so that we don't emit 223 // them again for this specialization. However, we don't obsolete this 224 // entry from the table, because we want to avoid ever emitting these 225 // diagnostics again. 226 Pos->second.clear(); 227 } 228 229 // C++ [basic.start.main]p3: 230 // The function 'main' shall not be used within a program. 231 if (cast<FunctionDecl>(D)->isMain()) 232 Diag(Loc, diag::ext_main_used); 233 234 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 235 } 236 237 // See if this is an auto-typed variable whose initializer we are parsing. 238 if (ParsingInitForAutoVars.count(D)) { 239 if (isa<BindingDecl>(D)) { 240 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 241 << D->getDeclName(); 242 } else { 243 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 244 << D->getDeclName() << cast<VarDecl>(D)->getType(); 245 } 246 return true; 247 } 248 249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 250 // See if this is a deleted function. 251 if (FD->isDeleted()) { 252 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 253 if (Ctor && Ctor->isInheritingConstructor()) 254 Diag(Loc, diag::err_deleted_inherited_ctor_use) 255 << Ctor->getParent() 256 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 257 else 258 Diag(Loc, diag::err_deleted_function_use); 259 NoteDeletedFunction(FD); 260 return true; 261 } 262 263 // [expr.prim.id]p4 264 // A program that refers explicitly or implicitly to a function with a 265 // trailing requires-clause whose constraint-expression is not satisfied, 266 // other than to declare it, is ill-formed. [...] 267 // 268 // See if this is a function with constraints that need to be satisfied. 269 // Check this before deducing the return type, as it might instantiate the 270 // definition. 271 if (FD->getTrailingRequiresClause()) { 272 ConstraintSatisfaction Satisfaction; 273 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 274 // A diagnostic will have already been generated (non-constant 275 // constraint expression, for example) 276 return true; 277 if (!Satisfaction.IsSatisfied) { 278 Diag(Loc, 279 diag::err_reference_to_function_with_unsatisfied_constraints) 280 << D; 281 DiagnoseUnsatisfiedConstraint(Satisfaction); 282 return true; 283 } 284 } 285 286 // If the function has a deduced return type, and we can't deduce it, 287 // then we can't use it either. 288 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 289 DeduceReturnType(FD, Loc)) 290 return true; 291 292 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 293 return true; 294 } 295 296 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 297 // Lambdas are only default-constructible or assignable in C++2a onwards. 298 if (MD->getParent()->isLambda() && 299 ((isa<CXXConstructorDecl>(MD) && 300 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 301 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 302 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 303 << !isa<CXXConstructorDecl>(MD); 304 } 305 } 306 307 auto getReferencedObjCProp = [](const NamedDecl *D) -> 308 const ObjCPropertyDecl * { 309 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 310 return MD->findPropertyDecl(); 311 return nullptr; 312 }; 313 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 314 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 315 return true; 316 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 317 return true; 318 } 319 320 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 321 // Only the variables omp_in and omp_out are allowed in the combiner. 322 // Only the variables omp_priv and omp_orig are allowed in the 323 // initializer-clause. 324 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 325 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 326 isa<VarDecl>(D)) { 327 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 328 << getCurFunction()->HasOMPDeclareReductionCombiner; 329 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 330 return true; 331 } 332 333 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 334 // List-items in map clauses on this construct may only refer to the declared 335 // variable var and entities that could be referenced by a procedure defined 336 // at the same location 337 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 338 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 339 isa<VarDecl>(D)) { 340 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 341 << DMD->getVarName().getAsString(); 342 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 343 return true; 344 } 345 346 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 347 AvoidPartialAvailabilityChecks, ClassReceiver); 348 349 DiagnoseUnusedOfDecl(*this, D, Loc); 350 351 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 352 353 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 354 !isUnevaluatedContext()) { 355 // C++ [expr.prim.req.nested] p3 356 // A local parameter shall only appear as an unevaluated operand 357 // (Clause 8) within the constraint-expression. 358 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 359 << D; 360 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 361 return true; 362 } 363 364 return false; 365 } 366 367 /// DiagnoseSentinelCalls - This routine checks whether a call or 368 /// message-send is to a declaration with the sentinel attribute, and 369 /// if so, it checks that the requirements of the sentinel are 370 /// satisfied. 371 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 372 ArrayRef<Expr *> Args) { 373 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 374 if (!attr) 375 return; 376 377 // The number of formal parameters of the declaration. 378 unsigned numFormalParams; 379 380 // The kind of declaration. This is also an index into a %select in 381 // the diagnostic. 382 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 383 384 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 385 numFormalParams = MD->param_size(); 386 calleeType = CT_Method; 387 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 388 numFormalParams = FD->param_size(); 389 calleeType = CT_Function; 390 } else if (isa<VarDecl>(D)) { 391 QualType type = cast<ValueDecl>(D)->getType(); 392 const FunctionType *fn = nullptr; 393 if (const PointerType *ptr = type->getAs<PointerType>()) { 394 fn = ptr->getPointeeType()->getAs<FunctionType>(); 395 if (!fn) return; 396 calleeType = CT_Function; 397 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 398 fn = ptr->getPointeeType()->castAs<FunctionType>(); 399 calleeType = CT_Block; 400 } else { 401 return; 402 } 403 404 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 405 numFormalParams = proto->getNumParams(); 406 } else { 407 numFormalParams = 0; 408 } 409 } else { 410 return; 411 } 412 413 // "nullPos" is the number of formal parameters at the end which 414 // effectively count as part of the variadic arguments. This is 415 // useful if you would prefer to not have *any* formal parameters, 416 // but the language forces you to have at least one. 417 unsigned nullPos = attr->getNullPos(); 418 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 419 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 420 421 // The number of arguments which should follow the sentinel. 422 unsigned numArgsAfterSentinel = attr->getSentinel(); 423 424 // If there aren't enough arguments for all the formal parameters, 425 // the sentinel, and the args after the sentinel, complain. 426 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 427 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 429 return; 430 } 431 432 // Otherwise, find the sentinel expression. 433 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 434 if (!sentinelExpr) return; 435 if (sentinelExpr->isValueDependent()) return; 436 if (Context.isSentinelNullExpr(sentinelExpr)) return; 437 438 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 439 // or 'NULL' if those are actually defined in the context. Only use 440 // 'nil' for ObjC methods, where it's much more likely that the 441 // variadic arguments form a list of object pointers. 442 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 443 std::string NullValue; 444 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 445 NullValue = "nil"; 446 else if (getLangOpts().CPlusPlus11) 447 NullValue = "nullptr"; 448 else if (PP.isMacroDefined("NULL")) 449 NullValue = "NULL"; 450 else 451 NullValue = "(void*) 0"; 452 453 if (MissingNilLoc.isInvalid()) 454 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 455 else 456 Diag(MissingNilLoc, diag::warn_missing_sentinel) 457 << int(calleeType) 458 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 460 } 461 462 SourceRange Sema::getExprRange(Expr *E) const { 463 return E ? E->getSourceRange() : SourceRange(); 464 } 465 466 //===----------------------------------------------------------------------===// 467 // Standard Promotions and Conversions 468 //===----------------------------------------------------------------------===// 469 470 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 471 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 472 // Handle any placeholder expressions which made it here. 473 if (E->getType()->isPlaceholderType()) { 474 ExprResult result = CheckPlaceholderExpr(E); 475 if (result.isInvalid()) return ExprError(); 476 E = result.get(); 477 } 478 479 QualType Ty = E->getType(); 480 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 481 482 if (Ty->isFunctionType()) { 483 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 484 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 485 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 486 return ExprError(); 487 488 E = ImpCastExprToType(E, Context.getPointerType(Ty), 489 CK_FunctionToPointerDecay).get(); 490 } else if (Ty->isArrayType()) { 491 // In C90 mode, arrays only promote to pointers if the array expression is 492 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 493 // type 'array of type' is converted to an expression that has type 'pointer 494 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 495 // that has type 'array of type' ...". The relevant change is "an lvalue" 496 // (C90) to "an expression" (C99). 497 // 498 // C++ 4.2p1: 499 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 500 // T" can be converted to an rvalue of type "pointer to T". 501 // 502 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 503 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 504 CK_ArrayToPointerDecay).get(); 505 } 506 return E; 507 } 508 509 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 510 // Check to see if we are dereferencing a null pointer. If so, 511 // and if not volatile-qualified, this is undefined behavior that the 512 // optimizer will delete, so warn about it. People sometimes try to use this 513 // to get a deterministic trap and are surprised by clang's behavior. This 514 // only handles the pattern "*null", which is a very syntactic check. 515 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 516 if (UO && UO->getOpcode() == UO_Deref && 517 UO->getSubExpr()->getType()->isPointerType()) { 518 const LangAS AS = 519 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 520 if ((!isTargetAddressSpace(AS) || 521 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 522 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 523 S.Context, Expr::NPC_ValueDependentIsNotNull) && 524 !UO->getType().isVolatileQualified()) { 525 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 526 S.PDiag(diag::warn_indirection_through_null) 527 << UO->getSubExpr()->getSourceRange()); 528 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 529 S.PDiag(diag::note_indirection_through_null)); 530 } 531 } 532 } 533 534 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 535 SourceLocation AssignLoc, 536 const Expr* RHS) { 537 const ObjCIvarDecl *IV = OIRE->getDecl(); 538 if (!IV) 539 return; 540 541 DeclarationName MemberName = IV->getDeclName(); 542 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 543 if (!Member || !Member->isStr("isa")) 544 return; 545 546 const Expr *Base = OIRE->getBase(); 547 QualType BaseType = Base->getType(); 548 if (OIRE->isArrow()) 549 BaseType = BaseType->getPointeeType(); 550 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 551 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 552 ObjCInterfaceDecl *ClassDeclared = nullptr; 553 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 554 if (!ClassDeclared->getSuperClass() 555 && (*ClassDeclared->ivar_begin()) == IV) { 556 if (RHS) { 557 NamedDecl *ObjectSetClass = 558 S.LookupSingleName(S.TUScope, 559 &S.Context.Idents.get("object_setClass"), 560 SourceLocation(), S.LookupOrdinaryName); 561 if (ObjectSetClass) { 562 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 563 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 564 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 565 "object_setClass(") 566 << FixItHint::CreateReplacement( 567 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 568 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 569 } 570 else 571 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 572 } else { 573 NamedDecl *ObjectGetClass = 574 S.LookupSingleName(S.TUScope, 575 &S.Context.Idents.get("object_getClass"), 576 SourceLocation(), S.LookupOrdinaryName); 577 if (ObjectGetClass) 578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 580 "object_getClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 583 else 584 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 585 } 586 S.Diag(IV->getLocation(), diag::note_ivar_decl); 587 } 588 } 589 } 590 591 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 592 // Handle any placeholder expressions which made it here. 593 if (E->getType()->isPlaceholderType()) { 594 ExprResult result = CheckPlaceholderExpr(E); 595 if (result.isInvalid()) return ExprError(); 596 E = result.get(); 597 } 598 599 // C++ [conv.lval]p1: 600 // A glvalue of a non-function, non-array type T can be 601 // converted to a prvalue. 602 if (!E->isGLValue()) return E; 603 604 QualType T = E->getType(); 605 assert(!T.isNull() && "r-value conversion on typeless expression?"); 606 607 // We don't want to throw lvalue-to-rvalue casts on top of 608 // expressions of certain types in C++. 609 if (getLangOpts().CPlusPlus && 610 (E->getType() == Context.OverloadTy || 611 T->isDependentType() || 612 T->isRecordType())) 613 return E; 614 615 // The C standard is actually really unclear on this point, and 616 // DR106 tells us what the result should be but not why. It's 617 // generally best to say that void types just doesn't undergo 618 // lvalue-to-rvalue at all. Note that expressions of unqualified 619 // 'void' type are never l-values, but qualified void can be. 620 if (T->isVoidType()) 621 return E; 622 623 // OpenCL usually rejects direct accesses to values of 'half' type. 624 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 625 T->isHalfType()) { 626 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 627 << 0 << T; 628 return ExprError(); 629 } 630 631 CheckForNullPointerDereference(*this, E); 632 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 633 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 634 &Context.Idents.get("object_getClass"), 635 SourceLocation(), LookupOrdinaryName); 636 if (ObjectGetClass) 637 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 638 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 639 << FixItHint::CreateReplacement( 640 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 641 else 642 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 643 } 644 else if (const ObjCIvarRefExpr *OIRE = 645 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 646 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 647 648 // C++ [conv.lval]p1: 649 // [...] If T is a non-class type, the type of the prvalue is the 650 // cv-unqualified version of T. Otherwise, the type of the 651 // rvalue is T. 652 // 653 // C99 6.3.2.1p2: 654 // If the lvalue has qualified type, the value has the unqualified 655 // version of the type of the lvalue; otherwise, the value has the 656 // type of the lvalue. 657 if (T.hasQualifiers()) 658 T = T.getUnqualifiedType(); 659 660 // Under the MS ABI, lock down the inheritance model now. 661 if (T->isMemberPointerType() && 662 Context.getTargetInfo().getCXXABI().isMicrosoft()) 663 (void)isCompleteType(E->getExprLoc(), T); 664 665 ExprResult Res = CheckLValueToRValueConversionOperand(E); 666 if (Res.isInvalid()) 667 return Res; 668 E = Res.get(); 669 670 // Loading a __weak object implicitly retains the value, so we need a cleanup to 671 // balance that. 672 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 673 Cleanup.setExprNeedsCleanups(true); 674 675 // C++ [conv.lval]p3: 676 // If T is cv std::nullptr_t, the result is a null pointer constant. 677 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 678 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 679 680 // C11 6.3.2.1p2: 681 // ... if the lvalue has atomic type, the value has the non-atomic version 682 // of the type of the lvalue ... 683 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 684 T = Atomic->getValueType().getUnqualifiedType(); 685 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 686 nullptr, VK_RValue); 687 } 688 689 return Res; 690 } 691 692 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 693 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 694 if (Res.isInvalid()) 695 return ExprError(); 696 Res = DefaultLvalueConversion(Res.get()); 697 if (Res.isInvalid()) 698 return ExprError(); 699 return Res; 700 } 701 702 /// CallExprUnaryConversions - a special case of an unary conversion 703 /// performed on a function designator of a call expression. 704 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 705 QualType Ty = E->getType(); 706 ExprResult Res = E; 707 // Only do implicit cast for a function type, but not for a pointer 708 // to function type. 709 if (Ty->isFunctionType()) { 710 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 711 CK_FunctionToPointerDecay).get(); 712 if (Res.isInvalid()) 713 return ExprError(); 714 } 715 Res = DefaultLvalueConversion(Res.get()); 716 if (Res.isInvalid()) 717 return ExprError(); 718 return Res.get(); 719 } 720 721 /// UsualUnaryConversions - Performs various conversions that are common to most 722 /// operators (C99 6.3). The conversions of array and function types are 723 /// sometimes suppressed. For example, the array->pointer conversion doesn't 724 /// apply if the array is an argument to the sizeof or address (&) operators. 725 /// In these instances, this routine should *not* be called. 726 ExprResult Sema::UsualUnaryConversions(Expr *E) { 727 // First, convert to an r-value. 728 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 729 if (Res.isInvalid()) 730 return ExprError(); 731 E = Res.get(); 732 733 QualType Ty = E->getType(); 734 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 735 736 // Half FP have to be promoted to float unless it is natively supported 737 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 738 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 739 740 // Try to perform integral promotions if the object has a theoretically 741 // promotable type. 742 if (Ty->isIntegralOrUnscopedEnumerationType()) { 743 // C99 6.3.1.1p2: 744 // 745 // The following may be used in an expression wherever an int or 746 // unsigned int may be used: 747 // - an object or expression with an integer type whose integer 748 // conversion rank is less than or equal to the rank of int 749 // and unsigned int. 750 // - A bit-field of type _Bool, int, signed int, or unsigned int. 751 // 752 // If an int can represent all values of the original type, the 753 // value is converted to an int; otherwise, it is converted to an 754 // unsigned int. These are called the integer promotions. All 755 // other types are unchanged by the integer promotions. 756 757 QualType PTy = Context.isPromotableBitField(E); 758 if (!PTy.isNull()) { 759 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 760 return E; 761 } 762 if (Ty->isPromotableIntegerType()) { 763 QualType PT = Context.getPromotedIntegerType(Ty); 764 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 765 return E; 766 } 767 } 768 return E; 769 } 770 771 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 772 /// do not have a prototype. Arguments that have type float or __fp16 773 /// are promoted to double. All other argument types are converted by 774 /// UsualUnaryConversions(). 775 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 776 QualType Ty = E->getType(); 777 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 778 779 ExprResult Res = UsualUnaryConversions(E); 780 if (Res.isInvalid()) 781 return ExprError(); 782 E = Res.get(); 783 784 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 785 // promote to double. 786 // Note that default argument promotion applies only to float (and 787 // half/fp16); it does not apply to _Float16. 788 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 789 if (BTy && (BTy->getKind() == BuiltinType::Half || 790 BTy->getKind() == BuiltinType::Float)) { 791 if (getLangOpts().OpenCL && 792 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 793 if (BTy->getKind() == BuiltinType::Half) { 794 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 795 } 796 } else { 797 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 798 } 799 } 800 801 // C++ performs lvalue-to-rvalue conversion as a default argument 802 // promotion, even on class types, but note: 803 // C++11 [conv.lval]p2: 804 // When an lvalue-to-rvalue conversion occurs in an unevaluated 805 // operand or a subexpression thereof the value contained in the 806 // referenced object is not accessed. Otherwise, if the glvalue 807 // has a class type, the conversion copy-initializes a temporary 808 // of type T from the glvalue and the result of the conversion 809 // is a prvalue for the temporary. 810 // FIXME: add some way to gate this entire thing for correctness in 811 // potentially potentially evaluated contexts. 812 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 813 ExprResult Temp = PerformCopyInitialization( 814 InitializedEntity::InitializeTemporary(E->getType()), 815 E->getExprLoc(), E); 816 if (Temp.isInvalid()) 817 return ExprError(); 818 E = Temp.get(); 819 } 820 821 return E; 822 } 823 824 /// Determine the degree of POD-ness for an expression. 825 /// Incomplete types are considered POD, since this check can be performed 826 /// when we're in an unevaluated context. 827 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 828 if (Ty->isIncompleteType()) { 829 // C++11 [expr.call]p7: 830 // After these conversions, if the argument does not have arithmetic, 831 // enumeration, pointer, pointer to member, or class type, the program 832 // is ill-formed. 833 // 834 // Since we've already performed array-to-pointer and function-to-pointer 835 // decay, the only such type in C++ is cv void. This also handles 836 // initializer lists as variadic arguments. 837 if (Ty->isVoidType()) 838 return VAK_Invalid; 839 840 if (Ty->isObjCObjectType()) 841 return VAK_Invalid; 842 return VAK_Valid; 843 } 844 845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 846 return VAK_Invalid; 847 848 if (Ty.isCXX98PODType(Context)) 849 return VAK_Valid; 850 851 // C++11 [expr.call]p7: 852 // Passing a potentially-evaluated argument of class type (Clause 9) 853 // having a non-trivial copy constructor, a non-trivial move constructor, 854 // or a non-trivial destructor, with no corresponding parameter, 855 // is conditionally-supported with implementation-defined semantics. 856 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 857 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 858 if (!Record->hasNonTrivialCopyConstructor() && 859 !Record->hasNonTrivialMoveConstructor() && 860 !Record->hasNonTrivialDestructor()) 861 return VAK_ValidInCXX11; 862 863 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 864 return VAK_Valid; 865 866 if (Ty->isObjCObjectType()) 867 return VAK_Invalid; 868 869 if (getLangOpts().MSVCCompat) 870 return VAK_MSVCUndefined; 871 872 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 873 // permitted to reject them. We should consider doing so. 874 return VAK_Undefined; 875 } 876 877 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 878 // Don't allow one to pass an Objective-C interface to a vararg. 879 const QualType &Ty = E->getType(); 880 VarArgKind VAK = isValidVarArgType(Ty); 881 882 // Complain about passing non-POD types through varargs. 883 switch (VAK) { 884 case VAK_ValidInCXX11: 885 DiagRuntimeBehavior( 886 E->getBeginLoc(), nullptr, 887 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 888 LLVM_FALLTHROUGH; 889 case VAK_Valid: 890 if (Ty->isRecordType()) { 891 // This is unlikely to be what the user intended. If the class has a 892 // 'c_str' member function, the user probably meant to call that. 893 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 894 PDiag(diag::warn_pass_class_arg_to_vararg) 895 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 896 } 897 break; 898 899 case VAK_Undefined: 900 case VAK_MSVCUndefined: 901 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 902 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 903 << getLangOpts().CPlusPlus11 << Ty << CT); 904 break; 905 906 case VAK_Invalid: 907 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 908 Diag(E->getBeginLoc(), 909 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 910 << Ty << CT; 911 else if (Ty->isObjCObjectType()) 912 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 913 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 914 << Ty << CT); 915 else 916 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 917 << isa<InitListExpr>(E) << Ty << CT; 918 break; 919 } 920 } 921 922 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 923 /// will create a trap if the resulting type is not a POD type. 924 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 925 FunctionDecl *FDecl) { 926 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 927 // Strip the unbridged-cast placeholder expression off, if applicable. 928 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 929 (CT == VariadicMethod || 930 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 931 E = stripARCUnbridgedCast(E); 932 933 // Otherwise, do normal placeholder checking. 934 } else { 935 ExprResult ExprRes = CheckPlaceholderExpr(E); 936 if (ExprRes.isInvalid()) 937 return ExprError(); 938 E = ExprRes.get(); 939 } 940 } 941 942 ExprResult ExprRes = DefaultArgumentPromotion(E); 943 if (ExprRes.isInvalid()) 944 return ExprError(); 945 E = ExprRes.get(); 946 947 // Diagnostics regarding non-POD argument types are 948 // emitted along with format string checking in Sema::CheckFunctionCall(). 949 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 950 // Turn this into a trap. 951 CXXScopeSpec SS; 952 SourceLocation TemplateKWLoc; 953 UnqualifiedId Name; 954 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 955 E->getBeginLoc()); 956 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 957 /*HasTrailingLParen=*/true, 958 /*IsAddressOfOperand=*/false); 959 if (TrapFn.isInvalid()) 960 return ExprError(); 961 962 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 963 None, E->getEndLoc()); 964 if (Call.isInvalid()) 965 return ExprError(); 966 967 ExprResult Comma = 968 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 969 if (Comma.isInvalid()) 970 return ExprError(); 971 return Comma.get(); 972 } 973 974 if (!getLangOpts().CPlusPlus && 975 RequireCompleteType(E->getExprLoc(), E->getType(), 976 diag::err_call_incomplete_argument)) 977 return ExprError(); 978 979 return E; 980 } 981 982 /// Converts an integer to complex float type. Helper function of 983 /// UsualArithmeticConversions() 984 /// 985 /// \return false if the integer expression is an integer type and is 986 /// successfully converted to the complex type. 987 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 988 ExprResult &ComplexExpr, 989 QualType IntTy, 990 QualType ComplexTy, 991 bool SkipCast) { 992 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 993 if (SkipCast) return false; 994 if (IntTy->isIntegerType()) { 995 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 996 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 997 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 998 CK_FloatingRealToComplex); 999 } else { 1000 assert(IntTy->isComplexIntegerType()); 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1002 CK_IntegralComplexToFloatingComplex); 1003 } 1004 return false; 1005 } 1006 1007 /// Handle arithmetic conversion with complex types. Helper function of 1008 /// UsualArithmeticConversions() 1009 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1010 ExprResult &RHS, QualType LHSType, 1011 QualType RHSType, 1012 bool IsCompAssign) { 1013 // if we have an integer operand, the result is the complex type. 1014 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1015 /*skipCast*/false)) 1016 return LHSType; 1017 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1018 /*skipCast*/IsCompAssign)) 1019 return RHSType; 1020 1021 // This handles complex/complex, complex/float, or float/complex. 1022 // When both operands are complex, the shorter operand is converted to the 1023 // type of the longer, and that is the type of the result. This corresponds 1024 // to what is done when combining two real floating-point operands. 1025 // The fun begins when size promotion occur across type domains. 1026 // From H&S 6.3.4: When one operand is complex and the other is a real 1027 // floating-point type, the less precise type is converted, within it's 1028 // real or complex domain, to the precision of the other type. For example, 1029 // when combining a "long double" with a "double _Complex", the 1030 // "double _Complex" is promoted to "long double _Complex". 1031 1032 // Compute the rank of the two types, regardless of whether they are complex. 1033 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1034 1035 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1036 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1037 QualType LHSElementType = 1038 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1039 QualType RHSElementType = 1040 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1041 1042 QualType ResultType = S.Context.getComplexType(LHSElementType); 1043 if (Order < 0) { 1044 // Promote the precision of the LHS if not an assignment. 1045 ResultType = S.Context.getComplexType(RHSElementType); 1046 if (!IsCompAssign) { 1047 if (LHSComplexType) 1048 LHS = 1049 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1050 else 1051 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1052 } 1053 } else if (Order > 0) { 1054 // Promote the precision of the RHS. 1055 if (RHSComplexType) 1056 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1057 else 1058 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1059 } 1060 return ResultType; 1061 } 1062 1063 /// Handle arithmetic conversion from integer to float. Helper function 1064 /// of UsualArithmeticConversions() 1065 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1066 ExprResult &IntExpr, 1067 QualType FloatTy, QualType IntTy, 1068 bool ConvertFloat, bool ConvertInt) { 1069 if (IntTy->isIntegerType()) { 1070 if (ConvertInt) 1071 // Convert intExpr to the lhs floating point type. 1072 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1073 CK_IntegralToFloating); 1074 return FloatTy; 1075 } 1076 1077 // Convert both sides to the appropriate complex float. 1078 assert(IntTy->isComplexIntegerType()); 1079 QualType result = S.Context.getComplexType(FloatTy); 1080 1081 // _Complex int -> _Complex float 1082 if (ConvertInt) 1083 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1084 CK_IntegralComplexToFloatingComplex); 1085 1086 // float -> _Complex float 1087 if (ConvertFloat) 1088 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1089 CK_FloatingRealToComplex); 1090 1091 return result; 1092 } 1093 1094 /// Handle arithmethic conversion with floating point types. Helper 1095 /// function of UsualArithmeticConversions() 1096 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1097 ExprResult &RHS, QualType LHSType, 1098 QualType RHSType, bool IsCompAssign) { 1099 bool LHSFloat = LHSType->isRealFloatingType(); 1100 bool RHSFloat = RHSType->isRealFloatingType(); 1101 1102 // If we have two real floating types, convert the smaller operand 1103 // to the bigger result. 1104 if (LHSFloat && RHSFloat) { 1105 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1106 if (order > 0) { 1107 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1108 return LHSType; 1109 } 1110 1111 assert(order < 0 && "illegal float comparison"); 1112 if (!IsCompAssign) 1113 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1114 return RHSType; 1115 } 1116 1117 if (LHSFloat) { 1118 // Half FP has to be promoted to float unless it is natively supported 1119 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1120 LHSType = S.Context.FloatTy; 1121 1122 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1123 /*ConvertFloat=*/!IsCompAssign, 1124 /*ConvertInt=*/ true); 1125 } 1126 assert(RHSFloat); 1127 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1128 /*convertInt=*/ true, 1129 /*convertFloat=*/!IsCompAssign); 1130 } 1131 1132 /// Diagnose attempts to convert between __float128 and long double if 1133 /// there is no support for such conversion. Helper function of 1134 /// UsualArithmeticConversions(). 1135 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1136 QualType RHSType) { 1137 /* No issue converting if at least one of the types is not a floating point 1138 type or the two types have the same rank. 1139 */ 1140 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1141 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1142 return false; 1143 1144 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1145 "The remaining types must be floating point types."); 1146 1147 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1148 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1149 1150 QualType LHSElemType = LHSComplex ? 1151 LHSComplex->getElementType() : LHSType; 1152 QualType RHSElemType = RHSComplex ? 1153 RHSComplex->getElementType() : RHSType; 1154 1155 // No issue if the two types have the same representation 1156 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1157 &S.Context.getFloatTypeSemantics(RHSElemType)) 1158 return false; 1159 1160 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1161 RHSElemType == S.Context.LongDoubleTy); 1162 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1163 RHSElemType == S.Context.Float128Ty); 1164 1165 // We've handled the situation where __float128 and long double have the same 1166 // representation. We allow all conversions for all possible long double types 1167 // except PPC's double double. 1168 return Float128AndLongDouble && 1169 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1170 &llvm::APFloat::PPCDoubleDouble()); 1171 } 1172 1173 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1174 1175 namespace { 1176 /// These helper callbacks are placed in an anonymous namespace to 1177 /// permit their use as function template parameters. 1178 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1179 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1180 } 1181 1182 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1183 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1184 CK_IntegralComplexCast); 1185 } 1186 } 1187 1188 /// Handle integer arithmetic conversions. Helper function of 1189 /// UsualArithmeticConversions() 1190 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1191 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1192 ExprResult &RHS, QualType LHSType, 1193 QualType RHSType, bool IsCompAssign) { 1194 // The rules for this case are in C99 6.3.1.8 1195 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1196 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1197 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1198 if (LHSSigned == RHSSigned) { 1199 // Same signedness; use the higher-ranked type 1200 if (order >= 0) { 1201 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1202 return LHSType; 1203 } else if (!IsCompAssign) 1204 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1205 return RHSType; 1206 } else if (order != (LHSSigned ? 1 : -1)) { 1207 // The unsigned type has greater than or equal rank to the 1208 // signed type, so use the unsigned type 1209 if (RHSSigned) { 1210 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1211 return LHSType; 1212 } else if (!IsCompAssign) 1213 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1214 return RHSType; 1215 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1216 // The two types are different widths; if we are here, that 1217 // means the signed type is larger than the unsigned type, so 1218 // use the signed type. 1219 if (LHSSigned) { 1220 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1221 return LHSType; 1222 } else if (!IsCompAssign) 1223 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1224 return RHSType; 1225 } else { 1226 // The signed type is higher-ranked than the unsigned type, 1227 // but isn't actually any bigger (like unsigned int and long 1228 // on most 32-bit systems). Use the unsigned type corresponding 1229 // to the signed type. 1230 QualType result = 1231 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1232 RHS = (*doRHSCast)(S, RHS.get(), result); 1233 if (!IsCompAssign) 1234 LHS = (*doLHSCast)(S, LHS.get(), result); 1235 return result; 1236 } 1237 } 1238 1239 /// Handle conversions with GCC complex int extension. Helper function 1240 /// of UsualArithmeticConversions() 1241 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1242 ExprResult &RHS, QualType LHSType, 1243 QualType RHSType, 1244 bool IsCompAssign) { 1245 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1246 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1247 1248 if (LHSComplexInt && RHSComplexInt) { 1249 QualType LHSEltType = LHSComplexInt->getElementType(); 1250 QualType RHSEltType = RHSComplexInt->getElementType(); 1251 QualType ScalarType = 1252 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1253 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1254 1255 return S.Context.getComplexType(ScalarType); 1256 } 1257 1258 if (LHSComplexInt) { 1259 QualType LHSEltType = LHSComplexInt->getElementType(); 1260 QualType ScalarType = 1261 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1262 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1263 QualType ComplexType = S.Context.getComplexType(ScalarType); 1264 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1265 CK_IntegralRealToComplex); 1266 1267 return ComplexType; 1268 } 1269 1270 assert(RHSComplexInt); 1271 1272 QualType RHSEltType = RHSComplexInt->getElementType(); 1273 QualType ScalarType = 1274 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1275 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1276 QualType ComplexType = S.Context.getComplexType(ScalarType); 1277 1278 if (!IsCompAssign) 1279 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1280 CK_IntegralRealToComplex); 1281 return ComplexType; 1282 } 1283 1284 /// Return the rank of a given fixed point or integer type. The value itself 1285 /// doesn't matter, but the values must be increasing with proper increasing 1286 /// rank as described in N1169 4.1.1. 1287 static unsigned GetFixedPointRank(QualType Ty) { 1288 const auto *BTy = Ty->getAs<BuiltinType>(); 1289 assert(BTy && "Expected a builtin type."); 1290 1291 switch (BTy->getKind()) { 1292 case BuiltinType::ShortFract: 1293 case BuiltinType::UShortFract: 1294 case BuiltinType::SatShortFract: 1295 case BuiltinType::SatUShortFract: 1296 return 1; 1297 case BuiltinType::Fract: 1298 case BuiltinType::UFract: 1299 case BuiltinType::SatFract: 1300 case BuiltinType::SatUFract: 1301 return 2; 1302 case BuiltinType::LongFract: 1303 case BuiltinType::ULongFract: 1304 case BuiltinType::SatLongFract: 1305 case BuiltinType::SatULongFract: 1306 return 3; 1307 case BuiltinType::ShortAccum: 1308 case BuiltinType::UShortAccum: 1309 case BuiltinType::SatShortAccum: 1310 case BuiltinType::SatUShortAccum: 1311 return 4; 1312 case BuiltinType::Accum: 1313 case BuiltinType::UAccum: 1314 case BuiltinType::SatAccum: 1315 case BuiltinType::SatUAccum: 1316 return 5; 1317 case BuiltinType::LongAccum: 1318 case BuiltinType::ULongAccum: 1319 case BuiltinType::SatLongAccum: 1320 case BuiltinType::SatULongAccum: 1321 return 6; 1322 default: 1323 if (BTy->isInteger()) 1324 return 0; 1325 llvm_unreachable("Unexpected fixed point or integer type"); 1326 } 1327 } 1328 1329 /// handleFixedPointConversion - Fixed point operations between fixed 1330 /// point types and integers or other fixed point types do not fall under 1331 /// usual arithmetic conversion since these conversions could result in loss 1332 /// of precsision (N1169 4.1.4). These operations should be calculated with 1333 /// the full precision of their result type (N1169 4.1.6.2.1). 1334 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1335 QualType RHSTy) { 1336 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1337 "Expected at least one of the operands to be a fixed point type"); 1338 assert((LHSTy->isFixedPointOrIntegerType() || 1339 RHSTy->isFixedPointOrIntegerType()) && 1340 "Special fixed point arithmetic operation conversions are only " 1341 "applied to ints or other fixed point types"); 1342 1343 // If one operand has signed fixed-point type and the other operand has 1344 // unsigned fixed-point type, then the unsigned fixed-point operand is 1345 // converted to its corresponding signed fixed-point type and the resulting 1346 // type is the type of the converted operand. 1347 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1348 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1349 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1350 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1351 1352 // The result type is the type with the highest rank, whereby a fixed-point 1353 // conversion rank is always greater than an integer conversion rank; if the 1354 // type of either of the operands is a saturating fixedpoint type, the result 1355 // type shall be the saturating fixed-point type corresponding to the type 1356 // with the highest rank; the resulting value is converted (taking into 1357 // account rounding and overflow) to the precision of the resulting type. 1358 // Same ranks between signed and unsigned types are resolved earlier, so both 1359 // types are either signed or both unsigned at this point. 1360 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1361 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1362 1363 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1364 1365 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1366 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1367 1368 return ResultTy; 1369 } 1370 1371 /// Check that the usual arithmetic conversions can be performed on this pair of 1372 /// expressions that might be of enumeration type. 1373 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1374 SourceLocation Loc, 1375 Sema::ArithConvKind ACK) { 1376 // C++2a [expr.arith.conv]p1: 1377 // If one operand is of enumeration type and the other operand is of a 1378 // different enumeration type or a floating-point type, this behavior is 1379 // deprecated ([depr.arith.conv.enum]). 1380 // 1381 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1382 // Eventually we will presumably reject these cases (in C++23 onwards?). 1383 QualType L = LHS->getType(), R = RHS->getType(); 1384 bool LEnum = L->isUnscopedEnumerationType(), 1385 REnum = R->isUnscopedEnumerationType(); 1386 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1387 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1388 (REnum && L->isFloatingType())) { 1389 S.Diag(Loc, S.getLangOpts().CPlusPlus2a 1390 ? diag::warn_arith_conv_enum_float_cxx2a 1391 : diag::warn_arith_conv_enum_float) 1392 << LHS->getSourceRange() << RHS->getSourceRange() 1393 << (int)ACK << LEnum << L << R; 1394 } else if (!IsCompAssign && LEnum && REnum && 1395 !S.Context.hasSameUnqualifiedType(L, R)) { 1396 unsigned DiagID; 1397 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1398 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1399 // If either enumeration type is unnamed, it's less likely that the 1400 // user cares about this, but this situation is still deprecated in 1401 // C++2a. Use a different warning group. 1402 DiagID = S.getLangOpts().CPlusPlus2a 1403 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a 1404 : diag::warn_arith_conv_mixed_anon_enum_types; 1405 } else if (ACK == Sema::ACK_Conditional) { 1406 // Conditional expressions are separated out because they have 1407 // historically had a different warning flag. 1408 DiagID = S.getLangOpts().CPlusPlus2a 1409 ? diag::warn_conditional_mixed_enum_types_cxx2a 1410 : diag::warn_conditional_mixed_enum_types; 1411 } else if (ACK == Sema::ACK_Comparison) { 1412 // Comparison expressions are separated out because they have 1413 // historically had a different warning flag. 1414 DiagID = S.getLangOpts().CPlusPlus2a 1415 ? diag::warn_comparison_mixed_enum_types_cxx2a 1416 : diag::warn_comparison_mixed_enum_types; 1417 } else { 1418 DiagID = S.getLangOpts().CPlusPlus2a 1419 ? diag::warn_arith_conv_mixed_enum_types_cxx2a 1420 : diag::warn_arith_conv_mixed_enum_types; 1421 } 1422 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1423 << (int)ACK << L << R; 1424 } 1425 } 1426 1427 /// UsualArithmeticConversions - Performs various conversions that are common to 1428 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1429 /// routine returns the first non-arithmetic type found. The client is 1430 /// responsible for emitting appropriate error diagnostics. 1431 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1432 SourceLocation Loc, 1433 ArithConvKind ACK) { 1434 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1435 1436 if (ACK != ACK_CompAssign) { 1437 LHS = UsualUnaryConversions(LHS.get()); 1438 if (LHS.isInvalid()) 1439 return QualType(); 1440 } 1441 1442 RHS = UsualUnaryConversions(RHS.get()); 1443 if (RHS.isInvalid()) 1444 return QualType(); 1445 1446 // For conversion purposes, we ignore any qualifiers. 1447 // For example, "const float" and "float" are equivalent. 1448 QualType LHSType = 1449 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1450 QualType RHSType = 1451 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1452 1453 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1454 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1455 LHSType = AtomicLHS->getValueType(); 1456 1457 // If both types are identical, no conversion is needed. 1458 if (LHSType == RHSType) 1459 return LHSType; 1460 1461 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1462 // The caller can deal with this (e.g. pointer + int). 1463 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1464 return QualType(); 1465 1466 // Apply unary and bitfield promotions to the LHS's type. 1467 QualType LHSUnpromotedType = LHSType; 1468 if (LHSType->isPromotableIntegerType()) 1469 LHSType = Context.getPromotedIntegerType(LHSType); 1470 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1471 if (!LHSBitfieldPromoteTy.isNull()) 1472 LHSType = LHSBitfieldPromoteTy; 1473 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1474 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1475 1476 // If both types are identical, no conversion is needed. 1477 if (LHSType == RHSType) 1478 return LHSType; 1479 1480 // At this point, we have two different arithmetic types. 1481 1482 // Diagnose attempts to convert between __float128 and long double where 1483 // such conversions currently can't be handled. 1484 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1485 return QualType(); 1486 1487 // Handle complex types first (C99 6.3.1.8p1). 1488 if (LHSType->isComplexType() || RHSType->isComplexType()) 1489 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1490 ACK == ACK_CompAssign); 1491 1492 // Now handle "real" floating types (i.e. float, double, long double). 1493 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1494 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1495 ACK == ACK_CompAssign); 1496 1497 // Handle GCC complex int extension. 1498 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1499 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1500 ACK == ACK_CompAssign); 1501 1502 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1503 return handleFixedPointConversion(*this, LHSType, RHSType); 1504 1505 // Finally, we have two differing integer types. 1506 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1507 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1508 } 1509 1510 //===----------------------------------------------------------------------===// 1511 // Semantic Analysis for various Expression Types 1512 //===----------------------------------------------------------------------===// 1513 1514 1515 ExprResult 1516 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1517 SourceLocation DefaultLoc, 1518 SourceLocation RParenLoc, 1519 Expr *ControllingExpr, 1520 ArrayRef<ParsedType> ArgTypes, 1521 ArrayRef<Expr *> ArgExprs) { 1522 unsigned NumAssocs = ArgTypes.size(); 1523 assert(NumAssocs == ArgExprs.size()); 1524 1525 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1526 for (unsigned i = 0; i < NumAssocs; ++i) { 1527 if (ArgTypes[i]) 1528 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1529 else 1530 Types[i] = nullptr; 1531 } 1532 1533 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1534 ControllingExpr, 1535 llvm::makeArrayRef(Types, NumAssocs), 1536 ArgExprs); 1537 delete [] Types; 1538 return ER; 1539 } 1540 1541 ExprResult 1542 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1543 SourceLocation DefaultLoc, 1544 SourceLocation RParenLoc, 1545 Expr *ControllingExpr, 1546 ArrayRef<TypeSourceInfo *> Types, 1547 ArrayRef<Expr *> Exprs) { 1548 unsigned NumAssocs = Types.size(); 1549 assert(NumAssocs == Exprs.size()); 1550 1551 // Decay and strip qualifiers for the controlling expression type, and handle 1552 // placeholder type replacement. See committee discussion from WG14 DR423. 1553 { 1554 EnterExpressionEvaluationContext Unevaluated( 1555 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1556 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1557 if (R.isInvalid()) 1558 return ExprError(); 1559 ControllingExpr = R.get(); 1560 } 1561 1562 // The controlling expression is an unevaluated operand, so side effects are 1563 // likely unintended. 1564 if (!inTemplateInstantiation() && 1565 ControllingExpr->HasSideEffects(Context, false)) 1566 Diag(ControllingExpr->getExprLoc(), 1567 diag::warn_side_effects_unevaluated_context); 1568 1569 bool TypeErrorFound = false, 1570 IsResultDependent = ControllingExpr->isTypeDependent(), 1571 ContainsUnexpandedParameterPack 1572 = ControllingExpr->containsUnexpandedParameterPack(); 1573 1574 for (unsigned i = 0; i < NumAssocs; ++i) { 1575 if (Exprs[i]->containsUnexpandedParameterPack()) 1576 ContainsUnexpandedParameterPack = true; 1577 1578 if (Types[i]) { 1579 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1580 ContainsUnexpandedParameterPack = true; 1581 1582 if (Types[i]->getType()->isDependentType()) { 1583 IsResultDependent = true; 1584 } else { 1585 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1586 // complete object type other than a variably modified type." 1587 unsigned D = 0; 1588 if (Types[i]->getType()->isIncompleteType()) 1589 D = diag::err_assoc_type_incomplete; 1590 else if (!Types[i]->getType()->isObjectType()) 1591 D = diag::err_assoc_type_nonobject; 1592 else if (Types[i]->getType()->isVariablyModifiedType()) 1593 D = diag::err_assoc_type_variably_modified; 1594 1595 if (D != 0) { 1596 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1597 << Types[i]->getTypeLoc().getSourceRange() 1598 << Types[i]->getType(); 1599 TypeErrorFound = true; 1600 } 1601 1602 // C11 6.5.1.1p2 "No two generic associations in the same generic 1603 // selection shall specify compatible types." 1604 for (unsigned j = i+1; j < NumAssocs; ++j) 1605 if (Types[j] && !Types[j]->getType()->isDependentType() && 1606 Context.typesAreCompatible(Types[i]->getType(), 1607 Types[j]->getType())) { 1608 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1609 diag::err_assoc_compatible_types) 1610 << Types[j]->getTypeLoc().getSourceRange() 1611 << Types[j]->getType() 1612 << Types[i]->getType(); 1613 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1614 diag::note_compat_assoc) 1615 << Types[i]->getTypeLoc().getSourceRange() 1616 << Types[i]->getType(); 1617 TypeErrorFound = true; 1618 } 1619 } 1620 } 1621 } 1622 if (TypeErrorFound) 1623 return ExprError(); 1624 1625 // If we determined that the generic selection is result-dependent, don't 1626 // try to compute the result expression. 1627 if (IsResultDependent) 1628 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1629 Exprs, DefaultLoc, RParenLoc, 1630 ContainsUnexpandedParameterPack); 1631 1632 SmallVector<unsigned, 1> CompatIndices; 1633 unsigned DefaultIndex = -1U; 1634 for (unsigned i = 0; i < NumAssocs; ++i) { 1635 if (!Types[i]) 1636 DefaultIndex = i; 1637 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1638 Types[i]->getType())) 1639 CompatIndices.push_back(i); 1640 } 1641 1642 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1643 // type compatible with at most one of the types named in its generic 1644 // association list." 1645 if (CompatIndices.size() > 1) { 1646 // We strip parens here because the controlling expression is typically 1647 // parenthesized in macro definitions. 1648 ControllingExpr = ControllingExpr->IgnoreParens(); 1649 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1650 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1651 << (unsigned)CompatIndices.size(); 1652 for (unsigned I : CompatIndices) { 1653 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1654 diag::note_compat_assoc) 1655 << Types[I]->getTypeLoc().getSourceRange() 1656 << Types[I]->getType(); 1657 } 1658 return ExprError(); 1659 } 1660 1661 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1662 // its controlling expression shall have type compatible with exactly one of 1663 // the types named in its generic association list." 1664 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1665 // We strip parens here because the controlling expression is typically 1666 // parenthesized in macro definitions. 1667 ControllingExpr = ControllingExpr->IgnoreParens(); 1668 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1669 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1670 return ExprError(); 1671 } 1672 1673 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1674 // type name that is compatible with the type of the controlling expression, 1675 // then the result expression of the generic selection is the expression 1676 // in that generic association. Otherwise, the result expression of the 1677 // generic selection is the expression in the default generic association." 1678 unsigned ResultIndex = 1679 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1680 1681 return GenericSelectionExpr::Create( 1682 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1683 ContainsUnexpandedParameterPack, ResultIndex); 1684 } 1685 1686 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1687 /// location of the token and the offset of the ud-suffix within it. 1688 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1689 unsigned Offset) { 1690 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1691 S.getLangOpts()); 1692 } 1693 1694 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1695 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1696 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1697 IdentifierInfo *UDSuffix, 1698 SourceLocation UDSuffixLoc, 1699 ArrayRef<Expr*> Args, 1700 SourceLocation LitEndLoc) { 1701 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1702 1703 QualType ArgTy[2]; 1704 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1705 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1706 if (ArgTy[ArgIdx]->isArrayType()) 1707 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1708 } 1709 1710 DeclarationName OpName = 1711 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1712 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1713 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1714 1715 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1716 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1717 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1718 /*AllowStringTemplate*/ false, 1719 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1720 return ExprError(); 1721 1722 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1723 } 1724 1725 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1726 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1727 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1728 /// multiple tokens. However, the common case is that StringToks points to one 1729 /// string. 1730 /// 1731 ExprResult 1732 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1733 assert(!StringToks.empty() && "Must have at least one string!"); 1734 1735 StringLiteralParser Literal(StringToks, PP); 1736 if (Literal.hadError) 1737 return ExprError(); 1738 1739 SmallVector<SourceLocation, 4> StringTokLocs; 1740 for (const Token &Tok : StringToks) 1741 StringTokLocs.push_back(Tok.getLocation()); 1742 1743 QualType CharTy = Context.CharTy; 1744 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1745 if (Literal.isWide()) { 1746 CharTy = Context.getWideCharType(); 1747 Kind = StringLiteral::Wide; 1748 } else if (Literal.isUTF8()) { 1749 if (getLangOpts().Char8) 1750 CharTy = Context.Char8Ty; 1751 Kind = StringLiteral::UTF8; 1752 } else if (Literal.isUTF16()) { 1753 CharTy = Context.Char16Ty; 1754 Kind = StringLiteral::UTF16; 1755 } else if (Literal.isUTF32()) { 1756 CharTy = Context.Char32Ty; 1757 Kind = StringLiteral::UTF32; 1758 } else if (Literal.isPascal()) { 1759 CharTy = Context.UnsignedCharTy; 1760 } 1761 1762 // Warn on initializing an array of char from a u8 string literal; this 1763 // becomes ill-formed in C++2a. 1764 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1765 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1766 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1767 1768 // Create removals for all 'u8' prefixes in the string literal(s). This 1769 // ensures C++2a compatibility (but may change the program behavior when 1770 // built by non-Clang compilers for which the execution character set is 1771 // not always UTF-8). 1772 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1773 SourceLocation RemovalDiagLoc; 1774 for (const Token &Tok : StringToks) { 1775 if (Tok.getKind() == tok::utf8_string_literal) { 1776 if (RemovalDiagLoc.isInvalid()) 1777 RemovalDiagLoc = Tok.getLocation(); 1778 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1779 Tok.getLocation(), 1780 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1781 getSourceManager(), getLangOpts()))); 1782 } 1783 } 1784 Diag(RemovalDiagLoc, RemovalDiag); 1785 } 1786 1787 QualType StrTy = 1788 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1789 1790 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1791 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1792 Kind, Literal.Pascal, StrTy, 1793 &StringTokLocs[0], 1794 StringTokLocs.size()); 1795 if (Literal.getUDSuffix().empty()) 1796 return Lit; 1797 1798 // We're building a user-defined literal. 1799 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1800 SourceLocation UDSuffixLoc = 1801 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1802 Literal.getUDSuffixOffset()); 1803 1804 // Make sure we're allowed user-defined literals here. 1805 if (!UDLScope) 1806 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1807 1808 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1809 // operator "" X (str, len) 1810 QualType SizeType = Context.getSizeType(); 1811 1812 DeclarationName OpName = 1813 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1814 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1815 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1816 1817 QualType ArgTy[] = { 1818 Context.getArrayDecayedType(StrTy), SizeType 1819 }; 1820 1821 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1822 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1823 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1824 /*AllowStringTemplate*/ true, 1825 /*DiagnoseMissing*/ true)) { 1826 1827 case LOLR_Cooked: { 1828 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1829 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1830 StringTokLocs[0]); 1831 Expr *Args[] = { Lit, LenArg }; 1832 1833 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1834 } 1835 1836 case LOLR_StringTemplate: { 1837 TemplateArgumentListInfo ExplicitArgs; 1838 1839 unsigned CharBits = Context.getIntWidth(CharTy); 1840 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1841 llvm::APSInt Value(CharBits, CharIsUnsigned); 1842 1843 TemplateArgument TypeArg(CharTy); 1844 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1845 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1846 1847 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1848 Value = Lit->getCodeUnit(I); 1849 TemplateArgument Arg(Context, Value, CharTy); 1850 TemplateArgumentLocInfo ArgInfo; 1851 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1852 } 1853 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1854 &ExplicitArgs); 1855 } 1856 case LOLR_Raw: 1857 case LOLR_Template: 1858 case LOLR_ErrorNoDiagnostic: 1859 llvm_unreachable("unexpected literal operator lookup result"); 1860 case LOLR_Error: 1861 return ExprError(); 1862 } 1863 llvm_unreachable("unexpected literal operator lookup result"); 1864 } 1865 1866 DeclRefExpr * 1867 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1868 SourceLocation Loc, 1869 const CXXScopeSpec *SS) { 1870 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1871 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1872 } 1873 1874 DeclRefExpr * 1875 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1876 const DeclarationNameInfo &NameInfo, 1877 const CXXScopeSpec *SS, NamedDecl *FoundD, 1878 SourceLocation TemplateKWLoc, 1879 const TemplateArgumentListInfo *TemplateArgs) { 1880 NestedNameSpecifierLoc NNS = 1881 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1882 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1883 TemplateArgs); 1884 } 1885 1886 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1887 // A declaration named in an unevaluated operand never constitutes an odr-use. 1888 if (isUnevaluatedContext()) 1889 return NOUR_Unevaluated; 1890 1891 // C++2a [basic.def.odr]p4: 1892 // A variable x whose name appears as a potentially-evaluated expression e 1893 // is odr-used by e unless [...] x is a reference that is usable in 1894 // constant expressions. 1895 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1896 if (VD->getType()->isReferenceType() && 1897 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1898 VD->isUsableInConstantExpressions(Context)) 1899 return NOUR_Constant; 1900 } 1901 1902 // All remaining non-variable cases constitute an odr-use. For variables, we 1903 // need to wait and see how the expression is used. 1904 return NOUR_None; 1905 } 1906 1907 /// BuildDeclRefExpr - Build an expression that references a 1908 /// declaration that does not require a closure capture. 1909 DeclRefExpr * 1910 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1911 const DeclarationNameInfo &NameInfo, 1912 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1913 SourceLocation TemplateKWLoc, 1914 const TemplateArgumentListInfo *TemplateArgs) { 1915 bool RefersToCapturedVariable = 1916 isa<VarDecl>(D) && 1917 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1918 1919 DeclRefExpr *E = DeclRefExpr::Create( 1920 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1921 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1922 MarkDeclRefReferenced(E); 1923 1924 // C++ [except.spec]p17: 1925 // An exception-specification is considered to be needed when: 1926 // - in an expression, the function is the unique lookup result or 1927 // the selected member of a set of overloaded functions. 1928 // 1929 // We delay doing this until after we've built the function reference and 1930 // marked it as used so that: 1931 // a) if the function is defaulted, we get errors from defining it before / 1932 // instead of errors from computing its exception specification, and 1933 // b) if the function is a defaulted comparison, we can use the body we 1934 // build when defining it as input to the exception specification 1935 // computation rather than computing a new body. 1936 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1937 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1938 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1939 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1940 } 1941 } 1942 1943 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1944 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1945 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1946 getCurFunction()->recordUseOfWeak(E); 1947 1948 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1949 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1950 FD = IFD->getAnonField(); 1951 if (FD) { 1952 UnusedPrivateFields.remove(FD); 1953 // Just in case we're building an illegal pointer-to-member. 1954 if (FD->isBitField()) 1955 E->setObjectKind(OK_BitField); 1956 } 1957 1958 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1959 // designates a bit-field. 1960 if (auto *BD = dyn_cast<BindingDecl>(D)) 1961 if (auto *BE = BD->getBinding()) 1962 E->setObjectKind(BE->getObjectKind()); 1963 1964 return E; 1965 } 1966 1967 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1968 /// possibly a list of template arguments. 1969 /// 1970 /// If this produces template arguments, it is permitted to call 1971 /// DecomposeTemplateName. 1972 /// 1973 /// This actually loses a lot of source location information for 1974 /// non-standard name kinds; we should consider preserving that in 1975 /// some way. 1976 void 1977 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1978 TemplateArgumentListInfo &Buffer, 1979 DeclarationNameInfo &NameInfo, 1980 const TemplateArgumentListInfo *&TemplateArgs) { 1981 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1982 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1983 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1984 1985 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1986 Id.TemplateId->NumArgs); 1987 translateTemplateArguments(TemplateArgsPtr, Buffer); 1988 1989 TemplateName TName = Id.TemplateId->Template.get(); 1990 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1991 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1992 TemplateArgs = &Buffer; 1993 } else { 1994 NameInfo = GetNameFromUnqualifiedId(Id); 1995 TemplateArgs = nullptr; 1996 } 1997 } 1998 1999 static void emitEmptyLookupTypoDiagnostic( 2000 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2001 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2002 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2003 DeclContext *Ctx = 2004 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2005 if (!TC) { 2006 // Emit a special diagnostic for failed member lookups. 2007 // FIXME: computing the declaration context might fail here (?) 2008 if (Ctx) 2009 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2010 << SS.getRange(); 2011 else 2012 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2013 return; 2014 } 2015 2016 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2017 bool DroppedSpecifier = 2018 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2019 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2020 ? diag::note_implicit_param_decl 2021 : diag::note_previous_decl; 2022 if (!Ctx) 2023 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2024 SemaRef.PDiag(NoteID)); 2025 else 2026 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2027 << Typo << Ctx << DroppedSpecifier 2028 << SS.getRange(), 2029 SemaRef.PDiag(NoteID)); 2030 } 2031 2032 /// Diagnose an empty lookup. 2033 /// 2034 /// \return false if new lookup candidates were found 2035 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2036 CorrectionCandidateCallback &CCC, 2037 TemplateArgumentListInfo *ExplicitTemplateArgs, 2038 ArrayRef<Expr *> Args, TypoExpr **Out) { 2039 DeclarationName Name = R.getLookupName(); 2040 2041 unsigned diagnostic = diag::err_undeclared_var_use; 2042 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2043 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2044 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2045 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2046 diagnostic = diag::err_undeclared_use; 2047 diagnostic_suggest = diag::err_undeclared_use_suggest; 2048 } 2049 2050 // If the original lookup was an unqualified lookup, fake an 2051 // unqualified lookup. This is useful when (for example) the 2052 // original lookup would not have found something because it was a 2053 // dependent name. 2054 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2055 while (DC) { 2056 if (isa<CXXRecordDecl>(DC)) { 2057 LookupQualifiedName(R, DC); 2058 2059 if (!R.empty()) { 2060 // Don't give errors about ambiguities in this lookup. 2061 R.suppressDiagnostics(); 2062 2063 // During a default argument instantiation the CurContext points 2064 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2065 // function parameter list, hence add an explicit check. 2066 bool isDefaultArgument = 2067 !CodeSynthesisContexts.empty() && 2068 CodeSynthesisContexts.back().Kind == 2069 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2070 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2071 bool isInstance = CurMethod && 2072 CurMethod->isInstance() && 2073 DC == CurMethod->getParent() && !isDefaultArgument; 2074 2075 // Give a code modification hint to insert 'this->'. 2076 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2077 // Actually quite difficult! 2078 if (getLangOpts().MSVCCompat) 2079 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2080 if (isInstance) { 2081 Diag(R.getNameLoc(), diagnostic) << Name 2082 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2083 CheckCXXThisCapture(R.getNameLoc()); 2084 } else { 2085 Diag(R.getNameLoc(), diagnostic) << Name; 2086 } 2087 2088 // Do we really want to note all of these? 2089 for (NamedDecl *D : R) 2090 Diag(D->getLocation(), diag::note_dependent_var_use); 2091 2092 // Return true if we are inside a default argument instantiation 2093 // and the found name refers to an instance member function, otherwise 2094 // the function calling DiagnoseEmptyLookup will try to create an 2095 // implicit member call and this is wrong for default argument. 2096 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2097 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2098 return true; 2099 } 2100 2101 // Tell the callee to try to recover. 2102 return false; 2103 } 2104 2105 R.clear(); 2106 } 2107 2108 DC = DC->getLookupParent(); 2109 } 2110 2111 // We didn't find anything, so try to correct for a typo. 2112 TypoCorrection Corrected; 2113 if (S && Out) { 2114 SourceLocation TypoLoc = R.getNameLoc(); 2115 assert(!ExplicitTemplateArgs && 2116 "Diagnosing an empty lookup with explicit template args!"); 2117 *Out = CorrectTypoDelayed( 2118 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2119 [=](const TypoCorrection &TC) { 2120 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2121 diagnostic, diagnostic_suggest); 2122 }, 2123 nullptr, CTK_ErrorRecovery); 2124 if (*Out) 2125 return true; 2126 } else if (S && 2127 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2128 S, &SS, CCC, CTK_ErrorRecovery))) { 2129 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2130 bool DroppedSpecifier = 2131 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2132 R.setLookupName(Corrected.getCorrection()); 2133 2134 bool AcceptableWithRecovery = false; 2135 bool AcceptableWithoutRecovery = false; 2136 NamedDecl *ND = Corrected.getFoundDecl(); 2137 if (ND) { 2138 if (Corrected.isOverloaded()) { 2139 OverloadCandidateSet OCS(R.getNameLoc(), 2140 OverloadCandidateSet::CSK_Normal); 2141 OverloadCandidateSet::iterator Best; 2142 for (NamedDecl *CD : Corrected) { 2143 if (FunctionTemplateDecl *FTD = 2144 dyn_cast<FunctionTemplateDecl>(CD)) 2145 AddTemplateOverloadCandidate( 2146 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2147 Args, OCS); 2148 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2149 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2150 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2151 Args, OCS); 2152 } 2153 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2154 case OR_Success: 2155 ND = Best->FoundDecl; 2156 Corrected.setCorrectionDecl(ND); 2157 break; 2158 default: 2159 // FIXME: Arbitrarily pick the first declaration for the note. 2160 Corrected.setCorrectionDecl(ND); 2161 break; 2162 } 2163 } 2164 R.addDecl(ND); 2165 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2166 CXXRecordDecl *Record = nullptr; 2167 if (Corrected.getCorrectionSpecifier()) { 2168 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2169 Record = Ty->getAsCXXRecordDecl(); 2170 } 2171 if (!Record) 2172 Record = cast<CXXRecordDecl>( 2173 ND->getDeclContext()->getRedeclContext()); 2174 R.setNamingClass(Record); 2175 } 2176 2177 auto *UnderlyingND = ND->getUnderlyingDecl(); 2178 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2179 isa<FunctionTemplateDecl>(UnderlyingND); 2180 // FIXME: If we ended up with a typo for a type name or 2181 // Objective-C class name, we're in trouble because the parser 2182 // is in the wrong place to recover. Suggest the typo 2183 // correction, but don't make it a fix-it since we're not going 2184 // to recover well anyway. 2185 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2186 getAsTypeTemplateDecl(UnderlyingND) || 2187 isa<ObjCInterfaceDecl>(UnderlyingND); 2188 } else { 2189 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2190 // because we aren't able to recover. 2191 AcceptableWithoutRecovery = true; 2192 } 2193 2194 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2195 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2196 ? diag::note_implicit_param_decl 2197 : diag::note_previous_decl; 2198 if (SS.isEmpty()) 2199 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2200 PDiag(NoteID), AcceptableWithRecovery); 2201 else 2202 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2203 << Name << computeDeclContext(SS, false) 2204 << DroppedSpecifier << SS.getRange(), 2205 PDiag(NoteID), AcceptableWithRecovery); 2206 2207 // Tell the callee whether to try to recover. 2208 return !AcceptableWithRecovery; 2209 } 2210 } 2211 R.clear(); 2212 2213 // Emit a special diagnostic for failed member lookups. 2214 // FIXME: computing the declaration context might fail here (?) 2215 if (!SS.isEmpty()) { 2216 Diag(R.getNameLoc(), diag::err_no_member) 2217 << Name << computeDeclContext(SS, false) 2218 << SS.getRange(); 2219 return true; 2220 } 2221 2222 // Give up, we can't recover. 2223 Diag(R.getNameLoc(), diagnostic) << Name; 2224 return true; 2225 } 2226 2227 /// In Microsoft mode, if we are inside a template class whose parent class has 2228 /// dependent base classes, and we can't resolve an unqualified identifier, then 2229 /// assume the identifier is a member of a dependent base class. We can only 2230 /// recover successfully in static methods, instance methods, and other contexts 2231 /// where 'this' is available. This doesn't precisely match MSVC's 2232 /// instantiation model, but it's close enough. 2233 static Expr * 2234 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2235 DeclarationNameInfo &NameInfo, 2236 SourceLocation TemplateKWLoc, 2237 const TemplateArgumentListInfo *TemplateArgs) { 2238 // Only try to recover from lookup into dependent bases in static methods or 2239 // contexts where 'this' is available. 2240 QualType ThisType = S.getCurrentThisType(); 2241 const CXXRecordDecl *RD = nullptr; 2242 if (!ThisType.isNull()) 2243 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2244 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2245 RD = MD->getParent(); 2246 if (!RD || !RD->hasAnyDependentBases()) 2247 return nullptr; 2248 2249 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2250 // is available, suggest inserting 'this->' as a fixit. 2251 SourceLocation Loc = NameInfo.getLoc(); 2252 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2253 DB << NameInfo.getName() << RD; 2254 2255 if (!ThisType.isNull()) { 2256 DB << FixItHint::CreateInsertion(Loc, "this->"); 2257 return CXXDependentScopeMemberExpr::Create( 2258 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2259 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2260 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2261 } 2262 2263 // Synthesize a fake NNS that points to the derived class. This will 2264 // perform name lookup during template instantiation. 2265 CXXScopeSpec SS; 2266 auto *NNS = 2267 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2268 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2269 return DependentScopeDeclRefExpr::Create( 2270 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2271 TemplateArgs); 2272 } 2273 2274 ExprResult 2275 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2276 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2277 bool HasTrailingLParen, bool IsAddressOfOperand, 2278 CorrectionCandidateCallback *CCC, 2279 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2280 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2281 "cannot be direct & operand and have a trailing lparen"); 2282 if (SS.isInvalid()) 2283 return ExprError(); 2284 2285 TemplateArgumentListInfo TemplateArgsBuffer; 2286 2287 // Decompose the UnqualifiedId into the following data. 2288 DeclarationNameInfo NameInfo; 2289 const TemplateArgumentListInfo *TemplateArgs; 2290 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2291 2292 DeclarationName Name = NameInfo.getName(); 2293 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2294 SourceLocation NameLoc = NameInfo.getLoc(); 2295 2296 if (II && II->isEditorPlaceholder()) { 2297 // FIXME: When typed placeholders are supported we can create a typed 2298 // placeholder expression node. 2299 return ExprError(); 2300 } 2301 2302 // C++ [temp.dep.expr]p3: 2303 // An id-expression is type-dependent if it contains: 2304 // -- an identifier that was declared with a dependent type, 2305 // (note: handled after lookup) 2306 // -- a template-id that is dependent, 2307 // (note: handled in BuildTemplateIdExpr) 2308 // -- a conversion-function-id that specifies a dependent type, 2309 // -- a nested-name-specifier that contains a class-name that 2310 // names a dependent type. 2311 // Determine whether this is a member of an unknown specialization; 2312 // we need to handle these differently. 2313 bool DependentID = false; 2314 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2315 Name.getCXXNameType()->isDependentType()) { 2316 DependentID = true; 2317 } else if (SS.isSet()) { 2318 if (DeclContext *DC = computeDeclContext(SS, false)) { 2319 if (RequireCompleteDeclContext(SS, DC)) 2320 return ExprError(); 2321 } else { 2322 DependentID = true; 2323 } 2324 } 2325 2326 if (DependentID) 2327 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2328 IsAddressOfOperand, TemplateArgs); 2329 2330 // Perform the required lookup. 2331 LookupResult R(*this, NameInfo, 2332 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2333 ? LookupObjCImplicitSelfParam 2334 : LookupOrdinaryName); 2335 if (TemplateKWLoc.isValid() || TemplateArgs) { 2336 // Lookup the template name again to correctly establish the context in 2337 // which it was found. This is really unfortunate as we already did the 2338 // lookup to determine that it was a template name in the first place. If 2339 // this becomes a performance hit, we can work harder to preserve those 2340 // results until we get here but it's likely not worth it. 2341 bool MemberOfUnknownSpecialization; 2342 AssumedTemplateKind AssumedTemplate; 2343 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2344 MemberOfUnknownSpecialization, TemplateKWLoc, 2345 &AssumedTemplate)) 2346 return ExprError(); 2347 2348 if (MemberOfUnknownSpecialization || 2349 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2350 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2351 IsAddressOfOperand, TemplateArgs); 2352 } else { 2353 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2354 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2355 2356 // If the result might be in a dependent base class, this is a dependent 2357 // id-expression. 2358 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2360 IsAddressOfOperand, TemplateArgs); 2361 2362 // If this reference is in an Objective-C method, then we need to do 2363 // some special Objective-C lookup, too. 2364 if (IvarLookupFollowUp) { 2365 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2366 if (E.isInvalid()) 2367 return ExprError(); 2368 2369 if (Expr *Ex = E.getAs<Expr>()) 2370 return Ex; 2371 } 2372 } 2373 2374 if (R.isAmbiguous()) 2375 return ExprError(); 2376 2377 // This could be an implicitly declared function reference (legal in C90, 2378 // extension in C99, forbidden in C++). 2379 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2380 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2381 if (D) R.addDecl(D); 2382 } 2383 2384 // Determine whether this name might be a candidate for 2385 // argument-dependent lookup. 2386 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2387 2388 if (R.empty() && !ADL) { 2389 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2390 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2391 TemplateKWLoc, TemplateArgs)) 2392 return E; 2393 } 2394 2395 // Don't diagnose an empty lookup for inline assembly. 2396 if (IsInlineAsmIdentifier) 2397 return ExprError(); 2398 2399 // If this name wasn't predeclared and if this is not a function 2400 // call, diagnose the problem. 2401 TypoExpr *TE = nullptr; 2402 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2403 : nullptr); 2404 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2405 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2406 "Typo correction callback misconfigured"); 2407 if (CCC) { 2408 // Make sure the callback knows what the typo being diagnosed is. 2409 CCC->setTypoName(II); 2410 if (SS.isValid()) 2411 CCC->setTypoNNS(SS.getScopeRep()); 2412 } 2413 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2414 // a template name, but we happen to have always already looked up the name 2415 // before we get here if it must be a template name. 2416 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2417 None, &TE)) { 2418 if (TE && KeywordReplacement) { 2419 auto &State = getTypoExprState(TE); 2420 auto BestTC = State.Consumer->getNextCorrection(); 2421 if (BestTC.isKeyword()) { 2422 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2423 if (State.DiagHandler) 2424 State.DiagHandler(BestTC); 2425 KeywordReplacement->startToken(); 2426 KeywordReplacement->setKind(II->getTokenID()); 2427 KeywordReplacement->setIdentifierInfo(II); 2428 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2429 // Clean up the state associated with the TypoExpr, since it has 2430 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2431 clearDelayedTypo(TE); 2432 // Signal that a correction to a keyword was performed by returning a 2433 // valid-but-null ExprResult. 2434 return (Expr*)nullptr; 2435 } 2436 State.Consumer->resetCorrectionStream(); 2437 } 2438 return TE ? TE : ExprError(); 2439 } 2440 2441 assert(!R.empty() && 2442 "DiagnoseEmptyLookup returned false but added no results"); 2443 2444 // If we found an Objective-C instance variable, let 2445 // LookupInObjCMethod build the appropriate expression to 2446 // reference the ivar. 2447 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2448 R.clear(); 2449 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2450 // In a hopelessly buggy code, Objective-C instance variable 2451 // lookup fails and no expression will be built to reference it. 2452 if (!E.isInvalid() && !E.get()) 2453 return ExprError(); 2454 return E; 2455 } 2456 } 2457 2458 // This is guaranteed from this point on. 2459 assert(!R.empty() || ADL); 2460 2461 // Check whether this might be a C++ implicit instance member access. 2462 // C++ [class.mfct.non-static]p3: 2463 // When an id-expression that is not part of a class member access 2464 // syntax and not used to form a pointer to member is used in the 2465 // body of a non-static member function of class X, if name lookup 2466 // resolves the name in the id-expression to a non-static non-type 2467 // member of some class C, the id-expression is transformed into a 2468 // class member access expression using (*this) as the 2469 // postfix-expression to the left of the . operator. 2470 // 2471 // But we don't actually need to do this for '&' operands if R 2472 // resolved to a function or overloaded function set, because the 2473 // expression is ill-formed if it actually works out to be a 2474 // non-static member function: 2475 // 2476 // C++ [expr.ref]p4: 2477 // Otherwise, if E1.E2 refers to a non-static member function. . . 2478 // [t]he expression can be used only as the left-hand operand of a 2479 // member function call. 2480 // 2481 // There are other safeguards against such uses, but it's important 2482 // to get this right here so that we don't end up making a 2483 // spuriously dependent expression if we're inside a dependent 2484 // instance method. 2485 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2486 bool MightBeImplicitMember; 2487 if (!IsAddressOfOperand) 2488 MightBeImplicitMember = true; 2489 else if (!SS.isEmpty()) 2490 MightBeImplicitMember = false; 2491 else if (R.isOverloadedResult()) 2492 MightBeImplicitMember = false; 2493 else if (R.isUnresolvableResult()) 2494 MightBeImplicitMember = true; 2495 else 2496 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2497 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2498 isa<MSPropertyDecl>(R.getFoundDecl()); 2499 2500 if (MightBeImplicitMember) 2501 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2502 R, TemplateArgs, S); 2503 } 2504 2505 if (TemplateArgs || TemplateKWLoc.isValid()) { 2506 2507 // In C++1y, if this is a variable template id, then check it 2508 // in BuildTemplateIdExpr(). 2509 // The single lookup result must be a variable template declaration. 2510 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2511 Id.TemplateId->Kind == TNK_Var_template) { 2512 assert(R.getAsSingle<VarTemplateDecl>() && 2513 "There should only be one declaration found."); 2514 } 2515 2516 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2517 } 2518 2519 return BuildDeclarationNameExpr(SS, R, ADL); 2520 } 2521 2522 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2523 /// declaration name, generally during template instantiation. 2524 /// There's a large number of things which don't need to be done along 2525 /// this path. 2526 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2527 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2528 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2529 DeclContext *DC = computeDeclContext(SS, false); 2530 if (!DC) 2531 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2532 NameInfo, /*TemplateArgs=*/nullptr); 2533 2534 if (RequireCompleteDeclContext(SS, DC)) 2535 return ExprError(); 2536 2537 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2538 LookupQualifiedName(R, DC); 2539 2540 if (R.isAmbiguous()) 2541 return ExprError(); 2542 2543 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2544 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2545 NameInfo, /*TemplateArgs=*/nullptr); 2546 2547 if (R.empty()) { 2548 Diag(NameInfo.getLoc(), diag::err_no_member) 2549 << NameInfo.getName() << DC << SS.getRange(); 2550 return ExprError(); 2551 } 2552 2553 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2554 // Diagnose a missing typename if this resolved unambiguously to a type in 2555 // a dependent context. If we can recover with a type, downgrade this to 2556 // a warning in Microsoft compatibility mode. 2557 unsigned DiagID = diag::err_typename_missing; 2558 if (RecoveryTSI && getLangOpts().MSVCCompat) 2559 DiagID = diag::ext_typename_missing; 2560 SourceLocation Loc = SS.getBeginLoc(); 2561 auto D = Diag(Loc, DiagID); 2562 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2563 << SourceRange(Loc, NameInfo.getEndLoc()); 2564 2565 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2566 // context. 2567 if (!RecoveryTSI) 2568 return ExprError(); 2569 2570 // Only issue the fixit if we're prepared to recover. 2571 D << FixItHint::CreateInsertion(Loc, "typename "); 2572 2573 // Recover by pretending this was an elaborated type. 2574 QualType Ty = Context.getTypeDeclType(TD); 2575 TypeLocBuilder TLB; 2576 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2577 2578 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2579 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2580 QTL.setElaboratedKeywordLoc(SourceLocation()); 2581 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2582 2583 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2584 2585 return ExprEmpty(); 2586 } 2587 2588 // Defend against this resolving to an implicit member access. We usually 2589 // won't get here if this might be a legitimate a class member (we end up in 2590 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2591 // a pointer-to-member or in an unevaluated context in C++11. 2592 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2593 return BuildPossibleImplicitMemberExpr(SS, 2594 /*TemplateKWLoc=*/SourceLocation(), 2595 R, /*TemplateArgs=*/nullptr, S); 2596 2597 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2598 } 2599 2600 /// The parser has read a name in, and Sema has detected that we're currently 2601 /// inside an ObjC method. Perform some additional checks and determine if we 2602 /// should form a reference to an ivar. 2603 /// 2604 /// Ideally, most of this would be done by lookup, but there's 2605 /// actually quite a lot of extra work involved. 2606 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2607 IdentifierInfo *II) { 2608 SourceLocation Loc = Lookup.getNameLoc(); 2609 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2610 2611 // Check for error condition which is already reported. 2612 if (!CurMethod) 2613 return DeclResult(true); 2614 2615 // There are two cases to handle here. 1) scoped lookup could have failed, 2616 // in which case we should look for an ivar. 2) scoped lookup could have 2617 // found a decl, but that decl is outside the current instance method (i.e. 2618 // a global variable). In these two cases, we do a lookup for an ivar with 2619 // this name, if the lookup sucedes, we replace it our current decl. 2620 2621 // If we're in a class method, we don't normally want to look for 2622 // ivars. But if we don't find anything else, and there's an 2623 // ivar, that's an error. 2624 bool IsClassMethod = CurMethod->isClassMethod(); 2625 2626 bool LookForIvars; 2627 if (Lookup.empty()) 2628 LookForIvars = true; 2629 else if (IsClassMethod) 2630 LookForIvars = false; 2631 else 2632 LookForIvars = (Lookup.isSingleResult() && 2633 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2634 ObjCInterfaceDecl *IFace = nullptr; 2635 if (LookForIvars) { 2636 IFace = CurMethod->getClassInterface(); 2637 ObjCInterfaceDecl *ClassDeclared; 2638 ObjCIvarDecl *IV = nullptr; 2639 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2640 // Diagnose using an ivar in a class method. 2641 if (IsClassMethod) { 2642 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2643 return DeclResult(true); 2644 } 2645 2646 // Diagnose the use of an ivar outside of the declaring class. 2647 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2648 !declaresSameEntity(ClassDeclared, IFace) && 2649 !getLangOpts().DebuggerSupport) 2650 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2651 2652 // Success. 2653 return IV; 2654 } 2655 } else if (CurMethod->isInstanceMethod()) { 2656 // We should warn if a local variable hides an ivar. 2657 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2658 ObjCInterfaceDecl *ClassDeclared; 2659 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2660 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2661 declaresSameEntity(IFace, ClassDeclared)) 2662 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2663 } 2664 } 2665 } else if (Lookup.isSingleResult() && 2666 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2667 // If accessing a stand-alone ivar in a class method, this is an error. 2668 if (const ObjCIvarDecl *IV = 2669 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2670 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2671 return DeclResult(true); 2672 } 2673 } 2674 2675 // Didn't encounter an error, didn't find an ivar. 2676 return DeclResult(false); 2677 } 2678 2679 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2680 ObjCIvarDecl *IV) { 2681 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2682 assert(CurMethod && CurMethod->isInstanceMethod() && 2683 "should not reference ivar from this context"); 2684 2685 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2686 assert(IFace && "should not reference ivar from this context"); 2687 2688 // If we're referencing an invalid decl, just return this as a silent 2689 // error node. The error diagnostic was already emitted on the decl. 2690 if (IV->isInvalidDecl()) 2691 return ExprError(); 2692 2693 // Check if referencing a field with __attribute__((deprecated)). 2694 if (DiagnoseUseOfDecl(IV, Loc)) 2695 return ExprError(); 2696 2697 // FIXME: This should use a new expr for a direct reference, don't 2698 // turn this into Self->ivar, just return a BareIVarExpr or something. 2699 IdentifierInfo &II = Context.Idents.get("self"); 2700 UnqualifiedId SelfName; 2701 SelfName.setIdentifier(&II, SourceLocation()); 2702 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2703 CXXScopeSpec SelfScopeSpec; 2704 SourceLocation TemplateKWLoc; 2705 ExprResult SelfExpr = 2706 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2707 /*HasTrailingLParen=*/false, 2708 /*IsAddressOfOperand=*/false); 2709 if (SelfExpr.isInvalid()) 2710 return ExprError(); 2711 2712 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2713 if (SelfExpr.isInvalid()) 2714 return ExprError(); 2715 2716 MarkAnyDeclReferenced(Loc, IV, true); 2717 2718 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2719 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2720 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2721 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2722 2723 ObjCIvarRefExpr *Result = new (Context) 2724 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2725 IV->getLocation(), SelfExpr.get(), true, true); 2726 2727 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2728 if (!isUnevaluatedContext() && 2729 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2730 getCurFunction()->recordUseOfWeak(Result); 2731 } 2732 if (getLangOpts().ObjCAutoRefCount) 2733 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2734 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2735 2736 return Result; 2737 } 2738 2739 /// The parser has read a name in, and Sema has detected that we're currently 2740 /// inside an ObjC method. Perform some additional checks and determine if we 2741 /// should form a reference to an ivar. If so, build an expression referencing 2742 /// that ivar. 2743 ExprResult 2744 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2745 IdentifierInfo *II, bool AllowBuiltinCreation) { 2746 // FIXME: Integrate this lookup step into LookupParsedName. 2747 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2748 if (Ivar.isInvalid()) 2749 return ExprError(); 2750 if (Ivar.isUsable()) 2751 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2752 cast<ObjCIvarDecl>(Ivar.get())); 2753 2754 if (Lookup.empty() && II && AllowBuiltinCreation) 2755 LookupBuiltin(Lookup); 2756 2757 // Sentinel value saying that we didn't do anything special. 2758 return ExprResult(false); 2759 } 2760 2761 /// Cast a base object to a member's actual type. 2762 /// 2763 /// Logically this happens in three phases: 2764 /// 2765 /// * First we cast from the base type to the naming class. 2766 /// The naming class is the class into which we were looking 2767 /// when we found the member; it's the qualifier type if a 2768 /// qualifier was provided, and otherwise it's the base type. 2769 /// 2770 /// * Next we cast from the naming class to the declaring class. 2771 /// If the member we found was brought into a class's scope by 2772 /// a using declaration, this is that class; otherwise it's 2773 /// the class declaring the member. 2774 /// 2775 /// * Finally we cast from the declaring class to the "true" 2776 /// declaring class of the member. This conversion does not 2777 /// obey access control. 2778 ExprResult 2779 Sema::PerformObjectMemberConversion(Expr *From, 2780 NestedNameSpecifier *Qualifier, 2781 NamedDecl *FoundDecl, 2782 NamedDecl *Member) { 2783 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2784 if (!RD) 2785 return From; 2786 2787 QualType DestRecordType; 2788 QualType DestType; 2789 QualType FromRecordType; 2790 QualType FromType = From->getType(); 2791 bool PointerConversions = false; 2792 if (isa<FieldDecl>(Member)) { 2793 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2794 auto FromPtrType = FromType->getAs<PointerType>(); 2795 DestRecordType = Context.getAddrSpaceQualType( 2796 DestRecordType, FromPtrType 2797 ? FromType->getPointeeType().getAddressSpace() 2798 : FromType.getAddressSpace()); 2799 2800 if (FromPtrType) { 2801 DestType = Context.getPointerType(DestRecordType); 2802 FromRecordType = FromPtrType->getPointeeType(); 2803 PointerConversions = true; 2804 } else { 2805 DestType = DestRecordType; 2806 FromRecordType = FromType; 2807 } 2808 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2809 if (Method->isStatic()) 2810 return From; 2811 2812 DestType = Method->getThisType(); 2813 DestRecordType = DestType->getPointeeType(); 2814 2815 if (FromType->getAs<PointerType>()) { 2816 FromRecordType = FromType->getPointeeType(); 2817 PointerConversions = true; 2818 } else { 2819 FromRecordType = FromType; 2820 DestType = DestRecordType; 2821 } 2822 2823 LangAS FromAS = FromRecordType.getAddressSpace(); 2824 LangAS DestAS = DestRecordType.getAddressSpace(); 2825 if (FromAS != DestAS) { 2826 QualType FromRecordTypeWithoutAS = 2827 Context.removeAddrSpaceQualType(FromRecordType); 2828 QualType FromTypeWithDestAS = 2829 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2830 if (PointerConversions) 2831 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2832 From = ImpCastExprToType(From, FromTypeWithDestAS, 2833 CK_AddressSpaceConversion, From->getValueKind()) 2834 .get(); 2835 } 2836 } else { 2837 // No conversion necessary. 2838 return From; 2839 } 2840 2841 if (DestType->isDependentType() || FromType->isDependentType()) 2842 return From; 2843 2844 // If the unqualified types are the same, no conversion is necessary. 2845 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2846 return From; 2847 2848 SourceRange FromRange = From->getSourceRange(); 2849 SourceLocation FromLoc = FromRange.getBegin(); 2850 2851 ExprValueKind VK = From->getValueKind(); 2852 2853 // C++ [class.member.lookup]p8: 2854 // [...] Ambiguities can often be resolved by qualifying a name with its 2855 // class name. 2856 // 2857 // If the member was a qualified name and the qualified referred to a 2858 // specific base subobject type, we'll cast to that intermediate type 2859 // first and then to the object in which the member is declared. That allows 2860 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2861 // 2862 // class Base { public: int x; }; 2863 // class Derived1 : public Base { }; 2864 // class Derived2 : public Base { }; 2865 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2866 // 2867 // void VeryDerived::f() { 2868 // x = 17; // error: ambiguous base subobjects 2869 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2870 // } 2871 if (Qualifier && Qualifier->getAsType()) { 2872 QualType QType = QualType(Qualifier->getAsType(), 0); 2873 assert(QType->isRecordType() && "lookup done with non-record type"); 2874 2875 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2876 2877 // In C++98, the qualifier type doesn't actually have to be a base 2878 // type of the object type, in which case we just ignore it. 2879 // Otherwise build the appropriate casts. 2880 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2881 CXXCastPath BasePath; 2882 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2883 FromLoc, FromRange, &BasePath)) 2884 return ExprError(); 2885 2886 if (PointerConversions) 2887 QType = Context.getPointerType(QType); 2888 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2889 VK, &BasePath).get(); 2890 2891 FromType = QType; 2892 FromRecordType = QRecordType; 2893 2894 // If the qualifier type was the same as the destination type, 2895 // we're done. 2896 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2897 return From; 2898 } 2899 } 2900 2901 bool IgnoreAccess = false; 2902 2903 // If we actually found the member through a using declaration, cast 2904 // down to the using declaration's type. 2905 // 2906 // Pointer equality is fine here because only one declaration of a 2907 // class ever has member declarations. 2908 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2909 assert(isa<UsingShadowDecl>(FoundDecl)); 2910 QualType URecordType = Context.getTypeDeclType( 2911 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2912 2913 // We only need to do this if the naming-class to declaring-class 2914 // conversion is non-trivial. 2915 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2916 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2917 CXXCastPath BasePath; 2918 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2919 FromLoc, FromRange, &BasePath)) 2920 return ExprError(); 2921 2922 QualType UType = URecordType; 2923 if (PointerConversions) 2924 UType = Context.getPointerType(UType); 2925 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2926 VK, &BasePath).get(); 2927 FromType = UType; 2928 FromRecordType = URecordType; 2929 } 2930 2931 // We don't do access control for the conversion from the 2932 // declaring class to the true declaring class. 2933 IgnoreAccess = true; 2934 } 2935 2936 CXXCastPath BasePath; 2937 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2938 FromLoc, FromRange, &BasePath, 2939 IgnoreAccess)) 2940 return ExprError(); 2941 2942 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2943 VK, &BasePath); 2944 } 2945 2946 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2947 const LookupResult &R, 2948 bool HasTrailingLParen) { 2949 // Only when used directly as the postfix-expression of a call. 2950 if (!HasTrailingLParen) 2951 return false; 2952 2953 // Never if a scope specifier was provided. 2954 if (SS.isSet()) 2955 return false; 2956 2957 // Only in C++ or ObjC++. 2958 if (!getLangOpts().CPlusPlus) 2959 return false; 2960 2961 // Turn off ADL when we find certain kinds of declarations during 2962 // normal lookup: 2963 for (NamedDecl *D : R) { 2964 // C++0x [basic.lookup.argdep]p3: 2965 // -- a declaration of a class member 2966 // Since using decls preserve this property, we check this on the 2967 // original decl. 2968 if (D->isCXXClassMember()) 2969 return false; 2970 2971 // C++0x [basic.lookup.argdep]p3: 2972 // -- a block-scope function declaration that is not a 2973 // using-declaration 2974 // NOTE: we also trigger this for function templates (in fact, we 2975 // don't check the decl type at all, since all other decl types 2976 // turn off ADL anyway). 2977 if (isa<UsingShadowDecl>(D)) 2978 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2979 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2980 return false; 2981 2982 // C++0x [basic.lookup.argdep]p3: 2983 // -- a declaration that is neither a function or a function 2984 // template 2985 // And also for builtin functions. 2986 if (isa<FunctionDecl>(D)) { 2987 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2988 2989 // But also builtin functions. 2990 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2991 return false; 2992 } else if (!isa<FunctionTemplateDecl>(D)) 2993 return false; 2994 } 2995 2996 return true; 2997 } 2998 2999 3000 /// Diagnoses obvious problems with the use of the given declaration 3001 /// as an expression. This is only actually called for lookups that 3002 /// were not overloaded, and it doesn't promise that the declaration 3003 /// will in fact be used. 3004 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3005 if (D->isInvalidDecl()) 3006 return true; 3007 3008 if (isa<TypedefNameDecl>(D)) { 3009 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3010 return true; 3011 } 3012 3013 if (isa<ObjCInterfaceDecl>(D)) { 3014 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3015 return true; 3016 } 3017 3018 if (isa<NamespaceDecl>(D)) { 3019 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3020 return true; 3021 } 3022 3023 return false; 3024 } 3025 3026 // Certain multiversion types should be treated as overloaded even when there is 3027 // only one result. 3028 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3029 assert(R.isSingleResult() && "Expected only a single result"); 3030 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3031 return FD && 3032 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3033 } 3034 3035 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3036 LookupResult &R, bool NeedsADL, 3037 bool AcceptInvalidDecl) { 3038 // If this is a single, fully-resolved result and we don't need ADL, 3039 // just build an ordinary singleton decl ref. 3040 if (!NeedsADL && R.isSingleResult() && 3041 !R.getAsSingle<FunctionTemplateDecl>() && 3042 !ShouldLookupResultBeMultiVersionOverload(R)) 3043 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3044 R.getRepresentativeDecl(), nullptr, 3045 AcceptInvalidDecl); 3046 3047 // We only need to check the declaration if there's exactly one 3048 // result, because in the overloaded case the results can only be 3049 // functions and function templates. 3050 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3051 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3052 return ExprError(); 3053 3054 // Otherwise, just build an unresolved lookup expression. Suppress 3055 // any lookup-related diagnostics; we'll hash these out later, when 3056 // we've picked a target. 3057 R.suppressDiagnostics(); 3058 3059 UnresolvedLookupExpr *ULE 3060 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3061 SS.getWithLocInContext(Context), 3062 R.getLookupNameInfo(), 3063 NeedsADL, R.isOverloadedResult(), 3064 R.begin(), R.end()); 3065 3066 return ULE; 3067 } 3068 3069 static void 3070 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3071 ValueDecl *var, DeclContext *DC); 3072 3073 /// Complete semantic analysis for a reference to the given declaration. 3074 ExprResult Sema::BuildDeclarationNameExpr( 3075 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3076 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3077 bool AcceptInvalidDecl) { 3078 assert(D && "Cannot refer to a NULL declaration"); 3079 assert(!isa<FunctionTemplateDecl>(D) && 3080 "Cannot refer unambiguously to a function template"); 3081 3082 SourceLocation Loc = NameInfo.getLoc(); 3083 if (CheckDeclInExpr(*this, Loc, D)) 3084 return ExprError(); 3085 3086 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3087 // Specifically diagnose references to class templates that are missing 3088 // a template argument list. 3089 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3090 return ExprError(); 3091 } 3092 3093 // Make sure that we're referring to a value. 3094 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3095 if (!VD) { 3096 Diag(Loc, diag::err_ref_non_value) 3097 << D << SS.getRange(); 3098 Diag(D->getLocation(), diag::note_declared_at); 3099 return ExprError(); 3100 } 3101 3102 // Check whether this declaration can be used. Note that we suppress 3103 // this check when we're going to perform argument-dependent lookup 3104 // on this function name, because this might not be the function 3105 // that overload resolution actually selects. 3106 if (DiagnoseUseOfDecl(VD, Loc)) 3107 return ExprError(); 3108 3109 // Only create DeclRefExpr's for valid Decl's. 3110 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3111 return ExprError(); 3112 3113 // Handle members of anonymous structs and unions. If we got here, 3114 // and the reference is to a class member indirect field, then this 3115 // must be the subject of a pointer-to-member expression. 3116 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3117 if (!indirectField->isCXXClassMember()) 3118 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3119 indirectField); 3120 3121 { 3122 QualType type = VD->getType(); 3123 if (type.isNull()) 3124 return ExprError(); 3125 ExprValueKind valueKind = VK_RValue; 3126 3127 switch (D->getKind()) { 3128 // Ignore all the non-ValueDecl kinds. 3129 #define ABSTRACT_DECL(kind) 3130 #define VALUE(type, base) 3131 #define DECL(type, base) \ 3132 case Decl::type: 3133 #include "clang/AST/DeclNodes.inc" 3134 llvm_unreachable("invalid value decl kind"); 3135 3136 // These shouldn't make it here. 3137 case Decl::ObjCAtDefsField: 3138 llvm_unreachable("forming non-member reference to ivar?"); 3139 3140 // Enum constants are always r-values and never references. 3141 // Unresolved using declarations are dependent. 3142 case Decl::EnumConstant: 3143 case Decl::UnresolvedUsingValue: 3144 case Decl::OMPDeclareReduction: 3145 case Decl::OMPDeclareMapper: 3146 valueKind = VK_RValue; 3147 break; 3148 3149 // Fields and indirect fields that got here must be for 3150 // pointer-to-member expressions; we just call them l-values for 3151 // internal consistency, because this subexpression doesn't really 3152 // exist in the high-level semantics. 3153 case Decl::Field: 3154 case Decl::IndirectField: 3155 case Decl::ObjCIvar: 3156 assert(getLangOpts().CPlusPlus && 3157 "building reference to field in C?"); 3158 3159 // These can't have reference type in well-formed programs, but 3160 // for internal consistency we do this anyway. 3161 type = type.getNonReferenceType(); 3162 valueKind = VK_LValue; 3163 break; 3164 3165 // Non-type template parameters are either l-values or r-values 3166 // depending on the type. 3167 case Decl::NonTypeTemplateParm: { 3168 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3169 type = reftype->getPointeeType(); 3170 valueKind = VK_LValue; // even if the parameter is an r-value reference 3171 break; 3172 } 3173 3174 // For non-references, we need to strip qualifiers just in case 3175 // the template parameter was declared as 'const int' or whatever. 3176 valueKind = VK_RValue; 3177 type = type.getUnqualifiedType(); 3178 break; 3179 } 3180 3181 case Decl::Var: 3182 case Decl::VarTemplateSpecialization: 3183 case Decl::VarTemplatePartialSpecialization: 3184 case Decl::Decomposition: 3185 case Decl::OMPCapturedExpr: 3186 // In C, "extern void blah;" is valid and is an r-value. 3187 if (!getLangOpts().CPlusPlus && 3188 !type.hasQualifiers() && 3189 type->isVoidType()) { 3190 valueKind = VK_RValue; 3191 break; 3192 } 3193 LLVM_FALLTHROUGH; 3194 3195 case Decl::ImplicitParam: 3196 case Decl::ParmVar: { 3197 // These are always l-values. 3198 valueKind = VK_LValue; 3199 type = type.getNonReferenceType(); 3200 3201 // FIXME: Does the addition of const really only apply in 3202 // potentially-evaluated contexts? Since the variable isn't actually 3203 // captured in an unevaluated context, it seems that the answer is no. 3204 if (!isUnevaluatedContext()) { 3205 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3206 if (!CapturedType.isNull()) 3207 type = CapturedType; 3208 } 3209 3210 break; 3211 } 3212 3213 case Decl::Binding: { 3214 // These are always lvalues. 3215 valueKind = VK_LValue; 3216 type = type.getNonReferenceType(); 3217 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3218 // decides how that's supposed to work. 3219 auto *BD = cast<BindingDecl>(VD); 3220 if (BD->getDeclContext() != CurContext) { 3221 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3222 if (DD && DD->hasLocalStorage()) 3223 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3224 } 3225 break; 3226 } 3227 3228 case Decl::Function: { 3229 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3230 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3231 type = Context.BuiltinFnTy; 3232 valueKind = VK_RValue; 3233 break; 3234 } 3235 } 3236 3237 const FunctionType *fty = type->castAs<FunctionType>(); 3238 3239 // If we're referring to a function with an __unknown_anytype 3240 // result type, make the entire expression __unknown_anytype. 3241 if (fty->getReturnType() == Context.UnknownAnyTy) { 3242 type = Context.UnknownAnyTy; 3243 valueKind = VK_RValue; 3244 break; 3245 } 3246 3247 // Functions are l-values in C++. 3248 if (getLangOpts().CPlusPlus) { 3249 valueKind = VK_LValue; 3250 break; 3251 } 3252 3253 // C99 DR 316 says that, if a function type comes from a 3254 // function definition (without a prototype), that type is only 3255 // used for checking compatibility. Therefore, when referencing 3256 // the function, we pretend that we don't have the full function 3257 // type. 3258 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3259 isa<FunctionProtoType>(fty)) 3260 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3261 fty->getExtInfo()); 3262 3263 // Functions are r-values in C. 3264 valueKind = VK_RValue; 3265 break; 3266 } 3267 3268 case Decl::CXXDeductionGuide: 3269 llvm_unreachable("building reference to deduction guide"); 3270 3271 case Decl::MSProperty: 3272 valueKind = VK_LValue; 3273 break; 3274 3275 case Decl::CXXMethod: 3276 // If we're referring to a method with an __unknown_anytype 3277 // result type, make the entire expression __unknown_anytype. 3278 // This should only be possible with a type written directly. 3279 if (const FunctionProtoType *proto 3280 = dyn_cast<FunctionProtoType>(VD->getType())) 3281 if (proto->getReturnType() == Context.UnknownAnyTy) { 3282 type = Context.UnknownAnyTy; 3283 valueKind = VK_RValue; 3284 break; 3285 } 3286 3287 // C++ methods are l-values if static, r-values if non-static. 3288 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3289 valueKind = VK_LValue; 3290 break; 3291 } 3292 LLVM_FALLTHROUGH; 3293 3294 case Decl::CXXConversion: 3295 case Decl::CXXDestructor: 3296 case Decl::CXXConstructor: 3297 valueKind = VK_RValue; 3298 break; 3299 } 3300 3301 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3302 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3303 TemplateArgs); 3304 } 3305 } 3306 3307 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3308 SmallString<32> &Target) { 3309 Target.resize(CharByteWidth * (Source.size() + 1)); 3310 char *ResultPtr = &Target[0]; 3311 const llvm::UTF8 *ErrorPtr; 3312 bool success = 3313 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3314 (void)success; 3315 assert(success); 3316 Target.resize(ResultPtr - &Target[0]); 3317 } 3318 3319 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3320 PredefinedExpr::IdentKind IK) { 3321 // Pick the current block, lambda, captured statement or function. 3322 Decl *currentDecl = nullptr; 3323 if (const BlockScopeInfo *BSI = getCurBlock()) 3324 currentDecl = BSI->TheDecl; 3325 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3326 currentDecl = LSI->CallOperator; 3327 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3328 currentDecl = CSI->TheCapturedDecl; 3329 else 3330 currentDecl = getCurFunctionOrMethodDecl(); 3331 3332 if (!currentDecl) { 3333 Diag(Loc, diag::ext_predef_outside_function); 3334 currentDecl = Context.getTranslationUnitDecl(); 3335 } 3336 3337 QualType ResTy; 3338 StringLiteral *SL = nullptr; 3339 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3340 ResTy = Context.DependentTy; 3341 else { 3342 // Pre-defined identifiers are of type char[x], where x is the length of 3343 // the string. 3344 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3345 unsigned Length = Str.length(); 3346 3347 llvm::APInt LengthI(32, Length + 1); 3348 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3349 ResTy = 3350 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3351 SmallString<32> RawChars; 3352 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3353 Str, RawChars); 3354 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3355 ArrayType::Normal, 3356 /*IndexTypeQuals*/ 0); 3357 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3358 /*Pascal*/ false, ResTy, Loc); 3359 } else { 3360 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3361 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3362 ArrayType::Normal, 3363 /*IndexTypeQuals*/ 0); 3364 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3365 /*Pascal*/ false, ResTy, Loc); 3366 } 3367 } 3368 3369 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3370 } 3371 3372 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3373 PredefinedExpr::IdentKind IK; 3374 3375 switch (Kind) { 3376 default: llvm_unreachable("Unknown simple primary expr!"); 3377 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3378 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3379 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3380 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3381 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3382 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3383 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3384 } 3385 3386 return BuildPredefinedExpr(Loc, IK); 3387 } 3388 3389 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3390 SmallString<16> CharBuffer; 3391 bool Invalid = false; 3392 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3393 if (Invalid) 3394 return ExprError(); 3395 3396 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3397 PP, Tok.getKind()); 3398 if (Literal.hadError()) 3399 return ExprError(); 3400 3401 QualType Ty; 3402 if (Literal.isWide()) 3403 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3404 else if (Literal.isUTF8() && getLangOpts().Char8) 3405 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3406 else if (Literal.isUTF16()) 3407 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3408 else if (Literal.isUTF32()) 3409 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3410 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3411 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3412 else 3413 Ty = Context.CharTy; // 'x' -> char in C++ 3414 3415 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3416 if (Literal.isWide()) 3417 Kind = CharacterLiteral::Wide; 3418 else if (Literal.isUTF16()) 3419 Kind = CharacterLiteral::UTF16; 3420 else if (Literal.isUTF32()) 3421 Kind = CharacterLiteral::UTF32; 3422 else if (Literal.isUTF8()) 3423 Kind = CharacterLiteral::UTF8; 3424 3425 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3426 Tok.getLocation()); 3427 3428 if (Literal.getUDSuffix().empty()) 3429 return Lit; 3430 3431 // We're building a user-defined literal. 3432 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3433 SourceLocation UDSuffixLoc = 3434 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3435 3436 // Make sure we're allowed user-defined literals here. 3437 if (!UDLScope) 3438 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3439 3440 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3441 // operator "" X (ch) 3442 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3443 Lit, Tok.getLocation()); 3444 } 3445 3446 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3447 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3448 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3449 Context.IntTy, Loc); 3450 } 3451 3452 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3453 QualType Ty, SourceLocation Loc) { 3454 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3455 3456 using llvm::APFloat; 3457 APFloat Val(Format); 3458 3459 APFloat::opStatus result = Literal.GetFloatValue(Val); 3460 3461 // Overflow is always an error, but underflow is only an error if 3462 // we underflowed to zero (APFloat reports denormals as underflow). 3463 if ((result & APFloat::opOverflow) || 3464 ((result & APFloat::opUnderflow) && Val.isZero())) { 3465 unsigned diagnostic; 3466 SmallString<20> buffer; 3467 if (result & APFloat::opOverflow) { 3468 diagnostic = diag::warn_float_overflow; 3469 APFloat::getLargest(Format).toString(buffer); 3470 } else { 3471 diagnostic = diag::warn_float_underflow; 3472 APFloat::getSmallest(Format).toString(buffer); 3473 } 3474 3475 S.Diag(Loc, diagnostic) 3476 << Ty 3477 << StringRef(buffer.data(), buffer.size()); 3478 } 3479 3480 bool isExact = (result == APFloat::opOK); 3481 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3482 } 3483 3484 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3485 assert(E && "Invalid expression"); 3486 3487 if (E->isValueDependent()) 3488 return false; 3489 3490 QualType QT = E->getType(); 3491 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3492 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3493 return true; 3494 } 3495 3496 llvm::APSInt ValueAPS; 3497 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3498 3499 if (R.isInvalid()) 3500 return true; 3501 3502 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3503 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3504 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3505 << ValueAPS.toString(10) << ValueIsPositive; 3506 return true; 3507 } 3508 3509 return false; 3510 } 3511 3512 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3513 // Fast path for a single digit (which is quite common). A single digit 3514 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3515 if (Tok.getLength() == 1) { 3516 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3517 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3518 } 3519 3520 SmallString<128> SpellingBuffer; 3521 // NumericLiteralParser wants to overread by one character. Add padding to 3522 // the buffer in case the token is copied to the buffer. If getSpelling() 3523 // returns a StringRef to the memory buffer, it should have a null char at 3524 // the EOF, so it is also safe. 3525 SpellingBuffer.resize(Tok.getLength() + 1); 3526 3527 // Get the spelling of the token, which eliminates trigraphs, etc. 3528 bool Invalid = false; 3529 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3530 if (Invalid) 3531 return ExprError(); 3532 3533 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3534 if (Literal.hadError) 3535 return ExprError(); 3536 3537 if (Literal.hasUDSuffix()) { 3538 // We're building a user-defined literal. 3539 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3540 SourceLocation UDSuffixLoc = 3541 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3542 3543 // Make sure we're allowed user-defined literals here. 3544 if (!UDLScope) 3545 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3546 3547 QualType CookedTy; 3548 if (Literal.isFloatingLiteral()) { 3549 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3550 // long double, the literal is treated as a call of the form 3551 // operator "" X (f L) 3552 CookedTy = Context.LongDoubleTy; 3553 } else { 3554 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3555 // unsigned long long, the literal is treated as a call of the form 3556 // operator "" X (n ULL) 3557 CookedTy = Context.UnsignedLongLongTy; 3558 } 3559 3560 DeclarationName OpName = 3561 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3562 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3563 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3564 3565 SourceLocation TokLoc = Tok.getLocation(); 3566 3567 // Perform literal operator lookup to determine if we're building a raw 3568 // literal or a cooked one. 3569 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3570 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3571 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3572 /*AllowStringTemplate*/ false, 3573 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3574 case LOLR_ErrorNoDiagnostic: 3575 // Lookup failure for imaginary constants isn't fatal, there's still the 3576 // GNU extension producing _Complex types. 3577 break; 3578 case LOLR_Error: 3579 return ExprError(); 3580 case LOLR_Cooked: { 3581 Expr *Lit; 3582 if (Literal.isFloatingLiteral()) { 3583 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3584 } else { 3585 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3586 if (Literal.GetIntegerValue(ResultVal)) 3587 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3588 << /* Unsigned */ 1; 3589 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3590 Tok.getLocation()); 3591 } 3592 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3593 } 3594 3595 case LOLR_Raw: { 3596 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3597 // literal is treated as a call of the form 3598 // operator "" X ("n") 3599 unsigned Length = Literal.getUDSuffixOffset(); 3600 QualType StrTy = Context.getConstantArrayType( 3601 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3602 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3603 Expr *Lit = StringLiteral::Create( 3604 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3605 /*Pascal*/false, StrTy, &TokLoc, 1); 3606 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3607 } 3608 3609 case LOLR_Template: { 3610 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3611 // template), L is treated as a call fo the form 3612 // operator "" X <'c1', 'c2', ... 'ck'>() 3613 // where n is the source character sequence c1 c2 ... ck. 3614 TemplateArgumentListInfo ExplicitArgs; 3615 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3616 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3617 llvm::APSInt Value(CharBits, CharIsUnsigned); 3618 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3619 Value = TokSpelling[I]; 3620 TemplateArgument Arg(Context, Value, Context.CharTy); 3621 TemplateArgumentLocInfo ArgInfo; 3622 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3623 } 3624 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3625 &ExplicitArgs); 3626 } 3627 case LOLR_StringTemplate: 3628 llvm_unreachable("unexpected literal operator lookup result"); 3629 } 3630 } 3631 3632 Expr *Res; 3633 3634 if (Literal.isFixedPointLiteral()) { 3635 QualType Ty; 3636 3637 if (Literal.isAccum) { 3638 if (Literal.isHalf) { 3639 Ty = Context.ShortAccumTy; 3640 } else if (Literal.isLong) { 3641 Ty = Context.LongAccumTy; 3642 } else { 3643 Ty = Context.AccumTy; 3644 } 3645 } else if (Literal.isFract) { 3646 if (Literal.isHalf) { 3647 Ty = Context.ShortFractTy; 3648 } else if (Literal.isLong) { 3649 Ty = Context.LongFractTy; 3650 } else { 3651 Ty = Context.FractTy; 3652 } 3653 } 3654 3655 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3656 3657 bool isSigned = !Literal.isUnsigned; 3658 unsigned scale = Context.getFixedPointScale(Ty); 3659 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3660 3661 llvm::APInt Val(bit_width, 0, isSigned); 3662 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3663 bool ValIsZero = Val.isNullValue() && !Overflowed; 3664 3665 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3666 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3667 // Clause 6.4.4 - The value of a constant shall be in the range of 3668 // representable values for its type, with exception for constants of a 3669 // fract type with a value of exactly 1; such a constant shall denote 3670 // the maximal value for the type. 3671 --Val; 3672 else if (Val.ugt(MaxVal) || Overflowed) 3673 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3674 3675 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3676 Tok.getLocation(), scale); 3677 } else if (Literal.isFloatingLiteral()) { 3678 QualType Ty; 3679 if (Literal.isHalf){ 3680 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3681 Ty = Context.HalfTy; 3682 else { 3683 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3684 return ExprError(); 3685 } 3686 } else if (Literal.isFloat) 3687 Ty = Context.FloatTy; 3688 else if (Literal.isLong) 3689 Ty = Context.LongDoubleTy; 3690 else if (Literal.isFloat16) 3691 Ty = Context.Float16Ty; 3692 else if (Literal.isFloat128) 3693 Ty = Context.Float128Ty; 3694 else 3695 Ty = Context.DoubleTy; 3696 3697 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3698 3699 if (Ty == Context.DoubleTy) { 3700 if (getLangOpts().SinglePrecisionConstants) { 3701 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3702 if (BTy->getKind() != BuiltinType::Float) { 3703 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3704 } 3705 } else if (getLangOpts().OpenCL && 3706 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3707 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3708 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3709 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3710 } 3711 } 3712 } else if (!Literal.isIntegerLiteral()) { 3713 return ExprError(); 3714 } else { 3715 QualType Ty; 3716 3717 // 'long long' is a C99 or C++11 feature. 3718 if (!getLangOpts().C99 && Literal.isLongLong) { 3719 if (getLangOpts().CPlusPlus) 3720 Diag(Tok.getLocation(), 3721 getLangOpts().CPlusPlus11 ? 3722 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3723 else 3724 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3725 } 3726 3727 // Get the value in the widest-possible width. 3728 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3729 llvm::APInt ResultVal(MaxWidth, 0); 3730 3731 if (Literal.GetIntegerValue(ResultVal)) { 3732 // If this value didn't fit into uintmax_t, error and force to ull. 3733 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3734 << /* Unsigned */ 1; 3735 Ty = Context.UnsignedLongLongTy; 3736 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3737 "long long is not intmax_t?"); 3738 } else { 3739 // If this value fits into a ULL, try to figure out what else it fits into 3740 // according to the rules of C99 6.4.4.1p5. 3741 3742 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3743 // be an unsigned int. 3744 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3745 3746 // Check from smallest to largest, picking the smallest type we can. 3747 unsigned Width = 0; 3748 3749 // Microsoft specific integer suffixes are explicitly sized. 3750 if (Literal.MicrosoftInteger) { 3751 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3752 Width = 8; 3753 Ty = Context.CharTy; 3754 } else { 3755 Width = Literal.MicrosoftInteger; 3756 Ty = Context.getIntTypeForBitwidth(Width, 3757 /*Signed=*/!Literal.isUnsigned); 3758 } 3759 } 3760 3761 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3762 // Are int/unsigned possibilities? 3763 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3764 3765 // Does it fit in a unsigned int? 3766 if (ResultVal.isIntN(IntSize)) { 3767 // Does it fit in a signed int? 3768 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3769 Ty = Context.IntTy; 3770 else if (AllowUnsigned) 3771 Ty = Context.UnsignedIntTy; 3772 Width = IntSize; 3773 } 3774 } 3775 3776 // Are long/unsigned long possibilities? 3777 if (Ty.isNull() && !Literal.isLongLong) { 3778 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3779 3780 // Does it fit in a unsigned long? 3781 if (ResultVal.isIntN(LongSize)) { 3782 // Does it fit in a signed long? 3783 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3784 Ty = Context.LongTy; 3785 else if (AllowUnsigned) 3786 Ty = Context.UnsignedLongTy; 3787 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3788 // is compatible. 3789 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3790 const unsigned LongLongSize = 3791 Context.getTargetInfo().getLongLongWidth(); 3792 Diag(Tok.getLocation(), 3793 getLangOpts().CPlusPlus 3794 ? Literal.isLong 3795 ? diag::warn_old_implicitly_unsigned_long_cxx 3796 : /*C++98 UB*/ diag:: 3797 ext_old_implicitly_unsigned_long_cxx 3798 : diag::warn_old_implicitly_unsigned_long) 3799 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3800 : /*will be ill-formed*/ 1); 3801 Ty = Context.UnsignedLongTy; 3802 } 3803 Width = LongSize; 3804 } 3805 } 3806 3807 // Check long long if needed. 3808 if (Ty.isNull()) { 3809 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3810 3811 // Does it fit in a unsigned long long? 3812 if (ResultVal.isIntN(LongLongSize)) { 3813 // Does it fit in a signed long long? 3814 // To be compatible with MSVC, hex integer literals ending with the 3815 // LL or i64 suffix are always signed in Microsoft mode. 3816 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3817 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3818 Ty = Context.LongLongTy; 3819 else if (AllowUnsigned) 3820 Ty = Context.UnsignedLongLongTy; 3821 Width = LongLongSize; 3822 } 3823 } 3824 3825 // If we still couldn't decide a type, we probably have something that 3826 // does not fit in a signed long long, but has no U suffix. 3827 if (Ty.isNull()) { 3828 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3829 Ty = Context.UnsignedLongLongTy; 3830 Width = Context.getTargetInfo().getLongLongWidth(); 3831 } 3832 3833 if (ResultVal.getBitWidth() != Width) 3834 ResultVal = ResultVal.trunc(Width); 3835 } 3836 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3837 } 3838 3839 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3840 if (Literal.isImaginary) { 3841 Res = new (Context) ImaginaryLiteral(Res, 3842 Context.getComplexType(Res->getType())); 3843 3844 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3845 } 3846 return Res; 3847 } 3848 3849 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3850 assert(E && "ActOnParenExpr() missing expr"); 3851 return new (Context) ParenExpr(L, R, E); 3852 } 3853 3854 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3855 SourceLocation Loc, 3856 SourceRange ArgRange) { 3857 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3858 // scalar or vector data type argument..." 3859 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3860 // type (C99 6.2.5p18) or void. 3861 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3862 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3863 << T << ArgRange; 3864 return true; 3865 } 3866 3867 assert((T->isVoidType() || !T->isIncompleteType()) && 3868 "Scalar types should always be complete"); 3869 return false; 3870 } 3871 3872 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3873 SourceLocation Loc, 3874 SourceRange ArgRange, 3875 UnaryExprOrTypeTrait TraitKind) { 3876 // Invalid types must be hard errors for SFINAE in C++. 3877 if (S.LangOpts.CPlusPlus) 3878 return true; 3879 3880 // C99 6.5.3.4p1: 3881 if (T->isFunctionType() && 3882 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3883 TraitKind == UETT_PreferredAlignOf)) { 3884 // sizeof(function)/alignof(function) is allowed as an extension. 3885 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3886 << TraitKind << ArgRange; 3887 return false; 3888 } 3889 3890 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3891 // this is an error (OpenCL v1.1 s6.3.k) 3892 if (T->isVoidType()) { 3893 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3894 : diag::ext_sizeof_alignof_void_type; 3895 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3896 return false; 3897 } 3898 3899 return true; 3900 } 3901 3902 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3903 SourceLocation Loc, 3904 SourceRange ArgRange, 3905 UnaryExprOrTypeTrait TraitKind) { 3906 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3907 // runtime doesn't allow it. 3908 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3909 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3910 << T << (TraitKind == UETT_SizeOf) 3911 << ArgRange; 3912 return true; 3913 } 3914 3915 return false; 3916 } 3917 3918 /// Check whether E is a pointer from a decayed array type (the decayed 3919 /// pointer type is equal to T) and emit a warning if it is. 3920 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3921 Expr *E) { 3922 // Don't warn if the operation changed the type. 3923 if (T != E->getType()) 3924 return; 3925 3926 // Now look for array decays. 3927 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3928 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3929 return; 3930 3931 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3932 << ICE->getType() 3933 << ICE->getSubExpr()->getType(); 3934 } 3935 3936 /// Check the constraints on expression operands to unary type expression 3937 /// and type traits. 3938 /// 3939 /// Completes any types necessary and validates the constraints on the operand 3940 /// expression. The logic mostly mirrors the type-based overload, but may modify 3941 /// the expression as it completes the type for that expression through template 3942 /// instantiation, etc. 3943 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3944 UnaryExprOrTypeTrait ExprKind) { 3945 QualType ExprTy = E->getType(); 3946 assert(!ExprTy->isReferenceType()); 3947 3948 bool IsUnevaluatedOperand = 3949 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3950 ExprKind == UETT_PreferredAlignOf); 3951 if (IsUnevaluatedOperand) { 3952 ExprResult Result = CheckUnevaluatedOperand(E); 3953 if (Result.isInvalid()) 3954 return true; 3955 E = Result.get(); 3956 } 3957 3958 if (ExprKind == UETT_VecStep) 3959 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3960 E->getSourceRange()); 3961 3962 // Whitelist some types as extensions 3963 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3964 E->getSourceRange(), ExprKind)) 3965 return false; 3966 3967 // 'alignof' applied to an expression only requires the base element type of 3968 // the expression to be complete. 'sizeof' requires the expression's type to 3969 // be complete (and will attempt to complete it if it's an array of unknown 3970 // bound). 3971 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3972 if (RequireCompleteSizedType( 3973 E->getExprLoc(), Context.getBaseElementType(E->getType()), 3974 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 3975 E->getSourceRange())) 3976 return true; 3977 } else { 3978 if (RequireCompleteSizedExprType( 3979 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 3980 E->getSourceRange())) 3981 return true; 3982 } 3983 3984 // Completing the expression's type may have changed it. 3985 ExprTy = E->getType(); 3986 assert(!ExprTy->isReferenceType()); 3987 3988 if (ExprTy->isFunctionType()) { 3989 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3990 << ExprKind << E->getSourceRange(); 3991 return true; 3992 } 3993 3994 // The operand for sizeof and alignof is in an unevaluated expression context, 3995 // so side effects could result in unintended consequences. 3996 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3997 E->HasSideEffects(Context, false)) 3998 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3999 4000 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4001 E->getSourceRange(), ExprKind)) 4002 return true; 4003 4004 if (ExprKind == UETT_SizeOf) { 4005 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4006 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4007 QualType OType = PVD->getOriginalType(); 4008 QualType Type = PVD->getType(); 4009 if (Type->isPointerType() && OType->isArrayType()) { 4010 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4011 << Type << OType; 4012 Diag(PVD->getLocation(), diag::note_declared_at); 4013 } 4014 } 4015 } 4016 4017 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4018 // decays into a pointer and returns an unintended result. This is most 4019 // likely a typo for "sizeof(array) op x". 4020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4021 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4022 BO->getLHS()); 4023 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4024 BO->getRHS()); 4025 } 4026 } 4027 4028 return false; 4029 } 4030 4031 /// Check the constraints on operands to unary expression and type 4032 /// traits. 4033 /// 4034 /// This will complete any types necessary, and validate the various constraints 4035 /// on those operands. 4036 /// 4037 /// The UsualUnaryConversions() function is *not* called by this routine. 4038 /// C99 6.3.2.1p[2-4] all state: 4039 /// Except when it is the operand of the sizeof operator ... 4040 /// 4041 /// C++ [expr.sizeof]p4 4042 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4043 /// standard conversions are not applied to the operand of sizeof. 4044 /// 4045 /// This policy is followed for all of the unary trait expressions. 4046 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4047 SourceLocation OpLoc, 4048 SourceRange ExprRange, 4049 UnaryExprOrTypeTrait ExprKind) { 4050 if (ExprType->isDependentType()) 4051 return false; 4052 4053 // C++ [expr.sizeof]p2: 4054 // When applied to a reference or a reference type, the result 4055 // is the size of the referenced type. 4056 // C++11 [expr.alignof]p3: 4057 // When alignof is applied to a reference type, the result 4058 // shall be the alignment of the referenced type. 4059 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4060 ExprType = Ref->getPointeeType(); 4061 4062 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4063 // When alignof or _Alignof is applied to an array type, the result 4064 // is the alignment of the element type. 4065 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4066 ExprKind == UETT_OpenMPRequiredSimdAlign) 4067 ExprType = Context.getBaseElementType(ExprType); 4068 4069 if (ExprKind == UETT_VecStep) 4070 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4071 4072 // Whitelist some types as extensions 4073 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4074 ExprKind)) 4075 return false; 4076 4077 if (RequireCompleteSizedType( 4078 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4079 ExprKind, ExprRange)) 4080 return true; 4081 4082 if (ExprType->isFunctionType()) { 4083 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4084 << ExprKind << ExprRange; 4085 return true; 4086 } 4087 4088 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4089 ExprKind)) 4090 return true; 4091 4092 return false; 4093 } 4094 4095 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4096 // Cannot know anything else if the expression is dependent. 4097 if (E->isTypeDependent()) 4098 return false; 4099 4100 if (E->getObjectKind() == OK_BitField) { 4101 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4102 << 1 << E->getSourceRange(); 4103 return true; 4104 } 4105 4106 ValueDecl *D = nullptr; 4107 Expr *Inner = E->IgnoreParens(); 4108 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4109 D = DRE->getDecl(); 4110 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4111 D = ME->getMemberDecl(); 4112 } 4113 4114 // If it's a field, require the containing struct to have a 4115 // complete definition so that we can compute the layout. 4116 // 4117 // This can happen in C++11 onwards, either by naming the member 4118 // in a way that is not transformed into a member access expression 4119 // (in an unevaluated operand, for instance), or by naming the member 4120 // in a trailing-return-type. 4121 // 4122 // For the record, since __alignof__ on expressions is a GCC 4123 // extension, GCC seems to permit this but always gives the 4124 // nonsensical answer 0. 4125 // 4126 // We don't really need the layout here --- we could instead just 4127 // directly check for all the appropriate alignment-lowing 4128 // attributes --- but that would require duplicating a lot of 4129 // logic that just isn't worth duplicating for such a marginal 4130 // use-case. 4131 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4132 // Fast path this check, since we at least know the record has a 4133 // definition if we can find a member of it. 4134 if (!FD->getParent()->isCompleteDefinition()) { 4135 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4136 << E->getSourceRange(); 4137 return true; 4138 } 4139 4140 // Otherwise, if it's a field, and the field doesn't have 4141 // reference type, then it must have a complete type (or be a 4142 // flexible array member, which we explicitly want to 4143 // white-list anyway), which makes the following checks trivial. 4144 if (!FD->getType()->isReferenceType()) 4145 return false; 4146 } 4147 4148 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4149 } 4150 4151 bool Sema::CheckVecStepExpr(Expr *E) { 4152 E = E->IgnoreParens(); 4153 4154 // Cannot know anything else if the expression is dependent. 4155 if (E->isTypeDependent()) 4156 return false; 4157 4158 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4159 } 4160 4161 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4162 CapturingScopeInfo *CSI) { 4163 assert(T->isVariablyModifiedType()); 4164 assert(CSI != nullptr); 4165 4166 // We're going to walk down into the type and look for VLA expressions. 4167 do { 4168 const Type *Ty = T.getTypePtr(); 4169 switch (Ty->getTypeClass()) { 4170 #define TYPE(Class, Base) 4171 #define ABSTRACT_TYPE(Class, Base) 4172 #define NON_CANONICAL_TYPE(Class, Base) 4173 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4175 #include "clang/AST/TypeNodes.inc" 4176 T = QualType(); 4177 break; 4178 // These types are never variably-modified. 4179 case Type::Builtin: 4180 case Type::Complex: 4181 case Type::Vector: 4182 case Type::ExtVector: 4183 case Type::Record: 4184 case Type::Enum: 4185 case Type::Elaborated: 4186 case Type::TemplateSpecialization: 4187 case Type::ObjCObject: 4188 case Type::ObjCInterface: 4189 case Type::ObjCObjectPointer: 4190 case Type::ObjCTypeParam: 4191 case Type::Pipe: 4192 llvm_unreachable("type class is never variably-modified!"); 4193 case Type::Adjusted: 4194 T = cast<AdjustedType>(Ty)->getOriginalType(); 4195 break; 4196 case Type::Decayed: 4197 T = cast<DecayedType>(Ty)->getPointeeType(); 4198 break; 4199 case Type::Pointer: 4200 T = cast<PointerType>(Ty)->getPointeeType(); 4201 break; 4202 case Type::BlockPointer: 4203 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4204 break; 4205 case Type::LValueReference: 4206 case Type::RValueReference: 4207 T = cast<ReferenceType>(Ty)->getPointeeType(); 4208 break; 4209 case Type::MemberPointer: 4210 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4211 break; 4212 case Type::ConstantArray: 4213 case Type::IncompleteArray: 4214 // Losing element qualification here is fine. 4215 T = cast<ArrayType>(Ty)->getElementType(); 4216 break; 4217 case Type::VariableArray: { 4218 // Losing element qualification here is fine. 4219 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4220 4221 // Unknown size indication requires no size computation. 4222 // Otherwise, evaluate and record it. 4223 auto Size = VAT->getSizeExpr(); 4224 if (Size && !CSI->isVLATypeCaptured(VAT) && 4225 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4226 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4227 4228 T = VAT->getElementType(); 4229 break; 4230 } 4231 case Type::FunctionProto: 4232 case Type::FunctionNoProto: 4233 T = cast<FunctionType>(Ty)->getReturnType(); 4234 break; 4235 case Type::Paren: 4236 case Type::TypeOf: 4237 case Type::UnaryTransform: 4238 case Type::Attributed: 4239 case Type::SubstTemplateTypeParm: 4240 case Type::PackExpansion: 4241 case Type::MacroQualified: 4242 // Keep walking after single level desugaring. 4243 T = T.getSingleStepDesugaredType(Context); 4244 break; 4245 case Type::Typedef: 4246 T = cast<TypedefType>(Ty)->desugar(); 4247 break; 4248 case Type::Decltype: 4249 T = cast<DecltypeType>(Ty)->desugar(); 4250 break; 4251 case Type::Auto: 4252 case Type::DeducedTemplateSpecialization: 4253 T = cast<DeducedType>(Ty)->getDeducedType(); 4254 break; 4255 case Type::TypeOfExpr: 4256 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4257 break; 4258 case Type::Atomic: 4259 T = cast<AtomicType>(Ty)->getValueType(); 4260 break; 4261 } 4262 } while (!T.isNull() && T->isVariablyModifiedType()); 4263 } 4264 4265 /// Build a sizeof or alignof expression given a type operand. 4266 ExprResult 4267 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4268 SourceLocation OpLoc, 4269 UnaryExprOrTypeTrait ExprKind, 4270 SourceRange R) { 4271 if (!TInfo) 4272 return ExprError(); 4273 4274 QualType T = TInfo->getType(); 4275 4276 if (!T->isDependentType() && 4277 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4278 return ExprError(); 4279 4280 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4281 if (auto *TT = T->getAs<TypedefType>()) { 4282 for (auto I = FunctionScopes.rbegin(), 4283 E = std::prev(FunctionScopes.rend()); 4284 I != E; ++I) { 4285 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4286 if (CSI == nullptr) 4287 break; 4288 DeclContext *DC = nullptr; 4289 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4290 DC = LSI->CallOperator; 4291 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4292 DC = CRSI->TheCapturedDecl; 4293 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4294 DC = BSI->TheDecl; 4295 if (DC) { 4296 if (DC->containsDecl(TT->getDecl())) 4297 break; 4298 captureVariablyModifiedType(Context, T, CSI); 4299 } 4300 } 4301 } 4302 } 4303 4304 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4305 return new (Context) UnaryExprOrTypeTraitExpr( 4306 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4307 } 4308 4309 /// Build a sizeof or alignof expression given an expression 4310 /// operand. 4311 ExprResult 4312 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4313 UnaryExprOrTypeTrait ExprKind) { 4314 ExprResult PE = CheckPlaceholderExpr(E); 4315 if (PE.isInvalid()) 4316 return ExprError(); 4317 4318 E = PE.get(); 4319 4320 // Verify that the operand is valid. 4321 bool isInvalid = false; 4322 if (E->isTypeDependent()) { 4323 // Delay type-checking for type-dependent expressions. 4324 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4325 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4326 } else if (ExprKind == UETT_VecStep) { 4327 isInvalid = CheckVecStepExpr(E); 4328 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4329 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4330 isInvalid = true; 4331 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4332 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4333 isInvalid = true; 4334 } else { 4335 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4336 } 4337 4338 if (isInvalid) 4339 return ExprError(); 4340 4341 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4342 PE = TransformToPotentiallyEvaluated(E); 4343 if (PE.isInvalid()) return ExprError(); 4344 E = PE.get(); 4345 } 4346 4347 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4348 return new (Context) UnaryExprOrTypeTraitExpr( 4349 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4350 } 4351 4352 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4353 /// expr and the same for @c alignof and @c __alignof 4354 /// Note that the ArgRange is invalid if isType is false. 4355 ExprResult 4356 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4357 UnaryExprOrTypeTrait ExprKind, bool IsType, 4358 void *TyOrEx, SourceRange ArgRange) { 4359 // If error parsing type, ignore. 4360 if (!TyOrEx) return ExprError(); 4361 4362 if (IsType) { 4363 TypeSourceInfo *TInfo; 4364 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4365 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4366 } 4367 4368 Expr *ArgEx = (Expr *)TyOrEx; 4369 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4370 return Result; 4371 } 4372 4373 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4374 bool IsReal) { 4375 if (V.get()->isTypeDependent()) 4376 return S.Context.DependentTy; 4377 4378 // _Real and _Imag are only l-values for normal l-values. 4379 if (V.get()->getObjectKind() != OK_Ordinary) { 4380 V = S.DefaultLvalueConversion(V.get()); 4381 if (V.isInvalid()) 4382 return QualType(); 4383 } 4384 4385 // These operators return the element type of a complex type. 4386 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4387 return CT->getElementType(); 4388 4389 // Otherwise they pass through real integer and floating point types here. 4390 if (V.get()->getType()->isArithmeticType()) 4391 return V.get()->getType(); 4392 4393 // Test for placeholders. 4394 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4395 if (PR.isInvalid()) return QualType(); 4396 if (PR.get() != V.get()) { 4397 V = PR; 4398 return CheckRealImagOperand(S, V, Loc, IsReal); 4399 } 4400 4401 // Reject anything else. 4402 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4403 << (IsReal ? "__real" : "__imag"); 4404 return QualType(); 4405 } 4406 4407 4408 4409 ExprResult 4410 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4411 tok::TokenKind Kind, Expr *Input) { 4412 UnaryOperatorKind Opc; 4413 switch (Kind) { 4414 default: llvm_unreachable("Unknown unary op!"); 4415 case tok::plusplus: Opc = UO_PostInc; break; 4416 case tok::minusminus: Opc = UO_PostDec; break; 4417 } 4418 4419 // Since this might is a postfix expression, get rid of ParenListExprs. 4420 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4421 if (Result.isInvalid()) return ExprError(); 4422 Input = Result.get(); 4423 4424 return BuildUnaryOp(S, OpLoc, Opc, Input); 4425 } 4426 4427 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4428 /// 4429 /// \return true on error 4430 static bool checkArithmeticOnObjCPointer(Sema &S, 4431 SourceLocation opLoc, 4432 Expr *op) { 4433 assert(op->getType()->isObjCObjectPointerType()); 4434 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4435 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4436 return false; 4437 4438 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4439 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4440 << op->getSourceRange(); 4441 return true; 4442 } 4443 4444 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4445 auto *BaseNoParens = Base->IgnoreParens(); 4446 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4447 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4448 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4449 } 4450 4451 ExprResult 4452 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4453 Expr *idx, SourceLocation rbLoc) { 4454 if (base && !base->getType().isNull() && 4455 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4456 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4457 /*Length=*/nullptr, rbLoc); 4458 4459 // Since this might be a postfix expression, get rid of ParenListExprs. 4460 if (isa<ParenListExpr>(base)) { 4461 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4462 if (result.isInvalid()) return ExprError(); 4463 base = result.get(); 4464 } 4465 4466 // A comma-expression as the index is deprecated in C++2a onwards. 4467 if (getLangOpts().CPlusPlus2a && 4468 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4469 (isa<CXXOperatorCallExpr>(idx) && 4470 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4471 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4472 << SourceRange(base->getBeginLoc(), rbLoc); 4473 } 4474 4475 // Handle any non-overload placeholder types in the base and index 4476 // expressions. We can't handle overloads here because the other 4477 // operand might be an overloadable type, in which case the overload 4478 // resolution for the operator overload should get the first crack 4479 // at the overload. 4480 bool IsMSPropertySubscript = false; 4481 if (base->getType()->isNonOverloadPlaceholderType()) { 4482 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4483 if (!IsMSPropertySubscript) { 4484 ExprResult result = CheckPlaceholderExpr(base); 4485 if (result.isInvalid()) 4486 return ExprError(); 4487 base = result.get(); 4488 } 4489 } 4490 if (idx->getType()->isNonOverloadPlaceholderType()) { 4491 ExprResult result = CheckPlaceholderExpr(idx); 4492 if (result.isInvalid()) return ExprError(); 4493 idx = result.get(); 4494 } 4495 4496 // Build an unanalyzed expression if either operand is type-dependent. 4497 if (getLangOpts().CPlusPlus && 4498 (base->isTypeDependent() || idx->isTypeDependent())) { 4499 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4500 VK_LValue, OK_Ordinary, rbLoc); 4501 } 4502 4503 // MSDN, property (C++) 4504 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4505 // This attribute can also be used in the declaration of an empty array in a 4506 // class or structure definition. For example: 4507 // __declspec(property(get=GetX, put=PutX)) int x[]; 4508 // The above statement indicates that x[] can be used with one or more array 4509 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4510 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4511 if (IsMSPropertySubscript) { 4512 // Build MS property subscript expression if base is MS property reference 4513 // or MS property subscript. 4514 return new (Context) MSPropertySubscriptExpr( 4515 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4516 } 4517 4518 // Use C++ overloaded-operator rules if either operand has record 4519 // type. The spec says to do this if either type is *overloadable*, 4520 // but enum types can't declare subscript operators or conversion 4521 // operators, so there's nothing interesting for overload resolution 4522 // to do if there aren't any record types involved. 4523 // 4524 // ObjC pointers have their own subscripting logic that is not tied 4525 // to overload resolution and so should not take this path. 4526 if (getLangOpts().CPlusPlus && 4527 (base->getType()->isRecordType() || 4528 (!base->getType()->isObjCObjectPointerType() && 4529 idx->getType()->isRecordType()))) { 4530 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4531 } 4532 4533 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4534 4535 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4536 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4537 4538 return Res; 4539 } 4540 4541 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4542 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4543 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4544 4545 // For expressions like `&(*s).b`, the base is recorded and what should be 4546 // checked. 4547 const MemberExpr *Member = nullptr; 4548 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4549 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4550 4551 LastRecord.PossibleDerefs.erase(StrippedExpr); 4552 } 4553 4554 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4555 QualType ResultTy = E->getType(); 4556 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4557 4558 // Bail if the element is an array since it is not memory access. 4559 if (isa<ArrayType>(ResultTy)) 4560 return; 4561 4562 if (ResultTy->hasAttr(attr::NoDeref)) { 4563 LastRecord.PossibleDerefs.insert(E); 4564 return; 4565 } 4566 4567 // Check if the base type is a pointer to a member access of a struct 4568 // marked with noderef. 4569 const Expr *Base = E->getBase(); 4570 QualType BaseTy = Base->getType(); 4571 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4572 // Not a pointer access 4573 return; 4574 4575 const MemberExpr *Member = nullptr; 4576 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4577 Member->isArrow()) 4578 Base = Member->getBase(); 4579 4580 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4581 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4582 LastRecord.PossibleDerefs.insert(E); 4583 } 4584 } 4585 4586 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4587 Expr *LowerBound, 4588 SourceLocation ColonLoc, Expr *Length, 4589 SourceLocation RBLoc) { 4590 if (Base->getType()->isPlaceholderType() && 4591 !Base->getType()->isSpecificPlaceholderType( 4592 BuiltinType::OMPArraySection)) { 4593 ExprResult Result = CheckPlaceholderExpr(Base); 4594 if (Result.isInvalid()) 4595 return ExprError(); 4596 Base = Result.get(); 4597 } 4598 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4599 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4600 if (Result.isInvalid()) 4601 return ExprError(); 4602 Result = DefaultLvalueConversion(Result.get()); 4603 if (Result.isInvalid()) 4604 return ExprError(); 4605 LowerBound = Result.get(); 4606 } 4607 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4608 ExprResult Result = CheckPlaceholderExpr(Length); 4609 if (Result.isInvalid()) 4610 return ExprError(); 4611 Result = DefaultLvalueConversion(Result.get()); 4612 if (Result.isInvalid()) 4613 return ExprError(); 4614 Length = Result.get(); 4615 } 4616 4617 // Build an unanalyzed expression if either operand is type-dependent. 4618 if (Base->isTypeDependent() || 4619 (LowerBound && 4620 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4621 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4622 return new (Context) 4623 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4624 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4625 } 4626 4627 // Perform default conversions. 4628 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4629 QualType ResultTy; 4630 if (OriginalTy->isAnyPointerType()) { 4631 ResultTy = OriginalTy->getPointeeType(); 4632 } else if (OriginalTy->isArrayType()) { 4633 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4634 } else { 4635 return ExprError( 4636 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4637 << Base->getSourceRange()); 4638 } 4639 // C99 6.5.2.1p1 4640 if (LowerBound) { 4641 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4642 LowerBound); 4643 if (Res.isInvalid()) 4644 return ExprError(Diag(LowerBound->getExprLoc(), 4645 diag::err_omp_typecheck_section_not_integer) 4646 << 0 << LowerBound->getSourceRange()); 4647 LowerBound = Res.get(); 4648 4649 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4650 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4651 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4652 << 0 << LowerBound->getSourceRange(); 4653 } 4654 if (Length) { 4655 auto Res = 4656 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4657 if (Res.isInvalid()) 4658 return ExprError(Diag(Length->getExprLoc(), 4659 diag::err_omp_typecheck_section_not_integer) 4660 << 1 << Length->getSourceRange()); 4661 Length = Res.get(); 4662 4663 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4664 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4665 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4666 << 1 << Length->getSourceRange(); 4667 } 4668 4669 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4670 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4671 // type. Note that functions are not objects, and that (in C99 parlance) 4672 // incomplete types are not object types. 4673 if (ResultTy->isFunctionType()) { 4674 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4675 << ResultTy << Base->getSourceRange(); 4676 return ExprError(); 4677 } 4678 4679 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4680 diag::err_omp_section_incomplete_type, Base)) 4681 return ExprError(); 4682 4683 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4684 Expr::EvalResult Result; 4685 if (LowerBound->EvaluateAsInt(Result, Context)) { 4686 // OpenMP 4.5, [2.4 Array Sections] 4687 // The array section must be a subset of the original array. 4688 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4689 if (LowerBoundValue.isNegative()) { 4690 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4691 << LowerBound->getSourceRange(); 4692 return ExprError(); 4693 } 4694 } 4695 } 4696 4697 if (Length) { 4698 Expr::EvalResult Result; 4699 if (Length->EvaluateAsInt(Result, Context)) { 4700 // OpenMP 4.5, [2.4 Array Sections] 4701 // The length must evaluate to non-negative integers. 4702 llvm::APSInt LengthValue = Result.Val.getInt(); 4703 if (LengthValue.isNegative()) { 4704 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4705 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4706 << Length->getSourceRange(); 4707 return ExprError(); 4708 } 4709 } 4710 } else if (ColonLoc.isValid() && 4711 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4712 !OriginalTy->isVariableArrayType()))) { 4713 // OpenMP 4.5, [2.4 Array Sections] 4714 // When the size of the array dimension is not known, the length must be 4715 // specified explicitly. 4716 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4717 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4718 return ExprError(); 4719 } 4720 4721 if (!Base->getType()->isSpecificPlaceholderType( 4722 BuiltinType::OMPArraySection)) { 4723 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4724 if (Result.isInvalid()) 4725 return ExprError(); 4726 Base = Result.get(); 4727 } 4728 return new (Context) 4729 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4730 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4731 } 4732 4733 ExprResult 4734 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4735 Expr *Idx, SourceLocation RLoc) { 4736 Expr *LHSExp = Base; 4737 Expr *RHSExp = Idx; 4738 4739 ExprValueKind VK = VK_LValue; 4740 ExprObjectKind OK = OK_Ordinary; 4741 4742 // Per C++ core issue 1213, the result is an xvalue if either operand is 4743 // a non-lvalue array, and an lvalue otherwise. 4744 if (getLangOpts().CPlusPlus11) { 4745 for (auto *Op : {LHSExp, RHSExp}) { 4746 Op = Op->IgnoreImplicit(); 4747 if (Op->getType()->isArrayType() && !Op->isLValue()) 4748 VK = VK_XValue; 4749 } 4750 } 4751 4752 // Perform default conversions. 4753 if (!LHSExp->getType()->getAs<VectorType>()) { 4754 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4755 if (Result.isInvalid()) 4756 return ExprError(); 4757 LHSExp = Result.get(); 4758 } 4759 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4760 if (Result.isInvalid()) 4761 return ExprError(); 4762 RHSExp = Result.get(); 4763 4764 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4765 4766 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4767 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4768 // in the subscript position. As a result, we need to derive the array base 4769 // and index from the expression types. 4770 Expr *BaseExpr, *IndexExpr; 4771 QualType ResultType; 4772 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4773 BaseExpr = LHSExp; 4774 IndexExpr = RHSExp; 4775 ResultType = Context.DependentTy; 4776 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4777 BaseExpr = LHSExp; 4778 IndexExpr = RHSExp; 4779 ResultType = PTy->getPointeeType(); 4780 } else if (const ObjCObjectPointerType *PTy = 4781 LHSTy->getAs<ObjCObjectPointerType>()) { 4782 BaseExpr = LHSExp; 4783 IndexExpr = RHSExp; 4784 4785 // Use custom logic if this should be the pseudo-object subscript 4786 // expression. 4787 if (!LangOpts.isSubscriptPointerArithmetic()) 4788 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4789 nullptr); 4790 4791 ResultType = PTy->getPointeeType(); 4792 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4793 // Handle the uncommon case of "123[Ptr]". 4794 BaseExpr = RHSExp; 4795 IndexExpr = LHSExp; 4796 ResultType = PTy->getPointeeType(); 4797 } else if (const ObjCObjectPointerType *PTy = 4798 RHSTy->getAs<ObjCObjectPointerType>()) { 4799 // Handle the uncommon case of "123[Ptr]". 4800 BaseExpr = RHSExp; 4801 IndexExpr = LHSExp; 4802 ResultType = PTy->getPointeeType(); 4803 if (!LangOpts.isSubscriptPointerArithmetic()) { 4804 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4805 << ResultType << BaseExpr->getSourceRange(); 4806 return ExprError(); 4807 } 4808 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4809 BaseExpr = LHSExp; // vectors: V[123] 4810 IndexExpr = RHSExp; 4811 // We apply C++ DR1213 to vector subscripting too. 4812 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4813 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4814 if (Materialized.isInvalid()) 4815 return ExprError(); 4816 LHSExp = Materialized.get(); 4817 } 4818 VK = LHSExp->getValueKind(); 4819 if (VK != VK_RValue) 4820 OK = OK_VectorComponent; 4821 4822 ResultType = VTy->getElementType(); 4823 QualType BaseType = BaseExpr->getType(); 4824 Qualifiers BaseQuals = BaseType.getQualifiers(); 4825 Qualifiers MemberQuals = ResultType.getQualifiers(); 4826 Qualifiers Combined = BaseQuals + MemberQuals; 4827 if (Combined != MemberQuals) 4828 ResultType = Context.getQualifiedType(ResultType, Combined); 4829 } else if (LHSTy->isArrayType()) { 4830 // If we see an array that wasn't promoted by 4831 // DefaultFunctionArrayLvalueConversion, it must be an array that 4832 // wasn't promoted because of the C90 rule that doesn't 4833 // allow promoting non-lvalue arrays. Warn, then 4834 // force the promotion here. 4835 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4836 << LHSExp->getSourceRange(); 4837 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4838 CK_ArrayToPointerDecay).get(); 4839 LHSTy = LHSExp->getType(); 4840 4841 BaseExpr = LHSExp; 4842 IndexExpr = RHSExp; 4843 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4844 } else if (RHSTy->isArrayType()) { 4845 // Same as previous, except for 123[f().a] case 4846 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4847 << RHSExp->getSourceRange(); 4848 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4849 CK_ArrayToPointerDecay).get(); 4850 RHSTy = RHSExp->getType(); 4851 4852 BaseExpr = RHSExp; 4853 IndexExpr = LHSExp; 4854 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4855 } else { 4856 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4857 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4858 } 4859 // C99 6.5.2.1p1 4860 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4861 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4862 << IndexExpr->getSourceRange()); 4863 4864 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4865 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4866 && !IndexExpr->isTypeDependent()) 4867 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4868 4869 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4870 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4871 // type. Note that Functions are not objects, and that (in C99 parlance) 4872 // incomplete types are not object types. 4873 if (ResultType->isFunctionType()) { 4874 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4875 << ResultType << BaseExpr->getSourceRange(); 4876 return ExprError(); 4877 } 4878 4879 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4880 // GNU extension: subscripting on pointer to void 4881 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4882 << BaseExpr->getSourceRange(); 4883 4884 // C forbids expressions of unqualified void type from being l-values. 4885 // See IsCForbiddenLValueType. 4886 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4887 } else if (!ResultType->isDependentType() && 4888 RequireCompleteType(LLoc, ResultType, 4889 diag::err_subscript_incomplete_type, BaseExpr)) 4890 return ExprError(); 4891 4892 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4893 !ResultType.isCForbiddenLValueType()); 4894 4895 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4896 FunctionScopes.size() > 1) { 4897 if (auto *TT = 4898 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4899 for (auto I = FunctionScopes.rbegin(), 4900 E = std::prev(FunctionScopes.rend()); 4901 I != E; ++I) { 4902 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4903 if (CSI == nullptr) 4904 break; 4905 DeclContext *DC = nullptr; 4906 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4907 DC = LSI->CallOperator; 4908 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4909 DC = CRSI->TheCapturedDecl; 4910 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4911 DC = BSI->TheDecl; 4912 if (DC) { 4913 if (DC->containsDecl(TT->getDecl())) 4914 break; 4915 captureVariablyModifiedType( 4916 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4917 } 4918 } 4919 } 4920 } 4921 4922 return new (Context) 4923 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4924 } 4925 4926 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4927 ParmVarDecl *Param) { 4928 if (Param->hasUnparsedDefaultArg()) { 4929 Diag(CallLoc, 4930 diag::err_use_of_default_argument_to_function_declared_later) << 4931 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4932 Diag(UnparsedDefaultArgLocs[Param], 4933 diag::note_default_argument_declared_here); 4934 return true; 4935 } 4936 4937 if (Param->hasUninstantiatedDefaultArg()) { 4938 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4939 4940 EnterExpressionEvaluationContext EvalContext( 4941 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4942 4943 // Instantiate the expression. 4944 // 4945 // FIXME: Pass in a correct Pattern argument, otherwise 4946 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4947 // 4948 // template<typename T> 4949 // struct A { 4950 // static int FooImpl(); 4951 // 4952 // template<typename Tp> 4953 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4954 // // template argument list [[T], [Tp]], should be [[Tp]]. 4955 // friend A<Tp> Foo(int a); 4956 // }; 4957 // 4958 // template<typename T> 4959 // A<T> Foo(int a = A<T>::FooImpl()); 4960 MultiLevelTemplateArgumentList MutiLevelArgList 4961 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4962 4963 InstantiatingTemplate Inst(*this, CallLoc, Param, 4964 MutiLevelArgList.getInnermost()); 4965 if (Inst.isInvalid()) 4966 return true; 4967 if (Inst.isAlreadyInstantiating()) { 4968 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4969 Param->setInvalidDecl(); 4970 return true; 4971 } 4972 4973 ExprResult Result; 4974 { 4975 // C++ [dcl.fct.default]p5: 4976 // The names in the [default argument] expression are bound, and 4977 // the semantic constraints are checked, at the point where the 4978 // default argument expression appears. 4979 ContextRAII SavedContext(*this, FD); 4980 LocalInstantiationScope Local(*this); 4981 runWithSufficientStackSpace(CallLoc, [&] { 4982 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4983 /*DirectInit*/false); 4984 }); 4985 } 4986 if (Result.isInvalid()) 4987 return true; 4988 4989 // Check the expression as an initializer for the parameter. 4990 InitializedEntity Entity 4991 = InitializedEntity::InitializeParameter(Context, Param); 4992 InitializationKind Kind = InitializationKind::CreateCopy( 4993 Param->getLocation(), 4994 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4995 Expr *ResultE = Result.getAs<Expr>(); 4996 4997 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4998 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4999 if (Result.isInvalid()) 5000 return true; 5001 5002 Result = 5003 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5004 /*DiscardedValue*/ false); 5005 if (Result.isInvalid()) 5006 return true; 5007 5008 // Remember the instantiated default argument. 5009 Param->setDefaultArg(Result.getAs<Expr>()); 5010 if (ASTMutationListener *L = getASTMutationListener()) { 5011 L->DefaultArgumentInstantiated(Param); 5012 } 5013 } 5014 5015 // If the default argument expression is not set yet, we are building it now. 5016 if (!Param->hasInit()) { 5017 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5018 Param->setInvalidDecl(); 5019 return true; 5020 } 5021 5022 // If the default expression creates temporaries, we need to 5023 // push them to the current stack of expression temporaries so they'll 5024 // be properly destroyed. 5025 // FIXME: We should really be rebuilding the default argument with new 5026 // bound temporaries; see the comment in PR5810. 5027 // We don't need to do that with block decls, though, because 5028 // blocks in default argument expression can never capture anything. 5029 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5030 // Set the "needs cleanups" bit regardless of whether there are 5031 // any explicit objects. 5032 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5033 5034 // Append all the objects to the cleanup list. Right now, this 5035 // should always be a no-op, because blocks in default argument 5036 // expressions should never be able to capture anything. 5037 assert(!Init->getNumObjects() && 5038 "default argument expression has capturing blocks?"); 5039 } 5040 5041 // We already type-checked the argument, so we know it works. 5042 // Just mark all of the declarations in this potentially-evaluated expression 5043 // as being "referenced". 5044 EnterExpressionEvaluationContext EvalContext( 5045 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5046 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5047 /*SkipLocalVariables=*/true); 5048 return false; 5049 } 5050 5051 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5052 FunctionDecl *FD, ParmVarDecl *Param) { 5053 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5054 return ExprError(); 5055 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5056 } 5057 5058 Sema::VariadicCallType 5059 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5060 Expr *Fn) { 5061 if (Proto && Proto->isVariadic()) { 5062 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5063 return VariadicConstructor; 5064 else if (Fn && Fn->getType()->isBlockPointerType()) 5065 return VariadicBlock; 5066 else if (FDecl) { 5067 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5068 if (Method->isInstance()) 5069 return VariadicMethod; 5070 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5071 return VariadicMethod; 5072 return VariadicFunction; 5073 } 5074 return VariadicDoesNotApply; 5075 } 5076 5077 namespace { 5078 class FunctionCallCCC final : public FunctionCallFilterCCC { 5079 public: 5080 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5081 unsigned NumArgs, MemberExpr *ME) 5082 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5083 FunctionName(FuncName) {} 5084 5085 bool ValidateCandidate(const TypoCorrection &candidate) override { 5086 if (!candidate.getCorrectionSpecifier() || 5087 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5088 return false; 5089 } 5090 5091 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5092 } 5093 5094 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5095 return std::make_unique<FunctionCallCCC>(*this); 5096 } 5097 5098 private: 5099 const IdentifierInfo *const FunctionName; 5100 }; 5101 } 5102 5103 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5104 FunctionDecl *FDecl, 5105 ArrayRef<Expr *> Args) { 5106 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5107 DeclarationName FuncName = FDecl->getDeclName(); 5108 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5109 5110 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5111 if (TypoCorrection Corrected = S.CorrectTypo( 5112 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5113 S.getScopeForContext(S.CurContext), nullptr, CCC, 5114 Sema::CTK_ErrorRecovery)) { 5115 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5116 if (Corrected.isOverloaded()) { 5117 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5118 OverloadCandidateSet::iterator Best; 5119 for (NamedDecl *CD : Corrected) { 5120 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5121 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5122 OCS); 5123 } 5124 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5125 case OR_Success: 5126 ND = Best->FoundDecl; 5127 Corrected.setCorrectionDecl(ND); 5128 break; 5129 default: 5130 break; 5131 } 5132 } 5133 ND = ND->getUnderlyingDecl(); 5134 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5135 return Corrected; 5136 } 5137 } 5138 return TypoCorrection(); 5139 } 5140 5141 /// ConvertArgumentsForCall - Converts the arguments specified in 5142 /// Args/NumArgs to the parameter types of the function FDecl with 5143 /// function prototype Proto. Call is the call expression itself, and 5144 /// Fn is the function expression. For a C++ member function, this 5145 /// routine does not attempt to convert the object argument. Returns 5146 /// true if the call is ill-formed. 5147 bool 5148 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5149 FunctionDecl *FDecl, 5150 const FunctionProtoType *Proto, 5151 ArrayRef<Expr *> Args, 5152 SourceLocation RParenLoc, 5153 bool IsExecConfig) { 5154 // Bail out early if calling a builtin with custom typechecking. 5155 if (FDecl) 5156 if (unsigned ID = FDecl->getBuiltinID()) 5157 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5158 return false; 5159 5160 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5161 // assignment, to the types of the corresponding parameter, ... 5162 unsigned NumParams = Proto->getNumParams(); 5163 bool Invalid = false; 5164 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5165 unsigned FnKind = Fn->getType()->isBlockPointerType() 5166 ? 1 /* block */ 5167 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5168 : 0 /* function */); 5169 5170 // If too few arguments are available (and we don't have default 5171 // arguments for the remaining parameters), don't make the call. 5172 if (Args.size() < NumParams) { 5173 if (Args.size() < MinArgs) { 5174 TypoCorrection TC; 5175 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5176 unsigned diag_id = 5177 MinArgs == NumParams && !Proto->isVariadic() 5178 ? diag::err_typecheck_call_too_few_args_suggest 5179 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5180 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5181 << static_cast<unsigned>(Args.size()) 5182 << TC.getCorrectionRange()); 5183 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5184 Diag(RParenLoc, 5185 MinArgs == NumParams && !Proto->isVariadic() 5186 ? diag::err_typecheck_call_too_few_args_one 5187 : diag::err_typecheck_call_too_few_args_at_least_one) 5188 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5189 else 5190 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5191 ? diag::err_typecheck_call_too_few_args 5192 : diag::err_typecheck_call_too_few_args_at_least) 5193 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5194 << Fn->getSourceRange(); 5195 5196 // Emit the location of the prototype. 5197 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5198 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5199 5200 return true; 5201 } 5202 // We reserve space for the default arguments when we create 5203 // the call expression, before calling ConvertArgumentsForCall. 5204 assert((Call->getNumArgs() == NumParams) && 5205 "We should have reserved space for the default arguments before!"); 5206 } 5207 5208 // If too many are passed and not variadic, error on the extras and drop 5209 // them. 5210 if (Args.size() > NumParams) { 5211 if (!Proto->isVariadic()) { 5212 TypoCorrection TC; 5213 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5214 unsigned diag_id = 5215 MinArgs == NumParams && !Proto->isVariadic() 5216 ? diag::err_typecheck_call_too_many_args_suggest 5217 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5218 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5219 << static_cast<unsigned>(Args.size()) 5220 << TC.getCorrectionRange()); 5221 } else if (NumParams == 1 && FDecl && 5222 FDecl->getParamDecl(0)->getDeclName()) 5223 Diag(Args[NumParams]->getBeginLoc(), 5224 MinArgs == NumParams 5225 ? diag::err_typecheck_call_too_many_args_one 5226 : diag::err_typecheck_call_too_many_args_at_most_one) 5227 << FnKind << FDecl->getParamDecl(0) 5228 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5229 << SourceRange(Args[NumParams]->getBeginLoc(), 5230 Args.back()->getEndLoc()); 5231 else 5232 Diag(Args[NumParams]->getBeginLoc(), 5233 MinArgs == NumParams 5234 ? diag::err_typecheck_call_too_many_args 5235 : diag::err_typecheck_call_too_many_args_at_most) 5236 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5237 << Fn->getSourceRange() 5238 << SourceRange(Args[NumParams]->getBeginLoc(), 5239 Args.back()->getEndLoc()); 5240 5241 // Emit the location of the prototype. 5242 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5243 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5244 5245 // This deletes the extra arguments. 5246 Call->shrinkNumArgs(NumParams); 5247 return true; 5248 } 5249 } 5250 SmallVector<Expr *, 8> AllArgs; 5251 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5252 5253 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5254 AllArgs, CallType); 5255 if (Invalid) 5256 return true; 5257 unsigned TotalNumArgs = AllArgs.size(); 5258 for (unsigned i = 0; i < TotalNumArgs; ++i) 5259 Call->setArg(i, AllArgs[i]); 5260 5261 return false; 5262 } 5263 5264 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5265 const FunctionProtoType *Proto, 5266 unsigned FirstParam, ArrayRef<Expr *> Args, 5267 SmallVectorImpl<Expr *> &AllArgs, 5268 VariadicCallType CallType, bool AllowExplicit, 5269 bool IsListInitialization) { 5270 unsigned NumParams = Proto->getNumParams(); 5271 bool Invalid = false; 5272 size_t ArgIx = 0; 5273 // Continue to check argument types (even if we have too few/many args). 5274 for (unsigned i = FirstParam; i < NumParams; i++) { 5275 QualType ProtoArgType = Proto->getParamType(i); 5276 5277 Expr *Arg; 5278 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5279 if (ArgIx < Args.size()) { 5280 Arg = Args[ArgIx++]; 5281 5282 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5283 diag::err_call_incomplete_argument, Arg)) 5284 return true; 5285 5286 // Strip the unbridged-cast placeholder expression off, if applicable. 5287 bool CFAudited = false; 5288 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5289 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5290 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5291 Arg = stripARCUnbridgedCast(Arg); 5292 else if (getLangOpts().ObjCAutoRefCount && 5293 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5294 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5295 CFAudited = true; 5296 5297 if (Proto->getExtParameterInfo(i).isNoEscape()) 5298 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5299 BE->getBlockDecl()->setDoesNotEscape(); 5300 5301 InitializedEntity Entity = 5302 Param ? InitializedEntity::InitializeParameter(Context, Param, 5303 ProtoArgType) 5304 : InitializedEntity::InitializeParameter( 5305 Context, ProtoArgType, Proto->isParamConsumed(i)); 5306 5307 // Remember that parameter belongs to a CF audited API. 5308 if (CFAudited) 5309 Entity.setParameterCFAudited(); 5310 5311 ExprResult ArgE = PerformCopyInitialization( 5312 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5313 if (ArgE.isInvalid()) 5314 return true; 5315 5316 Arg = ArgE.getAs<Expr>(); 5317 } else { 5318 assert(Param && "can't use default arguments without a known callee"); 5319 5320 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5321 if (ArgExpr.isInvalid()) 5322 return true; 5323 5324 Arg = ArgExpr.getAs<Expr>(); 5325 } 5326 5327 // Check for array bounds violations for each argument to the call. This 5328 // check only triggers warnings when the argument isn't a more complex Expr 5329 // with its own checking, such as a BinaryOperator. 5330 CheckArrayAccess(Arg); 5331 5332 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5333 CheckStaticArrayArgument(CallLoc, Param, Arg); 5334 5335 AllArgs.push_back(Arg); 5336 } 5337 5338 // If this is a variadic call, handle args passed through "...". 5339 if (CallType != VariadicDoesNotApply) { 5340 // Assume that extern "C" functions with variadic arguments that 5341 // return __unknown_anytype aren't *really* variadic. 5342 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5343 FDecl->isExternC()) { 5344 for (Expr *A : Args.slice(ArgIx)) { 5345 QualType paramType; // ignored 5346 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5347 Invalid |= arg.isInvalid(); 5348 AllArgs.push_back(arg.get()); 5349 } 5350 5351 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5352 } else { 5353 for (Expr *A : Args.slice(ArgIx)) { 5354 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5355 Invalid |= Arg.isInvalid(); 5356 // Copy blocks to the heap. 5357 if (A->getType()->isBlockPointerType()) 5358 maybeExtendBlockObject(Arg); 5359 AllArgs.push_back(Arg.get()); 5360 } 5361 } 5362 5363 // Check for array bounds violations. 5364 for (Expr *A : Args.slice(ArgIx)) 5365 CheckArrayAccess(A); 5366 } 5367 return Invalid; 5368 } 5369 5370 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5371 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5372 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5373 TL = DTL.getOriginalLoc(); 5374 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5375 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5376 << ATL.getLocalSourceRange(); 5377 } 5378 5379 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5380 /// array parameter, check that it is non-null, and that if it is formed by 5381 /// array-to-pointer decay, the underlying array is sufficiently large. 5382 /// 5383 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5384 /// array type derivation, then for each call to the function, the value of the 5385 /// corresponding actual argument shall provide access to the first element of 5386 /// an array with at least as many elements as specified by the size expression. 5387 void 5388 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5389 ParmVarDecl *Param, 5390 const Expr *ArgExpr) { 5391 // Static array parameters are not supported in C++. 5392 if (!Param || getLangOpts().CPlusPlus) 5393 return; 5394 5395 QualType OrigTy = Param->getOriginalType(); 5396 5397 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5398 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5399 return; 5400 5401 if (ArgExpr->isNullPointerConstant(Context, 5402 Expr::NPC_NeverValueDependent)) { 5403 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5404 DiagnoseCalleeStaticArrayParam(*this, Param); 5405 return; 5406 } 5407 5408 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5409 if (!CAT) 5410 return; 5411 5412 const ConstantArrayType *ArgCAT = 5413 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5414 if (!ArgCAT) 5415 return; 5416 5417 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5418 ArgCAT->getElementType())) { 5419 if (ArgCAT->getSize().ult(CAT->getSize())) { 5420 Diag(CallLoc, diag::warn_static_array_too_small) 5421 << ArgExpr->getSourceRange() 5422 << (unsigned)ArgCAT->getSize().getZExtValue() 5423 << (unsigned)CAT->getSize().getZExtValue() << 0; 5424 DiagnoseCalleeStaticArrayParam(*this, Param); 5425 } 5426 return; 5427 } 5428 5429 Optional<CharUnits> ArgSize = 5430 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5431 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5432 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5433 Diag(CallLoc, diag::warn_static_array_too_small) 5434 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5435 << (unsigned)ParmSize->getQuantity() << 1; 5436 DiagnoseCalleeStaticArrayParam(*this, Param); 5437 } 5438 } 5439 5440 /// Given a function expression of unknown-any type, try to rebuild it 5441 /// to have a function type. 5442 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5443 5444 /// Is the given type a placeholder that we need to lower out 5445 /// immediately during argument processing? 5446 static bool isPlaceholderToRemoveAsArg(QualType type) { 5447 // Placeholders are never sugared. 5448 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5449 if (!placeholder) return false; 5450 5451 switch (placeholder->getKind()) { 5452 // Ignore all the non-placeholder types. 5453 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5454 case BuiltinType::Id: 5455 #include "clang/Basic/OpenCLImageTypes.def" 5456 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5457 case BuiltinType::Id: 5458 #include "clang/Basic/OpenCLExtensionTypes.def" 5459 // In practice we'll never use this, since all SVE types are sugared 5460 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5461 #define SVE_TYPE(Name, Id, SingletonId) \ 5462 case BuiltinType::Id: 5463 #include "clang/Basic/AArch64SVEACLETypes.def" 5464 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5465 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5466 #include "clang/AST/BuiltinTypes.def" 5467 return false; 5468 5469 // We cannot lower out overload sets; they might validly be resolved 5470 // by the call machinery. 5471 case BuiltinType::Overload: 5472 return false; 5473 5474 // Unbridged casts in ARC can be handled in some call positions and 5475 // should be left in place. 5476 case BuiltinType::ARCUnbridgedCast: 5477 return false; 5478 5479 // Pseudo-objects should be converted as soon as possible. 5480 case BuiltinType::PseudoObject: 5481 return true; 5482 5483 // The debugger mode could theoretically but currently does not try 5484 // to resolve unknown-typed arguments based on known parameter types. 5485 case BuiltinType::UnknownAny: 5486 return true; 5487 5488 // These are always invalid as call arguments and should be reported. 5489 case BuiltinType::BoundMember: 5490 case BuiltinType::BuiltinFn: 5491 case BuiltinType::OMPArraySection: 5492 return true; 5493 5494 } 5495 llvm_unreachable("bad builtin type kind"); 5496 } 5497 5498 /// Check an argument list for placeholders that we won't try to 5499 /// handle later. 5500 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5501 // Apply this processing to all the arguments at once instead of 5502 // dying at the first failure. 5503 bool hasInvalid = false; 5504 for (size_t i = 0, e = args.size(); i != e; i++) { 5505 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5506 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5507 if (result.isInvalid()) hasInvalid = true; 5508 else args[i] = result.get(); 5509 } else if (hasInvalid) { 5510 (void)S.CorrectDelayedTyposInExpr(args[i]); 5511 } 5512 } 5513 return hasInvalid; 5514 } 5515 5516 /// If a builtin function has a pointer argument with no explicit address 5517 /// space, then it should be able to accept a pointer to any address 5518 /// space as input. In order to do this, we need to replace the 5519 /// standard builtin declaration with one that uses the same address space 5520 /// as the call. 5521 /// 5522 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5523 /// it does not contain any pointer arguments without 5524 /// an address space qualifer. Otherwise the rewritten 5525 /// FunctionDecl is returned. 5526 /// TODO: Handle pointer return types. 5527 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5528 FunctionDecl *FDecl, 5529 MultiExprArg ArgExprs) { 5530 5531 QualType DeclType = FDecl->getType(); 5532 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5533 5534 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5535 ArgExprs.size() < FT->getNumParams()) 5536 return nullptr; 5537 5538 bool NeedsNewDecl = false; 5539 unsigned i = 0; 5540 SmallVector<QualType, 8> OverloadParams; 5541 5542 for (QualType ParamType : FT->param_types()) { 5543 5544 // Convert array arguments to pointer to simplify type lookup. 5545 ExprResult ArgRes = 5546 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5547 if (ArgRes.isInvalid()) 5548 return nullptr; 5549 Expr *Arg = ArgRes.get(); 5550 QualType ArgType = Arg->getType(); 5551 if (!ParamType->isPointerType() || 5552 ParamType.hasAddressSpace() || 5553 !ArgType->isPointerType() || 5554 !ArgType->getPointeeType().hasAddressSpace()) { 5555 OverloadParams.push_back(ParamType); 5556 continue; 5557 } 5558 5559 QualType PointeeType = ParamType->getPointeeType(); 5560 if (PointeeType.hasAddressSpace()) 5561 continue; 5562 5563 NeedsNewDecl = true; 5564 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5565 5566 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5567 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5568 } 5569 5570 if (!NeedsNewDecl) 5571 return nullptr; 5572 5573 FunctionProtoType::ExtProtoInfo EPI; 5574 EPI.Variadic = FT->isVariadic(); 5575 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5576 OverloadParams, EPI); 5577 DeclContext *Parent = FDecl->getParent(); 5578 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5579 FDecl->getLocation(), 5580 FDecl->getLocation(), 5581 FDecl->getIdentifier(), 5582 OverloadTy, 5583 /*TInfo=*/nullptr, 5584 SC_Extern, false, 5585 /*hasPrototype=*/true); 5586 SmallVector<ParmVarDecl*, 16> Params; 5587 FT = cast<FunctionProtoType>(OverloadTy); 5588 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5589 QualType ParamType = FT->getParamType(i); 5590 ParmVarDecl *Parm = 5591 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5592 SourceLocation(), nullptr, ParamType, 5593 /*TInfo=*/nullptr, SC_None, nullptr); 5594 Parm->setScopeInfo(0, i); 5595 Params.push_back(Parm); 5596 } 5597 OverloadDecl->setParams(Params); 5598 return OverloadDecl; 5599 } 5600 5601 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5602 FunctionDecl *Callee, 5603 MultiExprArg ArgExprs) { 5604 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5605 // similar attributes) really don't like it when functions are called with an 5606 // invalid number of args. 5607 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5608 /*PartialOverloading=*/false) && 5609 !Callee->isVariadic()) 5610 return; 5611 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5612 return; 5613 5614 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5615 S.Diag(Fn->getBeginLoc(), 5616 isa<CXXMethodDecl>(Callee) 5617 ? diag::err_ovl_no_viable_member_function_in_call 5618 : diag::err_ovl_no_viable_function_in_call) 5619 << Callee << Callee->getSourceRange(); 5620 S.Diag(Callee->getLocation(), 5621 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5622 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5623 return; 5624 } 5625 } 5626 5627 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5628 const UnresolvedMemberExpr *const UME, Sema &S) { 5629 5630 const auto GetFunctionLevelDCIfCXXClass = 5631 [](Sema &S) -> const CXXRecordDecl * { 5632 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5633 if (!DC || !DC->getParent()) 5634 return nullptr; 5635 5636 // If the call to some member function was made from within a member 5637 // function body 'M' return return 'M's parent. 5638 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5639 return MD->getParent()->getCanonicalDecl(); 5640 // else the call was made from within a default member initializer of a 5641 // class, so return the class. 5642 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5643 return RD->getCanonicalDecl(); 5644 return nullptr; 5645 }; 5646 // If our DeclContext is neither a member function nor a class (in the 5647 // case of a lambda in a default member initializer), we can't have an 5648 // enclosing 'this'. 5649 5650 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5651 if (!CurParentClass) 5652 return false; 5653 5654 // The naming class for implicit member functions call is the class in which 5655 // name lookup starts. 5656 const CXXRecordDecl *const NamingClass = 5657 UME->getNamingClass()->getCanonicalDecl(); 5658 assert(NamingClass && "Must have naming class even for implicit access"); 5659 5660 // If the unresolved member functions were found in a 'naming class' that is 5661 // related (either the same or derived from) to the class that contains the 5662 // member function that itself contained the implicit member access. 5663 5664 return CurParentClass == NamingClass || 5665 CurParentClass->isDerivedFrom(NamingClass); 5666 } 5667 5668 static void 5669 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5670 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5671 5672 if (!UME) 5673 return; 5674 5675 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5676 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5677 // already been captured, or if this is an implicit member function call (if 5678 // it isn't, an attempt to capture 'this' should already have been made). 5679 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5680 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5681 return; 5682 5683 // Check if the naming class in which the unresolved members were found is 5684 // related (same as or is a base of) to the enclosing class. 5685 5686 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5687 return; 5688 5689 5690 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5691 // If the enclosing function is not dependent, then this lambda is 5692 // capture ready, so if we can capture this, do so. 5693 if (!EnclosingFunctionCtx->isDependentContext()) { 5694 // If the current lambda and all enclosing lambdas can capture 'this' - 5695 // then go ahead and capture 'this' (since our unresolved overload set 5696 // contains at least one non-static member function). 5697 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5698 S.CheckCXXThisCapture(CallLoc); 5699 } else if (S.CurContext->isDependentContext()) { 5700 // ... since this is an implicit member reference, that might potentially 5701 // involve a 'this' capture, mark 'this' for potential capture in 5702 // enclosing lambdas. 5703 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5704 CurLSI->addPotentialThisCapture(CallLoc); 5705 } 5706 } 5707 5708 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5709 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5710 Expr *ExecConfig) { 5711 ExprResult Call = 5712 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5713 if (Call.isInvalid()) 5714 return Call; 5715 5716 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5717 // language modes. 5718 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5719 if (ULE->hasExplicitTemplateArgs() && 5720 ULE->decls_begin() == ULE->decls_end()) { 5721 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5722 ? diag::warn_cxx17_compat_adl_only_template_id 5723 : diag::ext_adl_only_template_id) 5724 << ULE->getName(); 5725 } 5726 } 5727 5728 return Call; 5729 } 5730 5731 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5732 /// This provides the location of the left/right parens and a list of comma 5733 /// locations. 5734 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5735 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5736 Expr *ExecConfig, bool IsExecConfig) { 5737 // Since this might be a postfix expression, get rid of ParenListExprs. 5738 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5739 if (Result.isInvalid()) return ExprError(); 5740 Fn = Result.get(); 5741 5742 if (checkArgsForPlaceholders(*this, ArgExprs)) 5743 return ExprError(); 5744 5745 if (getLangOpts().CPlusPlus) { 5746 // If this is a pseudo-destructor expression, build the call immediately. 5747 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5748 if (!ArgExprs.empty()) { 5749 // Pseudo-destructor calls should not have any arguments. 5750 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5751 << FixItHint::CreateRemoval( 5752 SourceRange(ArgExprs.front()->getBeginLoc(), 5753 ArgExprs.back()->getEndLoc())); 5754 } 5755 5756 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5757 VK_RValue, RParenLoc); 5758 } 5759 if (Fn->getType() == Context.PseudoObjectTy) { 5760 ExprResult result = CheckPlaceholderExpr(Fn); 5761 if (result.isInvalid()) return ExprError(); 5762 Fn = result.get(); 5763 } 5764 5765 // Determine whether this is a dependent call inside a C++ template, 5766 // in which case we won't do any semantic analysis now. 5767 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5768 if (ExecConfig) { 5769 return CUDAKernelCallExpr::Create( 5770 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5771 Context.DependentTy, VK_RValue, RParenLoc); 5772 } else { 5773 5774 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5775 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5776 Fn->getBeginLoc()); 5777 5778 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5779 VK_RValue, RParenLoc); 5780 } 5781 } 5782 5783 // Determine whether this is a call to an object (C++ [over.call.object]). 5784 if (Fn->getType()->isRecordType()) 5785 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5786 RParenLoc); 5787 5788 if (Fn->getType() == Context.UnknownAnyTy) { 5789 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5790 if (result.isInvalid()) return ExprError(); 5791 Fn = result.get(); 5792 } 5793 5794 if (Fn->getType() == Context.BoundMemberTy) { 5795 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5796 RParenLoc); 5797 } 5798 } 5799 5800 // Check for overloaded calls. This can happen even in C due to extensions. 5801 if (Fn->getType() == Context.OverloadTy) { 5802 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5803 5804 // We aren't supposed to apply this logic if there's an '&' involved. 5805 if (!find.HasFormOfMemberPointer) { 5806 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5807 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5808 VK_RValue, RParenLoc); 5809 OverloadExpr *ovl = find.Expression; 5810 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5811 return BuildOverloadedCallExpr( 5812 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5813 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5814 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5815 RParenLoc); 5816 } 5817 } 5818 5819 // If we're directly calling a function, get the appropriate declaration. 5820 if (Fn->getType() == Context.UnknownAnyTy) { 5821 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5822 if (result.isInvalid()) return ExprError(); 5823 Fn = result.get(); 5824 } 5825 5826 Expr *NakedFn = Fn->IgnoreParens(); 5827 5828 bool CallingNDeclIndirectly = false; 5829 NamedDecl *NDecl = nullptr; 5830 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5831 if (UnOp->getOpcode() == UO_AddrOf) { 5832 CallingNDeclIndirectly = true; 5833 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5834 } 5835 } 5836 5837 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5838 NDecl = DRE->getDecl(); 5839 5840 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5841 if (FDecl && FDecl->getBuiltinID()) { 5842 // Rewrite the function decl for this builtin by replacing parameters 5843 // with no explicit address space with the address space of the arguments 5844 // in ArgExprs. 5845 if ((FDecl = 5846 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5847 NDecl = FDecl; 5848 Fn = DeclRefExpr::Create( 5849 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5850 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5851 nullptr, DRE->isNonOdrUse()); 5852 } 5853 } 5854 } else if (isa<MemberExpr>(NakedFn)) 5855 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5856 5857 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5858 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5859 FD, /*Complain=*/true, Fn->getBeginLoc())) 5860 return ExprError(); 5861 5862 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5863 return ExprError(); 5864 5865 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5866 } 5867 5868 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5869 ExecConfig, IsExecConfig); 5870 } 5871 5872 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5873 /// 5874 /// __builtin_astype( value, dst type ) 5875 /// 5876 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5877 SourceLocation BuiltinLoc, 5878 SourceLocation RParenLoc) { 5879 ExprValueKind VK = VK_RValue; 5880 ExprObjectKind OK = OK_Ordinary; 5881 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5882 QualType SrcTy = E->getType(); 5883 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5884 return ExprError(Diag(BuiltinLoc, 5885 diag::err_invalid_astype_of_different_size) 5886 << DstTy 5887 << SrcTy 5888 << E->getSourceRange()); 5889 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5890 } 5891 5892 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5893 /// provided arguments. 5894 /// 5895 /// __builtin_convertvector( value, dst type ) 5896 /// 5897 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5898 SourceLocation BuiltinLoc, 5899 SourceLocation RParenLoc) { 5900 TypeSourceInfo *TInfo; 5901 GetTypeFromParser(ParsedDestTy, &TInfo); 5902 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5903 } 5904 5905 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5906 /// i.e. an expression not of \p OverloadTy. The expression should 5907 /// unary-convert to an expression of function-pointer or 5908 /// block-pointer type. 5909 /// 5910 /// \param NDecl the declaration being called, if available 5911 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5912 SourceLocation LParenLoc, 5913 ArrayRef<Expr *> Args, 5914 SourceLocation RParenLoc, Expr *Config, 5915 bool IsExecConfig, ADLCallKind UsesADL) { 5916 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5917 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5918 5919 // Functions with 'interrupt' attribute cannot be called directly. 5920 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5921 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5922 return ExprError(); 5923 } 5924 5925 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5926 // so there's some risk when calling out to non-interrupt handler functions 5927 // that the callee might not preserve them. This is easy to diagnose here, 5928 // but can be very challenging to debug. 5929 if (auto *Caller = getCurFunctionDecl()) 5930 if (Caller->hasAttr<ARMInterruptAttr>()) { 5931 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5932 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5933 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5934 } 5935 5936 // Promote the function operand. 5937 // We special-case function promotion here because we only allow promoting 5938 // builtin functions to function pointers in the callee of a call. 5939 ExprResult Result; 5940 QualType ResultTy; 5941 if (BuiltinID && 5942 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5943 // Extract the return type from the (builtin) function pointer type. 5944 // FIXME Several builtins still have setType in 5945 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5946 // Builtins.def to ensure they are correct before removing setType calls. 5947 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5948 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5949 ResultTy = FDecl->getCallResultType(); 5950 } else { 5951 Result = CallExprUnaryConversions(Fn); 5952 ResultTy = Context.BoolTy; 5953 } 5954 if (Result.isInvalid()) 5955 return ExprError(); 5956 Fn = Result.get(); 5957 5958 // Check for a valid function type, but only if it is not a builtin which 5959 // requires custom type checking. These will be handled by 5960 // CheckBuiltinFunctionCall below just after creation of the call expression. 5961 const FunctionType *FuncT = nullptr; 5962 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5963 retry: 5964 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5965 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5966 // have type pointer to function". 5967 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5968 if (!FuncT) 5969 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5970 << Fn->getType() << Fn->getSourceRange()); 5971 } else if (const BlockPointerType *BPT = 5972 Fn->getType()->getAs<BlockPointerType>()) { 5973 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5974 } else { 5975 // Handle calls to expressions of unknown-any type. 5976 if (Fn->getType() == Context.UnknownAnyTy) { 5977 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5978 if (rewrite.isInvalid()) 5979 return ExprError(); 5980 Fn = rewrite.get(); 5981 goto retry; 5982 } 5983 5984 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5985 << Fn->getType() << Fn->getSourceRange()); 5986 } 5987 } 5988 5989 // Get the number of parameters in the function prototype, if any. 5990 // We will allocate space for max(Args.size(), NumParams) arguments 5991 // in the call expression. 5992 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5993 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5994 5995 CallExpr *TheCall; 5996 if (Config) { 5997 assert(UsesADL == ADLCallKind::NotADL && 5998 "CUDAKernelCallExpr should not use ADL"); 5999 TheCall = 6000 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6001 ResultTy, VK_RValue, RParenLoc, NumParams); 6002 } else { 6003 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6004 RParenLoc, NumParams, UsesADL); 6005 } 6006 6007 if (!getLangOpts().CPlusPlus) { 6008 // Forget about the nulled arguments since typo correction 6009 // do not handle them well. 6010 TheCall->shrinkNumArgs(Args.size()); 6011 // C cannot always handle TypoExpr nodes in builtin calls and direct 6012 // function calls as their argument checking don't necessarily handle 6013 // dependent types properly, so make sure any TypoExprs have been 6014 // dealt with. 6015 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6016 if (!Result.isUsable()) return ExprError(); 6017 CallExpr *TheOldCall = TheCall; 6018 TheCall = dyn_cast<CallExpr>(Result.get()); 6019 bool CorrectedTypos = TheCall != TheOldCall; 6020 if (!TheCall) return Result; 6021 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6022 6023 // A new call expression node was created if some typos were corrected. 6024 // However it may not have been constructed with enough storage. In this 6025 // case, rebuild the node with enough storage. The waste of space is 6026 // immaterial since this only happens when some typos were corrected. 6027 if (CorrectedTypos && Args.size() < NumParams) { 6028 if (Config) 6029 TheCall = CUDAKernelCallExpr::Create( 6030 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6031 RParenLoc, NumParams); 6032 else 6033 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6034 RParenLoc, NumParams, UsesADL); 6035 } 6036 // We can now handle the nulled arguments for the default arguments. 6037 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6038 } 6039 6040 // Bail out early if calling a builtin with custom type checking. 6041 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6042 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6043 6044 if (getLangOpts().CUDA) { 6045 if (Config) { 6046 // CUDA: Kernel calls must be to global functions 6047 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6048 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6049 << FDecl << Fn->getSourceRange()); 6050 6051 // CUDA: Kernel function must have 'void' return type 6052 if (!FuncT->getReturnType()->isVoidType() && 6053 !FuncT->getReturnType()->getAs<AutoType>() && 6054 !FuncT->getReturnType()->isInstantiationDependentType()) 6055 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6056 << Fn->getType() << Fn->getSourceRange()); 6057 } else { 6058 // CUDA: Calls to global functions must be configured 6059 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6060 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6061 << FDecl << Fn->getSourceRange()); 6062 } 6063 } 6064 6065 // Check for a valid return type 6066 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6067 FDecl)) 6068 return ExprError(); 6069 6070 // We know the result type of the call, set it. 6071 TheCall->setType(FuncT->getCallResultType(Context)); 6072 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6073 6074 if (Proto) { 6075 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6076 IsExecConfig)) 6077 return ExprError(); 6078 } else { 6079 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6080 6081 if (FDecl) { 6082 // Check if we have too few/too many template arguments, based 6083 // on our knowledge of the function definition. 6084 const FunctionDecl *Def = nullptr; 6085 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6086 Proto = Def->getType()->getAs<FunctionProtoType>(); 6087 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6088 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6089 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6090 } 6091 6092 // If the function we're calling isn't a function prototype, but we have 6093 // a function prototype from a prior declaratiom, use that prototype. 6094 if (!FDecl->hasPrototype()) 6095 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6096 } 6097 6098 // Promote the arguments (C99 6.5.2.2p6). 6099 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6100 Expr *Arg = Args[i]; 6101 6102 if (Proto && i < Proto->getNumParams()) { 6103 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6104 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6105 ExprResult ArgE = 6106 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6107 if (ArgE.isInvalid()) 6108 return true; 6109 6110 Arg = ArgE.getAs<Expr>(); 6111 6112 } else { 6113 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6114 6115 if (ArgE.isInvalid()) 6116 return true; 6117 6118 Arg = ArgE.getAs<Expr>(); 6119 } 6120 6121 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6122 diag::err_call_incomplete_argument, Arg)) 6123 return ExprError(); 6124 6125 TheCall->setArg(i, Arg); 6126 } 6127 } 6128 6129 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6130 if (!Method->isStatic()) 6131 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6132 << Fn->getSourceRange()); 6133 6134 // Check for sentinels 6135 if (NDecl) 6136 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6137 6138 // Do special checking on direct calls to functions. 6139 if (FDecl) { 6140 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6141 return ExprError(); 6142 6143 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6144 6145 if (BuiltinID) 6146 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6147 } else if (NDecl) { 6148 if (CheckPointerCall(NDecl, TheCall, Proto)) 6149 return ExprError(); 6150 } else { 6151 if (CheckOtherCall(TheCall, Proto)) 6152 return ExprError(); 6153 } 6154 6155 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6156 } 6157 6158 ExprResult 6159 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6160 SourceLocation RParenLoc, Expr *InitExpr) { 6161 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6162 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6163 6164 TypeSourceInfo *TInfo; 6165 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6166 if (!TInfo) 6167 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6168 6169 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6170 } 6171 6172 ExprResult 6173 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6174 SourceLocation RParenLoc, Expr *LiteralExpr) { 6175 QualType literalType = TInfo->getType(); 6176 6177 if (literalType->isArrayType()) { 6178 if (RequireCompleteSizedType( 6179 LParenLoc, Context.getBaseElementType(literalType), 6180 diag::err_array_incomplete_or_sizeless_type, 6181 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6182 return ExprError(); 6183 if (literalType->isVariableArrayType()) 6184 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6185 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6186 } else if (!literalType->isDependentType() && 6187 RequireCompleteType(LParenLoc, literalType, 6188 diag::err_typecheck_decl_incomplete_type, 6189 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6190 return ExprError(); 6191 6192 InitializedEntity Entity 6193 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6194 InitializationKind Kind 6195 = InitializationKind::CreateCStyleCast(LParenLoc, 6196 SourceRange(LParenLoc, RParenLoc), 6197 /*InitList=*/true); 6198 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6199 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6200 &literalType); 6201 if (Result.isInvalid()) 6202 return ExprError(); 6203 LiteralExpr = Result.get(); 6204 6205 bool isFileScope = !CurContext->isFunctionOrMethod(); 6206 6207 // In C, compound literals are l-values for some reason. 6208 // For GCC compatibility, in C++, file-scope array compound literals with 6209 // constant initializers are also l-values, and compound literals are 6210 // otherwise prvalues. 6211 // 6212 // (GCC also treats C++ list-initialized file-scope array prvalues with 6213 // constant initializers as l-values, but that's non-conforming, so we don't 6214 // follow it there.) 6215 // 6216 // FIXME: It would be better to handle the lvalue cases as materializing and 6217 // lifetime-extending a temporary object, but our materialized temporaries 6218 // representation only supports lifetime extension from a variable, not "out 6219 // of thin air". 6220 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6221 // is bound to the result of applying array-to-pointer decay to the compound 6222 // literal. 6223 // FIXME: GCC supports compound literals of reference type, which should 6224 // obviously have a value kind derived from the kind of reference involved. 6225 ExprValueKind VK = 6226 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6227 ? VK_RValue 6228 : VK_LValue; 6229 6230 if (isFileScope) 6231 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6232 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6233 Expr *Init = ILE->getInit(i); 6234 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6235 } 6236 6237 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6238 VK, LiteralExpr, isFileScope); 6239 if (isFileScope) { 6240 if (!LiteralExpr->isTypeDependent() && 6241 !LiteralExpr->isValueDependent() && 6242 !literalType->isDependentType()) // C99 6.5.2.5p3 6243 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6244 return ExprError(); 6245 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6246 literalType.getAddressSpace() != LangAS::Default) { 6247 // Embedded-C extensions to C99 6.5.2.5: 6248 // "If the compound literal occurs inside the body of a function, the 6249 // type name shall not be qualified by an address-space qualifier." 6250 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6251 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6252 return ExprError(); 6253 } 6254 6255 if (!isFileScope && !getLangOpts().CPlusPlus) { 6256 // Compound literals that have automatic storage duration are destroyed at 6257 // the end of the scope in C; in C++, they're just temporaries. 6258 6259 // Emit diagnostics if it is or contains a C union type that is non-trivial 6260 // to destruct. 6261 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6262 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6263 NTCUC_CompoundLiteral, NTCUK_Destruct); 6264 6265 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6266 if (literalType.isDestructedType()) { 6267 Cleanup.setExprNeedsCleanups(true); 6268 ExprCleanupObjects.push_back(E); 6269 getCurFunction()->setHasBranchProtectedScope(); 6270 } 6271 } 6272 6273 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6274 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6275 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6276 E->getInitializer()->getExprLoc()); 6277 6278 return MaybeBindToTemporary(E); 6279 } 6280 6281 ExprResult 6282 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6283 SourceLocation RBraceLoc) { 6284 // Only produce each kind of designated initialization diagnostic once. 6285 SourceLocation FirstDesignator; 6286 bool DiagnosedArrayDesignator = false; 6287 bool DiagnosedNestedDesignator = false; 6288 bool DiagnosedMixedDesignator = false; 6289 6290 // Check that any designated initializers are syntactically valid in the 6291 // current language mode. 6292 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6293 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6294 if (FirstDesignator.isInvalid()) 6295 FirstDesignator = DIE->getBeginLoc(); 6296 6297 if (!getLangOpts().CPlusPlus) 6298 break; 6299 6300 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6301 DiagnosedNestedDesignator = true; 6302 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6303 << DIE->getDesignatorsSourceRange(); 6304 } 6305 6306 for (auto &Desig : DIE->designators()) { 6307 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6308 DiagnosedArrayDesignator = true; 6309 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6310 << Desig.getSourceRange(); 6311 } 6312 } 6313 6314 if (!DiagnosedMixedDesignator && 6315 !isa<DesignatedInitExpr>(InitArgList[0])) { 6316 DiagnosedMixedDesignator = true; 6317 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6318 << DIE->getSourceRange(); 6319 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6320 << InitArgList[0]->getSourceRange(); 6321 } 6322 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6323 isa<DesignatedInitExpr>(InitArgList[0])) { 6324 DiagnosedMixedDesignator = true; 6325 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6326 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6327 << DIE->getSourceRange(); 6328 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6329 << InitArgList[I]->getSourceRange(); 6330 } 6331 } 6332 6333 if (FirstDesignator.isValid()) { 6334 // Only diagnose designated initiaization as a C++20 extension if we didn't 6335 // already diagnose use of (non-C++20) C99 designator syntax. 6336 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6337 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6338 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6339 ? diag::warn_cxx17_compat_designated_init 6340 : diag::ext_cxx_designated_init); 6341 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6342 Diag(FirstDesignator, diag::ext_designated_init); 6343 } 6344 } 6345 6346 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6347 } 6348 6349 ExprResult 6350 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6351 SourceLocation RBraceLoc) { 6352 // Semantic analysis for initializers is done by ActOnDeclarator() and 6353 // CheckInitializer() - it requires knowledge of the object being initialized. 6354 6355 // Immediately handle non-overload placeholders. Overloads can be 6356 // resolved contextually, but everything else here can't. 6357 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6358 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6359 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6360 6361 // Ignore failures; dropping the entire initializer list because 6362 // of one failure would be terrible for indexing/etc. 6363 if (result.isInvalid()) continue; 6364 6365 InitArgList[I] = result.get(); 6366 } 6367 } 6368 6369 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6370 RBraceLoc); 6371 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6372 return E; 6373 } 6374 6375 /// Do an explicit extend of the given block pointer if we're in ARC. 6376 void Sema::maybeExtendBlockObject(ExprResult &E) { 6377 assert(E.get()->getType()->isBlockPointerType()); 6378 assert(E.get()->isRValue()); 6379 6380 // Only do this in an r-value context. 6381 if (!getLangOpts().ObjCAutoRefCount) return; 6382 6383 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6384 CK_ARCExtendBlockObject, E.get(), 6385 /*base path*/ nullptr, VK_RValue); 6386 Cleanup.setExprNeedsCleanups(true); 6387 } 6388 6389 /// Prepare a conversion of the given expression to an ObjC object 6390 /// pointer type. 6391 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6392 QualType type = E.get()->getType(); 6393 if (type->isObjCObjectPointerType()) { 6394 return CK_BitCast; 6395 } else if (type->isBlockPointerType()) { 6396 maybeExtendBlockObject(E); 6397 return CK_BlockPointerToObjCPointerCast; 6398 } else { 6399 assert(type->isPointerType()); 6400 return CK_CPointerToObjCPointerCast; 6401 } 6402 } 6403 6404 /// Prepares for a scalar cast, performing all the necessary stages 6405 /// except the final cast and returning the kind required. 6406 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6407 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6408 // Also, callers should have filtered out the invalid cases with 6409 // pointers. Everything else should be possible. 6410 6411 QualType SrcTy = Src.get()->getType(); 6412 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6413 return CK_NoOp; 6414 6415 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6416 case Type::STK_MemberPointer: 6417 llvm_unreachable("member pointer type in C"); 6418 6419 case Type::STK_CPointer: 6420 case Type::STK_BlockPointer: 6421 case Type::STK_ObjCObjectPointer: 6422 switch (DestTy->getScalarTypeKind()) { 6423 case Type::STK_CPointer: { 6424 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6425 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6426 if (SrcAS != DestAS) 6427 return CK_AddressSpaceConversion; 6428 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6429 return CK_NoOp; 6430 return CK_BitCast; 6431 } 6432 case Type::STK_BlockPointer: 6433 return (SrcKind == Type::STK_BlockPointer 6434 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6435 case Type::STK_ObjCObjectPointer: 6436 if (SrcKind == Type::STK_ObjCObjectPointer) 6437 return CK_BitCast; 6438 if (SrcKind == Type::STK_CPointer) 6439 return CK_CPointerToObjCPointerCast; 6440 maybeExtendBlockObject(Src); 6441 return CK_BlockPointerToObjCPointerCast; 6442 case Type::STK_Bool: 6443 return CK_PointerToBoolean; 6444 case Type::STK_Integral: 6445 return CK_PointerToIntegral; 6446 case Type::STK_Floating: 6447 case Type::STK_FloatingComplex: 6448 case Type::STK_IntegralComplex: 6449 case Type::STK_MemberPointer: 6450 case Type::STK_FixedPoint: 6451 llvm_unreachable("illegal cast from pointer"); 6452 } 6453 llvm_unreachable("Should have returned before this"); 6454 6455 case Type::STK_FixedPoint: 6456 switch (DestTy->getScalarTypeKind()) { 6457 case Type::STK_FixedPoint: 6458 return CK_FixedPointCast; 6459 case Type::STK_Bool: 6460 return CK_FixedPointToBoolean; 6461 case Type::STK_Integral: 6462 return CK_FixedPointToIntegral; 6463 case Type::STK_Floating: 6464 case Type::STK_IntegralComplex: 6465 case Type::STK_FloatingComplex: 6466 Diag(Src.get()->getExprLoc(), 6467 diag::err_unimplemented_conversion_with_fixed_point_type) 6468 << DestTy; 6469 return CK_IntegralCast; 6470 case Type::STK_CPointer: 6471 case Type::STK_ObjCObjectPointer: 6472 case Type::STK_BlockPointer: 6473 case Type::STK_MemberPointer: 6474 llvm_unreachable("illegal cast to pointer type"); 6475 } 6476 llvm_unreachable("Should have returned before this"); 6477 6478 case Type::STK_Bool: // casting from bool is like casting from an integer 6479 case Type::STK_Integral: 6480 switch (DestTy->getScalarTypeKind()) { 6481 case Type::STK_CPointer: 6482 case Type::STK_ObjCObjectPointer: 6483 case Type::STK_BlockPointer: 6484 if (Src.get()->isNullPointerConstant(Context, 6485 Expr::NPC_ValueDependentIsNull)) 6486 return CK_NullToPointer; 6487 return CK_IntegralToPointer; 6488 case Type::STK_Bool: 6489 return CK_IntegralToBoolean; 6490 case Type::STK_Integral: 6491 return CK_IntegralCast; 6492 case Type::STK_Floating: 6493 return CK_IntegralToFloating; 6494 case Type::STK_IntegralComplex: 6495 Src = ImpCastExprToType(Src.get(), 6496 DestTy->castAs<ComplexType>()->getElementType(), 6497 CK_IntegralCast); 6498 return CK_IntegralRealToComplex; 6499 case Type::STK_FloatingComplex: 6500 Src = ImpCastExprToType(Src.get(), 6501 DestTy->castAs<ComplexType>()->getElementType(), 6502 CK_IntegralToFloating); 6503 return CK_FloatingRealToComplex; 6504 case Type::STK_MemberPointer: 6505 llvm_unreachable("member pointer type in C"); 6506 case Type::STK_FixedPoint: 6507 return CK_IntegralToFixedPoint; 6508 } 6509 llvm_unreachable("Should have returned before this"); 6510 6511 case Type::STK_Floating: 6512 switch (DestTy->getScalarTypeKind()) { 6513 case Type::STK_Floating: 6514 return CK_FloatingCast; 6515 case Type::STK_Bool: 6516 return CK_FloatingToBoolean; 6517 case Type::STK_Integral: 6518 return CK_FloatingToIntegral; 6519 case Type::STK_FloatingComplex: 6520 Src = ImpCastExprToType(Src.get(), 6521 DestTy->castAs<ComplexType>()->getElementType(), 6522 CK_FloatingCast); 6523 return CK_FloatingRealToComplex; 6524 case Type::STK_IntegralComplex: 6525 Src = ImpCastExprToType(Src.get(), 6526 DestTy->castAs<ComplexType>()->getElementType(), 6527 CK_FloatingToIntegral); 6528 return CK_IntegralRealToComplex; 6529 case Type::STK_CPointer: 6530 case Type::STK_ObjCObjectPointer: 6531 case Type::STK_BlockPointer: 6532 llvm_unreachable("valid float->pointer cast?"); 6533 case Type::STK_MemberPointer: 6534 llvm_unreachable("member pointer type in C"); 6535 case Type::STK_FixedPoint: 6536 Diag(Src.get()->getExprLoc(), 6537 diag::err_unimplemented_conversion_with_fixed_point_type) 6538 << SrcTy; 6539 return CK_IntegralCast; 6540 } 6541 llvm_unreachable("Should have returned before this"); 6542 6543 case Type::STK_FloatingComplex: 6544 switch (DestTy->getScalarTypeKind()) { 6545 case Type::STK_FloatingComplex: 6546 return CK_FloatingComplexCast; 6547 case Type::STK_IntegralComplex: 6548 return CK_FloatingComplexToIntegralComplex; 6549 case Type::STK_Floating: { 6550 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6551 if (Context.hasSameType(ET, DestTy)) 6552 return CK_FloatingComplexToReal; 6553 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6554 return CK_FloatingCast; 6555 } 6556 case Type::STK_Bool: 6557 return CK_FloatingComplexToBoolean; 6558 case Type::STK_Integral: 6559 Src = ImpCastExprToType(Src.get(), 6560 SrcTy->castAs<ComplexType>()->getElementType(), 6561 CK_FloatingComplexToReal); 6562 return CK_FloatingToIntegral; 6563 case Type::STK_CPointer: 6564 case Type::STK_ObjCObjectPointer: 6565 case Type::STK_BlockPointer: 6566 llvm_unreachable("valid complex float->pointer cast?"); 6567 case Type::STK_MemberPointer: 6568 llvm_unreachable("member pointer type in C"); 6569 case Type::STK_FixedPoint: 6570 Diag(Src.get()->getExprLoc(), 6571 diag::err_unimplemented_conversion_with_fixed_point_type) 6572 << SrcTy; 6573 return CK_IntegralCast; 6574 } 6575 llvm_unreachable("Should have returned before this"); 6576 6577 case Type::STK_IntegralComplex: 6578 switch (DestTy->getScalarTypeKind()) { 6579 case Type::STK_FloatingComplex: 6580 return CK_IntegralComplexToFloatingComplex; 6581 case Type::STK_IntegralComplex: 6582 return CK_IntegralComplexCast; 6583 case Type::STK_Integral: { 6584 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6585 if (Context.hasSameType(ET, DestTy)) 6586 return CK_IntegralComplexToReal; 6587 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6588 return CK_IntegralCast; 6589 } 6590 case Type::STK_Bool: 6591 return CK_IntegralComplexToBoolean; 6592 case Type::STK_Floating: 6593 Src = ImpCastExprToType(Src.get(), 6594 SrcTy->castAs<ComplexType>()->getElementType(), 6595 CK_IntegralComplexToReal); 6596 return CK_IntegralToFloating; 6597 case Type::STK_CPointer: 6598 case Type::STK_ObjCObjectPointer: 6599 case Type::STK_BlockPointer: 6600 llvm_unreachable("valid complex int->pointer cast?"); 6601 case Type::STK_MemberPointer: 6602 llvm_unreachable("member pointer type in C"); 6603 case Type::STK_FixedPoint: 6604 Diag(Src.get()->getExprLoc(), 6605 diag::err_unimplemented_conversion_with_fixed_point_type) 6606 << SrcTy; 6607 return CK_IntegralCast; 6608 } 6609 llvm_unreachable("Should have returned before this"); 6610 } 6611 6612 llvm_unreachable("Unhandled scalar cast"); 6613 } 6614 6615 static bool breakDownVectorType(QualType type, uint64_t &len, 6616 QualType &eltType) { 6617 // Vectors are simple. 6618 if (const VectorType *vecType = type->getAs<VectorType>()) { 6619 len = vecType->getNumElements(); 6620 eltType = vecType->getElementType(); 6621 assert(eltType->isScalarType()); 6622 return true; 6623 } 6624 6625 // We allow lax conversion to and from non-vector types, but only if 6626 // they're real types (i.e. non-complex, non-pointer scalar types). 6627 if (!type->isRealType()) return false; 6628 6629 len = 1; 6630 eltType = type; 6631 return true; 6632 } 6633 6634 /// Are the two types lax-compatible vector types? That is, given 6635 /// that one of them is a vector, do they have equal storage sizes, 6636 /// where the storage size is the number of elements times the element 6637 /// size? 6638 /// 6639 /// This will also return false if either of the types is neither a 6640 /// vector nor a real type. 6641 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6642 assert(destTy->isVectorType() || srcTy->isVectorType()); 6643 6644 // Disallow lax conversions between scalars and ExtVectors (these 6645 // conversions are allowed for other vector types because common headers 6646 // depend on them). Most scalar OP ExtVector cases are handled by the 6647 // splat path anyway, which does what we want (convert, not bitcast). 6648 // What this rules out for ExtVectors is crazy things like char4*float. 6649 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6650 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6651 6652 uint64_t srcLen, destLen; 6653 QualType srcEltTy, destEltTy; 6654 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6655 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6656 6657 // ASTContext::getTypeSize will return the size rounded up to a 6658 // power of 2, so instead of using that, we need to use the raw 6659 // element size multiplied by the element count. 6660 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6661 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6662 6663 return (srcLen * srcEltSize == destLen * destEltSize); 6664 } 6665 6666 /// Is this a legal conversion between two types, one of which is 6667 /// known to be a vector type? 6668 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6669 assert(destTy->isVectorType() || srcTy->isVectorType()); 6670 6671 switch (Context.getLangOpts().getLaxVectorConversions()) { 6672 case LangOptions::LaxVectorConversionKind::None: 6673 return false; 6674 6675 case LangOptions::LaxVectorConversionKind::Integer: 6676 if (!srcTy->isIntegralOrEnumerationType()) { 6677 auto *Vec = srcTy->getAs<VectorType>(); 6678 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6679 return false; 6680 } 6681 if (!destTy->isIntegralOrEnumerationType()) { 6682 auto *Vec = destTy->getAs<VectorType>(); 6683 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6684 return false; 6685 } 6686 // OK, integer (vector) -> integer (vector) bitcast. 6687 break; 6688 6689 case LangOptions::LaxVectorConversionKind::All: 6690 break; 6691 } 6692 6693 return areLaxCompatibleVectorTypes(srcTy, destTy); 6694 } 6695 6696 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6697 CastKind &Kind) { 6698 assert(VectorTy->isVectorType() && "Not a vector type!"); 6699 6700 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6701 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6702 return Diag(R.getBegin(), 6703 Ty->isVectorType() ? 6704 diag::err_invalid_conversion_between_vectors : 6705 diag::err_invalid_conversion_between_vector_and_integer) 6706 << VectorTy << Ty << R; 6707 } else 6708 return Diag(R.getBegin(), 6709 diag::err_invalid_conversion_between_vector_and_scalar) 6710 << VectorTy << Ty << R; 6711 6712 Kind = CK_BitCast; 6713 return false; 6714 } 6715 6716 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6717 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6718 6719 if (DestElemTy == SplattedExpr->getType()) 6720 return SplattedExpr; 6721 6722 assert(DestElemTy->isFloatingType() || 6723 DestElemTy->isIntegralOrEnumerationType()); 6724 6725 CastKind CK; 6726 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6727 // OpenCL requires that we convert `true` boolean expressions to -1, but 6728 // only when splatting vectors. 6729 if (DestElemTy->isFloatingType()) { 6730 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6731 // in two steps: boolean to signed integral, then to floating. 6732 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6733 CK_BooleanToSignedIntegral); 6734 SplattedExpr = CastExprRes.get(); 6735 CK = CK_IntegralToFloating; 6736 } else { 6737 CK = CK_BooleanToSignedIntegral; 6738 } 6739 } else { 6740 ExprResult CastExprRes = SplattedExpr; 6741 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6742 if (CastExprRes.isInvalid()) 6743 return ExprError(); 6744 SplattedExpr = CastExprRes.get(); 6745 } 6746 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6747 } 6748 6749 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6750 Expr *CastExpr, CastKind &Kind) { 6751 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6752 6753 QualType SrcTy = CastExpr->getType(); 6754 6755 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6756 // an ExtVectorType. 6757 // In OpenCL, casts between vectors of different types are not allowed. 6758 // (See OpenCL 6.2). 6759 if (SrcTy->isVectorType()) { 6760 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6761 (getLangOpts().OpenCL && 6762 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6763 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6764 << DestTy << SrcTy << R; 6765 return ExprError(); 6766 } 6767 Kind = CK_BitCast; 6768 return CastExpr; 6769 } 6770 6771 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6772 // conversion will take place first from scalar to elt type, and then 6773 // splat from elt type to vector. 6774 if (SrcTy->isPointerType()) 6775 return Diag(R.getBegin(), 6776 diag::err_invalid_conversion_between_vector_and_scalar) 6777 << DestTy << SrcTy << R; 6778 6779 Kind = CK_VectorSplat; 6780 return prepareVectorSplat(DestTy, CastExpr); 6781 } 6782 6783 ExprResult 6784 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6785 Declarator &D, ParsedType &Ty, 6786 SourceLocation RParenLoc, Expr *CastExpr) { 6787 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6788 "ActOnCastExpr(): missing type or expr"); 6789 6790 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6791 if (D.isInvalidType()) 6792 return ExprError(); 6793 6794 if (getLangOpts().CPlusPlus) { 6795 // Check that there are no default arguments (C++ only). 6796 CheckExtraCXXDefaultArguments(D); 6797 } else { 6798 // Make sure any TypoExprs have been dealt with. 6799 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6800 if (!Res.isUsable()) 6801 return ExprError(); 6802 CastExpr = Res.get(); 6803 } 6804 6805 checkUnusedDeclAttributes(D); 6806 6807 QualType castType = castTInfo->getType(); 6808 Ty = CreateParsedType(castType, castTInfo); 6809 6810 bool isVectorLiteral = false; 6811 6812 // Check for an altivec or OpenCL literal, 6813 // i.e. all the elements are integer constants. 6814 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6815 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6816 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6817 && castType->isVectorType() && (PE || PLE)) { 6818 if (PLE && PLE->getNumExprs() == 0) { 6819 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6820 return ExprError(); 6821 } 6822 if (PE || PLE->getNumExprs() == 1) { 6823 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6824 if (!E->getType()->isVectorType()) 6825 isVectorLiteral = true; 6826 } 6827 else 6828 isVectorLiteral = true; 6829 } 6830 6831 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6832 // then handle it as such. 6833 if (isVectorLiteral) 6834 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6835 6836 // If the Expr being casted is a ParenListExpr, handle it specially. 6837 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6838 // sequence of BinOp comma operators. 6839 if (isa<ParenListExpr>(CastExpr)) { 6840 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6841 if (Result.isInvalid()) return ExprError(); 6842 CastExpr = Result.get(); 6843 } 6844 6845 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6846 !getSourceManager().isInSystemMacro(LParenLoc)) 6847 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6848 6849 CheckTollFreeBridgeCast(castType, CastExpr); 6850 6851 CheckObjCBridgeRelatedCast(castType, CastExpr); 6852 6853 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6854 6855 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6856 } 6857 6858 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6859 SourceLocation RParenLoc, Expr *E, 6860 TypeSourceInfo *TInfo) { 6861 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6862 "Expected paren or paren list expression"); 6863 6864 Expr **exprs; 6865 unsigned numExprs; 6866 Expr *subExpr; 6867 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6868 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6869 LiteralLParenLoc = PE->getLParenLoc(); 6870 LiteralRParenLoc = PE->getRParenLoc(); 6871 exprs = PE->getExprs(); 6872 numExprs = PE->getNumExprs(); 6873 } else { // isa<ParenExpr> by assertion at function entrance 6874 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6875 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6876 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6877 exprs = &subExpr; 6878 numExprs = 1; 6879 } 6880 6881 QualType Ty = TInfo->getType(); 6882 assert(Ty->isVectorType() && "Expected vector type"); 6883 6884 SmallVector<Expr *, 8> initExprs; 6885 const VectorType *VTy = Ty->castAs<VectorType>(); 6886 unsigned numElems = VTy->getNumElements(); 6887 6888 // '(...)' form of vector initialization in AltiVec: the number of 6889 // initializers must be one or must match the size of the vector. 6890 // If a single value is specified in the initializer then it will be 6891 // replicated to all the components of the vector 6892 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6893 // The number of initializers must be one or must match the size of the 6894 // vector. If a single value is specified in the initializer then it will 6895 // be replicated to all the components of the vector 6896 if (numExprs == 1) { 6897 QualType ElemTy = VTy->getElementType(); 6898 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6899 if (Literal.isInvalid()) 6900 return ExprError(); 6901 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6902 PrepareScalarCast(Literal, ElemTy)); 6903 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6904 } 6905 else if (numExprs < numElems) { 6906 Diag(E->getExprLoc(), 6907 diag::err_incorrect_number_of_vector_initializers); 6908 return ExprError(); 6909 } 6910 else 6911 initExprs.append(exprs, exprs + numExprs); 6912 } 6913 else { 6914 // For OpenCL, when the number of initializers is a single value, 6915 // it will be replicated to all components of the vector. 6916 if (getLangOpts().OpenCL && 6917 VTy->getVectorKind() == VectorType::GenericVector && 6918 numExprs == 1) { 6919 QualType ElemTy = VTy->getElementType(); 6920 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6921 if (Literal.isInvalid()) 6922 return ExprError(); 6923 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6924 PrepareScalarCast(Literal, ElemTy)); 6925 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6926 } 6927 6928 initExprs.append(exprs, exprs + numExprs); 6929 } 6930 // FIXME: This means that pretty-printing the final AST will produce curly 6931 // braces instead of the original commas. 6932 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6933 initExprs, LiteralRParenLoc); 6934 initE->setType(Ty); 6935 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6936 } 6937 6938 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6939 /// the ParenListExpr into a sequence of comma binary operators. 6940 ExprResult 6941 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6942 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6943 if (!E) 6944 return OrigExpr; 6945 6946 ExprResult Result(E->getExpr(0)); 6947 6948 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6949 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6950 E->getExpr(i)); 6951 6952 if (Result.isInvalid()) return ExprError(); 6953 6954 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6955 } 6956 6957 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6958 SourceLocation R, 6959 MultiExprArg Val) { 6960 return ParenListExpr::Create(Context, L, Val, R); 6961 } 6962 6963 /// Emit a specialized diagnostic when one expression is a null pointer 6964 /// constant and the other is not a pointer. Returns true if a diagnostic is 6965 /// emitted. 6966 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6967 SourceLocation QuestionLoc) { 6968 Expr *NullExpr = LHSExpr; 6969 Expr *NonPointerExpr = RHSExpr; 6970 Expr::NullPointerConstantKind NullKind = 6971 NullExpr->isNullPointerConstant(Context, 6972 Expr::NPC_ValueDependentIsNotNull); 6973 6974 if (NullKind == Expr::NPCK_NotNull) { 6975 NullExpr = RHSExpr; 6976 NonPointerExpr = LHSExpr; 6977 NullKind = 6978 NullExpr->isNullPointerConstant(Context, 6979 Expr::NPC_ValueDependentIsNotNull); 6980 } 6981 6982 if (NullKind == Expr::NPCK_NotNull) 6983 return false; 6984 6985 if (NullKind == Expr::NPCK_ZeroExpression) 6986 return false; 6987 6988 if (NullKind == Expr::NPCK_ZeroLiteral) { 6989 // In this case, check to make sure that we got here from a "NULL" 6990 // string in the source code. 6991 NullExpr = NullExpr->IgnoreParenImpCasts(); 6992 SourceLocation loc = NullExpr->getExprLoc(); 6993 if (!findMacroSpelling(loc, "NULL")) 6994 return false; 6995 } 6996 6997 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6998 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6999 << NonPointerExpr->getType() << DiagType 7000 << NonPointerExpr->getSourceRange(); 7001 return true; 7002 } 7003 7004 /// Return false if the condition expression is valid, true otherwise. 7005 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7006 QualType CondTy = Cond->getType(); 7007 7008 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7009 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7010 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7011 << CondTy << Cond->getSourceRange(); 7012 return true; 7013 } 7014 7015 // C99 6.5.15p2 7016 if (CondTy->isScalarType()) return false; 7017 7018 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7019 << CondTy << Cond->getSourceRange(); 7020 return true; 7021 } 7022 7023 /// Handle when one or both operands are void type. 7024 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7025 ExprResult &RHS) { 7026 Expr *LHSExpr = LHS.get(); 7027 Expr *RHSExpr = RHS.get(); 7028 7029 if (!LHSExpr->getType()->isVoidType()) 7030 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7031 << RHSExpr->getSourceRange(); 7032 if (!RHSExpr->getType()->isVoidType()) 7033 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7034 << LHSExpr->getSourceRange(); 7035 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7036 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7037 return S.Context.VoidTy; 7038 } 7039 7040 /// Return false if the NullExpr can be promoted to PointerTy, 7041 /// true otherwise. 7042 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7043 QualType PointerTy) { 7044 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7045 !NullExpr.get()->isNullPointerConstant(S.Context, 7046 Expr::NPC_ValueDependentIsNull)) 7047 return true; 7048 7049 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7050 return false; 7051 } 7052 7053 /// Checks compatibility between two pointers and return the resulting 7054 /// type. 7055 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7056 ExprResult &RHS, 7057 SourceLocation Loc) { 7058 QualType LHSTy = LHS.get()->getType(); 7059 QualType RHSTy = RHS.get()->getType(); 7060 7061 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7062 // Two identical pointers types are always compatible. 7063 return LHSTy; 7064 } 7065 7066 QualType lhptee, rhptee; 7067 7068 // Get the pointee types. 7069 bool IsBlockPointer = false; 7070 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7071 lhptee = LHSBTy->getPointeeType(); 7072 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7073 IsBlockPointer = true; 7074 } else { 7075 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7076 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7077 } 7078 7079 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7080 // differently qualified versions of compatible types, the result type is 7081 // a pointer to an appropriately qualified version of the composite 7082 // type. 7083 7084 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7085 // clause doesn't make sense for our extensions. E.g. address space 2 should 7086 // be incompatible with address space 3: they may live on different devices or 7087 // anything. 7088 Qualifiers lhQual = lhptee.getQualifiers(); 7089 Qualifiers rhQual = rhptee.getQualifiers(); 7090 7091 LangAS ResultAddrSpace = LangAS::Default; 7092 LangAS LAddrSpace = lhQual.getAddressSpace(); 7093 LangAS RAddrSpace = rhQual.getAddressSpace(); 7094 7095 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7096 // spaces is disallowed. 7097 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7098 ResultAddrSpace = LAddrSpace; 7099 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7100 ResultAddrSpace = RAddrSpace; 7101 else { 7102 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7103 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7104 << RHS.get()->getSourceRange(); 7105 return QualType(); 7106 } 7107 7108 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7109 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7110 lhQual.removeCVRQualifiers(); 7111 rhQual.removeCVRQualifiers(); 7112 7113 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7114 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7115 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7116 // qual types are compatible iff 7117 // * corresponded types are compatible 7118 // * CVR qualifiers are equal 7119 // * address spaces are equal 7120 // Thus for conditional operator we merge CVR and address space unqualified 7121 // pointees and if there is a composite type we return a pointer to it with 7122 // merged qualifiers. 7123 LHSCastKind = 7124 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7125 RHSCastKind = 7126 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7127 lhQual.removeAddressSpace(); 7128 rhQual.removeAddressSpace(); 7129 7130 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7131 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7132 7133 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7134 7135 if (CompositeTy.isNull()) { 7136 // In this situation, we assume void* type. No especially good 7137 // reason, but this is what gcc does, and we do have to pick 7138 // to get a consistent AST. 7139 QualType incompatTy; 7140 incompatTy = S.Context.getPointerType( 7141 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7142 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7143 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7144 7145 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7146 // for casts between types with incompatible address space qualifiers. 7147 // For the following code the compiler produces casts between global and 7148 // local address spaces of the corresponded innermost pointees: 7149 // local int *global *a; 7150 // global int *global *b; 7151 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7152 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7153 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7154 << RHS.get()->getSourceRange(); 7155 7156 return incompatTy; 7157 } 7158 7159 // The pointer types are compatible. 7160 // In case of OpenCL ResultTy should have the address space qualifier 7161 // which is a superset of address spaces of both the 2nd and the 3rd 7162 // operands of the conditional operator. 7163 QualType ResultTy = [&, ResultAddrSpace]() { 7164 if (S.getLangOpts().OpenCL) { 7165 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7166 CompositeQuals.setAddressSpace(ResultAddrSpace); 7167 return S.Context 7168 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7169 .withCVRQualifiers(MergedCVRQual); 7170 } 7171 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7172 }(); 7173 if (IsBlockPointer) 7174 ResultTy = S.Context.getBlockPointerType(ResultTy); 7175 else 7176 ResultTy = S.Context.getPointerType(ResultTy); 7177 7178 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7179 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7180 return ResultTy; 7181 } 7182 7183 /// Return the resulting type when the operands are both block pointers. 7184 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7185 ExprResult &LHS, 7186 ExprResult &RHS, 7187 SourceLocation Loc) { 7188 QualType LHSTy = LHS.get()->getType(); 7189 QualType RHSTy = RHS.get()->getType(); 7190 7191 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7192 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7193 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7194 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7195 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7196 return destType; 7197 } 7198 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7199 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7200 << RHS.get()->getSourceRange(); 7201 return QualType(); 7202 } 7203 7204 // We have 2 block pointer types. 7205 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7206 } 7207 7208 /// Return the resulting type when the operands are both pointers. 7209 static QualType 7210 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7211 ExprResult &RHS, 7212 SourceLocation Loc) { 7213 // get the pointer types 7214 QualType LHSTy = LHS.get()->getType(); 7215 QualType RHSTy = RHS.get()->getType(); 7216 7217 // get the "pointed to" types 7218 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7219 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7220 7221 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7222 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7223 // Figure out necessary qualifiers (C99 6.5.15p6) 7224 QualType destPointee 7225 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7226 QualType destType = S.Context.getPointerType(destPointee); 7227 // Add qualifiers if necessary. 7228 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7229 // Promote to void*. 7230 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7231 return destType; 7232 } 7233 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7234 QualType destPointee 7235 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7236 QualType destType = S.Context.getPointerType(destPointee); 7237 // Add qualifiers if necessary. 7238 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7239 // Promote to void*. 7240 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7241 return destType; 7242 } 7243 7244 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7245 } 7246 7247 /// Return false if the first expression is not an integer and the second 7248 /// expression is not a pointer, true otherwise. 7249 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7250 Expr* PointerExpr, SourceLocation Loc, 7251 bool IsIntFirstExpr) { 7252 if (!PointerExpr->getType()->isPointerType() || 7253 !Int.get()->getType()->isIntegerType()) 7254 return false; 7255 7256 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7257 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7258 7259 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7260 << Expr1->getType() << Expr2->getType() 7261 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7262 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7263 CK_IntegralToPointer); 7264 return true; 7265 } 7266 7267 /// Simple conversion between integer and floating point types. 7268 /// 7269 /// Used when handling the OpenCL conditional operator where the 7270 /// condition is a vector while the other operands are scalar. 7271 /// 7272 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7273 /// types are either integer or floating type. Between the two 7274 /// operands, the type with the higher rank is defined as the "result 7275 /// type". The other operand needs to be promoted to the same type. No 7276 /// other type promotion is allowed. We cannot use 7277 /// UsualArithmeticConversions() for this purpose, since it always 7278 /// promotes promotable types. 7279 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7280 ExprResult &RHS, 7281 SourceLocation QuestionLoc) { 7282 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7283 if (LHS.isInvalid()) 7284 return QualType(); 7285 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7286 if (RHS.isInvalid()) 7287 return QualType(); 7288 7289 // For conversion purposes, we ignore any qualifiers. 7290 // For example, "const float" and "float" are equivalent. 7291 QualType LHSType = 7292 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7293 QualType RHSType = 7294 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7295 7296 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7297 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7298 << LHSType << LHS.get()->getSourceRange(); 7299 return QualType(); 7300 } 7301 7302 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7303 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7304 << RHSType << RHS.get()->getSourceRange(); 7305 return QualType(); 7306 } 7307 7308 // If both types are identical, no conversion is needed. 7309 if (LHSType == RHSType) 7310 return LHSType; 7311 7312 // Now handle "real" floating types (i.e. float, double, long double). 7313 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7314 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7315 /*IsCompAssign = */ false); 7316 7317 // Finally, we have two differing integer types. 7318 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7319 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7320 } 7321 7322 /// Convert scalar operands to a vector that matches the 7323 /// condition in length. 7324 /// 7325 /// Used when handling the OpenCL conditional operator where the 7326 /// condition is a vector while the other operands are scalar. 7327 /// 7328 /// We first compute the "result type" for the scalar operands 7329 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7330 /// into a vector of that type where the length matches the condition 7331 /// vector type. s6.11.6 requires that the element types of the result 7332 /// and the condition must have the same number of bits. 7333 static QualType 7334 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7335 QualType CondTy, SourceLocation QuestionLoc) { 7336 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7337 if (ResTy.isNull()) return QualType(); 7338 7339 const VectorType *CV = CondTy->getAs<VectorType>(); 7340 assert(CV); 7341 7342 // Determine the vector result type 7343 unsigned NumElements = CV->getNumElements(); 7344 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7345 7346 // Ensure that all types have the same number of bits 7347 if (S.Context.getTypeSize(CV->getElementType()) 7348 != S.Context.getTypeSize(ResTy)) { 7349 // Since VectorTy is created internally, it does not pretty print 7350 // with an OpenCL name. Instead, we just print a description. 7351 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7352 SmallString<64> Str; 7353 llvm::raw_svector_ostream OS(Str); 7354 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7355 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7356 << CondTy << OS.str(); 7357 return QualType(); 7358 } 7359 7360 // Convert operands to the vector result type 7361 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7362 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7363 7364 return VectorTy; 7365 } 7366 7367 /// Return false if this is a valid OpenCL condition vector 7368 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7369 SourceLocation QuestionLoc) { 7370 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7371 // integral type. 7372 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7373 assert(CondTy); 7374 QualType EleTy = CondTy->getElementType(); 7375 if (EleTy->isIntegerType()) return false; 7376 7377 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7378 << Cond->getType() << Cond->getSourceRange(); 7379 return true; 7380 } 7381 7382 /// Return false if the vector condition type and the vector 7383 /// result type are compatible. 7384 /// 7385 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7386 /// number of elements, and their element types have the same number 7387 /// of bits. 7388 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7389 SourceLocation QuestionLoc) { 7390 const VectorType *CV = CondTy->getAs<VectorType>(); 7391 const VectorType *RV = VecResTy->getAs<VectorType>(); 7392 assert(CV && RV); 7393 7394 if (CV->getNumElements() != RV->getNumElements()) { 7395 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7396 << CondTy << VecResTy; 7397 return true; 7398 } 7399 7400 QualType CVE = CV->getElementType(); 7401 QualType RVE = RV->getElementType(); 7402 7403 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7404 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7405 << CondTy << VecResTy; 7406 return true; 7407 } 7408 7409 return false; 7410 } 7411 7412 /// Return the resulting type for the conditional operator in 7413 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7414 /// s6.3.i) when the condition is a vector type. 7415 static QualType 7416 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7417 ExprResult &LHS, ExprResult &RHS, 7418 SourceLocation QuestionLoc) { 7419 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7420 if (Cond.isInvalid()) 7421 return QualType(); 7422 QualType CondTy = Cond.get()->getType(); 7423 7424 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7425 return QualType(); 7426 7427 // If either operand is a vector then find the vector type of the 7428 // result as specified in OpenCL v1.1 s6.3.i. 7429 if (LHS.get()->getType()->isVectorType() || 7430 RHS.get()->getType()->isVectorType()) { 7431 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7432 /*isCompAssign*/false, 7433 /*AllowBothBool*/true, 7434 /*AllowBoolConversions*/false); 7435 if (VecResTy.isNull()) return QualType(); 7436 // The result type must match the condition type as specified in 7437 // OpenCL v1.1 s6.11.6. 7438 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7439 return QualType(); 7440 return VecResTy; 7441 } 7442 7443 // Both operands are scalar. 7444 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7445 } 7446 7447 /// Return true if the Expr is block type 7448 static bool checkBlockType(Sema &S, const Expr *E) { 7449 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7450 QualType Ty = CE->getCallee()->getType(); 7451 if (Ty->isBlockPointerType()) { 7452 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7453 return true; 7454 } 7455 } 7456 return false; 7457 } 7458 7459 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7460 /// In that case, LHS = cond. 7461 /// C99 6.5.15 7462 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7463 ExprResult &RHS, ExprValueKind &VK, 7464 ExprObjectKind &OK, 7465 SourceLocation QuestionLoc) { 7466 7467 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7468 if (!LHSResult.isUsable()) return QualType(); 7469 LHS = LHSResult; 7470 7471 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7472 if (!RHSResult.isUsable()) return QualType(); 7473 RHS = RHSResult; 7474 7475 // C++ is sufficiently different to merit its own checker. 7476 if (getLangOpts().CPlusPlus) 7477 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7478 7479 VK = VK_RValue; 7480 OK = OK_Ordinary; 7481 7482 // The OpenCL operator with a vector condition is sufficiently 7483 // different to merit its own checker. 7484 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7485 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7486 7487 // First, check the condition. 7488 Cond = UsualUnaryConversions(Cond.get()); 7489 if (Cond.isInvalid()) 7490 return QualType(); 7491 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7492 return QualType(); 7493 7494 // Now check the two expressions. 7495 if (LHS.get()->getType()->isVectorType() || 7496 RHS.get()->getType()->isVectorType()) 7497 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7498 /*AllowBothBool*/true, 7499 /*AllowBoolConversions*/false); 7500 7501 QualType ResTy = 7502 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7503 if (LHS.isInvalid() || RHS.isInvalid()) 7504 return QualType(); 7505 7506 QualType LHSTy = LHS.get()->getType(); 7507 QualType RHSTy = RHS.get()->getType(); 7508 7509 // Diagnose attempts to convert between __float128 and long double where 7510 // such conversions currently can't be handled. 7511 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7512 Diag(QuestionLoc, 7513 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7514 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7515 return QualType(); 7516 } 7517 7518 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7519 // selection operator (?:). 7520 if (getLangOpts().OpenCL && 7521 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7522 return QualType(); 7523 } 7524 7525 // If both operands have arithmetic type, do the usual arithmetic conversions 7526 // to find a common type: C99 6.5.15p3,5. 7527 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7528 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7529 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7530 7531 return ResTy; 7532 } 7533 7534 // If both operands are the same structure or union type, the result is that 7535 // type. 7536 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7537 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7538 if (LHSRT->getDecl() == RHSRT->getDecl()) 7539 // "If both the operands have structure or union type, the result has 7540 // that type." This implies that CV qualifiers are dropped. 7541 return LHSTy.getUnqualifiedType(); 7542 // FIXME: Type of conditional expression must be complete in C mode. 7543 } 7544 7545 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7546 // The following || allows only one side to be void (a GCC-ism). 7547 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7548 return checkConditionalVoidType(*this, LHS, RHS); 7549 } 7550 7551 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7552 // the type of the other operand." 7553 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7554 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7555 7556 // All objective-c pointer type analysis is done here. 7557 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7558 QuestionLoc); 7559 if (LHS.isInvalid() || RHS.isInvalid()) 7560 return QualType(); 7561 if (!compositeType.isNull()) 7562 return compositeType; 7563 7564 7565 // Handle block pointer types. 7566 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7567 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7568 QuestionLoc); 7569 7570 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7571 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7572 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7573 QuestionLoc); 7574 7575 // GCC compatibility: soften pointer/integer mismatch. Note that 7576 // null pointers have been filtered out by this point. 7577 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7578 /*IsIntFirstExpr=*/true)) 7579 return RHSTy; 7580 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7581 /*IsIntFirstExpr=*/false)) 7582 return LHSTy; 7583 7584 // Emit a better diagnostic if one of the expressions is a null pointer 7585 // constant and the other is not a pointer type. In this case, the user most 7586 // likely forgot to take the address of the other expression. 7587 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7588 return QualType(); 7589 7590 // Otherwise, the operands are not compatible. 7591 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7592 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7593 << RHS.get()->getSourceRange(); 7594 return QualType(); 7595 } 7596 7597 /// FindCompositeObjCPointerType - Helper method to find composite type of 7598 /// two objective-c pointer types of the two input expressions. 7599 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7600 SourceLocation QuestionLoc) { 7601 QualType LHSTy = LHS.get()->getType(); 7602 QualType RHSTy = RHS.get()->getType(); 7603 7604 // Handle things like Class and struct objc_class*. Here we case the result 7605 // to the pseudo-builtin, because that will be implicitly cast back to the 7606 // redefinition type if an attempt is made to access its fields. 7607 if (LHSTy->isObjCClassType() && 7608 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7609 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7610 return LHSTy; 7611 } 7612 if (RHSTy->isObjCClassType() && 7613 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7614 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7615 return RHSTy; 7616 } 7617 // And the same for struct objc_object* / id 7618 if (LHSTy->isObjCIdType() && 7619 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7620 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7621 return LHSTy; 7622 } 7623 if (RHSTy->isObjCIdType() && 7624 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7625 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7626 return RHSTy; 7627 } 7628 // And the same for struct objc_selector* / SEL 7629 if (Context.isObjCSelType(LHSTy) && 7630 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7631 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7632 return LHSTy; 7633 } 7634 if (Context.isObjCSelType(RHSTy) && 7635 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7636 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7637 return RHSTy; 7638 } 7639 // Check constraints for Objective-C object pointers types. 7640 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7641 7642 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7643 // Two identical object pointer types are always compatible. 7644 return LHSTy; 7645 } 7646 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7647 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7648 QualType compositeType = LHSTy; 7649 7650 // If both operands are interfaces and either operand can be 7651 // assigned to the other, use that type as the composite 7652 // type. This allows 7653 // xxx ? (A*) a : (B*) b 7654 // where B is a subclass of A. 7655 // 7656 // Additionally, as for assignment, if either type is 'id' 7657 // allow silent coercion. Finally, if the types are 7658 // incompatible then make sure to use 'id' as the composite 7659 // type so the result is acceptable for sending messages to. 7660 7661 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7662 // It could return the composite type. 7663 if (!(compositeType = 7664 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7665 // Nothing more to do. 7666 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7667 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7668 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7669 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7670 } else if ((LHSOPT->isObjCQualifiedIdType() || 7671 RHSOPT->isObjCQualifiedIdType()) && 7672 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7673 true)) { 7674 // Need to handle "id<xx>" explicitly. 7675 // GCC allows qualified id and any Objective-C type to devolve to 7676 // id. Currently localizing to here until clear this should be 7677 // part of ObjCQualifiedIdTypesAreCompatible. 7678 compositeType = Context.getObjCIdType(); 7679 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7680 compositeType = Context.getObjCIdType(); 7681 } else { 7682 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7683 << LHSTy << RHSTy 7684 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7685 QualType incompatTy = Context.getObjCIdType(); 7686 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7687 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7688 return incompatTy; 7689 } 7690 // The object pointer types are compatible. 7691 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7692 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7693 return compositeType; 7694 } 7695 // Check Objective-C object pointer types and 'void *' 7696 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7697 if (getLangOpts().ObjCAutoRefCount) { 7698 // ARC forbids the implicit conversion of object pointers to 'void *', 7699 // so these types are not compatible. 7700 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7701 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7702 LHS = RHS = true; 7703 return QualType(); 7704 } 7705 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7706 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7707 QualType destPointee 7708 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7709 QualType destType = Context.getPointerType(destPointee); 7710 // Add qualifiers if necessary. 7711 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7712 // Promote to void*. 7713 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7714 return destType; 7715 } 7716 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7717 if (getLangOpts().ObjCAutoRefCount) { 7718 // ARC forbids the implicit conversion of object pointers to 'void *', 7719 // so these types are not compatible. 7720 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7721 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7722 LHS = RHS = true; 7723 return QualType(); 7724 } 7725 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7726 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7727 QualType destPointee 7728 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7729 QualType destType = Context.getPointerType(destPointee); 7730 // Add qualifiers if necessary. 7731 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7732 // Promote to void*. 7733 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7734 return destType; 7735 } 7736 return QualType(); 7737 } 7738 7739 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7740 /// ParenRange in parentheses. 7741 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7742 const PartialDiagnostic &Note, 7743 SourceRange ParenRange) { 7744 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7745 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7746 EndLoc.isValid()) { 7747 Self.Diag(Loc, Note) 7748 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7749 << FixItHint::CreateInsertion(EndLoc, ")"); 7750 } else { 7751 // We can't display the parentheses, so just show the bare note. 7752 Self.Diag(Loc, Note) << ParenRange; 7753 } 7754 } 7755 7756 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7757 return BinaryOperator::isAdditiveOp(Opc) || 7758 BinaryOperator::isMultiplicativeOp(Opc) || 7759 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7760 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7761 // not any of the logical operators. Bitwise-xor is commonly used as a 7762 // logical-xor because there is no logical-xor operator. The logical 7763 // operators, including uses of xor, have a high false positive rate for 7764 // precedence warnings. 7765 } 7766 7767 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7768 /// expression, either using a built-in or overloaded operator, 7769 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7770 /// expression. 7771 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7772 Expr **RHSExprs) { 7773 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7774 E = E->IgnoreImpCasts(); 7775 E = E->IgnoreConversionOperator(); 7776 E = E->IgnoreImpCasts(); 7777 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7778 E = MTE->getSubExpr(); 7779 E = E->IgnoreImpCasts(); 7780 } 7781 7782 // Built-in binary operator. 7783 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7784 if (IsArithmeticOp(OP->getOpcode())) { 7785 *Opcode = OP->getOpcode(); 7786 *RHSExprs = OP->getRHS(); 7787 return true; 7788 } 7789 } 7790 7791 // Overloaded operator. 7792 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7793 if (Call->getNumArgs() != 2) 7794 return false; 7795 7796 // Make sure this is really a binary operator that is safe to pass into 7797 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7798 OverloadedOperatorKind OO = Call->getOperator(); 7799 if (OO < OO_Plus || OO > OO_Arrow || 7800 OO == OO_PlusPlus || OO == OO_MinusMinus) 7801 return false; 7802 7803 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7804 if (IsArithmeticOp(OpKind)) { 7805 *Opcode = OpKind; 7806 *RHSExprs = Call->getArg(1); 7807 return true; 7808 } 7809 } 7810 7811 return false; 7812 } 7813 7814 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7815 /// or is a logical expression such as (x==y) which has int type, but is 7816 /// commonly interpreted as boolean. 7817 static bool ExprLooksBoolean(Expr *E) { 7818 E = E->IgnoreParenImpCasts(); 7819 7820 if (E->getType()->isBooleanType()) 7821 return true; 7822 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7823 return OP->isComparisonOp() || OP->isLogicalOp(); 7824 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7825 return OP->getOpcode() == UO_LNot; 7826 if (E->getType()->isPointerType()) 7827 return true; 7828 // FIXME: What about overloaded operator calls returning "unspecified boolean 7829 // type"s (commonly pointer-to-members)? 7830 7831 return false; 7832 } 7833 7834 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7835 /// and binary operator are mixed in a way that suggests the programmer assumed 7836 /// the conditional operator has higher precedence, for example: 7837 /// "int x = a + someBinaryCondition ? 1 : 2". 7838 static void DiagnoseConditionalPrecedence(Sema &Self, 7839 SourceLocation OpLoc, 7840 Expr *Condition, 7841 Expr *LHSExpr, 7842 Expr *RHSExpr) { 7843 BinaryOperatorKind CondOpcode; 7844 Expr *CondRHS; 7845 7846 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7847 return; 7848 if (!ExprLooksBoolean(CondRHS)) 7849 return; 7850 7851 // The condition is an arithmetic binary expression, with a right- 7852 // hand side that looks boolean, so warn. 7853 7854 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7855 ? diag::warn_precedence_bitwise_conditional 7856 : diag::warn_precedence_conditional; 7857 7858 Self.Diag(OpLoc, DiagID) 7859 << Condition->getSourceRange() 7860 << BinaryOperator::getOpcodeStr(CondOpcode); 7861 7862 SuggestParentheses( 7863 Self, OpLoc, 7864 Self.PDiag(diag::note_precedence_silence) 7865 << BinaryOperator::getOpcodeStr(CondOpcode), 7866 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7867 7868 SuggestParentheses(Self, OpLoc, 7869 Self.PDiag(diag::note_precedence_conditional_first), 7870 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7871 } 7872 7873 /// Compute the nullability of a conditional expression. 7874 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7875 QualType LHSTy, QualType RHSTy, 7876 ASTContext &Ctx) { 7877 if (!ResTy->isAnyPointerType()) 7878 return ResTy; 7879 7880 auto GetNullability = [&Ctx](QualType Ty) { 7881 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7882 if (Kind) 7883 return *Kind; 7884 return NullabilityKind::Unspecified; 7885 }; 7886 7887 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7888 NullabilityKind MergedKind; 7889 7890 // Compute nullability of a binary conditional expression. 7891 if (IsBin) { 7892 if (LHSKind == NullabilityKind::NonNull) 7893 MergedKind = NullabilityKind::NonNull; 7894 else 7895 MergedKind = RHSKind; 7896 // Compute nullability of a normal conditional expression. 7897 } else { 7898 if (LHSKind == NullabilityKind::Nullable || 7899 RHSKind == NullabilityKind::Nullable) 7900 MergedKind = NullabilityKind::Nullable; 7901 else if (LHSKind == NullabilityKind::NonNull) 7902 MergedKind = RHSKind; 7903 else if (RHSKind == NullabilityKind::NonNull) 7904 MergedKind = LHSKind; 7905 else 7906 MergedKind = NullabilityKind::Unspecified; 7907 } 7908 7909 // Return if ResTy already has the correct nullability. 7910 if (GetNullability(ResTy) == MergedKind) 7911 return ResTy; 7912 7913 // Strip all nullability from ResTy. 7914 while (ResTy->getNullability(Ctx)) 7915 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7916 7917 // Create a new AttributedType with the new nullability kind. 7918 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7919 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7920 } 7921 7922 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7923 /// in the case of a the GNU conditional expr extension. 7924 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7925 SourceLocation ColonLoc, 7926 Expr *CondExpr, Expr *LHSExpr, 7927 Expr *RHSExpr) { 7928 if (!getLangOpts().CPlusPlus) { 7929 // C cannot handle TypoExpr nodes in the condition because it 7930 // doesn't handle dependent types properly, so make sure any TypoExprs have 7931 // been dealt with before checking the operands. 7932 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7933 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7934 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7935 7936 if (!CondResult.isUsable()) 7937 return ExprError(); 7938 7939 if (LHSExpr) { 7940 if (!LHSResult.isUsable()) 7941 return ExprError(); 7942 } 7943 7944 if (!RHSResult.isUsable()) 7945 return ExprError(); 7946 7947 CondExpr = CondResult.get(); 7948 LHSExpr = LHSResult.get(); 7949 RHSExpr = RHSResult.get(); 7950 } 7951 7952 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7953 // was the condition. 7954 OpaqueValueExpr *opaqueValue = nullptr; 7955 Expr *commonExpr = nullptr; 7956 if (!LHSExpr) { 7957 commonExpr = CondExpr; 7958 // Lower out placeholder types first. This is important so that we don't 7959 // try to capture a placeholder. This happens in few cases in C++; such 7960 // as Objective-C++'s dictionary subscripting syntax. 7961 if (commonExpr->hasPlaceholderType()) { 7962 ExprResult result = CheckPlaceholderExpr(commonExpr); 7963 if (!result.isUsable()) return ExprError(); 7964 commonExpr = result.get(); 7965 } 7966 // We usually want to apply unary conversions *before* saving, except 7967 // in the special case of a C++ l-value conditional. 7968 if (!(getLangOpts().CPlusPlus 7969 && !commonExpr->isTypeDependent() 7970 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7971 && commonExpr->isGLValue() 7972 && commonExpr->isOrdinaryOrBitFieldObject() 7973 && RHSExpr->isOrdinaryOrBitFieldObject() 7974 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7975 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7976 if (commonRes.isInvalid()) 7977 return ExprError(); 7978 commonExpr = commonRes.get(); 7979 } 7980 7981 // If the common expression is a class or array prvalue, materialize it 7982 // so that we can safely refer to it multiple times. 7983 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7984 commonExpr->getType()->isArrayType())) { 7985 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7986 if (MatExpr.isInvalid()) 7987 return ExprError(); 7988 commonExpr = MatExpr.get(); 7989 } 7990 7991 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7992 commonExpr->getType(), 7993 commonExpr->getValueKind(), 7994 commonExpr->getObjectKind(), 7995 commonExpr); 7996 LHSExpr = CondExpr = opaqueValue; 7997 } 7998 7999 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8000 ExprValueKind VK = VK_RValue; 8001 ExprObjectKind OK = OK_Ordinary; 8002 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8003 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8004 VK, OK, QuestionLoc); 8005 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8006 RHS.isInvalid()) 8007 return ExprError(); 8008 8009 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8010 RHS.get()); 8011 8012 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8013 8014 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8015 Context); 8016 8017 if (!commonExpr) 8018 return new (Context) 8019 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8020 RHS.get(), result, VK, OK); 8021 8022 return new (Context) BinaryConditionalOperator( 8023 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8024 ColonLoc, result, VK, OK); 8025 } 8026 8027 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8028 // being closely modeled after the C99 spec:-). The odd characteristic of this 8029 // routine is it effectively iqnores the qualifiers on the top level pointee. 8030 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8031 // FIXME: add a couple examples in this comment. 8032 static Sema::AssignConvertType 8033 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8034 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8035 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8036 8037 // get the "pointed to" type (ignoring qualifiers at the top level) 8038 const Type *lhptee, *rhptee; 8039 Qualifiers lhq, rhq; 8040 std::tie(lhptee, lhq) = 8041 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8042 std::tie(rhptee, rhq) = 8043 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8044 8045 Sema::AssignConvertType ConvTy = Sema::Compatible; 8046 8047 // C99 6.5.16.1p1: This following citation is common to constraints 8048 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8049 // qualifiers of the type *pointed to* by the right; 8050 8051 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8052 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8053 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8054 // Ignore lifetime for further calculation. 8055 lhq.removeObjCLifetime(); 8056 rhq.removeObjCLifetime(); 8057 } 8058 8059 if (!lhq.compatiblyIncludes(rhq)) { 8060 // Treat address-space mismatches as fatal. 8061 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8062 return Sema::IncompatiblePointerDiscardsQualifiers; 8063 8064 // It's okay to add or remove GC or lifetime qualifiers when converting to 8065 // and from void*. 8066 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8067 .compatiblyIncludes( 8068 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8069 && (lhptee->isVoidType() || rhptee->isVoidType())) 8070 ; // keep old 8071 8072 // Treat lifetime mismatches as fatal. 8073 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8074 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8075 8076 // For GCC/MS compatibility, other qualifier mismatches are treated 8077 // as still compatible in C. 8078 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8079 } 8080 8081 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8082 // incomplete type and the other is a pointer to a qualified or unqualified 8083 // version of void... 8084 if (lhptee->isVoidType()) { 8085 if (rhptee->isIncompleteOrObjectType()) 8086 return ConvTy; 8087 8088 // As an extension, we allow cast to/from void* to function pointer. 8089 assert(rhptee->isFunctionType()); 8090 return Sema::FunctionVoidPointer; 8091 } 8092 8093 if (rhptee->isVoidType()) { 8094 if (lhptee->isIncompleteOrObjectType()) 8095 return ConvTy; 8096 8097 // As an extension, we allow cast to/from void* to function pointer. 8098 assert(lhptee->isFunctionType()); 8099 return Sema::FunctionVoidPointer; 8100 } 8101 8102 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8103 // unqualified versions of compatible types, ... 8104 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8105 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8106 // Check if the pointee types are compatible ignoring the sign. 8107 // We explicitly check for char so that we catch "char" vs 8108 // "unsigned char" on systems where "char" is unsigned. 8109 if (lhptee->isCharType()) 8110 ltrans = S.Context.UnsignedCharTy; 8111 else if (lhptee->hasSignedIntegerRepresentation()) 8112 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8113 8114 if (rhptee->isCharType()) 8115 rtrans = S.Context.UnsignedCharTy; 8116 else if (rhptee->hasSignedIntegerRepresentation()) 8117 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8118 8119 if (ltrans == rtrans) { 8120 // Types are compatible ignoring the sign. Qualifier incompatibility 8121 // takes priority over sign incompatibility because the sign 8122 // warning can be disabled. 8123 if (ConvTy != Sema::Compatible) 8124 return ConvTy; 8125 8126 return Sema::IncompatiblePointerSign; 8127 } 8128 8129 // If we are a multi-level pointer, it's possible that our issue is simply 8130 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8131 // the eventual target type is the same and the pointers have the same 8132 // level of indirection, this must be the issue. 8133 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8134 do { 8135 std::tie(lhptee, lhq) = 8136 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8137 std::tie(rhptee, rhq) = 8138 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8139 8140 // Inconsistent address spaces at this point is invalid, even if the 8141 // address spaces would be compatible. 8142 // FIXME: This doesn't catch address space mismatches for pointers of 8143 // different nesting levels, like: 8144 // __local int *** a; 8145 // int ** b = a; 8146 // It's not clear how to actually determine when such pointers are 8147 // invalidly incompatible. 8148 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8149 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8150 8151 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8152 8153 if (lhptee == rhptee) 8154 return Sema::IncompatibleNestedPointerQualifiers; 8155 } 8156 8157 // General pointer incompatibility takes priority over qualifiers. 8158 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8159 return Sema::IncompatibleFunctionPointer; 8160 return Sema::IncompatiblePointer; 8161 } 8162 if (!S.getLangOpts().CPlusPlus && 8163 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8164 return Sema::IncompatibleFunctionPointer; 8165 return ConvTy; 8166 } 8167 8168 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8169 /// block pointer types are compatible or whether a block and normal pointer 8170 /// are compatible. It is more restrict than comparing two function pointer 8171 // types. 8172 static Sema::AssignConvertType 8173 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8174 QualType RHSType) { 8175 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8176 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8177 8178 QualType lhptee, rhptee; 8179 8180 // get the "pointed to" type (ignoring qualifiers at the top level) 8181 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8182 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8183 8184 // In C++, the types have to match exactly. 8185 if (S.getLangOpts().CPlusPlus) 8186 return Sema::IncompatibleBlockPointer; 8187 8188 Sema::AssignConvertType ConvTy = Sema::Compatible; 8189 8190 // For blocks we enforce that qualifiers are identical. 8191 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8192 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8193 if (S.getLangOpts().OpenCL) { 8194 LQuals.removeAddressSpace(); 8195 RQuals.removeAddressSpace(); 8196 } 8197 if (LQuals != RQuals) 8198 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8199 8200 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8201 // assignment. 8202 // The current behavior is similar to C++ lambdas. A block might be 8203 // assigned to a variable iff its return type and parameters are compatible 8204 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8205 // an assignment. Presumably it should behave in way that a function pointer 8206 // assignment does in C, so for each parameter and return type: 8207 // * CVR and address space of LHS should be a superset of CVR and address 8208 // space of RHS. 8209 // * unqualified types should be compatible. 8210 if (S.getLangOpts().OpenCL) { 8211 if (!S.Context.typesAreBlockPointerCompatible( 8212 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8213 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8214 return Sema::IncompatibleBlockPointer; 8215 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8216 return Sema::IncompatibleBlockPointer; 8217 8218 return ConvTy; 8219 } 8220 8221 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8222 /// for assignment compatibility. 8223 static Sema::AssignConvertType 8224 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8225 QualType RHSType) { 8226 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8227 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8228 8229 if (LHSType->isObjCBuiltinType()) { 8230 // Class is not compatible with ObjC object pointers. 8231 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8232 !RHSType->isObjCQualifiedClassType()) 8233 return Sema::IncompatiblePointer; 8234 return Sema::Compatible; 8235 } 8236 if (RHSType->isObjCBuiltinType()) { 8237 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8238 !LHSType->isObjCQualifiedClassType()) 8239 return Sema::IncompatiblePointer; 8240 return Sema::Compatible; 8241 } 8242 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8243 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8244 8245 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8246 // make an exception for id<P> 8247 !LHSType->isObjCQualifiedIdType()) 8248 return Sema::CompatiblePointerDiscardsQualifiers; 8249 8250 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8251 return Sema::Compatible; 8252 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8253 return Sema::IncompatibleObjCQualifiedId; 8254 return Sema::IncompatiblePointer; 8255 } 8256 8257 Sema::AssignConvertType 8258 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8259 QualType LHSType, QualType RHSType) { 8260 // Fake up an opaque expression. We don't actually care about what 8261 // cast operations are required, so if CheckAssignmentConstraints 8262 // adds casts to this they'll be wasted, but fortunately that doesn't 8263 // usually happen on valid code. 8264 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8265 ExprResult RHSPtr = &RHSExpr; 8266 CastKind K; 8267 8268 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8269 } 8270 8271 /// This helper function returns true if QT is a vector type that has element 8272 /// type ElementType. 8273 static bool isVector(QualType QT, QualType ElementType) { 8274 if (const VectorType *VT = QT->getAs<VectorType>()) 8275 return VT->getElementType().getCanonicalType() == ElementType; 8276 return false; 8277 } 8278 8279 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8280 /// has code to accommodate several GCC extensions when type checking 8281 /// pointers. Here are some objectionable examples that GCC considers warnings: 8282 /// 8283 /// int a, *pint; 8284 /// short *pshort; 8285 /// struct foo *pfoo; 8286 /// 8287 /// pint = pshort; // warning: assignment from incompatible pointer type 8288 /// a = pint; // warning: assignment makes integer from pointer without a cast 8289 /// pint = a; // warning: assignment makes pointer from integer without a cast 8290 /// pint = pfoo; // warning: assignment from incompatible pointer type 8291 /// 8292 /// As a result, the code for dealing with pointers is more complex than the 8293 /// C99 spec dictates. 8294 /// 8295 /// Sets 'Kind' for any result kind except Incompatible. 8296 Sema::AssignConvertType 8297 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8298 CastKind &Kind, bool ConvertRHS) { 8299 QualType RHSType = RHS.get()->getType(); 8300 QualType OrigLHSType = LHSType; 8301 8302 // Get canonical types. We're not formatting these types, just comparing 8303 // them. 8304 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8305 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8306 8307 // Common case: no conversion required. 8308 if (LHSType == RHSType) { 8309 Kind = CK_NoOp; 8310 return Compatible; 8311 } 8312 8313 // If we have an atomic type, try a non-atomic assignment, then just add an 8314 // atomic qualification step. 8315 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8316 Sema::AssignConvertType result = 8317 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8318 if (result != Compatible) 8319 return result; 8320 if (Kind != CK_NoOp && ConvertRHS) 8321 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8322 Kind = CK_NonAtomicToAtomic; 8323 return Compatible; 8324 } 8325 8326 // If the left-hand side is a reference type, then we are in a 8327 // (rare!) case where we've allowed the use of references in C, 8328 // e.g., as a parameter type in a built-in function. In this case, 8329 // just make sure that the type referenced is compatible with the 8330 // right-hand side type. The caller is responsible for adjusting 8331 // LHSType so that the resulting expression does not have reference 8332 // type. 8333 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8334 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8335 Kind = CK_LValueBitCast; 8336 return Compatible; 8337 } 8338 return Incompatible; 8339 } 8340 8341 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8342 // to the same ExtVector type. 8343 if (LHSType->isExtVectorType()) { 8344 if (RHSType->isExtVectorType()) 8345 return Incompatible; 8346 if (RHSType->isArithmeticType()) { 8347 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8348 if (ConvertRHS) 8349 RHS = prepareVectorSplat(LHSType, RHS.get()); 8350 Kind = CK_VectorSplat; 8351 return Compatible; 8352 } 8353 } 8354 8355 // Conversions to or from vector type. 8356 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8357 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8358 // Allow assignments of an AltiVec vector type to an equivalent GCC 8359 // vector type and vice versa 8360 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8361 Kind = CK_BitCast; 8362 return Compatible; 8363 } 8364 8365 // If we are allowing lax vector conversions, and LHS and RHS are both 8366 // vectors, the total size only needs to be the same. This is a bitcast; 8367 // no bits are changed but the result type is different. 8368 if (isLaxVectorConversion(RHSType, LHSType)) { 8369 Kind = CK_BitCast; 8370 return IncompatibleVectors; 8371 } 8372 } 8373 8374 // When the RHS comes from another lax conversion (e.g. binops between 8375 // scalars and vectors) the result is canonicalized as a vector. When the 8376 // LHS is also a vector, the lax is allowed by the condition above. Handle 8377 // the case where LHS is a scalar. 8378 if (LHSType->isScalarType()) { 8379 const VectorType *VecType = RHSType->getAs<VectorType>(); 8380 if (VecType && VecType->getNumElements() == 1 && 8381 isLaxVectorConversion(RHSType, LHSType)) { 8382 ExprResult *VecExpr = &RHS; 8383 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8384 Kind = CK_BitCast; 8385 return Compatible; 8386 } 8387 } 8388 8389 return Incompatible; 8390 } 8391 8392 // Diagnose attempts to convert between __float128 and long double where 8393 // such conversions currently can't be handled. 8394 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8395 return Incompatible; 8396 8397 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8398 // discards the imaginary part. 8399 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8400 !LHSType->getAs<ComplexType>()) 8401 return Incompatible; 8402 8403 // Arithmetic conversions. 8404 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8405 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8406 if (ConvertRHS) 8407 Kind = PrepareScalarCast(RHS, LHSType); 8408 return Compatible; 8409 } 8410 8411 // Conversions to normal pointers. 8412 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8413 // U* -> T* 8414 if (isa<PointerType>(RHSType)) { 8415 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8416 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8417 if (AddrSpaceL != AddrSpaceR) 8418 Kind = CK_AddressSpaceConversion; 8419 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8420 Kind = CK_NoOp; 8421 else 8422 Kind = CK_BitCast; 8423 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8424 } 8425 8426 // int -> T* 8427 if (RHSType->isIntegerType()) { 8428 Kind = CK_IntegralToPointer; // FIXME: null? 8429 return IntToPointer; 8430 } 8431 8432 // C pointers are not compatible with ObjC object pointers, 8433 // with two exceptions: 8434 if (isa<ObjCObjectPointerType>(RHSType)) { 8435 // - conversions to void* 8436 if (LHSPointer->getPointeeType()->isVoidType()) { 8437 Kind = CK_BitCast; 8438 return Compatible; 8439 } 8440 8441 // - conversions from 'Class' to the redefinition type 8442 if (RHSType->isObjCClassType() && 8443 Context.hasSameType(LHSType, 8444 Context.getObjCClassRedefinitionType())) { 8445 Kind = CK_BitCast; 8446 return Compatible; 8447 } 8448 8449 Kind = CK_BitCast; 8450 return IncompatiblePointer; 8451 } 8452 8453 // U^ -> void* 8454 if (RHSType->getAs<BlockPointerType>()) { 8455 if (LHSPointer->getPointeeType()->isVoidType()) { 8456 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8457 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8458 ->getPointeeType() 8459 .getAddressSpace(); 8460 Kind = 8461 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8462 return Compatible; 8463 } 8464 } 8465 8466 return Incompatible; 8467 } 8468 8469 // Conversions to block pointers. 8470 if (isa<BlockPointerType>(LHSType)) { 8471 // U^ -> T^ 8472 if (RHSType->isBlockPointerType()) { 8473 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8474 ->getPointeeType() 8475 .getAddressSpace(); 8476 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8477 ->getPointeeType() 8478 .getAddressSpace(); 8479 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8480 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8481 } 8482 8483 // int or null -> T^ 8484 if (RHSType->isIntegerType()) { 8485 Kind = CK_IntegralToPointer; // FIXME: null 8486 return IntToBlockPointer; 8487 } 8488 8489 // id -> T^ 8490 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8491 Kind = CK_AnyPointerToBlockPointerCast; 8492 return Compatible; 8493 } 8494 8495 // void* -> T^ 8496 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8497 if (RHSPT->getPointeeType()->isVoidType()) { 8498 Kind = CK_AnyPointerToBlockPointerCast; 8499 return Compatible; 8500 } 8501 8502 return Incompatible; 8503 } 8504 8505 // Conversions to Objective-C pointers. 8506 if (isa<ObjCObjectPointerType>(LHSType)) { 8507 // A* -> B* 8508 if (RHSType->isObjCObjectPointerType()) { 8509 Kind = CK_BitCast; 8510 Sema::AssignConvertType result = 8511 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8512 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8513 result == Compatible && 8514 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8515 result = IncompatibleObjCWeakRef; 8516 return result; 8517 } 8518 8519 // int or null -> A* 8520 if (RHSType->isIntegerType()) { 8521 Kind = CK_IntegralToPointer; // FIXME: null 8522 return IntToPointer; 8523 } 8524 8525 // In general, C pointers are not compatible with ObjC object pointers, 8526 // with two exceptions: 8527 if (isa<PointerType>(RHSType)) { 8528 Kind = CK_CPointerToObjCPointerCast; 8529 8530 // - conversions from 'void*' 8531 if (RHSType->isVoidPointerType()) { 8532 return Compatible; 8533 } 8534 8535 // - conversions to 'Class' from its redefinition type 8536 if (LHSType->isObjCClassType() && 8537 Context.hasSameType(RHSType, 8538 Context.getObjCClassRedefinitionType())) { 8539 return Compatible; 8540 } 8541 8542 return IncompatiblePointer; 8543 } 8544 8545 // Only under strict condition T^ is compatible with an Objective-C pointer. 8546 if (RHSType->isBlockPointerType() && 8547 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8548 if (ConvertRHS) 8549 maybeExtendBlockObject(RHS); 8550 Kind = CK_BlockPointerToObjCPointerCast; 8551 return Compatible; 8552 } 8553 8554 return Incompatible; 8555 } 8556 8557 // Conversions from pointers that are not covered by the above. 8558 if (isa<PointerType>(RHSType)) { 8559 // T* -> _Bool 8560 if (LHSType == Context.BoolTy) { 8561 Kind = CK_PointerToBoolean; 8562 return Compatible; 8563 } 8564 8565 // T* -> int 8566 if (LHSType->isIntegerType()) { 8567 Kind = CK_PointerToIntegral; 8568 return PointerToInt; 8569 } 8570 8571 return Incompatible; 8572 } 8573 8574 // Conversions from Objective-C pointers that are not covered by the above. 8575 if (isa<ObjCObjectPointerType>(RHSType)) { 8576 // T* -> _Bool 8577 if (LHSType == Context.BoolTy) { 8578 Kind = CK_PointerToBoolean; 8579 return Compatible; 8580 } 8581 8582 // T* -> int 8583 if (LHSType->isIntegerType()) { 8584 Kind = CK_PointerToIntegral; 8585 return PointerToInt; 8586 } 8587 8588 return Incompatible; 8589 } 8590 8591 // struct A -> struct B 8592 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8593 if (Context.typesAreCompatible(LHSType, RHSType)) { 8594 Kind = CK_NoOp; 8595 return Compatible; 8596 } 8597 } 8598 8599 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8600 Kind = CK_IntToOCLSampler; 8601 return Compatible; 8602 } 8603 8604 return Incompatible; 8605 } 8606 8607 /// Constructs a transparent union from an expression that is 8608 /// used to initialize the transparent union. 8609 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8610 ExprResult &EResult, QualType UnionType, 8611 FieldDecl *Field) { 8612 // Build an initializer list that designates the appropriate member 8613 // of the transparent union. 8614 Expr *E = EResult.get(); 8615 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8616 E, SourceLocation()); 8617 Initializer->setType(UnionType); 8618 Initializer->setInitializedFieldInUnion(Field); 8619 8620 // Build a compound literal constructing a value of the transparent 8621 // union type from this initializer list. 8622 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8623 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8624 VK_RValue, Initializer, false); 8625 } 8626 8627 Sema::AssignConvertType 8628 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8629 ExprResult &RHS) { 8630 QualType RHSType = RHS.get()->getType(); 8631 8632 // If the ArgType is a Union type, we want to handle a potential 8633 // transparent_union GCC extension. 8634 const RecordType *UT = ArgType->getAsUnionType(); 8635 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8636 return Incompatible; 8637 8638 // The field to initialize within the transparent union. 8639 RecordDecl *UD = UT->getDecl(); 8640 FieldDecl *InitField = nullptr; 8641 // It's compatible if the expression matches any of the fields. 8642 for (auto *it : UD->fields()) { 8643 if (it->getType()->isPointerType()) { 8644 // If the transparent union contains a pointer type, we allow: 8645 // 1) void pointer 8646 // 2) null pointer constant 8647 if (RHSType->isPointerType()) 8648 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8649 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8650 InitField = it; 8651 break; 8652 } 8653 8654 if (RHS.get()->isNullPointerConstant(Context, 8655 Expr::NPC_ValueDependentIsNull)) { 8656 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8657 CK_NullToPointer); 8658 InitField = it; 8659 break; 8660 } 8661 } 8662 8663 CastKind Kind; 8664 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8665 == Compatible) { 8666 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8667 InitField = it; 8668 break; 8669 } 8670 } 8671 8672 if (!InitField) 8673 return Incompatible; 8674 8675 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8676 return Compatible; 8677 } 8678 8679 Sema::AssignConvertType 8680 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8681 bool Diagnose, 8682 bool DiagnoseCFAudited, 8683 bool ConvertRHS) { 8684 // We need to be able to tell the caller whether we diagnosed a problem, if 8685 // they ask us to issue diagnostics. 8686 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8687 8688 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8689 // we can't avoid *all* modifications at the moment, so we need some somewhere 8690 // to put the updated value. 8691 ExprResult LocalRHS = CallerRHS; 8692 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8693 8694 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8695 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8696 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8697 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8698 Diag(RHS.get()->getExprLoc(), 8699 diag::warn_noderef_to_dereferenceable_pointer) 8700 << RHS.get()->getSourceRange(); 8701 } 8702 } 8703 } 8704 8705 if (getLangOpts().CPlusPlus) { 8706 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8707 // C++ 5.17p3: If the left operand is not of class type, the 8708 // expression is implicitly converted (C++ 4) to the 8709 // cv-unqualified type of the left operand. 8710 QualType RHSType = RHS.get()->getType(); 8711 if (Diagnose) { 8712 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8713 AA_Assigning); 8714 } else { 8715 ImplicitConversionSequence ICS = 8716 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8717 /*SuppressUserConversions=*/false, 8718 AllowedExplicit::None, 8719 /*InOverloadResolution=*/false, 8720 /*CStyle=*/false, 8721 /*AllowObjCWritebackConversion=*/false); 8722 if (ICS.isFailure()) 8723 return Incompatible; 8724 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8725 ICS, AA_Assigning); 8726 } 8727 if (RHS.isInvalid()) 8728 return Incompatible; 8729 Sema::AssignConvertType result = Compatible; 8730 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8731 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8732 result = IncompatibleObjCWeakRef; 8733 return result; 8734 } 8735 8736 // FIXME: Currently, we fall through and treat C++ classes like C 8737 // structures. 8738 // FIXME: We also fall through for atomics; not sure what should 8739 // happen there, though. 8740 } else if (RHS.get()->getType() == Context.OverloadTy) { 8741 // As a set of extensions to C, we support overloading on functions. These 8742 // functions need to be resolved here. 8743 DeclAccessPair DAP; 8744 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8745 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8746 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8747 else 8748 return Incompatible; 8749 } 8750 8751 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8752 // a null pointer constant. 8753 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8754 LHSType->isBlockPointerType()) && 8755 RHS.get()->isNullPointerConstant(Context, 8756 Expr::NPC_ValueDependentIsNull)) { 8757 if (Diagnose || ConvertRHS) { 8758 CastKind Kind; 8759 CXXCastPath Path; 8760 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8761 /*IgnoreBaseAccess=*/false, Diagnose); 8762 if (ConvertRHS) 8763 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8764 } 8765 return Compatible; 8766 } 8767 8768 // OpenCL queue_t type assignment. 8769 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8770 Context, Expr::NPC_ValueDependentIsNull)) { 8771 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8772 return Compatible; 8773 } 8774 8775 // This check seems unnatural, however it is necessary to ensure the proper 8776 // conversion of functions/arrays. If the conversion were done for all 8777 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8778 // expressions that suppress this implicit conversion (&, sizeof). 8779 // 8780 // Suppress this for references: C++ 8.5.3p5. 8781 if (!LHSType->isReferenceType()) { 8782 // FIXME: We potentially allocate here even if ConvertRHS is false. 8783 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8784 if (RHS.isInvalid()) 8785 return Incompatible; 8786 } 8787 CastKind Kind; 8788 Sema::AssignConvertType result = 8789 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8790 8791 // C99 6.5.16.1p2: The value of the right operand is converted to the 8792 // type of the assignment expression. 8793 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8794 // so that we can use references in built-in functions even in C. 8795 // The getNonReferenceType() call makes sure that the resulting expression 8796 // does not have reference type. 8797 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8798 QualType Ty = LHSType.getNonLValueExprType(Context); 8799 Expr *E = RHS.get(); 8800 8801 // Check for various Objective-C errors. If we are not reporting 8802 // diagnostics and just checking for errors, e.g., during overload 8803 // resolution, return Incompatible to indicate the failure. 8804 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8805 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8806 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8807 if (!Diagnose) 8808 return Incompatible; 8809 } 8810 if (getLangOpts().ObjC && 8811 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8812 E->getType(), E, Diagnose) || 8813 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8814 if (!Diagnose) 8815 return Incompatible; 8816 // Replace the expression with a corrected version and continue so we 8817 // can find further errors. 8818 RHS = E; 8819 return Compatible; 8820 } 8821 8822 if (ConvertRHS) 8823 RHS = ImpCastExprToType(E, Ty, Kind); 8824 } 8825 8826 return result; 8827 } 8828 8829 namespace { 8830 /// The original operand to an operator, prior to the application of the usual 8831 /// arithmetic conversions and converting the arguments of a builtin operator 8832 /// candidate. 8833 struct OriginalOperand { 8834 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8835 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8836 Op = MTE->getSubExpr(); 8837 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8838 Op = BTE->getSubExpr(); 8839 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8840 Orig = ICE->getSubExprAsWritten(); 8841 Conversion = ICE->getConversionFunction(); 8842 } 8843 } 8844 8845 QualType getType() const { return Orig->getType(); } 8846 8847 Expr *Orig; 8848 NamedDecl *Conversion; 8849 }; 8850 } 8851 8852 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8853 ExprResult &RHS) { 8854 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8855 8856 Diag(Loc, diag::err_typecheck_invalid_operands) 8857 << OrigLHS.getType() << OrigRHS.getType() 8858 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8859 8860 // If a user-defined conversion was applied to either of the operands prior 8861 // to applying the built-in operator rules, tell the user about it. 8862 if (OrigLHS.Conversion) { 8863 Diag(OrigLHS.Conversion->getLocation(), 8864 diag::note_typecheck_invalid_operands_converted) 8865 << 0 << LHS.get()->getType(); 8866 } 8867 if (OrigRHS.Conversion) { 8868 Diag(OrigRHS.Conversion->getLocation(), 8869 diag::note_typecheck_invalid_operands_converted) 8870 << 1 << RHS.get()->getType(); 8871 } 8872 8873 return QualType(); 8874 } 8875 8876 // Diagnose cases where a scalar was implicitly converted to a vector and 8877 // diagnose the underlying types. Otherwise, diagnose the error 8878 // as invalid vector logical operands for non-C++ cases. 8879 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8880 ExprResult &RHS) { 8881 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8882 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8883 8884 bool LHSNatVec = LHSType->isVectorType(); 8885 bool RHSNatVec = RHSType->isVectorType(); 8886 8887 if (!(LHSNatVec && RHSNatVec)) { 8888 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8889 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8890 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8891 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8892 << Vector->getSourceRange(); 8893 return QualType(); 8894 } 8895 8896 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8897 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8898 << RHS.get()->getSourceRange(); 8899 8900 return QualType(); 8901 } 8902 8903 /// Try to convert a value of non-vector type to a vector type by converting 8904 /// the type to the element type of the vector and then performing a splat. 8905 /// If the language is OpenCL, we only use conversions that promote scalar 8906 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8907 /// for float->int. 8908 /// 8909 /// OpenCL V2.0 6.2.6.p2: 8910 /// An error shall occur if any scalar operand type has greater rank 8911 /// than the type of the vector element. 8912 /// 8913 /// \param scalar - if non-null, actually perform the conversions 8914 /// \return true if the operation fails (but without diagnosing the failure) 8915 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8916 QualType scalarTy, 8917 QualType vectorEltTy, 8918 QualType vectorTy, 8919 unsigned &DiagID) { 8920 // The conversion to apply to the scalar before splatting it, 8921 // if necessary. 8922 CastKind scalarCast = CK_NoOp; 8923 8924 if (vectorEltTy->isIntegralType(S.Context)) { 8925 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8926 (scalarTy->isIntegerType() && 8927 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8928 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8929 return true; 8930 } 8931 if (!scalarTy->isIntegralType(S.Context)) 8932 return true; 8933 scalarCast = CK_IntegralCast; 8934 } else if (vectorEltTy->isRealFloatingType()) { 8935 if (scalarTy->isRealFloatingType()) { 8936 if (S.getLangOpts().OpenCL && 8937 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8938 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8939 return true; 8940 } 8941 scalarCast = CK_FloatingCast; 8942 } 8943 else if (scalarTy->isIntegralType(S.Context)) 8944 scalarCast = CK_IntegralToFloating; 8945 else 8946 return true; 8947 } else { 8948 return true; 8949 } 8950 8951 // Adjust scalar if desired. 8952 if (scalar) { 8953 if (scalarCast != CK_NoOp) 8954 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8955 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8956 } 8957 return false; 8958 } 8959 8960 /// Convert vector E to a vector with the same number of elements but different 8961 /// element type. 8962 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8963 const auto *VecTy = E->getType()->getAs<VectorType>(); 8964 assert(VecTy && "Expression E must be a vector"); 8965 QualType NewVecTy = S.Context.getVectorType(ElementType, 8966 VecTy->getNumElements(), 8967 VecTy->getVectorKind()); 8968 8969 // Look through the implicit cast. Return the subexpression if its type is 8970 // NewVecTy. 8971 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8972 if (ICE->getSubExpr()->getType() == NewVecTy) 8973 return ICE->getSubExpr(); 8974 8975 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8976 return S.ImpCastExprToType(E, NewVecTy, Cast); 8977 } 8978 8979 /// Test if a (constant) integer Int can be casted to another integer type 8980 /// IntTy without losing precision. 8981 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8982 QualType OtherIntTy) { 8983 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8984 8985 // Reject cases where the value of the Int is unknown as that would 8986 // possibly cause truncation, but accept cases where the scalar can be 8987 // demoted without loss of precision. 8988 Expr::EvalResult EVResult; 8989 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8990 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8991 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8992 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8993 8994 if (CstInt) { 8995 // If the scalar is constant and is of a higher order and has more active 8996 // bits that the vector element type, reject it. 8997 llvm::APSInt Result = EVResult.Val.getInt(); 8998 unsigned NumBits = IntSigned 8999 ? (Result.isNegative() ? Result.getMinSignedBits() 9000 : Result.getActiveBits()) 9001 : Result.getActiveBits(); 9002 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9003 return true; 9004 9005 // If the signedness of the scalar type and the vector element type 9006 // differs and the number of bits is greater than that of the vector 9007 // element reject it. 9008 return (IntSigned != OtherIntSigned && 9009 NumBits > S.Context.getIntWidth(OtherIntTy)); 9010 } 9011 9012 // Reject cases where the value of the scalar is not constant and it's 9013 // order is greater than that of the vector element type. 9014 return (Order < 0); 9015 } 9016 9017 /// Test if a (constant) integer Int can be casted to floating point type 9018 /// FloatTy without losing precision. 9019 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9020 QualType FloatTy) { 9021 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9022 9023 // Determine if the integer constant can be expressed as a floating point 9024 // number of the appropriate type. 9025 Expr::EvalResult EVResult; 9026 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9027 9028 uint64_t Bits = 0; 9029 if (CstInt) { 9030 // Reject constants that would be truncated if they were converted to 9031 // the floating point type. Test by simple to/from conversion. 9032 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9033 // could be avoided if there was a convertFromAPInt method 9034 // which could signal back if implicit truncation occurred. 9035 llvm::APSInt Result = EVResult.Val.getInt(); 9036 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9037 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9038 llvm::APFloat::rmTowardZero); 9039 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9040 !IntTy->hasSignedIntegerRepresentation()); 9041 bool Ignored = false; 9042 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9043 &Ignored); 9044 if (Result != ConvertBack) 9045 return true; 9046 } else { 9047 // Reject types that cannot be fully encoded into the mantissa of 9048 // the float. 9049 Bits = S.Context.getTypeSize(IntTy); 9050 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9051 S.Context.getFloatTypeSemantics(FloatTy)); 9052 if (Bits > FloatPrec) 9053 return true; 9054 } 9055 9056 return false; 9057 } 9058 9059 /// Attempt to convert and splat Scalar into a vector whose types matches 9060 /// Vector following GCC conversion rules. The rule is that implicit 9061 /// conversion can occur when Scalar can be casted to match Vector's element 9062 /// type without causing truncation of Scalar. 9063 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9064 ExprResult *Vector) { 9065 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9066 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9067 const VectorType *VT = VectorTy->getAs<VectorType>(); 9068 9069 assert(!isa<ExtVectorType>(VT) && 9070 "ExtVectorTypes should not be handled here!"); 9071 9072 QualType VectorEltTy = VT->getElementType(); 9073 9074 // Reject cases where the vector element type or the scalar element type are 9075 // not integral or floating point types. 9076 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9077 return true; 9078 9079 // The conversion to apply to the scalar before splatting it, 9080 // if necessary. 9081 CastKind ScalarCast = CK_NoOp; 9082 9083 // Accept cases where the vector elements are integers and the scalar is 9084 // an integer. 9085 // FIXME: Notionally if the scalar was a floating point value with a precise 9086 // integral representation, we could cast it to an appropriate integer 9087 // type and then perform the rest of the checks here. GCC will perform 9088 // this conversion in some cases as determined by the input language. 9089 // We should accept it on a language independent basis. 9090 if (VectorEltTy->isIntegralType(S.Context) && 9091 ScalarTy->isIntegralType(S.Context) && 9092 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9093 9094 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9095 return true; 9096 9097 ScalarCast = CK_IntegralCast; 9098 } else if (VectorEltTy->isIntegralType(S.Context) && 9099 ScalarTy->isRealFloatingType()) { 9100 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9101 ScalarCast = CK_FloatingToIntegral; 9102 else 9103 return true; 9104 } else if (VectorEltTy->isRealFloatingType()) { 9105 if (ScalarTy->isRealFloatingType()) { 9106 9107 // Reject cases where the scalar type is not a constant and has a higher 9108 // Order than the vector element type. 9109 llvm::APFloat Result(0.0); 9110 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 9111 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9112 if (!CstScalar && Order < 0) 9113 return true; 9114 9115 // If the scalar cannot be safely casted to the vector element type, 9116 // reject it. 9117 if (CstScalar) { 9118 bool Truncated = false; 9119 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9120 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9121 if (Truncated) 9122 return true; 9123 } 9124 9125 ScalarCast = CK_FloatingCast; 9126 } else if (ScalarTy->isIntegralType(S.Context)) { 9127 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9128 return true; 9129 9130 ScalarCast = CK_IntegralToFloating; 9131 } else 9132 return true; 9133 } 9134 9135 // Adjust scalar if desired. 9136 if (Scalar) { 9137 if (ScalarCast != CK_NoOp) 9138 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9139 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9140 } 9141 return false; 9142 } 9143 9144 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9145 SourceLocation Loc, bool IsCompAssign, 9146 bool AllowBothBool, 9147 bool AllowBoolConversions) { 9148 if (!IsCompAssign) { 9149 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9150 if (LHS.isInvalid()) 9151 return QualType(); 9152 } 9153 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9154 if (RHS.isInvalid()) 9155 return QualType(); 9156 9157 // For conversion purposes, we ignore any qualifiers. 9158 // For example, "const float" and "float" are equivalent. 9159 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9160 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9161 9162 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9163 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9164 assert(LHSVecType || RHSVecType); 9165 9166 // AltiVec-style "vector bool op vector bool" combinations are allowed 9167 // for some operators but not others. 9168 if (!AllowBothBool && 9169 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9170 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9171 return InvalidOperands(Loc, LHS, RHS); 9172 9173 // If the vector types are identical, return. 9174 if (Context.hasSameType(LHSType, RHSType)) 9175 return LHSType; 9176 9177 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9178 if (LHSVecType && RHSVecType && 9179 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9180 if (isa<ExtVectorType>(LHSVecType)) { 9181 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9182 return LHSType; 9183 } 9184 9185 if (!IsCompAssign) 9186 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9187 return RHSType; 9188 } 9189 9190 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9191 // can be mixed, with the result being the non-bool type. The non-bool 9192 // operand must have integer element type. 9193 if (AllowBoolConversions && LHSVecType && RHSVecType && 9194 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9195 (Context.getTypeSize(LHSVecType->getElementType()) == 9196 Context.getTypeSize(RHSVecType->getElementType()))) { 9197 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9198 LHSVecType->getElementType()->isIntegerType() && 9199 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9200 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9201 return LHSType; 9202 } 9203 if (!IsCompAssign && 9204 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9205 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9206 RHSVecType->getElementType()->isIntegerType()) { 9207 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9208 return RHSType; 9209 } 9210 } 9211 9212 // If there's a vector type and a scalar, try to convert the scalar to 9213 // the vector element type and splat. 9214 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9215 if (!RHSVecType) { 9216 if (isa<ExtVectorType>(LHSVecType)) { 9217 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9218 LHSVecType->getElementType(), LHSType, 9219 DiagID)) 9220 return LHSType; 9221 } else { 9222 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9223 return LHSType; 9224 } 9225 } 9226 if (!LHSVecType) { 9227 if (isa<ExtVectorType>(RHSVecType)) { 9228 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9229 LHSType, RHSVecType->getElementType(), 9230 RHSType, DiagID)) 9231 return RHSType; 9232 } else { 9233 if (LHS.get()->getValueKind() == VK_LValue || 9234 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9235 return RHSType; 9236 } 9237 } 9238 9239 // FIXME: The code below also handles conversion between vectors and 9240 // non-scalars, we should break this down into fine grained specific checks 9241 // and emit proper diagnostics. 9242 QualType VecType = LHSVecType ? LHSType : RHSType; 9243 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9244 QualType OtherType = LHSVecType ? RHSType : LHSType; 9245 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9246 if (isLaxVectorConversion(OtherType, VecType)) { 9247 // If we're allowing lax vector conversions, only the total (data) size 9248 // needs to be the same. For non compound assignment, if one of the types is 9249 // scalar, the result is always the vector type. 9250 if (!IsCompAssign) { 9251 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9252 return VecType; 9253 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9254 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9255 // type. Note that this is already done by non-compound assignments in 9256 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9257 // <1 x T> -> T. The result is also a vector type. 9258 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9259 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9260 ExprResult *RHSExpr = &RHS; 9261 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9262 return VecType; 9263 } 9264 } 9265 9266 // Okay, the expression is invalid. 9267 9268 // If there's a non-vector, non-real operand, diagnose that. 9269 if ((!RHSVecType && !RHSType->isRealType()) || 9270 (!LHSVecType && !LHSType->isRealType())) { 9271 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9272 << LHSType << RHSType 9273 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9274 return QualType(); 9275 } 9276 9277 // OpenCL V1.1 6.2.6.p1: 9278 // If the operands are of more than one vector type, then an error shall 9279 // occur. Implicit conversions between vector types are not permitted, per 9280 // section 6.2.1. 9281 if (getLangOpts().OpenCL && 9282 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9283 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9284 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9285 << RHSType; 9286 return QualType(); 9287 } 9288 9289 9290 // If there is a vector type that is not a ExtVector and a scalar, we reach 9291 // this point if scalar could not be converted to the vector's element type 9292 // without truncation. 9293 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9294 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9295 QualType Scalar = LHSVecType ? RHSType : LHSType; 9296 QualType Vector = LHSVecType ? LHSType : RHSType; 9297 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9298 Diag(Loc, 9299 diag::err_typecheck_vector_not_convertable_implict_truncation) 9300 << ScalarOrVector << Scalar << Vector; 9301 9302 return QualType(); 9303 } 9304 9305 // Otherwise, use the generic diagnostic. 9306 Diag(Loc, DiagID) 9307 << LHSType << RHSType 9308 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9309 return QualType(); 9310 } 9311 9312 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9313 // expression. These are mainly cases where the null pointer is used as an 9314 // integer instead of a pointer. 9315 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9316 SourceLocation Loc, bool IsCompare) { 9317 // The canonical way to check for a GNU null is with isNullPointerConstant, 9318 // but we use a bit of a hack here for speed; this is a relatively 9319 // hot path, and isNullPointerConstant is slow. 9320 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9321 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9322 9323 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9324 9325 // Avoid analyzing cases where the result will either be invalid (and 9326 // diagnosed as such) or entirely valid and not something to warn about. 9327 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9328 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9329 return; 9330 9331 // Comparison operations would not make sense with a null pointer no matter 9332 // what the other expression is. 9333 if (!IsCompare) { 9334 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9335 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9336 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9337 return; 9338 } 9339 9340 // The rest of the operations only make sense with a null pointer 9341 // if the other expression is a pointer. 9342 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9343 NonNullType->canDecayToPointerType()) 9344 return; 9345 9346 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9347 << LHSNull /* LHS is NULL */ << NonNullType 9348 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9349 } 9350 9351 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9352 SourceLocation Loc) { 9353 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9354 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9355 if (!LUE || !RUE) 9356 return; 9357 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9358 RUE->getKind() != UETT_SizeOf) 9359 return; 9360 9361 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9362 QualType LHSTy = LHSArg->getType(); 9363 QualType RHSTy; 9364 9365 if (RUE->isArgumentType()) 9366 RHSTy = RUE->getArgumentType(); 9367 else 9368 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9369 9370 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9371 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9372 return; 9373 9374 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9375 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9376 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9377 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9378 << LHSArgDecl; 9379 } 9380 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9381 QualType ArrayElemTy = ArrayTy->getElementType(); 9382 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9383 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9384 ArrayElemTy->isCharType() || 9385 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9386 return; 9387 S.Diag(Loc, diag::warn_division_sizeof_array) 9388 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9389 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9390 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9391 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9392 << LHSArgDecl; 9393 } 9394 9395 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9396 } 9397 } 9398 9399 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9400 ExprResult &RHS, 9401 SourceLocation Loc, bool IsDiv) { 9402 // Check for division/remainder by zero. 9403 Expr::EvalResult RHSValue; 9404 if (!RHS.get()->isValueDependent() && 9405 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9406 RHSValue.Val.getInt() == 0) 9407 S.DiagRuntimeBehavior(Loc, RHS.get(), 9408 S.PDiag(diag::warn_remainder_division_by_zero) 9409 << IsDiv << RHS.get()->getSourceRange()); 9410 } 9411 9412 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9413 SourceLocation Loc, 9414 bool IsCompAssign, bool IsDiv) { 9415 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9416 9417 if (LHS.get()->getType()->isVectorType() || 9418 RHS.get()->getType()->isVectorType()) 9419 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9420 /*AllowBothBool*/getLangOpts().AltiVec, 9421 /*AllowBoolConversions*/false); 9422 9423 QualType compType = UsualArithmeticConversions( 9424 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9425 if (LHS.isInvalid() || RHS.isInvalid()) 9426 return QualType(); 9427 9428 9429 if (compType.isNull() || !compType->isArithmeticType()) 9430 return InvalidOperands(Loc, LHS, RHS); 9431 if (IsDiv) { 9432 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9433 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9434 } 9435 return compType; 9436 } 9437 9438 QualType Sema::CheckRemainderOperands( 9439 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9440 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9441 9442 if (LHS.get()->getType()->isVectorType() || 9443 RHS.get()->getType()->isVectorType()) { 9444 if (LHS.get()->getType()->hasIntegerRepresentation() && 9445 RHS.get()->getType()->hasIntegerRepresentation()) 9446 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9447 /*AllowBothBool*/getLangOpts().AltiVec, 9448 /*AllowBoolConversions*/false); 9449 return InvalidOperands(Loc, LHS, RHS); 9450 } 9451 9452 QualType compType = UsualArithmeticConversions( 9453 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9454 if (LHS.isInvalid() || RHS.isInvalid()) 9455 return QualType(); 9456 9457 if (compType.isNull() || !compType->isIntegerType()) 9458 return InvalidOperands(Loc, LHS, RHS); 9459 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9460 return compType; 9461 } 9462 9463 /// Diagnose invalid arithmetic on two void pointers. 9464 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9465 Expr *LHSExpr, Expr *RHSExpr) { 9466 S.Diag(Loc, S.getLangOpts().CPlusPlus 9467 ? diag::err_typecheck_pointer_arith_void_type 9468 : diag::ext_gnu_void_ptr) 9469 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9470 << RHSExpr->getSourceRange(); 9471 } 9472 9473 /// Diagnose invalid arithmetic on a void pointer. 9474 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9475 Expr *Pointer) { 9476 S.Diag(Loc, S.getLangOpts().CPlusPlus 9477 ? diag::err_typecheck_pointer_arith_void_type 9478 : diag::ext_gnu_void_ptr) 9479 << 0 /* one pointer */ << Pointer->getSourceRange(); 9480 } 9481 9482 /// Diagnose invalid arithmetic on a null pointer. 9483 /// 9484 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9485 /// idiom, which we recognize as a GNU extension. 9486 /// 9487 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9488 Expr *Pointer, bool IsGNUIdiom) { 9489 if (IsGNUIdiom) 9490 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9491 << Pointer->getSourceRange(); 9492 else 9493 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9494 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9495 } 9496 9497 /// Diagnose invalid arithmetic on two function pointers. 9498 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9499 Expr *LHS, Expr *RHS) { 9500 assert(LHS->getType()->isAnyPointerType()); 9501 assert(RHS->getType()->isAnyPointerType()); 9502 S.Diag(Loc, S.getLangOpts().CPlusPlus 9503 ? diag::err_typecheck_pointer_arith_function_type 9504 : diag::ext_gnu_ptr_func_arith) 9505 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9506 // We only show the second type if it differs from the first. 9507 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9508 RHS->getType()) 9509 << RHS->getType()->getPointeeType() 9510 << LHS->getSourceRange() << RHS->getSourceRange(); 9511 } 9512 9513 /// Diagnose invalid arithmetic on a function pointer. 9514 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9515 Expr *Pointer) { 9516 assert(Pointer->getType()->isAnyPointerType()); 9517 S.Diag(Loc, S.getLangOpts().CPlusPlus 9518 ? diag::err_typecheck_pointer_arith_function_type 9519 : diag::ext_gnu_ptr_func_arith) 9520 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9521 << 0 /* one pointer, so only one type */ 9522 << Pointer->getSourceRange(); 9523 } 9524 9525 /// Emit error if Operand is incomplete pointer type 9526 /// 9527 /// \returns True if pointer has incomplete type 9528 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9529 Expr *Operand) { 9530 QualType ResType = Operand->getType(); 9531 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9532 ResType = ResAtomicType->getValueType(); 9533 9534 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9535 QualType PointeeTy = ResType->getPointeeType(); 9536 return S.RequireCompleteType(Loc, PointeeTy, 9537 diag::err_typecheck_arithmetic_incomplete_type, 9538 PointeeTy, Operand->getSourceRange()); 9539 } 9540 9541 /// Check the validity of an arithmetic pointer operand. 9542 /// 9543 /// If the operand has pointer type, this code will check for pointer types 9544 /// which are invalid in arithmetic operations. These will be diagnosed 9545 /// appropriately, including whether or not the use is supported as an 9546 /// extension. 9547 /// 9548 /// \returns True when the operand is valid to use (even if as an extension). 9549 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9550 Expr *Operand) { 9551 QualType ResType = Operand->getType(); 9552 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9553 ResType = ResAtomicType->getValueType(); 9554 9555 if (!ResType->isAnyPointerType()) return true; 9556 9557 QualType PointeeTy = ResType->getPointeeType(); 9558 if (PointeeTy->isVoidType()) { 9559 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9560 return !S.getLangOpts().CPlusPlus; 9561 } 9562 if (PointeeTy->isFunctionType()) { 9563 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9564 return !S.getLangOpts().CPlusPlus; 9565 } 9566 9567 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9568 9569 return true; 9570 } 9571 9572 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9573 /// operands. 9574 /// 9575 /// This routine will diagnose any invalid arithmetic on pointer operands much 9576 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9577 /// for emitting a single diagnostic even for operations where both LHS and RHS 9578 /// are (potentially problematic) pointers. 9579 /// 9580 /// \returns True when the operand is valid to use (even if as an extension). 9581 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9582 Expr *LHSExpr, Expr *RHSExpr) { 9583 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9584 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9585 if (!isLHSPointer && !isRHSPointer) return true; 9586 9587 QualType LHSPointeeTy, RHSPointeeTy; 9588 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9589 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9590 9591 // if both are pointers check if operation is valid wrt address spaces 9592 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9593 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9594 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9595 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9596 S.Diag(Loc, 9597 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9598 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9599 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9600 return false; 9601 } 9602 } 9603 9604 // Check for arithmetic on pointers to incomplete types. 9605 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9606 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9607 if (isLHSVoidPtr || isRHSVoidPtr) { 9608 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9609 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9610 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9611 9612 return !S.getLangOpts().CPlusPlus; 9613 } 9614 9615 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9616 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9617 if (isLHSFuncPtr || isRHSFuncPtr) { 9618 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9619 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9620 RHSExpr); 9621 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9622 9623 return !S.getLangOpts().CPlusPlus; 9624 } 9625 9626 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9627 return false; 9628 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9629 return false; 9630 9631 return true; 9632 } 9633 9634 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9635 /// literal. 9636 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9637 Expr *LHSExpr, Expr *RHSExpr) { 9638 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9639 Expr* IndexExpr = RHSExpr; 9640 if (!StrExpr) { 9641 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9642 IndexExpr = LHSExpr; 9643 } 9644 9645 bool IsStringPlusInt = StrExpr && 9646 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9647 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9648 return; 9649 9650 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9651 Self.Diag(OpLoc, diag::warn_string_plus_int) 9652 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9653 9654 // Only print a fixit for "str" + int, not for int + "str". 9655 if (IndexExpr == RHSExpr) { 9656 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9657 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9658 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9659 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9660 << FixItHint::CreateInsertion(EndLoc, "]"); 9661 } else 9662 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9663 } 9664 9665 /// Emit a warning when adding a char literal to a string. 9666 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9667 Expr *LHSExpr, Expr *RHSExpr) { 9668 const Expr *StringRefExpr = LHSExpr; 9669 const CharacterLiteral *CharExpr = 9670 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9671 9672 if (!CharExpr) { 9673 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9674 StringRefExpr = RHSExpr; 9675 } 9676 9677 if (!CharExpr || !StringRefExpr) 9678 return; 9679 9680 const QualType StringType = StringRefExpr->getType(); 9681 9682 // Return if not a PointerType. 9683 if (!StringType->isAnyPointerType()) 9684 return; 9685 9686 // Return if not a CharacterType. 9687 if (!StringType->getPointeeType()->isAnyCharacterType()) 9688 return; 9689 9690 ASTContext &Ctx = Self.getASTContext(); 9691 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9692 9693 const QualType CharType = CharExpr->getType(); 9694 if (!CharType->isAnyCharacterType() && 9695 CharType->isIntegerType() && 9696 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9697 Self.Diag(OpLoc, diag::warn_string_plus_char) 9698 << DiagRange << Ctx.CharTy; 9699 } else { 9700 Self.Diag(OpLoc, diag::warn_string_plus_char) 9701 << DiagRange << CharExpr->getType(); 9702 } 9703 9704 // Only print a fixit for str + char, not for char + str. 9705 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9706 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9707 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9708 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9709 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9710 << FixItHint::CreateInsertion(EndLoc, "]"); 9711 } else { 9712 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9713 } 9714 } 9715 9716 /// Emit error when two pointers are incompatible. 9717 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9718 Expr *LHSExpr, Expr *RHSExpr) { 9719 assert(LHSExpr->getType()->isAnyPointerType()); 9720 assert(RHSExpr->getType()->isAnyPointerType()); 9721 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9722 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9723 << RHSExpr->getSourceRange(); 9724 } 9725 9726 // C99 6.5.6 9727 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9728 SourceLocation Loc, BinaryOperatorKind Opc, 9729 QualType* CompLHSTy) { 9730 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9731 9732 if (LHS.get()->getType()->isVectorType() || 9733 RHS.get()->getType()->isVectorType()) { 9734 QualType compType = CheckVectorOperands( 9735 LHS, RHS, Loc, CompLHSTy, 9736 /*AllowBothBool*/getLangOpts().AltiVec, 9737 /*AllowBoolConversions*/getLangOpts().ZVector); 9738 if (CompLHSTy) *CompLHSTy = compType; 9739 return compType; 9740 } 9741 9742 QualType compType = UsualArithmeticConversions( 9743 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9744 if (LHS.isInvalid() || RHS.isInvalid()) 9745 return QualType(); 9746 9747 // Diagnose "string literal" '+' int and string '+' "char literal". 9748 if (Opc == BO_Add) { 9749 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9750 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9751 } 9752 9753 // handle the common case first (both operands are arithmetic). 9754 if (!compType.isNull() && compType->isArithmeticType()) { 9755 if (CompLHSTy) *CompLHSTy = compType; 9756 return compType; 9757 } 9758 9759 // Type-checking. Ultimately the pointer's going to be in PExp; 9760 // note that we bias towards the LHS being the pointer. 9761 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9762 9763 bool isObjCPointer; 9764 if (PExp->getType()->isPointerType()) { 9765 isObjCPointer = false; 9766 } else if (PExp->getType()->isObjCObjectPointerType()) { 9767 isObjCPointer = true; 9768 } else { 9769 std::swap(PExp, IExp); 9770 if (PExp->getType()->isPointerType()) { 9771 isObjCPointer = false; 9772 } else if (PExp->getType()->isObjCObjectPointerType()) { 9773 isObjCPointer = true; 9774 } else { 9775 return InvalidOperands(Loc, LHS, RHS); 9776 } 9777 } 9778 assert(PExp->getType()->isAnyPointerType()); 9779 9780 if (!IExp->getType()->isIntegerType()) 9781 return InvalidOperands(Loc, LHS, RHS); 9782 9783 // Adding to a null pointer results in undefined behavior. 9784 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9785 Context, Expr::NPC_ValueDependentIsNotNull)) { 9786 // In C++ adding zero to a null pointer is defined. 9787 Expr::EvalResult KnownVal; 9788 if (!getLangOpts().CPlusPlus || 9789 (!IExp->isValueDependent() && 9790 (!IExp->EvaluateAsInt(KnownVal, Context) || 9791 KnownVal.Val.getInt() != 0))) { 9792 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9793 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9794 Context, BO_Add, PExp, IExp); 9795 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9796 } 9797 } 9798 9799 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9800 return QualType(); 9801 9802 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9803 return QualType(); 9804 9805 // Check array bounds for pointer arithemtic 9806 CheckArrayAccess(PExp, IExp); 9807 9808 if (CompLHSTy) { 9809 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9810 if (LHSTy.isNull()) { 9811 LHSTy = LHS.get()->getType(); 9812 if (LHSTy->isPromotableIntegerType()) 9813 LHSTy = Context.getPromotedIntegerType(LHSTy); 9814 } 9815 *CompLHSTy = LHSTy; 9816 } 9817 9818 return PExp->getType(); 9819 } 9820 9821 // C99 6.5.6 9822 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9823 SourceLocation Loc, 9824 QualType* CompLHSTy) { 9825 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9826 9827 if (LHS.get()->getType()->isVectorType() || 9828 RHS.get()->getType()->isVectorType()) { 9829 QualType compType = CheckVectorOperands( 9830 LHS, RHS, Loc, CompLHSTy, 9831 /*AllowBothBool*/getLangOpts().AltiVec, 9832 /*AllowBoolConversions*/getLangOpts().ZVector); 9833 if (CompLHSTy) *CompLHSTy = compType; 9834 return compType; 9835 } 9836 9837 QualType compType = UsualArithmeticConversions( 9838 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9839 if (LHS.isInvalid() || RHS.isInvalid()) 9840 return QualType(); 9841 9842 // Enforce type constraints: C99 6.5.6p3. 9843 9844 // Handle the common case first (both operands are arithmetic). 9845 if (!compType.isNull() && compType->isArithmeticType()) { 9846 if (CompLHSTy) *CompLHSTy = compType; 9847 return compType; 9848 } 9849 9850 // Either ptr - int or ptr - ptr. 9851 if (LHS.get()->getType()->isAnyPointerType()) { 9852 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9853 9854 // Diagnose bad cases where we step over interface counts. 9855 if (LHS.get()->getType()->isObjCObjectPointerType() && 9856 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9857 return QualType(); 9858 9859 // The result type of a pointer-int computation is the pointer type. 9860 if (RHS.get()->getType()->isIntegerType()) { 9861 // Subtracting from a null pointer should produce a warning. 9862 // The last argument to the diagnose call says this doesn't match the 9863 // GNU int-to-pointer idiom. 9864 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9865 Expr::NPC_ValueDependentIsNotNull)) { 9866 // In C++ adding zero to a null pointer is defined. 9867 Expr::EvalResult KnownVal; 9868 if (!getLangOpts().CPlusPlus || 9869 (!RHS.get()->isValueDependent() && 9870 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9871 KnownVal.Val.getInt() != 0))) { 9872 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9873 } 9874 } 9875 9876 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9877 return QualType(); 9878 9879 // Check array bounds for pointer arithemtic 9880 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9881 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9882 9883 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9884 return LHS.get()->getType(); 9885 } 9886 9887 // Handle pointer-pointer subtractions. 9888 if (const PointerType *RHSPTy 9889 = RHS.get()->getType()->getAs<PointerType>()) { 9890 QualType rpointee = RHSPTy->getPointeeType(); 9891 9892 if (getLangOpts().CPlusPlus) { 9893 // Pointee types must be the same: C++ [expr.add] 9894 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9895 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9896 } 9897 } else { 9898 // Pointee types must be compatible C99 6.5.6p3 9899 if (!Context.typesAreCompatible( 9900 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9901 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9902 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9903 return QualType(); 9904 } 9905 } 9906 9907 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9908 LHS.get(), RHS.get())) 9909 return QualType(); 9910 9911 // FIXME: Add warnings for nullptr - ptr. 9912 9913 // The pointee type may have zero size. As an extension, a structure or 9914 // union may have zero size or an array may have zero length. In this 9915 // case subtraction does not make sense. 9916 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9917 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9918 if (ElementSize.isZero()) { 9919 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9920 << rpointee.getUnqualifiedType() 9921 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9922 } 9923 } 9924 9925 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9926 return Context.getPointerDiffType(); 9927 } 9928 } 9929 9930 return InvalidOperands(Loc, LHS, RHS); 9931 } 9932 9933 static bool isScopedEnumerationType(QualType T) { 9934 if (const EnumType *ET = T->getAs<EnumType>()) 9935 return ET->getDecl()->isScoped(); 9936 return false; 9937 } 9938 9939 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9940 SourceLocation Loc, BinaryOperatorKind Opc, 9941 QualType LHSType) { 9942 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9943 // so skip remaining warnings as we don't want to modify values within Sema. 9944 if (S.getLangOpts().OpenCL) 9945 return; 9946 9947 // Check right/shifter operand 9948 Expr::EvalResult RHSResult; 9949 if (RHS.get()->isValueDependent() || 9950 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9951 return; 9952 llvm::APSInt Right = RHSResult.Val.getInt(); 9953 9954 if (Right.isNegative()) { 9955 S.DiagRuntimeBehavior(Loc, RHS.get(), 9956 S.PDiag(diag::warn_shift_negative) 9957 << RHS.get()->getSourceRange()); 9958 return; 9959 } 9960 llvm::APInt LeftBits(Right.getBitWidth(), 9961 S.Context.getTypeSize(LHS.get()->getType())); 9962 if (Right.uge(LeftBits)) { 9963 S.DiagRuntimeBehavior(Loc, RHS.get(), 9964 S.PDiag(diag::warn_shift_gt_typewidth) 9965 << RHS.get()->getSourceRange()); 9966 return; 9967 } 9968 if (Opc != BO_Shl) 9969 return; 9970 9971 // When left shifting an ICE which is signed, we can check for overflow which 9972 // according to C++ standards prior to C++2a has undefined behavior 9973 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9974 // more than the maximum value representable in the result type, so never 9975 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9976 // expression is still probably a bug.) 9977 Expr::EvalResult LHSResult; 9978 if (LHS.get()->isValueDependent() || 9979 LHSType->hasUnsignedIntegerRepresentation() || 9980 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9981 return; 9982 llvm::APSInt Left = LHSResult.Val.getInt(); 9983 9984 // If LHS does not have a signed type and non-negative value 9985 // then, the behavior is undefined before C++2a. Warn about it. 9986 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9987 !S.getLangOpts().CPlusPlus2a) { 9988 S.DiagRuntimeBehavior(Loc, LHS.get(), 9989 S.PDiag(diag::warn_shift_lhs_negative) 9990 << LHS.get()->getSourceRange()); 9991 return; 9992 } 9993 9994 llvm::APInt ResultBits = 9995 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9996 if (LeftBits.uge(ResultBits)) 9997 return; 9998 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9999 Result = Result.shl(Right); 10000 10001 // Print the bit representation of the signed integer as an unsigned 10002 // hexadecimal number. 10003 SmallString<40> HexResult; 10004 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10005 10006 // If we are only missing a sign bit, this is less likely to result in actual 10007 // bugs -- if the result is cast back to an unsigned type, it will have the 10008 // expected value. Thus we place this behind a different warning that can be 10009 // turned off separately if needed. 10010 if (LeftBits == ResultBits - 1) { 10011 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10012 << HexResult << LHSType 10013 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10014 return; 10015 } 10016 10017 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10018 << HexResult.str() << Result.getMinSignedBits() << LHSType 10019 << Left.getBitWidth() << LHS.get()->getSourceRange() 10020 << RHS.get()->getSourceRange(); 10021 } 10022 10023 /// Return the resulting type when a vector is shifted 10024 /// by a scalar or vector shift amount. 10025 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10026 SourceLocation Loc, bool IsCompAssign) { 10027 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10028 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10029 !LHS.get()->getType()->isVectorType()) { 10030 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10031 << RHS.get()->getType() << LHS.get()->getType() 10032 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10033 return QualType(); 10034 } 10035 10036 if (!IsCompAssign) { 10037 LHS = S.UsualUnaryConversions(LHS.get()); 10038 if (LHS.isInvalid()) return QualType(); 10039 } 10040 10041 RHS = S.UsualUnaryConversions(RHS.get()); 10042 if (RHS.isInvalid()) return QualType(); 10043 10044 QualType LHSType = LHS.get()->getType(); 10045 // Note that LHS might be a scalar because the routine calls not only in 10046 // OpenCL case. 10047 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10048 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10049 10050 // Note that RHS might not be a vector. 10051 QualType RHSType = RHS.get()->getType(); 10052 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10053 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10054 10055 // The operands need to be integers. 10056 if (!LHSEleType->isIntegerType()) { 10057 S.Diag(Loc, diag::err_typecheck_expect_int) 10058 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10059 return QualType(); 10060 } 10061 10062 if (!RHSEleType->isIntegerType()) { 10063 S.Diag(Loc, diag::err_typecheck_expect_int) 10064 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10065 return QualType(); 10066 } 10067 10068 if (!LHSVecTy) { 10069 assert(RHSVecTy); 10070 if (IsCompAssign) 10071 return RHSType; 10072 if (LHSEleType != RHSEleType) { 10073 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10074 LHSEleType = RHSEleType; 10075 } 10076 QualType VecTy = 10077 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10078 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10079 LHSType = VecTy; 10080 } else if (RHSVecTy) { 10081 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10082 // are applied component-wise. So if RHS is a vector, then ensure 10083 // that the number of elements is the same as LHS... 10084 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10085 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10086 << LHS.get()->getType() << RHS.get()->getType() 10087 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10088 return QualType(); 10089 } 10090 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10091 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10092 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10093 if (LHSBT != RHSBT && 10094 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10095 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10096 << LHS.get()->getType() << RHS.get()->getType() 10097 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10098 } 10099 } 10100 } else { 10101 // ...else expand RHS to match the number of elements in LHS. 10102 QualType VecTy = 10103 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10104 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10105 } 10106 10107 return LHSType; 10108 } 10109 10110 // C99 6.5.7 10111 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10112 SourceLocation Loc, BinaryOperatorKind Opc, 10113 bool IsCompAssign) { 10114 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10115 10116 // Vector shifts promote their scalar inputs to vector type. 10117 if (LHS.get()->getType()->isVectorType() || 10118 RHS.get()->getType()->isVectorType()) { 10119 if (LangOpts.ZVector) { 10120 // The shift operators for the z vector extensions work basically 10121 // like general shifts, except that neither the LHS nor the RHS is 10122 // allowed to be a "vector bool". 10123 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10124 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10125 return InvalidOperands(Loc, LHS, RHS); 10126 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10127 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10128 return InvalidOperands(Loc, LHS, RHS); 10129 } 10130 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10131 } 10132 10133 // Shifts don't perform usual arithmetic conversions, they just do integer 10134 // promotions on each operand. C99 6.5.7p3 10135 10136 // For the LHS, do usual unary conversions, but then reset them away 10137 // if this is a compound assignment. 10138 ExprResult OldLHS = LHS; 10139 LHS = UsualUnaryConversions(LHS.get()); 10140 if (LHS.isInvalid()) 10141 return QualType(); 10142 QualType LHSType = LHS.get()->getType(); 10143 if (IsCompAssign) LHS = OldLHS; 10144 10145 // The RHS is simpler. 10146 RHS = UsualUnaryConversions(RHS.get()); 10147 if (RHS.isInvalid()) 10148 return QualType(); 10149 QualType RHSType = RHS.get()->getType(); 10150 10151 // C99 6.5.7p2: Each of the operands shall have integer type. 10152 if (!LHSType->hasIntegerRepresentation() || 10153 !RHSType->hasIntegerRepresentation()) 10154 return InvalidOperands(Loc, LHS, RHS); 10155 10156 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10157 // hasIntegerRepresentation() above instead of this. 10158 if (isScopedEnumerationType(LHSType) || 10159 isScopedEnumerationType(RHSType)) { 10160 return InvalidOperands(Loc, LHS, RHS); 10161 } 10162 // Sanity-check shift operands 10163 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10164 10165 // "The type of the result is that of the promoted left operand." 10166 return LHSType; 10167 } 10168 10169 /// Diagnose bad pointer comparisons. 10170 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10171 ExprResult &LHS, ExprResult &RHS, 10172 bool IsError) { 10173 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10174 : diag::ext_typecheck_comparison_of_distinct_pointers) 10175 << LHS.get()->getType() << RHS.get()->getType() 10176 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10177 } 10178 10179 /// Returns false if the pointers are converted to a composite type, 10180 /// true otherwise. 10181 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10182 ExprResult &LHS, ExprResult &RHS) { 10183 // C++ [expr.rel]p2: 10184 // [...] Pointer conversions (4.10) and qualification 10185 // conversions (4.4) are performed on pointer operands (or on 10186 // a pointer operand and a null pointer constant) to bring 10187 // them to their composite pointer type. [...] 10188 // 10189 // C++ [expr.eq]p1 uses the same notion for (in)equality 10190 // comparisons of pointers. 10191 10192 QualType LHSType = LHS.get()->getType(); 10193 QualType RHSType = RHS.get()->getType(); 10194 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10195 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10196 10197 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10198 if (T.isNull()) { 10199 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10200 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10201 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10202 else 10203 S.InvalidOperands(Loc, LHS, RHS); 10204 return true; 10205 } 10206 10207 return false; 10208 } 10209 10210 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10211 ExprResult &LHS, 10212 ExprResult &RHS, 10213 bool IsError) { 10214 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10215 : diag::ext_typecheck_comparison_of_fptr_to_void) 10216 << LHS.get()->getType() << RHS.get()->getType() 10217 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10218 } 10219 10220 static bool isObjCObjectLiteral(ExprResult &E) { 10221 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10222 case Stmt::ObjCArrayLiteralClass: 10223 case Stmt::ObjCDictionaryLiteralClass: 10224 case Stmt::ObjCStringLiteralClass: 10225 case Stmt::ObjCBoxedExprClass: 10226 return true; 10227 default: 10228 // Note that ObjCBoolLiteral is NOT an object literal! 10229 return false; 10230 } 10231 } 10232 10233 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10234 const ObjCObjectPointerType *Type = 10235 LHS->getType()->getAs<ObjCObjectPointerType>(); 10236 10237 // If this is not actually an Objective-C object, bail out. 10238 if (!Type) 10239 return false; 10240 10241 // Get the LHS object's interface type. 10242 QualType InterfaceType = Type->getPointeeType(); 10243 10244 // If the RHS isn't an Objective-C object, bail out. 10245 if (!RHS->getType()->isObjCObjectPointerType()) 10246 return false; 10247 10248 // Try to find the -isEqual: method. 10249 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10250 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10251 InterfaceType, 10252 /*IsInstance=*/true); 10253 if (!Method) { 10254 if (Type->isObjCIdType()) { 10255 // For 'id', just check the global pool. 10256 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10257 /*receiverId=*/true); 10258 } else { 10259 // Check protocols. 10260 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10261 /*IsInstance=*/true); 10262 } 10263 } 10264 10265 if (!Method) 10266 return false; 10267 10268 QualType T = Method->parameters()[0]->getType(); 10269 if (!T->isObjCObjectPointerType()) 10270 return false; 10271 10272 QualType R = Method->getReturnType(); 10273 if (!R->isScalarType()) 10274 return false; 10275 10276 return true; 10277 } 10278 10279 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10280 FromE = FromE->IgnoreParenImpCasts(); 10281 switch (FromE->getStmtClass()) { 10282 default: 10283 break; 10284 case Stmt::ObjCStringLiteralClass: 10285 // "string literal" 10286 return LK_String; 10287 case Stmt::ObjCArrayLiteralClass: 10288 // "array literal" 10289 return LK_Array; 10290 case Stmt::ObjCDictionaryLiteralClass: 10291 // "dictionary literal" 10292 return LK_Dictionary; 10293 case Stmt::BlockExprClass: 10294 return LK_Block; 10295 case Stmt::ObjCBoxedExprClass: { 10296 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10297 switch (Inner->getStmtClass()) { 10298 case Stmt::IntegerLiteralClass: 10299 case Stmt::FloatingLiteralClass: 10300 case Stmt::CharacterLiteralClass: 10301 case Stmt::ObjCBoolLiteralExprClass: 10302 case Stmt::CXXBoolLiteralExprClass: 10303 // "numeric literal" 10304 return LK_Numeric; 10305 case Stmt::ImplicitCastExprClass: { 10306 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10307 // Boolean literals can be represented by implicit casts. 10308 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10309 return LK_Numeric; 10310 break; 10311 } 10312 default: 10313 break; 10314 } 10315 return LK_Boxed; 10316 } 10317 } 10318 return LK_None; 10319 } 10320 10321 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10322 ExprResult &LHS, ExprResult &RHS, 10323 BinaryOperator::Opcode Opc){ 10324 Expr *Literal; 10325 Expr *Other; 10326 if (isObjCObjectLiteral(LHS)) { 10327 Literal = LHS.get(); 10328 Other = RHS.get(); 10329 } else { 10330 Literal = RHS.get(); 10331 Other = LHS.get(); 10332 } 10333 10334 // Don't warn on comparisons against nil. 10335 Other = Other->IgnoreParenCasts(); 10336 if (Other->isNullPointerConstant(S.getASTContext(), 10337 Expr::NPC_ValueDependentIsNotNull)) 10338 return; 10339 10340 // This should be kept in sync with warn_objc_literal_comparison. 10341 // LK_String should always be after the other literals, since it has its own 10342 // warning flag. 10343 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10344 assert(LiteralKind != Sema::LK_Block); 10345 if (LiteralKind == Sema::LK_None) { 10346 llvm_unreachable("Unknown Objective-C object literal kind"); 10347 } 10348 10349 if (LiteralKind == Sema::LK_String) 10350 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10351 << Literal->getSourceRange(); 10352 else 10353 S.Diag(Loc, diag::warn_objc_literal_comparison) 10354 << LiteralKind << Literal->getSourceRange(); 10355 10356 if (BinaryOperator::isEqualityOp(Opc) && 10357 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10358 SourceLocation Start = LHS.get()->getBeginLoc(); 10359 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10360 CharSourceRange OpRange = 10361 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10362 10363 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10364 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10365 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10366 << FixItHint::CreateInsertion(End, "]"); 10367 } 10368 } 10369 10370 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10371 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10372 ExprResult &RHS, SourceLocation Loc, 10373 BinaryOperatorKind Opc) { 10374 // Check that left hand side is !something. 10375 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10376 if (!UO || UO->getOpcode() != UO_LNot) return; 10377 10378 // Only check if the right hand side is non-bool arithmetic type. 10379 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10380 10381 // Make sure that the something in !something is not bool. 10382 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10383 if (SubExpr->isKnownToHaveBooleanValue()) return; 10384 10385 // Emit warning. 10386 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10387 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10388 << Loc << IsBitwiseOp; 10389 10390 // First note suggest !(x < y) 10391 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10392 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10393 FirstClose = S.getLocForEndOfToken(FirstClose); 10394 if (FirstClose.isInvalid()) 10395 FirstOpen = SourceLocation(); 10396 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10397 << IsBitwiseOp 10398 << FixItHint::CreateInsertion(FirstOpen, "(") 10399 << FixItHint::CreateInsertion(FirstClose, ")"); 10400 10401 // Second note suggests (!x) < y 10402 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10403 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10404 SecondClose = S.getLocForEndOfToken(SecondClose); 10405 if (SecondClose.isInvalid()) 10406 SecondOpen = SourceLocation(); 10407 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10408 << FixItHint::CreateInsertion(SecondOpen, "(") 10409 << FixItHint::CreateInsertion(SecondClose, ")"); 10410 } 10411 10412 // Returns true if E refers to a non-weak array. 10413 static bool checkForArray(const Expr *E) { 10414 const ValueDecl *D = nullptr; 10415 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10416 D = DR->getDecl(); 10417 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10418 if (Mem->isImplicitAccess()) 10419 D = Mem->getMemberDecl(); 10420 } 10421 if (!D) 10422 return false; 10423 return D->getType()->isArrayType() && !D->isWeak(); 10424 } 10425 10426 /// Diagnose some forms of syntactically-obvious tautological comparison. 10427 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10428 Expr *LHS, Expr *RHS, 10429 BinaryOperatorKind Opc) { 10430 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10431 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10432 10433 QualType LHSType = LHS->getType(); 10434 QualType RHSType = RHS->getType(); 10435 if (LHSType->hasFloatingRepresentation() || 10436 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10437 S.inTemplateInstantiation()) 10438 return; 10439 10440 // Comparisons between two array types are ill-formed for operator<=>, so 10441 // we shouldn't emit any additional warnings about it. 10442 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10443 return; 10444 10445 // For non-floating point types, check for self-comparisons of the form 10446 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10447 // often indicate logic errors in the program. 10448 // 10449 // NOTE: Don't warn about comparison expressions resulting from macro 10450 // expansion. Also don't warn about comparisons which are only self 10451 // comparisons within a template instantiation. The warnings should catch 10452 // obvious cases in the definition of the template anyways. The idea is to 10453 // warn when the typed comparison operator will always evaluate to the same 10454 // result. 10455 10456 // Used for indexing into %select in warn_comparison_always 10457 enum { 10458 AlwaysConstant, 10459 AlwaysTrue, 10460 AlwaysFalse, 10461 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10462 }; 10463 10464 // C++2a [depr.array.comp]: 10465 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10466 // operands of array type are deprecated. 10467 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10468 RHSStripped->getType()->isArrayType()) { 10469 S.Diag(Loc, diag::warn_depr_array_comparison) 10470 << LHS->getSourceRange() << RHS->getSourceRange() 10471 << LHSStripped->getType() << RHSStripped->getType(); 10472 // Carry on to produce the tautological comparison warning, if this 10473 // expression is potentially-evaluated, we can resolve the array to a 10474 // non-weak declaration, and so on. 10475 } 10476 10477 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10478 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10479 unsigned Result; 10480 switch (Opc) { 10481 case BO_EQ: 10482 case BO_LE: 10483 case BO_GE: 10484 Result = AlwaysTrue; 10485 break; 10486 case BO_NE: 10487 case BO_LT: 10488 case BO_GT: 10489 Result = AlwaysFalse; 10490 break; 10491 case BO_Cmp: 10492 Result = AlwaysEqual; 10493 break; 10494 default: 10495 Result = AlwaysConstant; 10496 break; 10497 } 10498 S.DiagRuntimeBehavior(Loc, nullptr, 10499 S.PDiag(diag::warn_comparison_always) 10500 << 0 /*self-comparison*/ 10501 << Result); 10502 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10503 // What is it always going to evaluate to? 10504 unsigned Result; 10505 switch (Opc) { 10506 case BO_EQ: // e.g. array1 == array2 10507 Result = AlwaysFalse; 10508 break; 10509 case BO_NE: // e.g. array1 != array2 10510 Result = AlwaysTrue; 10511 break; 10512 default: // e.g. array1 <= array2 10513 // The best we can say is 'a constant' 10514 Result = AlwaysConstant; 10515 break; 10516 } 10517 S.DiagRuntimeBehavior(Loc, nullptr, 10518 S.PDiag(diag::warn_comparison_always) 10519 << 1 /*array comparison*/ 10520 << Result); 10521 } 10522 } 10523 10524 if (isa<CastExpr>(LHSStripped)) 10525 LHSStripped = LHSStripped->IgnoreParenCasts(); 10526 if (isa<CastExpr>(RHSStripped)) 10527 RHSStripped = RHSStripped->IgnoreParenCasts(); 10528 10529 // Warn about comparisons against a string constant (unless the other 10530 // operand is null); the user probably wants string comparison function. 10531 Expr *LiteralString = nullptr; 10532 Expr *LiteralStringStripped = nullptr; 10533 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10534 !RHSStripped->isNullPointerConstant(S.Context, 10535 Expr::NPC_ValueDependentIsNull)) { 10536 LiteralString = LHS; 10537 LiteralStringStripped = LHSStripped; 10538 } else if ((isa<StringLiteral>(RHSStripped) || 10539 isa<ObjCEncodeExpr>(RHSStripped)) && 10540 !LHSStripped->isNullPointerConstant(S.Context, 10541 Expr::NPC_ValueDependentIsNull)) { 10542 LiteralString = RHS; 10543 LiteralStringStripped = RHSStripped; 10544 } 10545 10546 if (LiteralString) { 10547 S.DiagRuntimeBehavior(Loc, nullptr, 10548 S.PDiag(diag::warn_stringcompare) 10549 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10550 << LiteralString->getSourceRange()); 10551 } 10552 } 10553 10554 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10555 switch (CK) { 10556 default: { 10557 #ifndef NDEBUG 10558 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10559 << "\n"; 10560 #endif 10561 llvm_unreachable("unhandled cast kind"); 10562 } 10563 case CK_UserDefinedConversion: 10564 return ICK_Identity; 10565 case CK_LValueToRValue: 10566 return ICK_Lvalue_To_Rvalue; 10567 case CK_ArrayToPointerDecay: 10568 return ICK_Array_To_Pointer; 10569 case CK_FunctionToPointerDecay: 10570 return ICK_Function_To_Pointer; 10571 case CK_IntegralCast: 10572 return ICK_Integral_Conversion; 10573 case CK_FloatingCast: 10574 return ICK_Floating_Conversion; 10575 case CK_IntegralToFloating: 10576 case CK_FloatingToIntegral: 10577 return ICK_Floating_Integral; 10578 case CK_IntegralComplexCast: 10579 case CK_FloatingComplexCast: 10580 case CK_FloatingComplexToIntegralComplex: 10581 case CK_IntegralComplexToFloatingComplex: 10582 return ICK_Complex_Conversion; 10583 case CK_FloatingComplexToReal: 10584 case CK_FloatingRealToComplex: 10585 case CK_IntegralComplexToReal: 10586 case CK_IntegralRealToComplex: 10587 return ICK_Complex_Real; 10588 } 10589 } 10590 10591 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10592 QualType FromType, 10593 SourceLocation Loc) { 10594 // Check for a narrowing implicit conversion. 10595 StandardConversionSequence SCS; 10596 SCS.setAsIdentityConversion(); 10597 SCS.setToType(0, FromType); 10598 SCS.setToType(1, ToType); 10599 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10600 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10601 10602 APValue PreNarrowingValue; 10603 QualType PreNarrowingType; 10604 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10605 PreNarrowingType, 10606 /*IgnoreFloatToIntegralConversion*/ true)) { 10607 case NK_Dependent_Narrowing: 10608 // Implicit conversion to a narrower type, but the expression is 10609 // value-dependent so we can't tell whether it's actually narrowing. 10610 case NK_Not_Narrowing: 10611 return false; 10612 10613 case NK_Constant_Narrowing: 10614 // Implicit conversion to a narrower type, and the value is not a constant 10615 // expression. 10616 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10617 << /*Constant*/ 1 10618 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10619 return true; 10620 10621 case NK_Variable_Narrowing: 10622 // Implicit conversion to a narrower type, and the value is not a constant 10623 // expression. 10624 case NK_Type_Narrowing: 10625 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10626 << /*Constant*/ 0 << FromType << ToType; 10627 // TODO: It's not a constant expression, but what if the user intended it 10628 // to be? Can we produce notes to help them figure out why it isn't? 10629 return true; 10630 } 10631 llvm_unreachable("unhandled case in switch"); 10632 } 10633 10634 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10635 ExprResult &LHS, 10636 ExprResult &RHS, 10637 SourceLocation Loc) { 10638 QualType LHSType = LHS.get()->getType(); 10639 QualType RHSType = RHS.get()->getType(); 10640 // Dig out the original argument type and expression before implicit casts 10641 // were applied. These are the types/expressions we need to check the 10642 // [expr.spaceship] requirements against. 10643 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10644 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10645 QualType LHSStrippedType = LHSStripped.get()->getType(); 10646 QualType RHSStrippedType = RHSStripped.get()->getType(); 10647 10648 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10649 // other is not, the program is ill-formed. 10650 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10651 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10652 return QualType(); 10653 } 10654 10655 // FIXME: Consider combining this with checkEnumArithmeticConversions. 10656 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10657 RHSStrippedType->isEnumeralType(); 10658 if (NumEnumArgs == 1) { 10659 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10660 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10661 if (OtherTy->hasFloatingRepresentation()) { 10662 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10663 return QualType(); 10664 } 10665 } 10666 if (NumEnumArgs == 2) { 10667 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10668 // type E, the operator yields the result of converting the operands 10669 // to the underlying type of E and applying <=> to the converted operands. 10670 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10671 S.InvalidOperands(Loc, LHS, RHS); 10672 return QualType(); 10673 } 10674 QualType IntType = 10675 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10676 assert(IntType->isArithmeticType()); 10677 10678 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10679 // promote the boolean type, and all other promotable integer types, to 10680 // avoid this. 10681 if (IntType->isPromotableIntegerType()) 10682 IntType = S.Context.getPromotedIntegerType(IntType); 10683 10684 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10685 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10686 LHSType = RHSType = IntType; 10687 } 10688 10689 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10690 // usual arithmetic conversions are applied to the operands. 10691 QualType Type = 10692 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10693 if (LHS.isInvalid() || RHS.isInvalid()) 10694 return QualType(); 10695 if (Type.isNull()) 10696 return S.InvalidOperands(Loc, LHS, RHS); 10697 10698 Optional<ComparisonCategoryType> CCT = 10699 getComparisonCategoryForBuiltinCmp(Type); 10700 if (!CCT) 10701 return S.InvalidOperands(Loc, LHS, RHS); 10702 10703 bool HasNarrowing = checkThreeWayNarrowingConversion( 10704 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10705 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10706 RHS.get()->getBeginLoc()); 10707 if (HasNarrowing) 10708 return QualType(); 10709 10710 assert(!Type.isNull() && "composite type for <=> has not been set"); 10711 10712 return S.CheckComparisonCategoryType( 10713 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 10714 } 10715 10716 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10717 ExprResult &RHS, 10718 SourceLocation Loc, 10719 BinaryOperatorKind Opc) { 10720 if (Opc == BO_Cmp) 10721 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10722 10723 // C99 6.5.8p3 / C99 6.5.9p4 10724 QualType Type = 10725 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10726 if (LHS.isInvalid() || RHS.isInvalid()) 10727 return QualType(); 10728 if (Type.isNull()) 10729 return S.InvalidOperands(Loc, LHS, RHS); 10730 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10731 10732 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10733 return S.InvalidOperands(Loc, LHS, RHS); 10734 10735 // Check for comparisons of floating point operands using != and ==. 10736 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10737 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10738 10739 // The result of comparisons is 'bool' in C++, 'int' in C. 10740 return S.Context.getLogicalOperationType(); 10741 } 10742 10743 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10744 if (!NullE.get()->getType()->isAnyPointerType()) 10745 return; 10746 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10747 if (!E.get()->getType()->isAnyPointerType() && 10748 E.get()->isNullPointerConstant(Context, 10749 Expr::NPC_ValueDependentIsNotNull) == 10750 Expr::NPCK_ZeroExpression) { 10751 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10752 if (CL->getValue() == 0) 10753 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10754 << NullValue 10755 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10756 NullValue ? "NULL" : "(void *)0"); 10757 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10758 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10759 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10760 if (T == Context.CharTy) 10761 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10762 << NullValue 10763 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10764 NullValue ? "NULL" : "(void *)0"); 10765 } 10766 } 10767 } 10768 10769 // C99 6.5.8, C++ [expr.rel] 10770 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10771 SourceLocation Loc, 10772 BinaryOperatorKind Opc) { 10773 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10774 bool IsThreeWay = Opc == BO_Cmp; 10775 bool IsOrdered = IsRelational || IsThreeWay; 10776 auto IsAnyPointerType = [](ExprResult E) { 10777 QualType Ty = E.get()->getType(); 10778 return Ty->isPointerType() || Ty->isMemberPointerType(); 10779 }; 10780 10781 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10782 // type, array-to-pointer, ..., conversions are performed on both operands to 10783 // bring them to their composite type. 10784 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10785 // any type-related checks. 10786 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10787 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10788 if (LHS.isInvalid()) 10789 return QualType(); 10790 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10791 if (RHS.isInvalid()) 10792 return QualType(); 10793 } else { 10794 LHS = DefaultLvalueConversion(LHS.get()); 10795 if (LHS.isInvalid()) 10796 return QualType(); 10797 RHS = DefaultLvalueConversion(RHS.get()); 10798 if (RHS.isInvalid()) 10799 return QualType(); 10800 } 10801 10802 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10803 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10804 CheckPtrComparisonWithNullChar(LHS, RHS); 10805 CheckPtrComparisonWithNullChar(RHS, LHS); 10806 } 10807 10808 // Handle vector comparisons separately. 10809 if (LHS.get()->getType()->isVectorType() || 10810 RHS.get()->getType()->isVectorType()) 10811 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10812 10813 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10814 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10815 10816 QualType LHSType = LHS.get()->getType(); 10817 QualType RHSType = RHS.get()->getType(); 10818 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10819 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10820 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10821 10822 const Expr::NullPointerConstantKind LHSNullKind = 10823 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10824 const Expr::NullPointerConstantKind RHSNullKind = 10825 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10826 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10827 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10828 10829 auto computeResultTy = [&]() { 10830 if (Opc != BO_Cmp) 10831 return Context.getLogicalOperationType(); 10832 assert(getLangOpts().CPlusPlus); 10833 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10834 10835 QualType CompositeTy = LHS.get()->getType(); 10836 assert(!CompositeTy->isReferenceType()); 10837 10838 Optional<ComparisonCategoryType> CCT = 10839 getComparisonCategoryForBuiltinCmp(CompositeTy); 10840 if (!CCT) 10841 return InvalidOperands(Loc, LHS, RHS); 10842 10843 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 10844 // P0946R0: Comparisons between a null pointer constant and an object 10845 // pointer result in std::strong_equality, which is ill-formed under 10846 // P1959R0. 10847 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 10848 << (LHSIsNull ? LHS.get()->getSourceRange() 10849 : RHS.get()->getSourceRange()); 10850 return QualType(); 10851 } 10852 10853 return CheckComparisonCategoryType( 10854 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 10855 }; 10856 10857 if (!IsOrdered && LHSIsNull != RHSIsNull) { 10858 bool IsEquality = Opc == BO_EQ; 10859 if (RHSIsNull) 10860 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10861 RHS.get()->getSourceRange()); 10862 else 10863 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10864 LHS.get()->getSourceRange()); 10865 } 10866 10867 if ((LHSType->isIntegerType() && !LHSIsNull) || 10868 (RHSType->isIntegerType() && !RHSIsNull)) { 10869 // Skip normal pointer conversion checks in this case; we have better 10870 // diagnostics for this below. 10871 } else if (getLangOpts().CPlusPlus) { 10872 // Equality comparison of a function pointer to a void pointer is invalid, 10873 // but we allow it as an extension. 10874 // FIXME: If we really want to allow this, should it be part of composite 10875 // pointer type computation so it works in conditionals too? 10876 if (!IsOrdered && 10877 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10878 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10879 // This is a gcc extension compatibility comparison. 10880 // In a SFINAE context, we treat this as a hard error to maintain 10881 // conformance with the C++ standard. 10882 diagnoseFunctionPointerToVoidComparison( 10883 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10884 10885 if (isSFINAEContext()) 10886 return QualType(); 10887 10888 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10889 return computeResultTy(); 10890 } 10891 10892 // C++ [expr.eq]p2: 10893 // If at least one operand is a pointer [...] bring them to their 10894 // composite pointer type. 10895 // C++ [expr.spaceship]p6 10896 // If at least one of the operands is of pointer type, [...] bring them 10897 // to their composite pointer type. 10898 // C++ [expr.rel]p2: 10899 // If both operands are pointers, [...] bring them to their composite 10900 // pointer type. 10901 // For <=>, the only valid non-pointer types are arrays and functions, and 10902 // we already decayed those, so this is really the same as the relational 10903 // comparison rule. 10904 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10905 (IsOrdered ? 2 : 1) && 10906 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10907 RHSType->isObjCObjectPointerType()))) { 10908 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10909 return QualType(); 10910 return computeResultTy(); 10911 } 10912 } else if (LHSType->isPointerType() && 10913 RHSType->isPointerType()) { // C99 6.5.8p2 10914 // All of the following pointer-related warnings are GCC extensions, except 10915 // when handling null pointer constants. 10916 QualType LCanPointeeTy = 10917 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10918 QualType RCanPointeeTy = 10919 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10920 10921 // C99 6.5.9p2 and C99 6.5.8p2 10922 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10923 RCanPointeeTy.getUnqualifiedType())) { 10924 // Valid unless a relational comparison of function pointers 10925 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10926 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10927 << LHSType << RHSType << LHS.get()->getSourceRange() 10928 << RHS.get()->getSourceRange(); 10929 } 10930 } else if (!IsRelational && 10931 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10932 // Valid unless comparison between non-null pointer and function pointer 10933 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10934 && !LHSIsNull && !RHSIsNull) 10935 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10936 /*isError*/false); 10937 } else { 10938 // Invalid 10939 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10940 } 10941 if (LCanPointeeTy != RCanPointeeTy) { 10942 // Treat NULL constant as a special case in OpenCL. 10943 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10944 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10945 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10946 Diag(Loc, 10947 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10948 << LHSType << RHSType << 0 /* comparison */ 10949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10950 } 10951 } 10952 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10953 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10954 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10955 : CK_BitCast; 10956 if (LHSIsNull && !RHSIsNull) 10957 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10958 else 10959 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10960 } 10961 return computeResultTy(); 10962 } 10963 10964 if (getLangOpts().CPlusPlus) { 10965 // C++ [expr.eq]p4: 10966 // Two operands of type std::nullptr_t or one operand of type 10967 // std::nullptr_t and the other a null pointer constant compare equal. 10968 if (!IsOrdered && LHSIsNull && RHSIsNull) { 10969 if (LHSType->isNullPtrType()) { 10970 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10971 return computeResultTy(); 10972 } 10973 if (RHSType->isNullPtrType()) { 10974 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10975 return computeResultTy(); 10976 } 10977 } 10978 10979 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10980 // These aren't covered by the composite pointer type rules. 10981 if (!IsOrdered && RHSType->isNullPtrType() && 10982 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10983 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10984 return computeResultTy(); 10985 } 10986 if (!IsOrdered && LHSType->isNullPtrType() && 10987 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10988 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10989 return computeResultTy(); 10990 } 10991 10992 if (IsRelational && 10993 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10994 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10995 // HACK: Relational comparison of nullptr_t against a pointer type is 10996 // invalid per DR583, but we allow it within std::less<> and friends, 10997 // since otherwise common uses of it break. 10998 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10999 // friends to have std::nullptr_t overload candidates. 11000 DeclContext *DC = CurContext; 11001 if (isa<FunctionDecl>(DC)) 11002 DC = DC->getParent(); 11003 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11004 if (CTSD->isInStdNamespace() && 11005 llvm::StringSwitch<bool>(CTSD->getName()) 11006 .Cases("less", "less_equal", "greater", "greater_equal", true) 11007 .Default(false)) { 11008 if (RHSType->isNullPtrType()) 11009 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11010 else 11011 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11012 return computeResultTy(); 11013 } 11014 } 11015 } 11016 11017 // C++ [expr.eq]p2: 11018 // If at least one operand is a pointer to member, [...] bring them to 11019 // their composite pointer type. 11020 if (!IsOrdered && 11021 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11022 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11023 return QualType(); 11024 else 11025 return computeResultTy(); 11026 } 11027 } 11028 11029 // Handle block pointer types. 11030 if (!IsOrdered && LHSType->isBlockPointerType() && 11031 RHSType->isBlockPointerType()) { 11032 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11033 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11034 11035 if (!LHSIsNull && !RHSIsNull && 11036 !Context.typesAreCompatible(lpointee, rpointee)) { 11037 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11038 << LHSType << RHSType << LHS.get()->getSourceRange() 11039 << RHS.get()->getSourceRange(); 11040 } 11041 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11042 return computeResultTy(); 11043 } 11044 11045 // Allow block pointers to be compared with null pointer constants. 11046 if (!IsOrdered 11047 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11048 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11049 if (!LHSIsNull && !RHSIsNull) { 11050 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11051 ->getPointeeType()->isVoidType()) 11052 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11053 ->getPointeeType()->isVoidType()))) 11054 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11055 << LHSType << RHSType << LHS.get()->getSourceRange() 11056 << RHS.get()->getSourceRange(); 11057 } 11058 if (LHSIsNull && !RHSIsNull) 11059 LHS = ImpCastExprToType(LHS.get(), RHSType, 11060 RHSType->isPointerType() ? CK_BitCast 11061 : CK_AnyPointerToBlockPointerCast); 11062 else 11063 RHS = ImpCastExprToType(RHS.get(), LHSType, 11064 LHSType->isPointerType() ? CK_BitCast 11065 : CK_AnyPointerToBlockPointerCast); 11066 return computeResultTy(); 11067 } 11068 11069 if (LHSType->isObjCObjectPointerType() || 11070 RHSType->isObjCObjectPointerType()) { 11071 const PointerType *LPT = LHSType->getAs<PointerType>(); 11072 const PointerType *RPT = RHSType->getAs<PointerType>(); 11073 if (LPT || RPT) { 11074 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11075 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11076 11077 if (!LPtrToVoid && !RPtrToVoid && 11078 !Context.typesAreCompatible(LHSType, RHSType)) { 11079 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11080 /*isError*/false); 11081 } 11082 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11083 // the RHS, but we have test coverage for this behavior. 11084 // FIXME: Consider using convertPointersToCompositeType in C++. 11085 if (LHSIsNull && !RHSIsNull) { 11086 Expr *E = LHS.get(); 11087 if (getLangOpts().ObjCAutoRefCount) 11088 CheckObjCConversion(SourceRange(), RHSType, E, 11089 CCK_ImplicitConversion); 11090 LHS = ImpCastExprToType(E, RHSType, 11091 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11092 } 11093 else { 11094 Expr *E = RHS.get(); 11095 if (getLangOpts().ObjCAutoRefCount) 11096 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11097 /*Diagnose=*/true, 11098 /*DiagnoseCFAudited=*/false, Opc); 11099 RHS = ImpCastExprToType(E, LHSType, 11100 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11101 } 11102 return computeResultTy(); 11103 } 11104 if (LHSType->isObjCObjectPointerType() && 11105 RHSType->isObjCObjectPointerType()) { 11106 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11107 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11108 /*isError*/false); 11109 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11110 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11111 11112 if (LHSIsNull && !RHSIsNull) 11113 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11114 else 11115 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11116 return computeResultTy(); 11117 } 11118 11119 if (!IsOrdered && LHSType->isBlockPointerType() && 11120 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11121 LHS = ImpCastExprToType(LHS.get(), RHSType, 11122 CK_BlockPointerToObjCPointerCast); 11123 return computeResultTy(); 11124 } else if (!IsOrdered && 11125 LHSType->isBlockCompatibleObjCPointerType(Context) && 11126 RHSType->isBlockPointerType()) { 11127 RHS = ImpCastExprToType(RHS.get(), LHSType, 11128 CK_BlockPointerToObjCPointerCast); 11129 return computeResultTy(); 11130 } 11131 } 11132 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11133 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11134 unsigned DiagID = 0; 11135 bool isError = false; 11136 if (LangOpts.DebuggerSupport) { 11137 // Under a debugger, allow the comparison of pointers to integers, 11138 // since users tend to want to compare addresses. 11139 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11140 (RHSIsNull && RHSType->isIntegerType())) { 11141 if (IsOrdered) { 11142 isError = getLangOpts().CPlusPlus; 11143 DiagID = 11144 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11145 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11146 } 11147 } else if (getLangOpts().CPlusPlus) { 11148 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11149 isError = true; 11150 } else if (IsOrdered) 11151 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11152 else 11153 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11154 11155 if (DiagID) { 11156 Diag(Loc, DiagID) 11157 << LHSType << RHSType << LHS.get()->getSourceRange() 11158 << RHS.get()->getSourceRange(); 11159 if (isError) 11160 return QualType(); 11161 } 11162 11163 if (LHSType->isIntegerType()) 11164 LHS = ImpCastExprToType(LHS.get(), RHSType, 11165 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11166 else 11167 RHS = ImpCastExprToType(RHS.get(), LHSType, 11168 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11169 return computeResultTy(); 11170 } 11171 11172 // Handle block pointers. 11173 if (!IsOrdered && RHSIsNull 11174 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11175 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11176 return computeResultTy(); 11177 } 11178 if (!IsOrdered && LHSIsNull 11179 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11180 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11181 return computeResultTy(); 11182 } 11183 11184 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11185 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11186 return computeResultTy(); 11187 } 11188 11189 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11190 return computeResultTy(); 11191 } 11192 11193 if (LHSIsNull && RHSType->isQueueT()) { 11194 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11195 return computeResultTy(); 11196 } 11197 11198 if (LHSType->isQueueT() && RHSIsNull) { 11199 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11200 return computeResultTy(); 11201 } 11202 } 11203 11204 return InvalidOperands(Loc, LHS, RHS); 11205 } 11206 11207 // Return a signed ext_vector_type that is of identical size and number of 11208 // elements. For floating point vectors, return an integer type of identical 11209 // size and number of elements. In the non ext_vector_type case, search from 11210 // the largest type to the smallest type to avoid cases where long long == long, 11211 // where long gets picked over long long. 11212 QualType Sema::GetSignedVectorType(QualType V) { 11213 const VectorType *VTy = V->castAs<VectorType>(); 11214 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11215 11216 if (isa<ExtVectorType>(VTy)) { 11217 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11218 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11219 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11220 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11221 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11222 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11223 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11224 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11225 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11226 "Unhandled vector element size in vector compare"); 11227 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11228 } 11229 11230 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11231 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11232 VectorType::GenericVector); 11233 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11234 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11235 VectorType::GenericVector); 11236 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11237 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11238 VectorType::GenericVector); 11239 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11240 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11241 VectorType::GenericVector); 11242 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11243 "Unhandled vector element size in vector compare"); 11244 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11245 VectorType::GenericVector); 11246 } 11247 11248 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11249 /// operates on extended vector types. Instead of producing an IntTy result, 11250 /// like a scalar comparison, a vector comparison produces a vector of integer 11251 /// types. 11252 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11253 SourceLocation Loc, 11254 BinaryOperatorKind Opc) { 11255 if (Opc == BO_Cmp) { 11256 Diag(Loc, diag::err_three_way_vector_comparison); 11257 return QualType(); 11258 } 11259 11260 // Check to make sure we're operating on vectors of the same type and width, 11261 // Allowing one side to be a scalar of element type. 11262 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11263 /*AllowBothBool*/true, 11264 /*AllowBoolConversions*/getLangOpts().ZVector); 11265 if (vType.isNull()) 11266 return vType; 11267 11268 QualType LHSType = LHS.get()->getType(); 11269 11270 // If AltiVec, the comparison results in a numeric type, i.e. 11271 // bool for C++, int for C 11272 if (getLangOpts().AltiVec && 11273 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11274 return Context.getLogicalOperationType(); 11275 11276 // For non-floating point types, check for self-comparisons of the form 11277 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11278 // often indicate logic errors in the program. 11279 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11280 11281 // Check for comparisons of floating point operands using != and ==. 11282 if (BinaryOperator::isEqualityOp(Opc) && 11283 LHSType->hasFloatingRepresentation()) { 11284 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11285 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11286 } 11287 11288 // Return a signed type for the vector. 11289 return GetSignedVectorType(vType); 11290 } 11291 11292 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11293 const ExprResult &XorRHS, 11294 const SourceLocation Loc) { 11295 // Do not diagnose macros. 11296 if (Loc.isMacroID()) 11297 return; 11298 11299 bool Negative = false; 11300 bool ExplicitPlus = false; 11301 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11302 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11303 11304 if (!LHSInt) 11305 return; 11306 if (!RHSInt) { 11307 // Check negative literals. 11308 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11309 UnaryOperatorKind Opc = UO->getOpcode(); 11310 if (Opc != UO_Minus && Opc != UO_Plus) 11311 return; 11312 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11313 if (!RHSInt) 11314 return; 11315 Negative = (Opc == UO_Minus); 11316 ExplicitPlus = !Negative; 11317 } else { 11318 return; 11319 } 11320 } 11321 11322 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11323 llvm::APInt RightSideValue = RHSInt->getValue(); 11324 if (LeftSideValue != 2 && LeftSideValue != 10) 11325 return; 11326 11327 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11328 return; 11329 11330 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11331 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11332 llvm::StringRef ExprStr = 11333 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11334 11335 CharSourceRange XorRange = 11336 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11337 llvm::StringRef XorStr = 11338 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11339 // Do not diagnose if xor keyword/macro is used. 11340 if (XorStr == "xor") 11341 return; 11342 11343 std::string LHSStr = std::string(Lexer::getSourceText( 11344 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11345 S.getSourceManager(), S.getLangOpts())); 11346 std::string RHSStr = std::string(Lexer::getSourceText( 11347 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11348 S.getSourceManager(), S.getLangOpts())); 11349 11350 if (Negative) { 11351 RightSideValue = -RightSideValue; 11352 RHSStr = "-" + RHSStr; 11353 } else if (ExplicitPlus) { 11354 RHSStr = "+" + RHSStr; 11355 } 11356 11357 StringRef LHSStrRef = LHSStr; 11358 StringRef RHSStrRef = RHSStr; 11359 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11360 // literals. 11361 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11362 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11363 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11364 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11365 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11366 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11367 LHSStrRef.find('\'') != StringRef::npos || 11368 RHSStrRef.find('\'') != StringRef::npos) 11369 return; 11370 11371 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11372 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11373 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11374 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11375 std::string SuggestedExpr = "1 << " + RHSStr; 11376 bool Overflow = false; 11377 llvm::APInt One = (LeftSideValue - 1); 11378 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11379 if (Overflow) { 11380 if (RightSideIntValue < 64) 11381 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11382 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11383 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11384 else if (RightSideIntValue == 64) 11385 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11386 else 11387 return; 11388 } else { 11389 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11390 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11391 << PowValue.toString(10, true) 11392 << FixItHint::CreateReplacement( 11393 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11394 } 11395 11396 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11397 } else if (LeftSideValue == 10) { 11398 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11399 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11400 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11401 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11402 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11403 } 11404 } 11405 11406 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11407 SourceLocation Loc) { 11408 // Ensure that either both operands are of the same vector type, or 11409 // one operand is of a vector type and the other is of its element type. 11410 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11411 /*AllowBothBool*/true, 11412 /*AllowBoolConversions*/false); 11413 if (vType.isNull()) 11414 return InvalidOperands(Loc, LHS, RHS); 11415 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11416 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11417 return InvalidOperands(Loc, LHS, RHS); 11418 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11419 // usage of the logical operators && and || with vectors in C. This 11420 // check could be notionally dropped. 11421 if (!getLangOpts().CPlusPlus && 11422 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11423 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11424 11425 return GetSignedVectorType(LHS.get()->getType()); 11426 } 11427 11428 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11429 SourceLocation Loc, 11430 BinaryOperatorKind Opc) { 11431 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11432 11433 bool IsCompAssign = 11434 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11435 11436 if (LHS.get()->getType()->isVectorType() || 11437 RHS.get()->getType()->isVectorType()) { 11438 if (LHS.get()->getType()->hasIntegerRepresentation() && 11439 RHS.get()->getType()->hasIntegerRepresentation()) 11440 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11441 /*AllowBothBool*/true, 11442 /*AllowBoolConversions*/getLangOpts().ZVector); 11443 return InvalidOperands(Loc, LHS, RHS); 11444 } 11445 11446 if (Opc == BO_And) 11447 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11448 11449 if (LHS.get()->getType()->hasFloatingRepresentation() || 11450 RHS.get()->getType()->hasFloatingRepresentation()) 11451 return InvalidOperands(Loc, LHS, RHS); 11452 11453 ExprResult LHSResult = LHS, RHSResult = RHS; 11454 QualType compType = UsualArithmeticConversions( 11455 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11456 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11457 return QualType(); 11458 LHS = LHSResult.get(); 11459 RHS = RHSResult.get(); 11460 11461 if (Opc == BO_Xor) 11462 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11463 11464 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11465 return compType; 11466 return InvalidOperands(Loc, LHS, RHS); 11467 } 11468 11469 // C99 6.5.[13,14] 11470 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11471 SourceLocation Loc, 11472 BinaryOperatorKind Opc) { 11473 // Check vector operands differently. 11474 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11475 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11476 11477 bool EnumConstantInBoolContext = false; 11478 for (const ExprResult &HS : {LHS, RHS}) { 11479 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11480 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11481 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11482 EnumConstantInBoolContext = true; 11483 } 11484 } 11485 11486 if (EnumConstantInBoolContext) 11487 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11488 11489 // Diagnose cases where the user write a logical and/or but probably meant a 11490 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11491 // is a constant. 11492 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11493 !LHS.get()->getType()->isBooleanType() && 11494 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11495 // Don't warn in macros or template instantiations. 11496 !Loc.isMacroID() && !inTemplateInstantiation()) { 11497 // If the RHS can be constant folded, and if it constant folds to something 11498 // that isn't 0 or 1 (which indicate a potential logical operation that 11499 // happened to fold to true/false) then warn. 11500 // Parens on the RHS are ignored. 11501 Expr::EvalResult EVResult; 11502 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11503 llvm::APSInt Result = EVResult.Val.getInt(); 11504 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11505 !RHS.get()->getExprLoc().isMacroID()) || 11506 (Result != 0 && Result != 1)) { 11507 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11508 << RHS.get()->getSourceRange() 11509 << (Opc == BO_LAnd ? "&&" : "||"); 11510 // Suggest replacing the logical operator with the bitwise version 11511 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11512 << (Opc == BO_LAnd ? "&" : "|") 11513 << FixItHint::CreateReplacement(SourceRange( 11514 Loc, getLocForEndOfToken(Loc)), 11515 Opc == BO_LAnd ? "&" : "|"); 11516 if (Opc == BO_LAnd) 11517 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11518 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11519 << FixItHint::CreateRemoval( 11520 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11521 RHS.get()->getEndLoc())); 11522 } 11523 } 11524 } 11525 11526 if (!Context.getLangOpts().CPlusPlus) { 11527 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11528 // not operate on the built-in scalar and vector float types. 11529 if (Context.getLangOpts().OpenCL && 11530 Context.getLangOpts().OpenCLVersion < 120) { 11531 if (LHS.get()->getType()->isFloatingType() || 11532 RHS.get()->getType()->isFloatingType()) 11533 return InvalidOperands(Loc, LHS, RHS); 11534 } 11535 11536 LHS = UsualUnaryConversions(LHS.get()); 11537 if (LHS.isInvalid()) 11538 return QualType(); 11539 11540 RHS = UsualUnaryConversions(RHS.get()); 11541 if (RHS.isInvalid()) 11542 return QualType(); 11543 11544 if (!LHS.get()->getType()->isScalarType() || 11545 !RHS.get()->getType()->isScalarType()) 11546 return InvalidOperands(Loc, LHS, RHS); 11547 11548 return Context.IntTy; 11549 } 11550 11551 // The following is safe because we only use this method for 11552 // non-overloadable operands. 11553 11554 // C++ [expr.log.and]p1 11555 // C++ [expr.log.or]p1 11556 // The operands are both contextually converted to type bool. 11557 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11558 if (LHSRes.isInvalid()) 11559 return InvalidOperands(Loc, LHS, RHS); 11560 LHS = LHSRes; 11561 11562 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11563 if (RHSRes.isInvalid()) 11564 return InvalidOperands(Loc, LHS, RHS); 11565 RHS = RHSRes; 11566 11567 // C++ [expr.log.and]p2 11568 // C++ [expr.log.or]p2 11569 // The result is a bool. 11570 return Context.BoolTy; 11571 } 11572 11573 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11574 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11575 if (!ME) return false; 11576 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11577 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11578 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11579 if (!Base) return false; 11580 return Base->getMethodDecl() != nullptr; 11581 } 11582 11583 /// Is the given expression (which must be 'const') a reference to a 11584 /// variable which was originally non-const, but which has become 11585 /// 'const' due to being captured within a block? 11586 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11587 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11588 assert(E->isLValue() && E->getType().isConstQualified()); 11589 E = E->IgnoreParens(); 11590 11591 // Must be a reference to a declaration from an enclosing scope. 11592 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11593 if (!DRE) return NCCK_None; 11594 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11595 11596 // The declaration must be a variable which is not declared 'const'. 11597 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11598 if (!var) return NCCK_None; 11599 if (var->getType().isConstQualified()) return NCCK_None; 11600 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11601 11602 // Decide whether the first capture was for a block or a lambda. 11603 DeclContext *DC = S.CurContext, *Prev = nullptr; 11604 // Decide whether the first capture was for a block or a lambda. 11605 while (DC) { 11606 // For init-capture, it is possible that the variable belongs to the 11607 // template pattern of the current context. 11608 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11609 if (var->isInitCapture() && 11610 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11611 break; 11612 if (DC == var->getDeclContext()) 11613 break; 11614 Prev = DC; 11615 DC = DC->getParent(); 11616 } 11617 // Unless we have an init-capture, we've gone one step too far. 11618 if (!var->isInitCapture()) 11619 DC = Prev; 11620 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11621 } 11622 11623 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11624 Ty = Ty.getNonReferenceType(); 11625 if (IsDereference && Ty->isPointerType()) 11626 Ty = Ty->getPointeeType(); 11627 return !Ty.isConstQualified(); 11628 } 11629 11630 // Update err_typecheck_assign_const and note_typecheck_assign_const 11631 // when this enum is changed. 11632 enum { 11633 ConstFunction, 11634 ConstVariable, 11635 ConstMember, 11636 ConstMethod, 11637 NestedConstMember, 11638 ConstUnknown, // Keep as last element 11639 }; 11640 11641 /// Emit the "read-only variable not assignable" error and print notes to give 11642 /// more information about why the variable is not assignable, such as pointing 11643 /// to the declaration of a const variable, showing that a method is const, or 11644 /// that the function is returning a const reference. 11645 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11646 SourceLocation Loc) { 11647 SourceRange ExprRange = E->getSourceRange(); 11648 11649 // Only emit one error on the first const found. All other consts will emit 11650 // a note to the error. 11651 bool DiagnosticEmitted = false; 11652 11653 // Track if the current expression is the result of a dereference, and if the 11654 // next checked expression is the result of a dereference. 11655 bool IsDereference = false; 11656 bool NextIsDereference = false; 11657 11658 // Loop to process MemberExpr chains. 11659 while (true) { 11660 IsDereference = NextIsDereference; 11661 11662 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11663 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11664 NextIsDereference = ME->isArrow(); 11665 const ValueDecl *VD = ME->getMemberDecl(); 11666 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11667 // Mutable fields can be modified even if the class is const. 11668 if (Field->isMutable()) { 11669 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11670 break; 11671 } 11672 11673 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11674 if (!DiagnosticEmitted) { 11675 S.Diag(Loc, diag::err_typecheck_assign_const) 11676 << ExprRange << ConstMember << false /*static*/ << Field 11677 << Field->getType(); 11678 DiagnosticEmitted = true; 11679 } 11680 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11681 << ConstMember << false /*static*/ << Field << Field->getType() 11682 << Field->getSourceRange(); 11683 } 11684 E = ME->getBase(); 11685 continue; 11686 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11687 if (VDecl->getType().isConstQualified()) { 11688 if (!DiagnosticEmitted) { 11689 S.Diag(Loc, diag::err_typecheck_assign_const) 11690 << ExprRange << ConstMember << true /*static*/ << VDecl 11691 << VDecl->getType(); 11692 DiagnosticEmitted = true; 11693 } 11694 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11695 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11696 << VDecl->getSourceRange(); 11697 } 11698 // Static fields do not inherit constness from parents. 11699 break; 11700 } 11701 break; // End MemberExpr 11702 } else if (const ArraySubscriptExpr *ASE = 11703 dyn_cast<ArraySubscriptExpr>(E)) { 11704 E = ASE->getBase()->IgnoreParenImpCasts(); 11705 continue; 11706 } else if (const ExtVectorElementExpr *EVE = 11707 dyn_cast<ExtVectorElementExpr>(E)) { 11708 E = EVE->getBase()->IgnoreParenImpCasts(); 11709 continue; 11710 } 11711 break; 11712 } 11713 11714 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11715 // Function calls 11716 const FunctionDecl *FD = CE->getDirectCallee(); 11717 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11718 if (!DiagnosticEmitted) { 11719 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11720 << ConstFunction << FD; 11721 DiagnosticEmitted = true; 11722 } 11723 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11724 diag::note_typecheck_assign_const) 11725 << ConstFunction << FD << FD->getReturnType() 11726 << FD->getReturnTypeSourceRange(); 11727 } 11728 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11729 // Point to variable declaration. 11730 if (const ValueDecl *VD = DRE->getDecl()) { 11731 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11732 if (!DiagnosticEmitted) { 11733 S.Diag(Loc, diag::err_typecheck_assign_const) 11734 << ExprRange << ConstVariable << VD << VD->getType(); 11735 DiagnosticEmitted = true; 11736 } 11737 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11738 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11739 } 11740 } 11741 } else if (isa<CXXThisExpr>(E)) { 11742 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11743 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11744 if (MD->isConst()) { 11745 if (!DiagnosticEmitted) { 11746 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11747 << ConstMethod << MD; 11748 DiagnosticEmitted = true; 11749 } 11750 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11751 << ConstMethod << MD << MD->getSourceRange(); 11752 } 11753 } 11754 } 11755 } 11756 11757 if (DiagnosticEmitted) 11758 return; 11759 11760 // Can't determine a more specific message, so display the generic error. 11761 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11762 } 11763 11764 enum OriginalExprKind { 11765 OEK_Variable, 11766 OEK_Member, 11767 OEK_LValue 11768 }; 11769 11770 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11771 const RecordType *Ty, 11772 SourceLocation Loc, SourceRange Range, 11773 OriginalExprKind OEK, 11774 bool &DiagnosticEmitted) { 11775 std::vector<const RecordType *> RecordTypeList; 11776 RecordTypeList.push_back(Ty); 11777 unsigned NextToCheckIndex = 0; 11778 // We walk the record hierarchy breadth-first to ensure that we print 11779 // diagnostics in field nesting order. 11780 while (RecordTypeList.size() > NextToCheckIndex) { 11781 bool IsNested = NextToCheckIndex > 0; 11782 for (const FieldDecl *Field : 11783 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11784 // First, check every field for constness. 11785 QualType FieldTy = Field->getType(); 11786 if (FieldTy.isConstQualified()) { 11787 if (!DiagnosticEmitted) { 11788 S.Diag(Loc, diag::err_typecheck_assign_const) 11789 << Range << NestedConstMember << OEK << VD 11790 << IsNested << Field; 11791 DiagnosticEmitted = true; 11792 } 11793 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11794 << NestedConstMember << IsNested << Field 11795 << FieldTy << Field->getSourceRange(); 11796 } 11797 11798 // Then we append it to the list to check next in order. 11799 FieldTy = FieldTy.getCanonicalType(); 11800 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11801 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11802 RecordTypeList.push_back(FieldRecTy); 11803 } 11804 } 11805 ++NextToCheckIndex; 11806 } 11807 } 11808 11809 /// Emit an error for the case where a record we are trying to assign to has a 11810 /// const-qualified field somewhere in its hierarchy. 11811 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11812 SourceLocation Loc) { 11813 QualType Ty = E->getType(); 11814 assert(Ty->isRecordType() && "lvalue was not record?"); 11815 SourceRange Range = E->getSourceRange(); 11816 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11817 bool DiagEmitted = false; 11818 11819 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11820 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11821 Range, OEK_Member, DiagEmitted); 11822 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11823 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11824 Range, OEK_Variable, DiagEmitted); 11825 else 11826 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11827 Range, OEK_LValue, DiagEmitted); 11828 if (!DiagEmitted) 11829 DiagnoseConstAssignment(S, E, Loc); 11830 } 11831 11832 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11833 /// emit an error and return true. If so, return false. 11834 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11835 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11836 11837 S.CheckShadowingDeclModification(E, Loc); 11838 11839 SourceLocation OrigLoc = Loc; 11840 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11841 &Loc); 11842 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11843 IsLV = Expr::MLV_InvalidMessageExpression; 11844 if (IsLV == Expr::MLV_Valid) 11845 return false; 11846 11847 unsigned DiagID = 0; 11848 bool NeedType = false; 11849 switch (IsLV) { // C99 6.5.16p2 11850 case Expr::MLV_ConstQualified: 11851 // Use a specialized diagnostic when we're assigning to an object 11852 // from an enclosing function or block. 11853 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11854 if (NCCK == NCCK_Block) 11855 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11856 else 11857 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11858 break; 11859 } 11860 11861 // In ARC, use some specialized diagnostics for occasions where we 11862 // infer 'const'. These are always pseudo-strong variables. 11863 if (S.getLangOpts().ObjCAutoRefCount) { 11864 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11865 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11866 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11867 11868 // Use the normal diagnostic if it's pseudo-__strong but the 11869 // user actually wrote 'const'. 11870 if (var->isARCPseudoStrong() && 11871 (!var->getTypeSourceInfo() || 11872 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11873 // There are three pseudo-strong cases: 11874 // - self 11875 ObjCMethodDecl *method = S.getCurMethodDecl(); 11876 if (method && var == method->getSelfDecl()) { 11877 DiagID = method->isClassMethod() 11878 ? diag::err_typecheck_arc_assign_self_class_method 11879 : diag::err_typecheck_arc_assign_self; 11880 11881 // - Objective-C externally_retained attribute. 11882 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11883 isa<ParmVarDecl>(var)) { 11884 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11885 11886 // - fast enumeration variables 11887 } else { 11888 DiagID = diag::err_typecheck_arr_assign_enumeration; 11889 } 11890 11891 SourceRange Assign; 11892 if (Loc != OrigLoc) 11893 Assign = SourceRange(OrigLoc, OrigLoc); 11894 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11895 // We need to preserve the AST regardless, so migration tool 11896 // can do its job. 11897 return false; 11898 } 11899 } 11900 } 11901 11902 // If none of the special cases above are triggered, then this is a 11903 // simple const assignment. 11904 if (DiagID == 0) { 11905 DiagnoseConstAssignment(S, E, Loc); 11906 return true; 11907 } 11908 11909 break; 11910 case Expr::MLV_ConstAddrSpace: 11911 DiagnoseConstAssignment(S, E, Loc); 11912 return true; 11913 case Expr::MLV_ConstQualifiedField: 11914 DiagnoseRecursiveConstFields(S, E, Loc); 11915 return true; 11916 case Expr::MLV_ArrayType: 11917 case Expr::MLV_ArrayTemporary: 11918 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11919 NeedType = true; 11920 break; 11921 case Expr::MLV_NotObjectType: 11922 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11923 NeedType = true; 11924 break; 11925 case Expr::MLV_LValueCast: 11926 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11927 break; 11928 case Expr::MLV_Valid: 11929 llvm_unreachable("did not take early return for MLV_Valid"); 11930 case Expr::MLV_InvalidExpression: 11931 case Expr::MLV_MemberFunction: 11932 case Expr::MLV_ClassTemporary: 11933 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11934 break; 11935 case Expr::MLV_IncompleteType: 11936 case Expr::MLV_IncompleteVoidType: 11937 return S.RequireCompleteType(Loc, E->getType(), 11938 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11939 case Expr::MLV_DuplicateVectorComponents: 11940 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11941 break; 11942 case Expr::MLV_NoSetterProperty: 11943 llvm_unreachable("readonly properties should be processed differently"); 11944 case Expr::MLV_InvalidMessageExpression: 11945 DiagID = diag::err_readonly_message_assignment; 11946 break; 11947 case Expr::MLV_SubObjCPropertySetting: 11948 DiagID = diag::err_no_subobject_property_setting; 11949 break; 11950 } 11951 11952 SourceRange Assign; 11953 if (Loc != OrigLoc) 11954 Assign = SourceRange(OrigLoc, OrigLoc); 11955 if (NeedType) 11956 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11957 else 11958 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11959 return true; 11960 } 11961 11962 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11963 SourceLocation Loc, 11964 Sema &Sema) { 11965 if (Sema.inTemplateInstantiation()) 11966 return; 11967 if (Sema.isUnevaluatedContext()) 11968 return; 11969 if (Loc.isInvalid() || Loc.isMacroID()) 11970 return; 11971 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11972 return; 11973 11974 // C / C++ fields 11975 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11976 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11977 if (ML && MR) { 11978 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11979 return; 11980 const ValueDecl *LHSDecl = 11981 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11982 const ValueDecl *RHSDecl = 11983 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11984 if (LHSDecl != RHSDecl) 11985 return; 11986 if (LHSDecl->getType().isVolatileQualified()) 11987 return; 11988 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11989 if (RefTy->getPointeeType().isVolatileQualified()) 11990 return; 11991 11992 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11993 } 11994 11995 // Objective-C instance variables 11996 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11997 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11998 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11999 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12000 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12001 if (RL && RR && RL->getDecl() == RR->getDecl()) 12002 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12003 } 12004 } 12005 12006 // C99 6.5.16.1 12007 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12008 SourceLocation Loc, 12009 QualType CompoundType) { 12010 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12011 12012 // Verify that LHS is a modifiable lvalue, and emit error if not. 12013 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12014 return QualType(); 12015 12016 QualType LHSType = LHSExpr->getType(); 12017 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12018 CompoundType; 12019 // OpenCL v1.2 s6.1.1.1 p2: 12020 // The half data type can only be used to declare a pointer to a buffer that 12021 // contains half values 12022 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12023 LHSType->isHalfType()) { 12024 Diag(Loc, diag::err_opencl_half_load_store) << 1 12025 << LHSType.getUnqualifiedType(); 12026 return QualType(); 12027 } 12028 12029 AssignConvertType ConvTy; 12030 if (CompoundType.isNull()) { 12031 Expr *RHSCheck = RHS.get(); 12032 12033 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12034 12035 QualType LHSTy(LHSType); 12036 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12037 if (RHS.isInvalid()) 12038 return QualType(); 12039 // Special case of NSObject attributes on c-style pointer types. 12040 if (ConvTy == IncompatiblePointer && 12041 ((Context.isObjCNSObjectType(LHSType) && 12042 RHSType->isObjCObjectPointerType()) || 12043 (Context.isObjCNSObjectType(RHSType) && 12044 LHSType->isObjCObjectPointerType()))) 12045 ConvTy = Compatible; 12046 12047 if (ConvTy == Compatible && 12048 LHSType->isObjCObjectType()) 12049 Diag(Loc, diag::err_objc_object_assignment) 12050 << LHSType; 12051 12052 // If the RHS is a unary plus or minus, check to see if they = and + are 12053 // right next to each other. If so, the user may have typo'd "x =+ 4" 12054 // instead of "x += 4". 12055 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12056 RHSCheck = ICE->getSubExpr(); 12057 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12058 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12059 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12060 // Only if the two operators are exactly adjacent. 12061 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12062 // And there is a space or other character before the subexpr of the 12063 // unary +/-. We don't want to warn on "x=-1". 12064 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12065 UO->getSubExpr()->getBeginLoc().isFileID()) { 12066 Diag(Loc, diag::warn_not_compound_assign) 12067 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12068 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12069 } 12070 } 12071 12072 if (ConvTy == Compatible) { 12073 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12074 // Warn about retain cycles where a block captures the LHS, but 12075 // not if the LHS is a simple variable into which the block is 12076 // being stored...unless that variable can be captured by reference! 12077 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12078 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12079 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12080 checkRetainCycles(LHSExpr, RHS.get()); 12081 } 12082 12083 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12084 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12085 // It is safe to assign a weak reference into a strong variable. 12086 // Although this code can still have problems: 12087 // id x = self.weakProp; 12088 // id y = self.weakProp; 12089 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12090 // paths through the function. This should be revisited if 12091 // -Wrepeated-use-of-weak is made flow-sensitive. 12092 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12093 // variable, which will be valid for the current autorelease scope. 12094 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12095 RHS.get()->getBeginLoc())) 12096 getCurFunction()->markSafeWeakUse(RHS.get()); 12097 12098 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12099 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12100 } 12101 } 12102 } else { 12103 // Compound assignment "x += y" 12104 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12105 } 12106 12107 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12108 RHS.get(), AA_Assigning)) 12109 return QualType(); 12110 12111 CheckForNullPointerDereference(*this, LHSExpr); 12112 12113 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12114 if (CompoundType.isNull()) { 12115 // C++2a [expr.ass]p5: 12116 // A simple-assignment whose left operand is of a volatile-qualified 12117 // type is deprecated unless the assignment is either a discarded-value 12118 // expression or an unevaluated operand 12119 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12120 } else { 12121 // C++2a [expr.ass]p6: 12122 // [Compound-assignment] expressions are deprecated if E1 has 12123 // volatile-qualified type 12124 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12125 } 12126 } 12127 12128 // C99 6.5.16p3: The type of an assignment expression is the type of the 12129 // left operand unless the left operand has qualified type, in which case 12130 // it is the unqualified version of the type of the left operand. 12131 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12132 // is converted to the type of the assignment expression (above). 12133 // C++ 5.17p1: the type of the assignment expression is that of its left 12134 // operand. 12135 return (getLangOpts().CPlusPlus 12136 ? LHSType : LHSType.getUnqualifiedType()); 12137 } 12138 12139 // Only ignore explicit casts to void. 12140 static bool IgnoreCommaOperand(const Expr *E) { 12141 E = E->IgnoreParens(); 12142 12143 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12144 if (CE->getCastKind() == CK_ToVoid) { 12145 return true; 12146 } 12147 12148 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12149 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12150 CE->getSubExpr()->getType()->isDependentType()) { 12151 return true; 12152 } 12153 } 12154 12155 return false; 12156 } 12157 12158 // Look for instances where it is likely the comma operator is confused with 12159 // another operator. There is a whitelist of acceptable expressions for the 12160 // left hand side of the comma operator, otherwise emit a warning. 12161 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12162 // No warnings in macros 12163 if (Loc.isMacroID()) 12164 return; 12165 12166 // Don't warn in template instantiations. 12167 if (inTemplateInstantiation()) 12168 return; 12169 12170 // Scope isn't fine-grained enough to whitelist the specific cases, so 12171 // instead, skip more than needed, then call back into here with the 12172 // CommaVisitor in SemaStmt.cpp. 12173 // The whitelisted locations are the initialization and increment portions 12174 // of a for loop. The additional checks are on the condition of 12175 // if statements, do/while loops, and for loops. 12176 // Differences in scope flags for C89 mode requires the extra logic. 12177 const unsigned ForIncrementFlags = 12178 getLangOpts().C99 || getLangOpts().CPlusPlus 12179 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12180 : Scope::ContinueScope | Scope::BreakScope; 12181 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12182 const unsigned ScopeFlags = getCurScope()->getFlags(); 12183 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12184 (ScopeFlags & ForInitFlags) == ForInitFlags) 12185 return; 12186 12187 // If there are multiple comma operators used together, get the RHS of the 12188 // of the comma operator as the LHS. 12189 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12190 if (BO->getOpcode() != BO_Comma) 12191 break; 12192 LHS = BO->getRHS(); 12193 } 12194 12195 // Only allow some expressions on LHS to not warn. 12196 if (IgnoreCommaOperand(LHS)) 12197 return; 12198 12199 Diag(Loc, diag::warn_comma_operator); 12200 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12201 << LHS->getSourceRange() 12202 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12203 LangOpts.CPlusPlus ? "static_cast<void>(" 12204 : "(void)(") 12205 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12206 ")"); 12207 } 12208 12209 // C99 6.5.17 12210 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12211 SourceLocation Loc) { 12212 LHS = S.CheckPlaceholderExpr(LHS.get()); 12213 RHS = S.CheckPlaceholderExpr(RHS.get()); 12214 if (LHS.isInvalid() || RHS.isInvalid()) 12215 return QualType(); 12216 12217 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12218 // operands, but not unary promotions. 12219 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12220 12221 // So we treat the LHS as a ignored value, and in C++ we allow the 12222 // containing site to determine what should be done with the RHS. 12223 LHS = S.IgnoredValueConversions(LHS.get()); 12224 if (LHS.isInvalid()) 12225 return QualType(); 12226 12227 S.DiagnoseUnusedExprResult(LHS.get()); 12228 12229 if (!S.getLangOpts().CPlusPlus) { 12230 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12231 if (RHS.isInvalid()) 12232 return QualType(); 12233 if (!RHS.get()->getType()->isVoidType()) 12234 S.RequireCompleteType(Loc, RHS.get()->getType(), 12235 diag::err_incomplete_type); 12236 } 12237 12238 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12239 S.DiagnoseCommaOperator(LHS.get(), Loc); 12240 12241 return RHS.get()->getType(); 12242 } 12243 12244 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12245 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12246 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12247 ExprValueKind &VK, 12248 ExprObjectKind &OK, 12249 SourceLocation OpLoc, 12250 bool IsInc, bool IsPrefix) { 12251 if (Op->isTypeDependent()) 12252 return S.Context.DependentTy; 12253 12254 QualType ResType = Op->getType(); 12255 // Atomic types can be used for increment / decrement where the non-atomic 12256 // versions can, so ignore the _Atomic() specifier for the purpose of 12257 // checking. 12258 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12259 ResType = ResAtomicType->getValueType(); 12260 12261 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12262 12263 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12264 // Decrement of bool is not allowed. 12265 if (!IsInc) { 12266 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12267 return QualType(); 12268 } 12269 // Increment of bool sets it to true, but is deprecated. 12270 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12271 : diag::warn_increment_bool) 12272 << Op->getSourceRange(); 12273 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12274 // Error on enum increments and decrements in C++ mode 12275 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12276 return QualType(); 12277 } else if (ResType->isRealType()) { 12278 // OK! 12279 } else if (ResType->isPointerType()) { 12280 // C99 6.5.2.4p2, 6.5.6p2 12281 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12282 return QualType(); 12283 } else if (ResType->isObjCObjectPointerType()) { 12284 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12285 // Otherwise, we just need a complete type. 12286 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12287 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12288 return QualType(); 12289 } else if (ResType->isAnyComplexType()) { 12290 // C99 does not support ++/-- on complex types, we allow as an extension. 12291 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12292 << ResType << Op->getSourceRange(); 12293 } else if (ResType->isPlaceholderType()) { 12294 ExprResult PR = S.CheckPlaceholderExpr(Op); 12295 if (PR.isInvalid()) return QualType(); 12296 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12297 IsInc, IsPrefix); 12298 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12299 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12300 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12301 (ResType->castAs<VectorType>()->getVectorKind() != 12302 VectorType::AltiVecBool)) { 12303 // The z vector extensions allow ++ and -- for non-bool vectors. 12304 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12305 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12306 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12307 } else { 12308 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12309 << ResType << int(IsInc) << Op->getSourceRange(); 12310 return QualType(); 12311 } 12312 // At this point, we know we have a real, complex or pointer type. 12313 // Now make sure the operand is a modifiable lvalue. 12314 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12315 return QualType(); 12316 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12317 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12318 // An operand with volatile-qualified type is deprecated 12319 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12320 << IsInc << ResType; 12321 } 12322 // In C++, a prefix increment is the same type as the operand. Otherwise 12323 // (in C or with postfix), the increment is the unqualified type of the 12324 // operand. 12325 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12326 VK = VK_LValue; 12327 OK = Op->getObjectKind(); 12328 return ResType; 12329 } else { 12330 VK = VK_RValue; 12331 return ResType.getUnqualifiedType(); 12332 } 12333 } 12334 12335 12336 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12337 /// This routine allows us to typecheck complex/recursive expressions 12338 /// where the declaration is needed for type checking. We only need to 12339 /// handle cases when the expression references a function designator 12340 /// or is an lvalue. Here are some examples: 12341 /// - &(x) => x 12342 /// - &*****f => f for f a function designator. 12343 /// - &s.xx => s 12344 /// - &s.zz[1].yy -> s, if zz is an array 12345 /// - *(x + 1) -> x, if x is an array 12346 /// - &"123"[2] -> 0 12347 /// - & __real__ x -> x 12348 static ValueDecl *getPrimaryDecl(Expr *E) { 12349 switch (E->getStmtClass()) { 12350 case Stmt::DeclRefExprClass: 12351 return cast<DeclRefExpr>(E)->getDecl(); 12352 case Stmt::MemberExprClass: 12353 // If this is an arrow operator, the address is an offset from 12354 // the base's value, so the object the base refers to is 12355 // irrelevant. 12356 if (cast<MemberExpr>(E)->isArrow()) 12357 return nullptr; 12358 // Otherwise, the expression refers to a part of the base 12359 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12360 case Stmt::ArraySubscriptExprClass: { 12361 // FIXME: This code shouldn't be necessary! We should catch the implicit 12362 // promotion of register arrays earlier. 12363 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12364 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12365 if (ICE->getSubExpr()->getType()->isArrayType()) 12366 return getPrimaryDecl(ICE->getSubExpr()); 12367 } 12368 return nullptr; 12369 } 12370 case Stmt::UnaryOperatorClass: { 12371 UnaryOperator *UO = cast<UnaryOperator>(E); 12372 12373 switch(UO->getOpcode()) { 12374 case UO_Real: 12375 case UO_Imag: 12376 case UO_Extension: 12377 return getPrimaryDecl(UO->getSubExpr()); 12378 default: 12379 return nullptr; 12380 } 12381 } 12382 case Stmt::ParenExprClass: 12383 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12384 case Stmt::ImplicitCastExprClass: 12385 // If the result of an implicit cast is an l-value, we care about 12386 // the sub-expression; otherwise, the result here doesn't matter. 12387 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12388 default: 12389 return nullptr; 12390 } 12391 } 12392 12393 namespace { 12394 enum { 12395 AO_Bit_Field = 0, 12396 AO_Vector_Element = 1, 12397 AO_Property_Expansion = 2, 12398 AO_Register_Variable = 3, 12399 AO_No_Error = 4 12400 }; 12401 } 12402 /// Diagnose invalid operand for address of operations. 12403 /// 12404 /// \param Type The type of operand which cannot have its address taken. 12405 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12406 Expr *E, unsigned Type) { 12407 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12408 } 12409 12410 /// CheckAddressOfOperand - The operand of & must be either a function 12411 /// designator or an lvalue designating an object. If it is an lvalue, the 12412 /// object cannot be declared with storage class register or be a bit field. 12413 /// Note: The usual conversions are *not* applied to the operand of the & 12414 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12415 /// In C++, the operand might be an overloaded function name, in which case 12416 /// we allow the '&' but retain the overloaded-function type. 12417 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12418 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12419 if (PTy->getKind() == BuiltinType::Overload) { 12420 Expr *E = OrigOp.get()->IgnoreParens(); 12421 if (!isa<OverloadExpr>(E)) { 12422 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12423 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12424 << OrigOp.get()->getSourceRange(); 12425 return QualType(); 12426 } 12427 12428 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12429 if (isa<UnresolvedMemberExpr>(Ovl)) 12430 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12431 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12432 << OrigOp.get()->getSourceRange(); 12433 return QualType(); 12434 } 12435 12436 return Context.OverloadTy; 12437 } 12438 12439 if (PTy->getKind() == BuiltinType::UnknownAny) 12440 return Context.UnknownAnyTy; 12441 12442 if (PTy->getKind() == BuiltinType::BoundMember) { 12443 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12444 << OrigOp.get()->getSourceRange(); 12445 return QualType(); 12446 } 12447 12448 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12449 if (OrigOp.isInvalid()) return QualType(); 12450 } 12451 12452 if (OrigOp.get()->isTypeDependent()) 12453 return Context.DependentTy; 12454 12455 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12456 12457 // Make sure to ignore parentheses in subsequent checks 12458 Expr *op = OrigOp.get()->IgnoreParens(); 12459 12460 // In OpenCL captures for blocks called as lambda functions 12461 // are located in the private address space. Blocks used in 12462 // enqueue_kernel can be located in a different address space 12463 // depending on a vendor implementation. Thus preventing 12464 // taking an address of the capture to avoid invalid AS casts. 12465 if (LangOpts.OpenCL) { 12466 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12467 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12468 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12469 return QualType(); 12470 } 12471 } 12472 12473 if (getLangOpts().C99) { 12474 // Implement C99-only parts of addressof rules. 12475 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12476 if (uOp->getOpcode() == UO_Deref) 12477 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12478 // (assuming the deref expression is valid). 12479 return uOp->getSubExpr()->getType(); 12480 } 12481 // Technically, there should be a check for array subscript 12482 // expressions here, but the result of one is always an lvalue anyway. 12483 } 12484 ValueDecl *dcl = getPrimaryDecl(op); 12485 12486 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12487 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12488 op->getBeginLoc())) 12489 return QualType(); 12490 12491 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12492 unsigned AddressOfError = AO_No_Error; 12493 12494 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12495 bool sfinae = (bool)isSFINAEContext(); 12496 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12497 : diag::ext_typecheck_addrof_temporary) 12498 << op->getType() << op->getSourceRange(); 12499 if (sfinae) 12500 return QualType(); 12501 // Materialize the temporary as an lvalue so that we can take its address. 12502 OrigOp = op = 12503 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12504 } else if (isa<ObjCSelectorExpr>(op)) { 12505 return Context.getPointerType(op->getType()); 12506 } else if (lval == Expr::LV_MemberFunction) { 12507 // If it's an instance method, make a member pointer. 12508 // The expression must have exactly the form &A::foo. 12509 12510 // If the underlying expression isn't a decl ref, give up. 12511 if (!isa<DeclRefExpr>(op)) { 12512 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12513 << OrigOp.get()->getSourceRange(); 12514 return QualType(); 12515 } 12516 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12517 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12518 12519 // The id-expression was parenthesized. 12520 if (OrigOp.get() != DRE) { 12521 Diag(OpLoc, diag::err_parens_pointer_member_function) 12522 << OrigOp.get()->getSourceRange(); 12523 12524 // The method was named without a qualifier. 12525 } else if (!DRE->getQualifier()) { 12526 if (MD->getParent()->getName().empty()) 12527 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12528 << op->getSourceRange(); 12529 else { 12530 SmallString<32> Str; 12531 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12532 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12533 << op->getSourceRange() 12534 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12535 } 12536 } 12537 12538 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12539 if (isa<CXXDestructorDecl>(MD)) 12540 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12541 12542 QualType MPTy = Context.getMemberPointerType( 12543 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12544 // Under the MS ABI, lock down the inheritance model now. 12545 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12546 (void)isCompleteType(OpLoc, MPTy); 12547 return MPTy; 12548 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12549 // C99 6.5.3.2p1 12550 // The operand must be either an l-value or a function designator 12551 if (!op->getType()->isFunctionType()) { 12552 // Use a special diagnostic for loads from property references. 12553 if (isa<PseudoObjectExpr>(op)) { 12554 AddressOfError = AO_Property_Expansion; 12555 } else { 12556 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12557 << op->getType() << op->getSourceRange(); 12558 return QualType(); 12559 } 12560 } 12561 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12562 // The operand cannot be a bit-field 12563 AddressOfError = AO_Bit_Field; 12564 } else if (op->getObjectKind() == OK_VectorComponent) { 12565 // The operand cannot be an element of a vector 12566 AddressOfError = AO_Vector_Element; 12567 } else if (dcl) { // C99 6.5.3.2p1 12568 // We have an lvalue with a decl. Make sure the decl is not declared 12569 // with the register storage-class specifier. 12570 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12571 // in C++ it is not error to take address of a register 12572 // variable (c++03 7.1.1P3) 12573 if (vd->getStorageClass() == SC_Register && 12574 !getLangOpts().CPlusPlus) { 12575 AddressOfError = AO_Register_Variable; 12576 } 12577 } else if (isa<MSPropertyDecl>(dcl)) { 12578 AddressOfError = AO_Property_Expansion; 12579 } else if (isa<FunctionTemplateDecl>(dcl)) { 12580 return Context.OverloadTy; 12581 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12582 // Okay: we can take the address of a field. 12583 // Could be a pointer to member, though, if there is an explicit 12584 // scope qualifier for the class. 12585 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12586 DeclContext *Ctx = dcl->getDeclContext(); 12587 if (Ctx && Ctx->isRecord()) { 12588 if (dcl->getType()->isReferenceType()) { 12589 Diag(OpLoc, 12590 diag::err_cannot_form_pointer_to_member_of_reference_type) 12591 << dcl->getDeclName() << dcl->getType(); 12592 return QualType(); 12593 } 12594 12595 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12596 Ctx = Ctx->getParent(); 12597 12598 QualType MPTy = Context.getMemberPointerType( 12599 op->getType(), 12600 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12601 // Under the MS ABI, lock down the inheritance model now. 12602 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12603 (void)isCompleteType(OpLoc, MPTy); 12604 return MPTy; 12605 } 12606 } 12607 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12608 !isa<BindingDecl>(dcl)) 12609 llvm_unreachable("Unknown/unexpected decl type"); 12610 } 12611 12612 if (AddressOfError != AO_No_Error) { 12613 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12614 return QualType(); 12615 } 12616 12617 if (lval == Expr::LV_IncompleteVoidType) { 12618 // Taking the address of a void variable is technically illegal, but we 12619 // allow it in cases which are otherwise valid. 12620 // Example: "extern void x; void* y = &x;". 12621 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12622 } 12623 12624 // If the operand has type "type", the result has type "pointer to type". 12625 if (op->getType()->isObjCObjectType()) 12626 return Context.getObjCObjectPointerType(op->getType()); 12627 12628 CheckAddressOfPackedMember(op); 12629 12630 return Context.getPointerType(op->getType()); 12631 } 12632 12633 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12634 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12635 if (!DRE) 12636 return; 12637 const Decl *D = DRE->getDecl(); 12638 if (!D) 12639 return; 12640 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12641 if (!Param) 12642 return; 12643 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12644 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12645 return; 12646 if (FunctionScopeInfo *FD = S.getCurFunction()) 12647 if (!FD->ModifiedNonNullParams.count(Param)) 12648 FD->ModifiedNonNullParams.insert(Param); 12649 } 12650 12651 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12652 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12653 SourceLocation OpLoc) { 12654 if (Op->isTypeDependent()) 12655 return S.Context.DependentTy; 12656 12657 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12658 if (ConvResult.isInvalid()) 12659 return QualType(); 12660 Op = ConvResult.get(); 12661 QualType OpTy = Op->getType(); 12662 QualType Result; 12663 12664 if (isa<CXXReinterpretCastExpr>(Op)) { 12665 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12666 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12667 Op->getSourceRange()); 12668 } 12669 12670 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12671 { 12672 Result = PT->getPointeeType(); 12673 } 12674 else if (const ObjCObjectPointerType *OPT = 12675 OpTy->getAs<ObjCObjectPointerType>()) 12676 Result = OPT->getPointeeType(); 12677 else { 12678 ExprResult PR = S.CheckPlaceholderExpr(Op); 12679 if (PR.isInvalid()) return QualType(); 12680 if (PR.get() != Op) 12681 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12682 } 12683 12684 if (Result.isNull()) { 12685 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12686 << OpTy << Op->getSourceRange(); 12687 return QualType(); 12688 } 12689 12690 // Note that per both C89 and C99, indirection is always legal, even if Result 12691 // is an incomplete type or void. It would be possible to warn about 12692 // dereferencing a void pointer, but it's completely well-defined, and such a 12693 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12694 // for pointers to 'void' but is fine for any other pointer type: 12695 // 12696 // C++ [expr.unary.op]p1: 12697 // [...] the expression to which [the unary * operator] is applied shall 12698 // be a pointer to an object type, or a pointer to a function type 12699 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12700 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12701 << OpTy << Op->getSourceRange(); 12702 12703 // Dereferences are usually l-values... 12704 VK = VK_LValue; 12705 12706 // ...except that certain expressions are never l-values in C. 12707 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12708 VK = VK_RValue; 12709 12710 return Result; 12711 } 12712 12713 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12714 BinaryOperatorKind Opc; 12715 switch (Kind) { 12716 default: llvm_unreachable("Unknown binop!"); 12717 case tok::periodstar: Opc = BO_PtrMemD; break; 12718 case tok::arrowstar: Opc = BO_PtrMemI; break; 12719 case tok::star: Opc = BO_Mul; break; 12720 case tok::slash: Opc = BO_Div; break; 12721 case tok::percent: Opc = BO_Rem; break; 12722 case tok::plus: Opc = BO_Add; break; 12723 case tok::minus: Opc = BO_Sub; break; 12724 case tok::lessless: Opc = BO_Shl; break; 12725 case tok::greatergreater: Opc = BO_Shr; break; 12726 case tok::lessequal: Opc = BO_LE; break; 12727 case tok::less: Opc = BO_LT; break; 12728 case tok::greaterequal: Opc = BO_GE; break; 12729 case tok::greater: Opc = BO_GT; break; 12730 case tok::exclaimequal: Opc = BO_NE; break; 12731 case tok::equalequal: Opc = BO_EQ; break; 12732 case tok::spaceship: Opc = BO_Cmp; break; 12733 case tok::amp: Opc = BO_And; break; 12734 case tok::caret: Opc = BO_Xor; break; 12735 case tok::pipe: Opc = BO_Or; break; 12736 case tok::ampamp: Opc = BO_LAnd; break; 12737 case tok::pipepipe: Opc = BO_LOr; break; 12738 case tok::equal: Opc = BO_Assign; break; 12739 case tok::starequal: Opc = BO_MulAssign; break; 12740 case tok::slashequal: Opc = BO_DivAssign; break; 12741 case tok::percentequal: Opc = BO_RemAssign; break; 12742 case tok::plusequal: Opc = BO_AddAssign; break; 12743 case tok::minusequal: Opc = BO_SubAssign; break; 12744 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12745 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12746 case tok::ampequal: Opc = BO_AndAssign; break; 12747 case tok::caretequal: Opc = BO_XorAssign; break; 12748 case tok::pipeequal: Opc = BO_OrAssign; break; 12749 case tok::comma: Opc = BO_Comma; break; 12750 } 12751 return Opc; 12752 } 12753 12754 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12755 tok::TokenKind Kind) { 12756 UnaryOperatorKind Opc; 12757 switch (Kind) { 12758 default: llvm_unreachable("Unknown unary op!"); 12759 case tok::plusplus: Opc = UO_PreInc; break; 12760 case tok::minusminus: Opc = UO_PreDec; break; 12761 case tok::amp: Opc = UO_AddrOf; break; 12762 case tok::star: Opc = UO_Deref; break; 12763 case tok::plus: Opc = UO_Plus; break; 12764 case tok::minus: Opc = UO_Minus; break; 12765 case tok::tilde: Opc = UO_Not; break; 12766 case tok::exclaim: Opc = UO_LNot; break; 12767 case tok::kw___real: Opc = UO_Real; break; 12768 case tok::kw___imag: Opc = UO_Imag; break; 12769 case tok::kw___extension__: Opc = UO_Extension; break; 12770 } 12771 return Opc; 12772 } 12773 12774 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12775 /// This warning suppressed in the event of macro expansions. 12776 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12777 SourceLocation OpLoc, bool IsBuiltin) { 12778 if (S.inTemplateInstantiation()) 12779 return; 12780 if (S.isUnevaluatedContext()) 12781 return; 12782 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12783 return; 12784 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12785 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12786 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12787 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12788 if (!LHSDeclRef || !RHSDeclRef || 12789 LHSDeclRef->getLocation().isMacroID() || 12790 RHSDeclRef->getLocation().isMacroID()) 12791 return; 12792 const ValueDecl *LHSDecl = 12793 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12794 const ValueDecl *RHSDecl = 12795 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12796 if (LHSDecl != RHSDecl) 12797 return; 12798 if (LHSDecl->getType().isVolatileQualified()) 12799 return; 12800 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12801 if (RefTy->getPointeeType().isVolatileQualified()) 12802 return; 12803 12804 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12805 : diag::warn_self_assignment_overloaded) 12806 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12807 << RHSExpr->getSourceRange(); 12808 } 12809 12810 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12811 /// is usually indicative of introspection within the Objective-C pointer. 12812 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12813 SourceLocation OpLoc) { 12814 if (!S.getLangOpts().ObjC) 12815 return; 12816 12817 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12818 const Expr *LHS = L.get(); 12819 const Expr *RHS = R.get(); 12820 12821 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12822 ObjCPointerExpr = LHS; 12823 OtherExpr = RHS; 12824 } 12825 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12826 ObjCPointerExpr = RHS; 12827 OtherExpr = LHS; 12828 } 12829 12830 // This warning is deliberately made very specific to reduce false 12831 // positives with logic that uses '&' for hashing. This logic mainly 12832 // looks for code trying to introspect into tagged pointers, which 12833 // code should generally never do. 12834 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12835 unsigned Diag = diag::warn_objc_pointer_masking; 12836 // Determine if we are introspecting the result of performSelectorXXX. 12837 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12838 // Special case messages to -performSelector and friends, which 12839 // can return non-pointer values boxed in a pointer value. 12840 // Some clients may wish to silence warnings in this subcase. 12841 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12842 Selector S = ME->getSelector(); 12843 StringRef SelArg0 = S.getNameForSlot(0); 12844 if (SelArg0.startswith("performSelector")) 12845 Diag = diag::warn_objc_pointer_masking_performSelector; 12846 } 12847 12848 S.Diag(OpLoc, Diag) 12849 << ObjCPointerExpr->getSourceRange(); 12850 } 12851 } 12852 12853 static NamedDecl *getDeclFromExpr(Expr *E) { 12854 if (!E) 12855 return nullptr; 12856 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12857 return DRE->getDecl(); 12858 if (auto *ME = dyn_cast<MemberExpr>(E)) 12859 return ME->getMemberDecl(); 12860 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12861 return IRE->getDecl(); 12862 return nullptr; 12863 } 12864 12865 // This helper function promotes a binary operator's operands (which are of a 12866 // half vector type) to a vector of floats and then truncates the result to 12867 // a vector of either half or short. 12868 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12869 BinaryOperatorKind Opc, QualType ResultTy, 12870 ExprValueKind VK, ExprObjectKind OK, 12871 bool IsCompAssign, SourceLocation OpLoc, 12872 FPOptions FPFeatures) { 12873 auto &Context = S.getASTContext(); 12874 assert((isVector(ResultTy, Context.HalfTy) || 12875 isVector(ResultTy, Context.ShortTy)) && 12876 "Result must be a vector of half or short"); 12877 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12878 isVector(RHS.get()->getType(), Context.HalfTy) && 12879 "both operands expected to be a half vector"); 12880 12881 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12882 QualType BinOpResTy = RHS.get()->getType(); 12883 12884 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12885 // change BinOpResTy to a vector of ints. 12886 if (isVector(ResultTy, Context.ShortTy)) 12887 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12888 12889 if (IsCompAssign) 12890 return new (Context) CompoundAssignOperator( 12891 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12892 OpLoc, FPFeatures); 12893 12894 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12895 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12896 VK, OK, OpLoc, FPFeatures); 12897 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12898 } 12899 12900 static std::pair<ExprResult, ExprResult> 12901 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12902 Expr *RHSExpr) { 12903 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12904 if (!S.getLangOpts().CPlusPlus) { 12905 // C cannot handle TypoExpr nodes on either side of a binop because it 12906 // doesn't handle dependent types properly, so make sure any TypoExprs have 12907 // been dealt with before checking the operands. 12908 LHS = S.CorrectDelayedTyposInExpr(LHS); 12909 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12910 if (Opc != BO_Assign) 12911 return ExprResult(E); 12912 // Avoid correcting the RHS to the same Expr as the LHS. 12913 Decl *D = getDeclFromExpr(E); 12914 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12915 }); 12916 } 12917 return std::make_pair(LHS, RHS); 12918 } 12919 12920 /// Returns true if conversion between vectors of halfs and vectors of floats 12921 /// is needed. 12922 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12923 Expr *E0, Expr *E1 = nullptr) { 12924 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 12925 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 12926 return false; 12927 12928 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 12929 QualType Ty = E->IgnoreImplicit()->getType(); 12930 12931 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 12932 // to vectors of floats. Although the element type of the vectors is __fp16, 12933 // the vectors shouldn't be treated as storage-only types. See the 12934 // discussion here: https://reviews.llvm.org/rG825235c140e7 12935 if (const VectorType *VT = Ty->getAs<VectorType>()) { 12936 if (VT->getVectorKind() == VectorType::NeonVector) 12937 return false; 12938 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 12939 } 12940 return false; 12941 }; 12942 12943 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 12944 } 12945 12946 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12947 /// operator @p Opc at location @c TokLoc. This routine only supports 12948 /// built-in operations; ActOnBinOp handles overloaded operators. 12949 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12950 BinaryOperatorKind Opc, 12951 Expr *LHSExpr, Expr *RHSExpr) { 12952 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12953 // The syntax only allows initializer lists on the RHS of assignment, 12954 // so we don't need to worry about accepting invalid code for 12955 // non-assignment operators. 12956 // C++11 5.17p9: 12957 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12958 // of x = {} is x = T(). 12959 InitializationKind Kind = InitializationKind::CreateDirectList( 12960 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12961 InitializedEntity Entity = 12962 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12963 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12964 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12965 if (Init.isInvalid()) 12966 return Init; 12967 RHSExpr = Init.get(); 12968 } 12969 12970 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12971 QualType ResultTy; // Result type of the binary operator. 12972 // The following two variables are used for compound assignment operators 12973 QualType CompLHSTy; // Type of LHS after promotions for computation 12974 QualType CompResultTy; // Type of computation result 12975 ExprValueKind VK = VK_RValue; 12976 ExprObjectKind OK = OK_Ordinary; 12977 bool ConvertHalfVec = false; 12978 12979 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12980 if (!LHS.isUsable() || !RHS.isUsable()) 12981 return ExprError(); 12982 12983 if (getLangOpts().OpenCL) { 12984 QualType LHSTy = LHSExpr->getType(); 12985 QualType RHSTy = RHSExpr->getType(); 12986 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12987 // the ATOMIC_VAR_INIT macro. 12988 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12989 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12990 if (BO_Assign == Opc) 12991 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12992 else 12993 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12994 return ExprError(); 12995 } 12996 12997 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12998 // only with a builtin functions and therefore should be disallowed here. 12999 if (LHSTy->isImageType() || RHSTy->isImageType() || 13000 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13001 LHSTy->isPipeType() || RHSTy->isPipeType() || 13002 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13003 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13004 return ExprError(); 13005 } 13006 } 13007 13008 // Diagnose operations on the unsupported types for OpenMP device compilation. 13009 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13010 if (Opc != BO_Assign && Opc != BO_Comma) { 13011 checkOpenMPDeviceExpr(LHSExpr); 13012 checkOpenMPDeviceExpr(RHSExpr); 13013 } 13014 } 13015 13016 switch (Opc) { 13017 case BO_Assign: 13018 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13019 if (getLangOpts().CPlusPlus && 13020 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13021 VK = LHS.get()->getValueKind(); 13022 OK = LHS.get()->getObjectKind(); 13023 } 13024 if (!ResultTy.isNull()) { 13025 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13026 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13027 13028 // Avoid copying a block to the heap if the block is assigned to a local 13029 // auto variable that is declared in the same scope as the block. This 13030 // optimization is unsafe if the local variable is declared in an outer 13031 // scope. For example: 13032 // 13033 // BlockTy b; 13034 // { 13035 // b = ^{...}; 13036 // } 13037 // // It is unsafe to invoke the block here if it wasn't copied to the 13038 // // heap. 13039 // b(); 13040 13041 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13042 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13043 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13044 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13045 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13046 13047 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13048 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13049 NTCUC_Assignment, NTCUK_Copy); 13050 } 13051 RecordModifiableNonNullParam(*this, LHS.get()); 13052 break; 13053 case BO_PtrMemD: 13054 case BO_PtrMemI: 13055 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13056 Opc == BO_PtrMemI); 13057 break; 13058 case BO_Mul: 13059 case BO_Div: 13060 ConvertHalfVec = true; 13061 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13062 Opc == BO_Div); 13063 break; 13064 case BO_Rem: 13065 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13066 break; 13067 case BO_Add: 13068 ConvertHalfVec = true; 13069 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13070 break; 13071 case BO_Sub: 13072 ConvertHalfVec = true; 13073 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13074 break; 13075 case BO_Shl: 13076 case BO_Shr: 13077 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13078 break; 13079 case BO_LE: 13080 case BO_LT: 13081 case BO_GE: 13082 case BO_GT: 13083 ConvertHalfVec = true; 13084 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13085 break; 13086 case BO_EQ: 13087 case BO_NE: 13088 ConvertHalfVec = true; 13089 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13090 break; 13091 case BO_Cmp: 13092 ConvertHalfVec = true; 13093 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13094 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13095 break; 13096 case BO_And: 13097 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13098 LLVM_FALLTHROUGH; 13099 case BO_Xor: 13100 case BO_Or: 13101 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13102 break; 13103 case BO_LAnd: 13104 case BO_LOr: 13105 ConvertHalfVec = true; 13106 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13107 break; 13108 case BO_MulAssign: 13109 case BO_DivAssign: 13110 ConvertHalfVec = true; 13111 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13112 Opc == BO_DivAssign); 13113 CompLHSTy = CompResultTy; 13114 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13115 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13116 break; 13117 case BO_RemAssign: 13118 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13119 CompLHSTy = CompResultTy; 13120 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13121 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13122 break; 13123 case BO_AddAssign: 13124 ConvertHalfVec = true; 13125 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13126 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13127 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13128 break; 13129 case BO_SubAssign: 13130 ConvertHalfVec = true; 13131 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13132 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13133 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13134 break; 13135 case BO_ShlAssign: 13136 case BO_ShrAssign: 13137 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13138 CompLHSTy = CompResultTy; 13139 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13140 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13141 break; 13142 case BO_AndAssign: 13143 case BO_OrAssign: // fallthrough 13144 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13145 LLVM_FALLTHROUGH; 13146 case BO_XorAssign: 13147 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13148 CompLHSTy = CompResultTy; 13149 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13150 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13151 break; 13152 case BO_Comma: 13153 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13154 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13155 VK = RHS.get()->getValueKind(); 13156 OK = RHS.get()->getObjectKind(); 13157 } 13158 break; 13159 } 13160 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13161 return ExprError(); 13162 13163 if (ResultTy->isRealFloatingType() && 13164 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13165 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13166 // Mark the current function as usng floating point constrained intrinsics 13167 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13168 F->setUsesFPIntrin(true); 13169 } 13170 13171 // Some of the binary operations require promoting operands of half vector to 13172 // float vectors and truncating the result back to half vector. For now, we do 13173 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13174 // arm64). 13175 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13176 isVector(LHS.get()->getType(), Context.HalfTy) && 13177 "both sides are half vectors or neither sides are"); 13178 ConvertHalfVec = 13179 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13180 13181 // Check for array bounds violations for both sides of the BinaryOperator 13182 CheckArrayAccess(LHS.get()); 13183 CheckArrayAccess(RHS.get()); 13184 13185 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13186 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13187 &Context.Idents.get("object_setClass"), 13188 SourceLocation(), LookupOrdinaryName); 13189 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13190 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13191 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13192 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13193 "object_setClass(") 13194 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13195 ",") 13196 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13197 } 13198 else 13199 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13200 } 13201 else if (const ObjCIvarRefExpr *OIRE = 13202 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13203 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13204 13205 // Opc is not a compound assignment if CompResultTy is null. 13206 if (CompResultTy.isNull()) { 13207 if (ConvertHalfVec) 13208 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13209 OpLoc, FPFeatures); 13210 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13211 OK, OpLoc, FPFeatures); 13212 } 13213 13214 // Handle compound assignments. 13215 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13216 OK_ObjCProperty) { 13217 VK = VK_LValue; 13218 OK = LHS.get()->getObjectKind(); 13219 } 13220 13221 if (ConvertHalfVec) 13222 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13223 OpLoc, FPFeatures); 13224 13225 return new (Context) CompoundAssignOperator( 13226 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13227 OpLoc, FPFeatures); 13228 } 13229 13230 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13231 /// operators are mixed in a way that suggests that the programmer forgot that 13232 /// comparison operators have higher precedence. The most typical example of 13233 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13234 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13235 SourceLocation OpLoc, Expr *LHSExpr, 13236 Expr *RHSExpr) { 13237 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13238 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13239 13240 // Check that one of the sides is a comparison operator and the other isn't. 13241 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13242 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13243 if (isLeftComp == isRightComp) 13244 return; 13245 13246 // Bitwise operations are sometimes used as eager logical ops. 13247 // Don't diagnose this. 13248 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13249 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13250 if (isLeftBitwise || isRightBitwise) 13251 return; 13252 13253 SourceRange DiagRange = isLeftComp 13254 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13255 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13256 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13257 SourceRange ParensRange = 13258 isLeftComp 13259 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13260 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13261 13262 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13263 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13264 SuggestParentheses(Self, OpLoc, 13265 Self.PDiag(diag::note_precedence_silence) << OpStr, 13266 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13267 SuggestParentheses(Self, OpLoc, 13268 Self.PDiag(diag::note_precedence_bitwise_first) 13269 << BinaryOperator::getOpcodeStr(Opc), 13270 ParensRange); 13271 } 13272 13273 /// It accepts a '&&' expr that is inside a '||' one. 13274 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13275 /// in parentheses. 13276 static void 13277 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13278 BinaryOperator *Bop) { 13279 assert(Bop->getOpcode() == BO_LAnd); 13280 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13281 << Bop->getSourceRange() << OpLoc; 13282 SuggestParentheses(Self, Bop->getOperatorLoc(), 13283 Self.PDiag(diag::note_precedence_silence) 13284 << Bop->getOpcodeStr(), 13285 Bop->getSourceRange()); 13286 } 13287 13288 /// Returns true if the given expression can be evaluated as a constant 13289 /// 'true'. 13290 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13291 bool Res; 13292 return !E->isValueDependent() && 13293 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13294 } 13295 13296 /// Returns true if the given expression can be evaluated as a constant 13297 /// 'false'. 13298 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13299 bool Res; 13300 return !E->isValueDependent() && 13301 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13302 } 13303 13304 /// Look for '&&' in the left hand of a '||' expr. 13305 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13306 Expr *LHSExpr, Expr *RHSExpr) { 13307 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13308 if (Bop->getOpcode() == BO_LAnd) { 13309 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13310 if (EvaluatesAsFalse(S, RHSExpr)) 13311 return; 13312 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13313 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13314 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13315 } else if (Bop->getOpcode() == BO_LOr) { 13316 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13317 // If it's "a || b && 1 || c" we didn't warn earlier for 13318 // "a || b && 1", but warn now. 13319 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13320 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13321 } 13322 } 13323 } 13324 } 13325 13326 /// Look for '&&' in the right hand of a '||' expr. 13327 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13328 Expr *LHSExpr, Expr *RHSExpr) { 13329 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13330 if (Bop->getOpcode() == BO_LAnd) { 13331 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13332 if (EvaluatesAsFalse(S, LHSExpr)) 13333 return; 13334 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13335 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13336 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13337 } 13338 } 13339 } 13340 13341 /// Look for bitwise op in the left or right hand of a bitwise op with 13342 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13343 /// the '&' expression in parentheses. 13344 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13345 SourceLocation OpLoc, Expr *SubExpr) { 13346 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13347 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13348 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13349 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13350 << Bop->getSourceRange() << OpLoc; 13351 SuggestParentheses(S, Bop->getOperatorLoc(), 13352 S.PDiag(diag::note_precedence_silence) 13353 << Bop->getOpcodeStr(), 13354 Bop->getSourceRange()); 13355 } 13356 } 13357 } 13358 13359 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13360 Expr *SubExpr, StringRef Shift) { 13361 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13362 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13363 StringRef Op = Bop->getOpcodeStr(); 13364 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13365 << Bop->getSourceRange() << OpLoc << Shift << Op; 13366 SuggestParentheses(S, Bop->getOperatorLoc(), 13367 S.PDiag(diag::note_precedence_silence) << Op, 13368 Bop->getSourceRange()); 13369 } 13370 } 13371 } 13372 13373 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13374 Expr *LHSExpr, Expr *RHSExpr) { 13375 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13376 if (!OCE) 13377 return; 13378 13379 FunctionDecl *FD = OCE->getDirectCallee(); 13380 if (!FD || !FD->isOverloadedOperator()) 13381 return; 13382 13383 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13384 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13385 return; 13386 13387 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13388 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13389 << (Kind == OO_LessLess); 13390 SuggestParentheses(S, OCE->getOperatorLoc(), 13391 S.PDiag(diag::note_precedence_silence) 13392 << (Kind == OO_LessLess ? "<<" : ">>"), 13393 OCE->getSourceRange()); 13394 SuggestParentheses( 13395 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13396 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13397 } 13398 13399 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13400 /// precedence. 13401 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13402 SourceLocation OpLoc, Expr *LHSExpr, 13403 Expr *RHSExpr){ 13404 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13405 if (BinaryOperator::isBitwiseOp(Opc)) 13406 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13407 13408 // Diagnose "arg1 & arg2 | arg3" 13409 if ((Opc == BO_Or || Opc == BO_Xor) && 13410 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13411 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13412 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13413 } 13414 13415 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13416 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13417 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13418 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13419 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13420 } 13421 13422 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13423 || Opc == BO_Shr) { 13424 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13425 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13426 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13427 } 13428 13429 // Warn on overloaded shift operators and comparisons, such as: 13430 // cout << 5 == 4; 13431 if (BinaryOperator::isComparisonOp(Opc)) 13432 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13433 } 13434 13435 // Binary Operators. 'Tok' is the token for the operator. 13436 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13437 tok::TokenKind Kind, 13438 Expr *LHSExpr, Expr *RHSExpr) { 13439 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13440 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13441 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13442 13443 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13444 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13445 13446 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13447 } 13448 13449 /// Build an overloaded binary operator expression in the given scope. 13450 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13451 BinaryOperatorKind Opc, 13452 Expr *LHS, Expr *RHS) { 13453 switch (Opc) { 13454 case BO_Assign: 13455 case BO_DivAssign: 13456 case BO_RemAssign: 13457 case BO_SubAssign: 13458 case BO_AndAssign: 13459 case BO_OrAssign: 13460 case BO_XorAssign: 13461 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13462 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13463 break; 13464 default: 13465 break; 13466 } 13467 13468 // Find all of the overloaded operators visible from this 13469 // point. We perform both an operator-name lookup from the local 13470 // scope and an argument-dependent lookup based on the types of 13471 // the arguments. 13472 UnresolvedSet<16> Functions; 13473 OverloadedOperatorKind OverOp 13474 = BinaryOperator::getOverloadedOperator(Opc); 13475 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13476 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13477 RHS->getType(), Functions); 13478 13479 // In C++20 onwards, we may have a second operator to look up. 13480 if (S.getLangOpts().CPlusPlus2a) { 13481 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13482 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13483 RHS->getType(), Functions); 13484 } 13485 13486 // Build the (potentially-overloaded, potentially-dependent) 13487 // binary operation. 13488 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13489 } 13490 13491 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13492 BinaryOperatorKind Opc, 13493 Expr *LHSExpr, Expr *RHSExpr) { 13494 ExprResult LHS, RHS; 13495 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13496 if (!LHS.isUsable() || !RHS.isUsable()) 13497 return ExprError(); 13498 LHSExpr = LHS.get(); 13499 RHSExpr = RHS.get(); 13500 13501 // We want to end up calling one of checkPseudoObjectAssignment 13502 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13503 // both expressions are overloadable or either is type-dependent), 13504 // or CreateBuiltinBinOp (in any other case). We also want to get 13505 // any placeholder types out of the way. 13506 13507 // Handle pseudo-objects in the LHS. 13508 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13509 // Assignments with a pseudo-object l-value need special analysis. 13510 if (pty->getKind() == BuiltinType::PseudoObject && 13511 BinaryOperator::isAssignmentOp(Opc)) 13512 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13513 13514 // Don't resolve overloads if the other type is overloadable. 13515 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13516 // We can't actually test that if we still have a placeholder, 13517 // though. Fortunately, none of the exceptions we see in that 13518 // code below are valid when the LHS is an overload set. Note 13519 // that an overload set can be dependently-typed, but it never 13520 // instantiates to having an overloadable type. 13521 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13522 if (resolvedRHS.isInvalid()) return ExprError(); 13523 RHSExpr = resolvedRHS.get(); 13524 13525 if (RHSExpr->isTypeDependent() || 13526 RHSExpr->getType()->isOverloadableType()) 13527 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13528 } 13529 13530 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13531 // template, diagnose the missing 'template' keyword instead of diagnosing 13532 // an invalid use of a bound member function. 13533 // 13534 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13535 // to C++1z [over.over]/1.4, but we already checked for that case above. 13536 if (Opc == BO_LT && inTemplateInstantiation() && 13537 (pty->getKind() == BuiltinType::BoundMember || 13538 pty->getKind() == BuiltinType::Overload)) { 13539 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13540 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13541 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13542 return isa<FunctionTemplateDecl>(ND); 13543 })) { 13544 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13545 : OE->getNameLoc(), 13546 diag::err_template_kw_missing) 13547 << OE->getName().getAsString() << ""; 13548 return ExprError(); 13549 } 13550 } 13551 13552 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13553 if (LHS.isInvalid()) return ExprError(); 13554 LHSExpr = LHS.get(); 13555 } 13556 13557 // Handle pseudo-objects in the RHS. 13558 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13559 // An overload in the RHS can potentially be resolved by the type 13560 // being assigned to. 13561 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13562 if (getLangOpts().CPlusPlus && 13563 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13564 LHSExpr->getType()->isOverloadableType())) 13565 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13566 13567 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13568 } 13569 13570 // Don't resolve overloads if the other type is overloadable. 13571 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13572 LHSExpr->getType()->isOverloadableType()) 13573 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13574 13575 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13576 if (!resolvedRHS.isUsable()) return ExprError(); 13577 RHSExpr = resolvedRHS.get(); 13578 } 13579 13580 if (getLangOpts().CPlusPlus) { 13581 // If either expression is type-dependent, always build an 13582 // overloaded op. 13583 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13584 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13585 13586 // Otherwise, build an overloaded op if either expression has an 13587 // overloadable type. 13588 if (LHSExpr->getType()->isOverloadableType() || 13589 RHSExpr->getType()->isOverloadableType()) 13590 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13591 } 13592 13593 // Build a built-in binary operation. 13594 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13595 } 13596 13597 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13598 if (T.isNull() || T->isDependentType()) 13599 return false; 13600 13601 if (!T->isPromotableIntegerType()) 13602 return true; 13603 13604 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13605 } 13606 13607 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13608 UnaryOperatorKind Opc, 13609 Expr *InputExpr) { 13610 ExprResult Input = InputExpr; 13611 ExprValueKind VK = VK_RValue; 13612 ExprObjectKind OK = OK_Ordinary; 13613 QualType resultType; 13614 bool CanOverflow = false; 13615 13616 bool ConvertHalfVec = false; 13617 if (getLangOpts().OpenCL) { 13618 QualType Ty = InputExpr->getType(); 13619 // The only legal unary operation for atomics is '&'. 13620 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13621 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13622 // only with a builtin functions and therefore should be disallowed here. 13623 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13624 || Ty->isBlockPointerType())) { 13625 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13626 << InputExpr->getType() 13627 << Input.get()->getSourceRange()); 13628 } 13629 } 13630 // Diagnose operations on the unsupported types for OpenMP device compilation. 13631 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13632 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13633 UnaryOperator::isArithmeticOp(Opc)) 13634 checkOpenMPDeviceExpr(InputExpr); 13635 } 13636 13637 switch (Opc) { 13638 case UO_PreInc: 13639 case UO_PreDec: 13640 case UO_PostInc: 13641 case UO_PostDec: 13642 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13643 OpLoc, 13644 Opc == UO_PreInc || 13645 Opc == UO_PostInc, 13646 Opc == UO_PreInc || 13647 Opc == UO_PreDec); 13648 CanOverflow = isOverflowingIntegerType(Context, resultType); 13649 break; 13650 case UO_AddrOf: 13651 resultType = CheckAddressOfOperand(Input, OpLoc); 13652 CheckAddressOfNoDeref(InputExpr); 13653 RecordModifiableNonNullParam(*this, InputExpr); 13654 break; 13655 case UO_Deref: { 13656 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13657 if (Input.isInvalid()) return ExprError(); 13658 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13659 break; 13660 } 13661 case UO_Plus: 13662 case UO_Minus: 13663 CanOverflow = Opc == UO_Minus && 13664 isOverflowingIntegerType(Context, Input.get()->getType()); 13665 Input = UsualUnaryConversions(Input.get()); 13666 if (Input.isInvalid()) return ExprError(); 13667 // Unary plus and minus require promoting an operand of half vector to a 13668 // float vector and truncating the result back to a half vector. For now, we 13669 // do this only when HalfArgsAndReturns is set (that is, when the target is 13670 // arm or arm64). 13671 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 13672 13673 // If the operand is a half vector, promote it to a float vector. 13674 if (ConvertHalfVec) 13675 Input = convertVector(Input.get(), Context.FloatTy, *this); 13676 resultType = Input.get()->getType(); 13677 if (resultType->isDependentType()) 13678 break; 13679 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13680 break; 13681 else if (resultType->isVectorType() && 13682 // The z vector extensions don't allow + or - with bool vectors. 13683 (!Context.getLangOpts().ZVector || 13684 resultType->castAs<VectorType>()->getVectorKind() != 13685 VectorType::AltiVecBool)) 13686 break; 13687 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13688 Opc == UO_Plus && 13689 resultType->isPointerType()) 13690 break; 13691 13692 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13693 << resultType << Input.get()->getSourceRange()); 13694 13695 case UO_Not: // bitwise complement 13696 Input = UsualUnaryConversions(Input.get()); 13697 if (Input.isInvalid()) 13698 return ExprError(); 13699 resultType = Input.get()->getType(); 13700 if (resultType->isDependentType()) 13701 break; 13702 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13703 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13704 // C99 does not support '~' for complex conjugation. 13705 Diag(OpLoc, diag::ext_integer_complement_complex) 13706 << resultType << Input.get()->getSourceRange(); 13707 else if (resultType->hasIntegerRepresentation()) 13708 break; 13709 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13710 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13711 // on vector float types. 13712 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13713 if (!T->isIntegerType()) 13714 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13715 << resultType << Input.get()->getSourceRange()); 13716 } else { 13717 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13718 << resultType << Input.get()->getSourceRange()); 13719 } 13720 break; 13721 13722 case UO_LNot: // logical negation 13723 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13724 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13725 if (Input.isInvalid()) return ExprError(); 13726 resultType = Input.get()->getType(); 13727 13728 // Though we still have to promote half FP to float... 13729 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13730 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13731 resultType = Context.FloatTy; 13732 } 13733 13734 if (resultType->isDependentType()) 13735 break; 13736 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13737 // C99 6.5.3.3p1: ok, fallthrough; 13738 if (Context.getLangOpts().CPlusPlus) { 13739 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13740 // operand contextually converted to bool. 13741 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13742 ScalarTypeToBooleanCastKind(resultType)); 13743 } else if (Context.getLangOpts().OpenCL && 13744 Context.getLangOpts().OpenCLVersion < 120) { 13745 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13746 // operate on scalar float types. 13747 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13748 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13749 << resultType << Input.get()->getSourceRange()); 13750 } 13751 } else if (resultType->isExtVectorType()) { 13752 if (Context.getLangOpts().OpenCL && 13753 Context.getLangOpts().OpenCLVersion < 120 && 13754 !Context.getLangOpts().OpenCLCPlusPlus) { 13755 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13756 // operate on vector float types. 13757 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13758 if (!T->isIntegerType()) 13759 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13760 << resultType << Input.get()->getSourceRange()); 13761 } 13762 // Vector logical not returns the signed variant of the operand type. 13763 resultType = GetSignedVectorType(resultType); 13764 break; 13765 } else { 13766 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13767 // type in C++. We should allow that here too. 13768 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13769 << resultType << Input.get()->getSourceRange()); 13770 } 13771 13772 // LNot always has type int. C99 6.5.3.3p5. 13773 // In C++, it's bool. C++ 5.3.1p8 13774 resultType = Context.getLogicalOperationType(); 13775 break; 13776 case UO_Real: 13777 case UO_Imag: 13778 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13779 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13780 // complex l-values to ordinary l-values and all other values to r-values. 13781 if (Input.isInvalid()) return ExprError(); 13782 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13783 if (Input.get()->getValueKind() != VK_RValue && 13784 Input.get()->getObjectKind() == OK_Ordinary) 13785 VK = Input.get()->getValueKind(); 13786 } else if (!getLangOpts().CPlusPlus) { 13787 // In C, a volatile scalar is read by __imag. In C++, it is not. 13788 Input = DefaultLvalueConversion(Input.get()); 13789 } 13790 break; 13791 case UO_Extension: 13792 resultType = Input.get()->getType(); 13793 VK = Input.get()->getValueKind(); 13794 OK = Input.get()->getObjectKind(); 13795 break; 13796 case UO_Coawait: 13797 // It's unnecessary to represent the pass-through operator co_await in the 13798 // AST; just return the input expression instead. 13799 assert(!Input.get()->getType()->isDependentType() && 13800 "the co_await expression must be non-dependant before " 13801 "building operator co_await"); 13802 return Input; 13803 } 13804 if (resultType.isNull() || Input.isInvalid()) 13805 return ExprError(); 13806 13807 // Check for array bounds violations in the operand of the UnaryOperator, 13808 // except for the '*' and '&' operators that have to be handled specially 13809 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13810 // that are explicitly defined as valid by the standard). 13811 if (Opc != UO_AddrOf && Opc != UO_Deref) 13812 CheckArrayAccess(Input.get()); 13813 13814 auto *UO = new (Context) 13815 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13816 13817 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13818 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13819 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13820 13821 // Convert the result back to a half vector. 13822 if (ConvertHalfVec) 13823 return convertVector(UO, Context.HalfTy, *this); 13824 return UO; 13825 } 13826 13827 /// Determine whether the given expression is a qualified member 13828 /// access expression, of a form that could be turned into a pointer to member 13829 /// with the address-of operator. 13830 bool Sema::isQualifiedMemberAccess(Expr *E) { 13831 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13832 if (!DRE->getQualifier()) 13833 return false; 13834 13835 ValueDecl *VD = DRE->getDecl(); 13836 if (!VD->isCXXClassMember()) 13837 return false; 13838 13839 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13840 return true; 13841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13842 return Method->isInstance(); 13843 13844 return false; 13845 } 13846 13847 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13848 if (!ULE->getQualifier()) 13849 return false; 13850 13851 for (NamedDecl *D : ULE->decls()) { 13852 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13853 if (Method->isInstance()) 13854 return true; 13855 } else { 13856 // Overload set does not contain methods. 13857 break; 13858 } 13859 } 13860 13861 return false; 13862 } 13863 13864 return false; 13865 } 13866 13867 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13868 UnaryOperatorKind Opc, Expr *Input) { 13869 // First things first: handle placeholders so that the 13870 // overloaded-operator check considers the right type. 13871 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13872 // Increment and decrement of pseudo-object references. 13873 if (pty->getKind() == BuiltinType::PseudoObject && 13874 UnaryOperator::isIncrementDecrementOp(Opc)) 13875 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13876 13877 // extension is always a builtin operator. 13878 if (Opc == UO_Extension) 13879 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13880 13881 // & gets special logic for several kinds of placeholder. 13882 // The builtin code knows what to do. 13883 if (Opc == UO_AddrOf && 13884 (pty->getKind() == BuiltinType::Overload || 13885 pty->getKind() == BuiltinType::UnknownAny || 13886 pty->getKind() == BuiltinType::BoundMember)) 13887 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13888 13889 // Anything else needs to be handled now. 13890 ExprResult Result = CheckPlaceholderExpr(Input); 13891 if (Result.isInvalid()) return ExprError(); 13892 Input = Result.get(); 13893 } 13894 13895 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13896 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13897 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13898 // Find all of the overloaded operators visible from this 13899 // point. We perform both an operator-name lookup from the local 13900 // scope and an argument-dependent lookup based on the types of 13901 // the arguments. 13902 UnresolvedSet<16> Functions; 13903 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13904 if (S && OverOp != OO_None) 13905 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13906 Functions); 13907 13908 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13909 } 13910 13911 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13912 } 13913 13914 // Unary Operators. 'Tok' is the token for the operator. 13915 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13916 tok::TokenKind Op, Expr *Input) { 13917 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13918 } 13919 13920 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13921 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13922 LabelDecl *TheDecl) { 13923 TheDecl->markUsed(Context); 13924 // Create the AST node. The address of a label always has type 'void*'. 13925 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13926 Context.getPointerType(Context.VoidTy)); 13927 } 13928 13929 void Sema::ActOnStartStmtExpr() { 13930 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13931 } 13932 13933 void Sema::ActOnStmtExprError() { 13934 // Note that function is also called by TreeTransform when leaving a 13935 // StmtExpr scope without rebuilding anything. 13936 13937 DiscardCleanupsInEvaluationContext(); 13938 PopExpressionEvaluationContext(); 13939 } 13940 13941 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 13942 SourceLocation RPLoc) { 13943 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 13944 } 13945 13946 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13947 SourceLocation RPLoc, unsigned TemplateDepth) { 13948 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13949 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13950 13951 if (hasAnyUnrecoverableErrorsInThisFunction()) 13952 DiscardCleanupsInEvaluationContext(); 13953 assert(!Cleanup.exprNeedsCleanups() && 13954 "cleanups within StmtExpr not correctly bound!"); 13955 PopExpressionEvaluationContext(); 13956 13957 // FIXME: there are a variety of strange constraints to enforce here, for 13958 // example, it is not possible to goto into a stmt expression apparently. 13959 // More semantic analysis is needed. 13960 13961 // If there are sub-stmts in the compound stmt, take the type of the last one 13962 // as the type of the stmtexpr. 13963 QualType Ty = Context.VoidTy; 13964 bool StmtExprMayBindToTemp = false; 13965 if (!Compound->body_empty()) { 13966 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13967 if (const auto *LastStmt = 13968 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13969 if (const Expr *Value = LastStmt->getExprStmt()) { 13970 StmtExprMayBindToTemp = true; 13971 Ty = Value->getType(); 13972 } 13973 } 13974 } 13975 13976 // FIXME: Check that expression type is complete/non-abstract; statement 13977 // expressions are not lvalues. 13978 Expr *ResStmtExpr = 13979 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 13980 if (StmtExprMayBindToTemp) 13981 return MaybeBindToTemporary(ResStmtExpr); 13982 return ResStmtExpr; 13983 } 13984 13985 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13986 if (ER.isInvalid()) 13987 return ExprError(); 13988 13989 // Do function/array conversion on the last expression, but not 13990 // lvalue-to-rvalue. However, initialize an unqualified type. 13991 ER = DefaultFunctionArrayConversion(ER.get()); 13992 if (ER.isInvalid()) 13993 return ExprError(); 13994 Expr *E = ER.get(); 13995 13996 if (E->isTypeDependent()) 13997 return E; 13998 13999 // In ARC, if the final expression ends in a consume, splice 14000 // the consume out and bind it later. In the alternate case 14001 // (when dealing with a retainable type), the result 14002 // initialization will create a produce. In both cases the 14003 // result will be +1, and we'll need to balance that out with 14004 // a bind. 14005 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14006 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14007 return Cast->getSubExpr(); 14008 14009 // FIXME: Provide a better location for the initialization. 14010 return PerformCopyInitialization( 14011 InitializedEntity::InitializeStmtExprResult( 14012 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14013 SourceLocation(), E); 14014 } 14015 14016 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14017 TypeSourceInfo *TInfo, 14018 ArrayRef<OffsetOfComponent> Components, 14019 SourceLocation RParenLoc) { 14020 QualType ArgTy = TInfo->getType(); 14021 bool Dependent = ArgTy->isDependentType(); 14022 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14023 14024 // We must have at least one component that refers to the type, and the first 14025 // one is known to be a field designator. Verify that the ArgTy represents 14026 // a struct/union/class. 14027 if (!Dependent && !ArgTy->isRecordType()) 14028 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14029 << ArgTy << TypeRange); 14030 14031 // Type must be complete per C99 7.17p3 because a declaring a variable 14032 // with an incomplete type would be ill-formed. 14033 if (!Dependent 14034 && RequireCompleteType(BuiltinLoc, ArgTy, 14035 diag::err_offsetof_incomplete_type, TypeRange)) 14036 return ExprError(); 14037 14038 bool DidWarnAboutNonPOD = false; 14039 QualType CurrentType = ArgTy; 14040 SmallVector<OffsetOfNode, 4> Comps; 14041 SmallVector<Expr*, 4> Exprs; 14042 for (const OffsetOfComponent &OC : Components) { 14043 if (OC.isBrackets) { 14044 // Offset of an array sub-field. TODO: Should we allow vector elements? 14045 if (!CurrentType->isDependentType()) { 14046 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14047 if(!AT) 14048 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14049 << CurrentType); 14050 CurrentType = AT->getElementType(); 14051 } else 14052 CurrentType = Context.DependentTy; 14053 14054 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14055 if (IdxRval.isInvalid()) 14056 return ExprError(); 14057 Expr *Idx = IdxRval.get(); 14058 14059 // The expression must be an integral expression. 14060 // FIXME: An integral constant expression? 14061 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14062 !Idx->getType()->isIntegerType()) 14063 return ExprError( 14064 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14065 << Idx->getSourceRange()); 14066 14067 // Record this array index. 14068 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14069 Exprs.push_back(Idx); 14070 continue; 14071 } 14072 14073 // Offset of a field. 14074 if (CurrentType->isDependentType()) { 14075 // We have the offset of a field, but we can't look into the dependent 14076 // type. Just record the identifier of the field. 14077 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14078 CurrentType = Context.DependentTy; 14079 continue; 14080 } 14081 14082 // We need to have a complete type to look into. 14083 if (RequireCompleteType(OC.LocStart, CurrentType, 14084 diag::err_offsetof_incomplete_type)) 14085 return ExprError(); 14086 14087 // Look for the designated field. 14088 const RecordType *RC = CurrentType->getAs<RecordType>(); 14089 if (!RC) 14090 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14091 << CurrentType); 14092 RecordDecl *RD = RC->getDecl(); 14093 14094 // C++ [lib.support.types]p5: 14095 // The macro offsetof accepts a restricted set of type arguments in this 14096 // International Standard. type shall be a POD structure or a POD union 14097 // (clause 9). 14098 // C++11 [support.types]p4: 14099 // If type is not a standard-layout class (Clause 9), the results are 14100 // undefined. 14101 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14102 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14103 unsigned DiagID = 14104 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14105 : diag::ext_offsetof_non_pod_type; 14106 14107 if (!IsSafe && !DidWarnAboutNonPOD && 14108 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14109 PDiag(DiagID) 14110 << SourceRange(Components[0].LocStart, OC.LocEnd) 14111 << CurrentType)) 14112 DidWarnAboutNonPOD = true; 14113 } 14114 14115 // Look for the field. 14116 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14117 LookupQualifiedName(R, RD); 14118 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14119 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14120 if (!MemberDecl) { 14121 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14122 MemberDecl = IndirectMemberDecl->getAnonField(); 14123 } 14124 14125 if (!MemberDecl) 14126 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14127 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14128 OC.LocEnd)); 14129 14130 // C99 7.17p3: 14131 // (If the specified member is a bit-field, the behavior is undefined.) 14132 // 14133 // We diagnose this as an error. 14134 if (MemberDecl->isBitField()) { 14135 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14136 << MemberDecl->getDeclName() 14137 << SourceRange(BuiltinLoc, RParenLoc); 14138 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14139 return ExprError(); 14140 } 14141 14142 RecordDecl *Parent = MemberDecl->getParent(); 14143 if (IndirectMemberDecl) 14144 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14145 14146 // If the member was found in a base class, introduce OffsetOfNodes for 14147 // the base class indirections. 14148 CXXBasePaths Paths; 14149 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14150 Paths)) { 14151 if (Paths.getDetectedVirtual()) { 14152 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14153 << MemberDecl->getDeclName() 14154 << SourceRange(BuiltinLoc, RParenLoc); 14155 return ExprError(); 14156 } 14157 14158 CXXBasePath &Path = Paths.front(); 14159 for (const CXXBasePathElement &B : Path) 14160 Comps.push_back(OffsetOfNode(B.Base)); 14161 } 14162 14163 if (IndirectMemberDecl) { 14164 for (auto *FI : IndirectMemberDecl->chain()) { 14165 assert(isa<FieldDecl>(FI)); 14166 Comps.push_back(OffsetOfNode(OC.LocStart, 14167 cast<FieldDecl>(FI), OC.LocEnd)); 14168 } 14169 } else 14170 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14171 14172 CurrentType = MemberDecl->getType().getNonReferenceType(); 14173 } 14174 14175 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14176 Comps, Exprs, RParenLoc); 14177 } 14178 14179 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14180 SourceLocation BuiltinLoc, 14181 SourceLocation TypeLoc, 14182 ParsedType ParsedArgTy, 14183 ArrayRef<OffsetOfComponent> Components, 14184 SourceLocation RParenLoc) { 14185 14186 TypeSourceInfo *ArgTInfo; 14187 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14188 if (ArgTy.isNull()) 14189 return ExprError(); 14190 14191 if (!ArgTInfo) 14192 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14193 14194 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14195 } 14196 14197 14198 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14199 Expr *CondExpr, 14200 Expr *LHSExpr, Expr *RHSExpr, 14201 SourceLocation RPLoc) { 14202 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14203 14204 ExprValueKind VK = VK_RValue; 14205 ExprObjectKind OK = OK_Ordinary; 14206 QualType resType; 14207 bool ValueDependent = false; 14208 bool CondIsTrue = false; 14209 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14210 resType = Context.DependentTy; 14211 ValueDependent = true; 14212 } else { 14213 // The conditional expression is required to be a constant expression. 14214 llvm::APSInt condEval(32); 14215 ExprResult CondICE 14216 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14217 diag::err_typecheck_choose_expr_requires_constant, false); 14218 if (CondICE.isInvalid()) 14219 return ExprError(); 14220 CondExpr = CondICE.get(); 14221 CondIsTrue = condEval.getZExtValue(); 14222 14223 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14224 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14225 14226 resType = ActiveExpr->getType(); 14227 ValueDependent = ActiveExpr->isValueDependent(); 14228 VK = ActiveExpr->getValueKind(); 14229 OK = ActiveExpr->getObjectKind(); 14230 } 14231 14232 return new (Context) 14233 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14234 CondIsTrue, resType->isDependentType(), ValueDependent); 14235 } 14236 14237 //===----------------------------------------------------------------------===// 14238 // Clang Extensions. 14239 //===----------------------------------------------------------------------===// 14240 14241 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14242 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14243 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14244 14245 if (LangOpts.CPlusPlus) { 14246 MangleNumberingContext *MCtx; 14247 Decl *ManglingContextDecl; 14248 std::tie(MCtx, ManglingContextDecl) = 14249 getCurrentMangleNumberContext(Block->getDeclContext()); 14250 if (MCtx) { 14251 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14252 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14253 } 14254 } 14255 14256 PushBlockScope(CurScope, Block); 14257 CurContext->addDecl(Block); 14258 if (CurScope) 14259 PushDeclContext(CurScope, Block); 14260 else 14261 CurContext = Block; 14262 14263 getCurBlock()->HasImplicitReturnType = true; 14264 14265 // Enter a new evaluation context to insulate the block from any 14266 // cleanups from the enclosing full-expression. 14267 PushExpressionEvaluationContext( 14268 ExpressionEvaluationContext::PotentiallyEvaluated); 14269 } 14270 14271 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14272 Scope *CurScope) { 14273 assert(ParamInfo.getIdentifier() == nullptr && 14274 "block-id should have no identifier!"); 14275 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14276 BlockScopeInfo *CurBlock = getCurBlock(); 14277 14278 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14279 QualType T = Sig->getType(); 14280 14281 // FIXME: We should allow unexpanded parameter packs here, but that would, 14282 // in turn, make the block expression contain unexpanded parameter packs. 14283 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14284 // Drop the parameters. 14285 FunctionProtoType::ExtProtoInfo EPI; 14286 EPI.HasTrailingReturn = false; 14287 EPI.TypeQuals.addConst(); 14288 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14289 Sig = Context.getTrivialTypeSourceInfo(T); 14290 } 14291 14292 // GetTypeForDeclarator always produces a function type for a block 14293 // literal signature. Furthermore, it is always a FunctionProtoType 14294 // unless the function was written with a typedef. 14295 assert(T->isFunctionType() && 14296 "GetTypeForDeclarator made a non-function block signature"); 14297 14298 // Look for an explicit signature in that function type. 14299 FunctionProtoTypeLoc ExplicitSignature; 14300 14301 if ((ExplicitSignature = Sig->getTypeLoc() 14302 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14303 14304 // Check whether that explicit signature was synthesized by 14305 // GetTypeForDeclarator. If so, don't save that as part of the 14306 // written signature. 14307 if (ExplicitSignature.getLocalRangeBegin() == 14308 ExplicitSignature.getLocalRangeEnd()) { 14309 // This would be much cheaper if we stored TypeLocs instead of 14310 // TypeSourceInfos. 14311 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14312 unsigned Size = Result.getFullDataSize(); 14313 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14314 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14315 14316 ExplicitSignature = FunctionProtoTypeLoc(); 14317 } 14318 } 14319 14320 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14321 CurBlock->FunctionType = T; 14322 14323 const FunctionType *Fn = T->getAs<FunctionType>(); 14324 QualType RetTy = Fn->getReturnType(); 14325 bool isVariadic = 14326 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14327 14328 CurBlock->TheDecl->setIsVariadic(isVariadic); 14329 14330 // Context.DependentTy is used as a placeholder for a missing block 14331 // return type. TODO: what should we do with declarators like: 14332 // ^ * { ... } 14333 // If the answer is "apply template argument deduction".... 14334 if (RetTy != Context.DependentTy) { 14335 CurBlock->ReturnType = RetTy; 14336 CurBlock->TheDecl->setBlockMissingReturnType(false); 14337 CurBlock->HasImplicitReturnType = false; 14338 } 14339 14340 // Push block parameters from the declarator if we had them. 14341 SmallVector<ParmVarDecl*, 8> Params; 14342 if (ExplicitSignature) { 14343 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14344 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14345 if (Param->getIdentifier() == nullptr && 14346 !Param->isImplicit() && 14347 !Param->isInvalidDecl() && 14348 !getLangOpts().CPlusPlus) 14349 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14350 Params.push_back(Param); 14351 } 14352 14353 // Fake up parameter variables if we have a typedef, like 14354 // ^ fntype { ... } 14355 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14356 for (const auto &I : Fn->param_types()) { 14357 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14358 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14359 Params.push_back(Param); 14360 } 14361 } 14362 14363 // Set the parameters on the block decl. 14364 if (!Params.empty()) { 14365 CurBlock->TheDecl->setParams(Params); 14366 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14367 /*CheckParameterNames=*/false); 14368 } 14369 14370 // Finally we can process decl attributes. 14371 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14372 14373 // Put the parameter variables in scope. 14374 for (auto AI : CurBlock->TheDecl->parameters()) { 14375 AI->setOwningFunction(CurBlock->TheDecl); 14376 14377 // If this has an identifier, add it to the scope stack. 14378 if (AI->getIdentifier()) { 14379 CheckShadow(CurBlock->TheScope, AI); 14380 14381 PushOnScopeChains(AI, CurBlock->TheScope); 14382 } 14383 } 14384 } 14385 14386 /// ActOnBlockError - If there is an error parsing a block, this callback 14387 /// is invoked to pop the information about the block from the action impl. 14388 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14389 // Leave the expression-evaluation context. 14390 DiscardCleanupsInEvaluationContext(); 14391 PopExpressionEvaluationContext(); 14392 14393 // Pop off CurBlock, handle nested blocks. 14394 PopDeclContext(); 14395 PopFunctionScopeInfo(); 14396 } 14397 14398 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14399 /// literal was successfully completed. ^(int x){...} 14400 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14401 Stmt *Body, Scope *CurScope) { 14402 // If blocks are disabled, emit an error. 14403 if (!LangOpts.Blocks) 14404 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14405 14406 // Leave the expression-evaluation context. 14407 if (hasAnyUnrecoverableErrorsInThisFunction()) 14408 DiscardCleanupsInEvaluationContext(); 14409 assert(!Cleanup.exprNeedsCleanups() && 14410 "cleanups within block not correctly bound!"); 14411 PopExpressionEvaluationContext(); 14412 14413 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14414 BlockDecl *BD = BSI->TheDecl; 14415 14416 if (BSI->HasImplicitReturnType) 14417 deduceClosureReturnType(*BSI); 14418 14419 QualType RetTy = Context.VoidTy; 14420 if (!BSI->ReturnType.isNull()) 14421 RetTy = BSI->ReturnType; 14422 14423 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14424 QualType BlockTy; 14425 14426 // If the user wrote a function type in some form, try to use that. 14427 if (!BSI->FunctionType.isNull()) { 14428 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14429 14430 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14431 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14432 14433 // Turn protoless block types into nullary block types. 14434 if (isa<FunctionNoProtoType>(FTy)) { 14435 FunctionProtoType::ExtProtoInfo EPI; 14436 EPI.ExtInfo = Ext; 14437 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14438 14439 // Otherwise, if we don't need to change anything about the function type, 14440 // preserve its sugar structure. 14441 } else if (FTy->getReturnType() == RetTy && 14442 (!NoReturn || FTy->getNoReturnAttr())) { 14443 BlockTy = BSI->FunctionType; 14444 14445 // Otherwise, make the minimal modifications to the function type. 14446 } else { 14447 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14448 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14449 EPI.TypeQuals = Qualifiers(); 14450 EPI.ExtInfo = Ext; 14451 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14452 } 14453 14454 // If we don't have a function type, just build one from nothing. 14455 } else { 14456 FunctionProtoType::ExtProtoInfo EPI; 14457 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14458 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14459 } 14460 14461 DiagnoseUnusedParameters(BD->parameters()); 14462 BlockTy = Context.getBlockPointerType(BlockTy); 14463 14464 // If needed, diagnose invalid gotos and switches in the block. 14465 if (getCurFunction()->NeedsScopeChecking() && 14466 !PP.isCodeCompletionEnabled()) 14467 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14468 14469 BD->setBody(cast<CompoundStmt>(Body)); 14470 14471 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14472 DiagnoseUnguardedAvailabilityViolations(BD); 14473 14474 // Try to apply the named return value optimization. We have to check again 14475 // if we can do this, though, because blocks keep return statements around 14476 // to deduce an implicit return type. 14477 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14478 !BD->isDependentContext()) 14479 computeNRVO(Body, BSI); 14480 14481 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14482 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14483 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14484 NTCUK_Destruct|NTCUK_Copy); 14485 14486 PopDeclContext(); 14487 14488 // Pop the block scope now but keep it alive to the end of this function. 14489 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14490 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14491 14492 // Set the captured variables on the block. 14493 SmallVector<BlockDecl::Capture, 4> Captures; 14494 for (Capture &Cap : BSI->Captures) { 14495 if (Cap.isInvalid() || Cap.isThisCapture()) 14496 continue; 14497 14498 VarDecl *Var = Cap.getVariable(); 14499 Expr *CopyExpr = nullptr; 14500 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14501 if (const RecordType *Record = 14502 Cap.getCaptureType()->getAs<RecordType>()) { 14503 // The capture logic needs the destructor, so make sure we mark it. 14504 // Usually this is unnecessary because most local variables have 14505 // their destructors marked at declaration time, but parameters are 14506 // an exception because it's technically only the call site that 14507 // actually requires the destructor. 14508 if (isa<ParmVarDecl>(Var)) 14509 FinalizeVarWithDestructor(Var, Record); 14510 14511 // Enter a separate potentially-evaluated context while building block 14512 // initializers to isolate their cleanups from those of the block 14513 // itself. 14514 // FIXME: Is this appropriate even when the block itself occurs in an 14515 // unevaluated operand? 14516 EnterExpressionEvaluationContext EvalContext( 14517 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14518 14519 SourceLocation Loc = Cap.getLocation(); 14520 14521 ExprResult Result = BuildDeclarationNameExpr( 14522 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14523 14524 // According to the blocks spec, the capture of a variable from 14525 // the stack requires a const copy constructor. This is not true 14526 // of the copy/move done to move a __block variable to the heap. 14527 if (!Result.isInvalid() && 14528 !Result.get()->getType().isConstQualified()) { 14529 Result = ImpCastExprToType(Result.get(), 14530 Result.get()->getType().withConst(), 14531 CK_NoOp, VK_LValue); 14532 } 14533 14534 if (!Result.isInvalid()) { 14535 Result = PerformCopyInitialization( 14536 InitializedEntity::InitializeBlock(Var->getLocation(), 14537 Cap.getCaptureType(), false), 14538 Loc, Result.get()); 14539 } 14540 14541 // Build a full-expression copy expression if initialization 14542 // succeeded and used a non-trivial constructor. Recover from 14543 // errors by pretending that the copy isn't necessary. 14544 if (!Result.isInvalid() && 14545 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14546 ->isTrivial()) { 14547 Result = MaybeCreateExprWithCleanups(Result); 14548 CopyExpr = Result.get(); 14549 } 14550 } 14551 } 14552 14553 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14554 CopyExpr); 14555 Captures.push_back(NewCap); 14556 } 14557 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14558 14559 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14560 14561 // If the block isn't obviously global, i.e. it captures anything at 14562 // all, then we need to do a few things in the surrounding context: 14563 if (Result->getBlockDecl()->hasCaptures()) { 14564 // First, this expression has a new cleanup object. 14565 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14566 Cleanup.setExprNeedsCleanups(true); 14567 14568 // It also gets a branch-protected scope if any of the captured 14569 // variables needs destruction. 14570 for (const auto &CI : Result->getBlockDecl()->captures()) { 14571 const VarDecl *var = CI.getVariable(); 14572 if (var->getType().isDestructedType() != QualType::DK_none) { 14573 setFunctionHasBranchProtectedScope(); 14574 break; 14575 } 14576 } 14577 } 14578 14579 if (getCurFunction()) 14580 getCurFunction()->addBlock(BD); 14581 14582 return Result; 14583 } 14584 14585 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14586 SourceLocation RPLoc) { 14587 TypeSourceInfo *TInfo; 14588 GetTypeFromParser(Ty, &TInfo); 14589 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14590 } 14591 14592 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14593 Expr *E, TypeSourceInfo *TInfo, 14594 SourceLocation RPLoc) { 14595 Expr *OrigExpr = E; 14596 bool IsMS = false; 14597 14598 // CUDA device code does not support varargs. 14599 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14600 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14601 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14602 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14603 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14604 } 14605 } 14606 14607 // NVPTX does not support va_arg expression. 14608 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14609 Context.getTargetInfo().getTriple().isNVPTX()) 14610 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14611 14612 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14613 // as Microsoft ABI on an actual Microsoft platform, where 14614 // __builtin_ms_va_list and __builtin_va_list are the same.) 14615 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14616 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14617 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14618 if (Context.hasSameType(MSVaListType, E->getType())) { 14619 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14620 return ExprError(); 14621 IsMS = true; 14622 } 14623 } 14624 14625 // Get the va_list type 14626 QualType VaListType = Context.getBuiltinVaListType(); 14627 if (!IsMS) { 14628 if (VaListType->isArrayType()) { 14629 // Deal with implicit array decay; for example, on x86-64, 14630 // va_list is an array, but it's supposed to decay to 14631 // a pointer for va_arg. 14632 VaListType = Context.getArrayDecayedType(VaListType); 14633 // Make sure the input expression also decays appropriately. 14634 ExprResult Result = UsualUnaryConversions(E); 14635 if (Result.isInvalid()) 14636 return ExprError(); 14637 E = Result.get(); 14638 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14639 // If va_list is a record type and we are compiling in C++ mode, 14640 // check the argument using reference binding. 14641 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14642 Context, Context.getLValueReferenceType(VaListType), false); 14643 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14644 if (Init.isInvalid()) 14645 return ExprError(); 14646 E = Init.getAs<Expr>(); 14647 } else { 14648 // Otherwise, the va_list argument must be an l-value because 14649 // it is modified by va_arg. 14650 if (!E->isTypeDependent() && 14651 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14652 return ExprError(); 14653 } 14654 } 14655 14656 if (!IsMS && !E->isTypeDependent() && 14657 !Context.hasSameType(VaListType, E->getType())) 14658 return ExprError( 14659 Diag(E->getBeginLoc(), 14660 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14661 << OrigExpr->getType() << E->getSourceRange()); 14662 14663 if (!TInfo->getType()->isDependentType()) { 14664 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14665 diag::err_second_parameter_to_va_arg_incomplete, 14666 TInfo->getTypeLoc())) 14667 return ExprError(); 14668 14669 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14670 TInfo->getType(), 14671 diag::err_second_parameter_to_va_arg_abstract, 14672 TInfo->getTypeLoc())) 14673 return ExprError(); 14674 14675 if (!TInfo->getType().isPODType(Context)) { 14676 Diag(TInfo->getTypeLoc().getBeginLoc(), 14677 TInfo->getType()->isObjCLifetimeType() 14678 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14679 : diag::warn_second_parameter_to_va_arg_not_pod) 14680 << TInfo->getType() 14681 << TInfo->getTypeLoc().getSourceRange(); 14682 } 14683 14684 // Check for va_arg where arguments of the given type will be promoted 14685 // (i.e. this va_arg is guaranteed to have undefined behavior). 14686 QualType PromoteType; 14687 if (TInfo->getType()->isPromotableIntegerType()) { 14688 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14689 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14690 PromoteType = QualType(); 14691 } 14692 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14693 PromoteType = Context.DoubleTy; 14694 if (!PromoteType.isNull()) 14695 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14696 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14697 << TInfo->getType() 14698 << PromoteType 14699 << TInfo->getTypeLoc().getSourceRange()); 14700 } 14701 14702 QualType T = TInfo->getType().getNonLValueExprType(Context); 14703 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14704 } 14705 14706 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14707 // The type of __null will be int or long, depending on the size of 14708 // pointers on the target. 14709 QualType Ty; 14710 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14711 if (pw == Context.getTargetInfo().getIntWidth()) 14712 Ty = Context.IntTy; 14713 else if (pw == Context.getTargetInfo().getLongWidth()) 14714 Ty = Context.LongTy; 14715 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14716 Ty = Context.LongLongTy; 14717 else { 14718 llvm_unreachable("I don't know size of pointer!"); 14719 } 14720 14721 return new (Context) GNUNullExpr(Ty, TokenLoc); 14722 } 14723 14724 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14725 SourceLocation BuiltinLoc, 14726 SourceLocation RPLoc) { 14727 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14728 } 14729 14730 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14731 SourceLocation BuiltinLoc, 14732 SourceLocation RPLoc, 14733 DeclContext *ParentContext) { 14734 return new (Context) 14735 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14736 } 14737 14738 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14739 bool Diagnose) { 14740 if (!getLangOpts().ObjC) 14741 return false; 14742 14743 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14744 if (!PT) 14745 return false; 14746 14747 if (!PT->isObjCIdType()) { 14748 // Check if the destination is the 'NSString' interface. 14749 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14750 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14751 return false; 14752 } 14753 14754 // Ignore any parens, implicit casts (should only be 14755 // array-to-pointer decays), and not-so-opaque values. The last is 14756 // important for making this trigger for property assignments. 14757 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14758 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14759 if (OV->getSourceExpr()) 14760 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14761 14762 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14763 if (!SL || !SL->isAscii()) 14764 return false; 14765 if (Diagnose) { 14766 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14767 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14768 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14769 } 14770 return true; 14771 } 14772 14773 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14774 const Expr *SrcExpr) { 14775 if (!DstType->isFunctionPointerType() || 14776 !SrcExpr->getType()->isFunctionType()) 14777 return false; 14778 14779 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14780 if (!DRE) 14781 return false; 14782 14783 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14784 if (!FD) 14785 return false; 14786 14787 return !S.checkAddressOfFunctionIsAvailable(FD, 14788 /*Complain=*/true, 14789 SrcExpr->getBeginLoc()); 14790 } 14791 14792 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14793 SourceLocation Loc, 14794 QualType DstType, QualType SrcType, 14795 Expr *SrcExpr, AssignmentAction Action, 14796 bool *Complained) { 14797 if (Complained) 14798 *Complained = false; 14799 14800 // Decode the result (notice that AST's are still created for extensions). 14801 bool CheckInferredResultType = false; 14802 bool isInvalid = false; 14803 unsigned DiagKind = 0; 14804 FixItHint Hint; 14805 ConversionFixItGenerator ConvHints; 14806 bool MayHaveConvFixit = false; 14807 bool MayHaveFunctionDiff = false; 14808 const ObjCInterfaceDecl *IFace = nullptr; 14809 const ObjCProtocolDecl *PDecl = nullptr; 14810 14811 switch (ConvTy) { 14812 case Compatible: 14813 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14814 return false; 14815 14816 case PointerToInt: 14817 if (getLangOpts().CPlusPlus) { 14818 DiagKind = diag::err_typecheck_convert_pointer_int; 14819 isInvalid = true; 14820 } else { 14821 DiagKind = diag::ext_typecheck_convert_pointer_int; 14822 } 14823 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14824 MayHaveConvFixit = true; 14825 break; 14826 case IntToPointer: 14827 if (getLangOpts().CPlusPlus) { 14828 DiagKind = diag::err_typecheck_convert_int_pointer; 14829 isInvalid = true; 14830 } else { 14831 DiagKind = diag::ext_typecheck_convert_int_pointer; 14832 } 14833 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14834 MayHaveConvFixit = true; 14835 break; 14836 case IncompatibleFunctionPointer: 14837 if (getLangOpts().CPlusPlus) { 14838 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 14839 isInvalid = true; 14840 } else { 14841 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14842 } 14843 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14844 MayHaveConvFixit = true; 14845 break; 14846 case IncompatiblePointer: 14847 if (Action == AA_Passing_CFAudited) { 14848 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14849 } else if (getLangOpts().CPlusPlus) { 14850 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 14851 isInvalid = true; 14852 } else { 14853 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14854 } 14855 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14856 SrcType->isObjCObjectPointerType(); 14857 if (Hint.isNull() && !CheckInferredResultType) { 14858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14859 } 14860 else if (CheckInferredResultType) { 14861 SrcType = SrcType.getUnqualifiedType(); 14862 DstType = DstType.getUnqualifiedType(); 14863 } 14864 MayHaveConvFixit = true; 14865 break; 14866 case IncompatiblePointerSign: 14867 if (getLangOpts().CPlusPlus) { 14868 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 14869 isInvalid = true; 14870 } else { 14871 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14872 } 14873 break; 14874 case FunctionVoidPointer: 14875 if (getLangOpts().CPlusPlus) { 14876 DiagKind = diag::err_typecheck_convert_pointer_void_func; 14877 isInvalid = true; 14878 } else { 14879 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14880 } 14881 break; 14882 case IncompatiblePointerDiscardsQualifiers: { 14883 // Perform array-to-pointer decay if necessary. 14884 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14885 14886 isInvalid = true; 14887 14888 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14889 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14890 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14891 DiagKind = diag::err_typecheck_incompatible_address_space; 14892 break; 14893 14894 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14895 DiagKind = diag::err_typecheck_incompatible_ownership; 14896 break; 14897 } 14898 14899 llvm_unreachable("unknown error case for discarding qualifiers!"); 14900 // fallthrough 14901 } 14902 case CompatiblePointerDiscardsQualifiers: 14903 // If the qualifiers lost were because we were applying the 14904 // (deprecated) C++ conversion from a string literal to a char* 14905 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14906 // Ideally, this check would be performed in 14907 // checkPointerTypesForAssignment. However, that would require a 14908 // bit of refactoring (so that the second argument is an 14909 // expression, rather than a type), which should be done as part 14910 // of a larger effort to fix checkPointerTypesForAssignment for 14911 // C++ semantics. 14912 if (getLangOpts().CPlusPlus && 14913 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14914 return false; 14915 if (getLangOpts().CPlusPlus) { 14916 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 14917 isInvalid = true; 14918 } else { 14919 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14920 } 14921 14922 break; 14923 case IncompatibleNestedPointerQualifiers: 14924 if (getLangOpts().CPlusPlus) { 14925 isInvalid = true; 14926 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 14927 } else { 14928 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14929 } 14930 break; 14931 case IncompatibleNestedPointerAddressSpaceMismatch: 14932 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14933 isInvalid = true; 14934 break; 14935 case IntToBlockPointer: 14936 DiagKind = diag::err_int_to_block_pointer; 14937 isInvalid = true; 14938 break; 14939 case IncompatibleBlockPointer: 14940 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14941 isInvalid = true; 14942 break; 14943 case IncompatibleObjCQualifiedId: { 14944 if (SrcType->isObjCQualifiedIdType()) { 14945 const ObjCObjectPointerType *srcOPT = 14946 SrcType->castAs<ObjCObjectPointerType>(); 14947 for (auto *srcProto : srcOPT->quals()) { 14948 PDecl = srcProto; 14949 break; 14950 } 14951 if (const ObjCInterfaceType *IFaceT = 14952 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14953 IFace = IFaceT->getDecl(); 14954 } 14955 else if (DstType->isObjCQualifiedIdType()) { 14956 const ObjCObjectPointerType *dstOPT = 14957 DstType->castAs<ObjCObjectPointerType>(); 14958 for (auto *dstProto : dstOPT->quals()) { 14959 PDecl = dstProto; 14960 break; 14961 } 14962 if (const ObjCInterfaceType *IFaceT = 14963 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14964 IFace = IFaceT->getDecl(); 14965 } 14966 if (getLangOpts().CPlusPlus) { 14967 DiagKind = diag::err_incompatible_qualified_id; 14968 isInvalid = true; 14969 } else { 14970 DiagKind = diag::warn_incompatible_qualified_id; 14971 } 14972 break; 14973 } 14974 case IncompatibleVectors: 14975 if (getLangOpts().CPlusPlus) { 14976 DiagKind = diag::err_incompatible_vectors; 14977 isInvalid = true; 14978 } else { 14979 DiagKind = diag::warn_incompatible_vectors; 14980 } 14981 break; 14982 case IncompatibleObjCWeakRef: 14983 DiagKind = diag::err_arc_weak_unavailable_assign; 14984 isInvalid = true; 14985 break; 14986 case Incompatible: 14987 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14988 if (Complained) 14989 *Complained = true; 14990 return true; 14991 } 14992 14993 DiagKind = diag::err_typecheck_convert_incompatible; 14994 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14995 MayHaveConvFixit = true; 14996 isInvalid = true; 14997 MayHaveFunctionDiff = true; 14998 break; 14999 } 15000 15001 QualType FirstType, SecondType; 15002 switch (Action) { 15003 case AA_Assigning: 15004 case AA_Initializing: 15005 // The destination type comes first. 15006 FirstType = DstType; 15007 SecondType = SrcType; 15008 break; 15009 15010 case AA_Returning: 15011 case AA_Passing: 15012 case AA_Passing_CFAudited: 15013 case AA_Converting: 15014 case AA_Sending: 15015 case AA_Casting: 15016 // The source type comes first. 15017 FirstType = SrcType; 15018 SecondType = DstType; 15019 break; 15020 } 15021 15022 PartialDiagnostic FDiag = PDiag(DiagKind); 15023 if (Action == AA_Passing_CFAudited) 15024 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15025 else 15026 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15027 15028 // If we can fix the conversion, suggest the FixIts. 15029 assert(ConvHints.isNull() || Hint.isNull()); 15030 if (!ConvHints.isNull()) { 15031 for (FixItHint &H : ConvHints.Hints) 15032 FDiag << H; 15033 } else { 15034 FDiag << Hint; 15035 } 15036 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15037 15038 if (MayHaveFunctionDiff) 15039 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15040 15041 Diag(Loc, FDiag); 15042 if ((DiagKind == diag::warn_incompatible_qualified_id || 15043 DiagKind == diag::err_incompatible_qualified_id) && 15044 PDecl && IFace && !IFace->hasDefinition()) 15045 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15046 << IFace << PDecl; 15047 15048 if (SecondType == Context.OverloadTy) 15049 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15050 FirstType, /*TakingAddress=*/true); 15051 15052 if (CheckInferredResultType) 15053 EmitRelatedResultTypeNote(SrcExpr); 15054 15055 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15056 EmitRelatedResultTypeNoteForReturn(DstType); 15057 15058 if (Complained) 15059 *Complained = true; 15060 return isInvalid; 15061 } 15062 15063 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15064 llvm::APSInt *Result) { 15065 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15066 public: 15067 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15068 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15069 } 15070 } Diagnoser; 15071 15072 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15073 } 15074 15075 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15076 llvm::APSInt *Result, 15077 unsigned DiagID, 15078 bool AllowFold) { 15079 class IDDiagnoser : public VerifyICEDiagnoser { 15080 unsigned DiagID; 15081 15082 public: 15083 IDDiagnoser(unsigned DiagID) 15084 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15085 15086 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15087 S.Diag(Loc, DiagID) << SR; 15088 } 15089 } Diagnoser(DiagID); 15090 15091 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15092 } 15093 15094 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15095 SourceRange SR) { 15096 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15097 } 15098 15099 ExprResult 15100 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15101 VerifyICEDiagnoser &Diagnoser, 15102 bool AllowFold) { 15103 SourceLocation DiagLoc = E->getBeginLoc(); 15104 15105 if (getLangOpts().CPlusPlus11) { 15106 // C++11 [expr.const]p5: 15107 // If an expression of literal class type is used in a context where an 15108 // integral constant expression is required, then that class type shall 15109 // have a single non-explicit conversion function to an integral or 15110 // unscoped enumeration type 15111 ExprResult Converted; 15112 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15113 public: 15114 CXX11ConvertDiagnoser(bool Silent) 15115 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15116 Silent, true) {} 15117 15118 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15119 QualType T) override { 15120 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15121 } 15122 15123 SemaDiagnosticBuilder diagnoseIncomplete( 15124 Sema &S, SourceLocation Loc, QualType T) override { 15125 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15126 } 15127 15128 SemaDiagnosticBuilder diagnoseExplicitConv( 15129 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15130 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15131 } 15132 15133 SemaDiagnosticBuilder noteExplicitConv( 15134 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15135 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15136 << ConvTy->isEnumeralType() << ConvTy; 15137 } 15138 15139 SemaDiagnosticBuilder diagnoseAmbiguous( 15140 Sema &S, SourceLocation Loc, QualType T) override { 15141 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15142 } 15143 15144 SemaDiagnosticBuilder noteAmbiguous( 15145 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15146 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15147 << ConvTy->isEnumeralType() << ConvTy; 15148 } 15149 15150 SemaDiagnosticBuilder diagnoseConversion( 15151 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15152 llvm_unreachable("conversion functions are permitted"); 15153 } 15154 } ConvertDiagnoser(Diagnoser.Suppress); 15155 15156 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15157 ConvertDiagnoser); 15158 if (Converted.isInvalid()) 15159 return Converted; 15160 E = Converted.get(); 15161 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15162 return ExprError(); 15163 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15164 // An ICE must be of integral or unscoped enumeration type. 15165 if (!Diagnoser.Suppress) 15166 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15167 return ExprError(); 15168 } 15169 15170 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15171 // in the non-ICE case. 15172 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15173 if (Result) 15174 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15175 if (!isa<ConstantExpr>(E)) 15176 E = ConstantExpr::Create(Context, E); 15177 return E; 15178 } 15179 15180 Expr::EvalResult EvalResult; 15181 SmallVector<PartialDiagnosticAt, 8> Notes; 15182 EvalResult.Diag = &Notes; 15183 15184 // Try to evaluate the expression, and produce diagnostics explaining why it's 15185 // not a constant expression as a side-effect. 15186 bool Folded = 15187 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15188 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15189 15190 if (!isa<ConstantExpr>(E)) 15191 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15192 15193 // In C++11, we can rely on diagnostics being produced for any expression 15194 // which is not a constant expression. If no diagnostics were produced, then 15195 // this is a constant expression. 15196 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15197 if (Result) 15198 *Result = EvalResult.Val.getInt(); 15199 return E; 15200 } 15201 15202 // If our only note is the usual "invalid subexpression" note, just point 15203 // the caret at its location rather than producing an essentially 15204 // redundant note. 15205 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15206 diag::note_invalid_subexpr_in_const_expr) { 15207 DiagLoc = Notes[0].first; 15208 Notes.clear(); 15209 } 15210 15211 if (!Folded || !AllowFold) { 15212 if (!Diagnoser.Suppress) { 15213 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15214 for (const PartialDiagnosticAt &Note : Notes) 15215 Diag(Note.first, Note.second); 15216 } 15217 15218 return ExprError(); 15219 } 15220 15221 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15222 for (const PartialDiagnosticAt &Note : Notes) 15223 Diag(Note.first, Note.second); 15224 15225 if (Result) 15226 *Result = EvalResult.Val.getInt(); 15227 return E; 15228 } 15229 15230 namespace { 15231 // Handle the case where we conclude a expression which we speculatively 15232 // considered to be unevaluated is actually evaluated. 15233 class TransformToPE : public TreeTransform<TransformToPE> { 15234 typedef TreeTransform<TransformToPE> BaseTransform; 15235 15236 public: 15237 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15238 15239 // Make sure we redo semantic analysis 15240 bool AlwaysRebuild() { return true; } 15241 bool ReplacingOriginal() { return true; } 15242 15243 // We need to special-case DeclRefExprs referring to FieldDecls which 15244 // are not part of a member pointer formation; normal TreeTransforming 15245 // doesn't catch this case because of the way we represent them in the AST. 15246 // FIXME: This is a bit ugly; is it really the best way to handle this 15247 // case? 15248 // 15249 // Error on DeclRefExprs referring to FieldDecls. 15250 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15251 if (isa<FieldDecl>(E->getDecl()) && 15252 !SemaRef.isUnevaluatedContext()) 15253 return SemaRef.Diag(E->getLocation(), 15254 diag::err_invalid_non_static_member_use) 15255 << E->getDecl() << E->getSourceRange(); 15256 15257 return BaseTransform::TransformDeclRefExpr(E); 15258 } 15259 15260 // Exception: filter out member pointer formation 15261 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15262 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15263 return E; 15264 15265 return BaseTransform::TransformUnaryOperator(E); 15266 } 15267 15268 // The body of a lambda-expression is in a separate expression evaluation 15269 // context so never needs to be transformed. 15270 // FIXME: Ideally we wouldn't transform the closure type either, and would 15271 // just recreate the capture expressions and lambda expression. 15272 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15273 return SkipLambdaBody(E, Body); 15274 } 15275 }; 15276 } 15277 15278 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15279 assert(isUnevaluatedContext() && 15280 "Should only transform unevaluated expressions"); 15281 ExprEvalContexts.back().Context = 15282 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15283 if (isUnevaluatedContext()) 15284 return E; 15285 return TransformToPE(*this).TransformExpr(E); 15286 } 15287 15288 void 15289 Sema::PushExpressionEvaluationContext( 15290 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15291 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15292 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15293 LambdaContextDecl, ExprContext); 15294 Cleanup.reset(); 15295 if (!MaybeODRUseExprs.empty()) 15296 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15297 } 15298 15299 void 15300 Sema::PushExpressionEvaluationContext( 15301 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15302 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15303 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15304 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15305 } 15306 15307 namespace { 15308 15309 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15310 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15311 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15312 if (E->getOpcode() == UO_Deref) 15313 return CheckPossibleDeref(S, E->getSubExpr()); 15314 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15315 return CheckPossibleDeref(S, E->getBase()); 15316 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15317 return CheckPossibleDeref(S, E->getBase()); 15318 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15319 QualType Inner; 15320 QualType Ty = E->getType(); 15321 if (const auto *Ptr = Ty->getAs<PointerType>()) 15322 Inner = Ptr->getPointeeType(); 15323 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15324 Inner = Arr->getElementType(); 15325 else 15326 return nullptr; 15327 15328 if (Inner->hasAttr(attr::NoDeref)) 15329 return E; 15330 } 15331 return nullptr; 15332 } 15333 15334 } // namespace 15335 15336 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15337 for (const Expr *E : Rec.PossibleDerefs) { 15338 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15339 if (DeclRef) { 15340 const ValueDecl *Decl = DeclRef->getDecl(); 15341 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15342 << Decl->getName() << E->getSourceRange(); 15343 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15344 } else { 15345 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15346 << E->getSourceRange(); 15347 } 15348 } 15349 Rec.PossibleDerefs.clear(); 15350 } 15351 15352 /// Check whether E, which is either a discarded-value expression or an 15353 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15354 /// and if so, remove it from the list of volatile-qualified assignments that 15355 /// we are going to warn are deprecated. 15356 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15357 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15358 return; 15359 15360 // Note: ignoring parens here is not justified by the standard rules, but 15361 // ignoring parentheses seems like a more reasonable approach, and this only 15362 // drives a deprecation warning so doesn't affect conformance. 15363 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15364 if (BO->getOpcode() == BO_Assign) { 15365 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15366 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15367 LHSs.end()); 15368 } 15369 } 15370 } 15371 15372 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15373 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15374 RebuildingImmediateInvocation) 15375 return E; 15376 15377 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15378 /// It's OK if this fails; we'll also remove this in 15379 /// HandleImmediateInvocations, but catching it here allows us to avoid 15380 /// walking the AST looking for it in simple cases. 15381 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15382 if (auto *DeclRef = 15383 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15384 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15385 15386 E = MaybeCreateExprWithCleanups(E); 15387 15388 ConstantExpr *Res = ConstantExpr::Create( 15389 getASTContext(), E.get(), 15390 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15391 getASTContext()), 15392 /*IsImmediateInvocation*/ true); 15393 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15394 return Res; 15395 } 15396 15397 static void EvaluateAndDiagnoseImmediateInvocation( 15398 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15399 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15400 Expr::EvalResult Eval; 15401 Eval.Diag = &Notes; 15402 ConstantExpr *CE = Candidate.getPointer(); 15403 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15404 SemaRef.getASTContext(), true); 15405 if (!Result || !Notes.empty()) { 15406 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15407 FunctionDecl *FD = nullptr; 15408 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15409 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15410 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15411 FD = Call->getConstructor(); 15412 else 15413 llvm_unreachable("unhandled decl kind"); 15414 assert(FD->isConsteval()); 15415 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15416 for (auto &Note : Notes) 15417 SemaRef.Diag(Note.first, Note.second); 15418 return; 15419 } 15420 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15421 } 15422 15423 static void RemoveNestedImmediateInvocation( 15424 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15425 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15426 struct ComplexRemove : TreeTransform<ComplexRemove> { 15427 using Base = TreeTransform<ComplexRemove>; 15428 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15429 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15430 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15431 CurrentII; 15432 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15433 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15434 SmallVector<Sema::ImmediateInvocationCandidate, 15435 4>::reverse_iterator Current) 15436 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15437 void RemoveImmediateInvocation(ConstantExpr* E) { 15438 auto It = std::find_if(CurrentII, IISet.rend(), 15439 [E](Sema::ImmediateInvocationCandidate Elem) { 15440 return Elem.getPointer() == E; 15441 }); 15442 assert(It != IISet.rend() && 15443 "ConstantExpr marked IsImmediateInvocation should " 15444 "be present"); 15445 It->setInt(1); // Mark as deleted 15446 } 15447 ExprResult TransformConstantExpr(ConstantExpr *E) { 15448 if (!E->isImmediateInvocation()) 15449 return Base::TransformConstantExpr(E); 15450 RemoveImmediateInvocation(E); 15451 return Base::TransformExpr(E->getSubExpr()); 15452 } 15453 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15454 /// we need to remove its DeclRefExpr from the DRSet. 15455 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15456 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15457 return Base::TransformCXXOperatorCallExpr(E); 15458 } 15459 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15460 /// here. 15461 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15462 if (!Init) 15463 return Init; 15464 /// ConstantExpr are the first layer of implicit node to be removed so if 15465 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15466 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 15467 if (CE->isImmediateInvocation()) 15468 RemoveImmediateInvocation(CE); 15469 return Base::TransformInitializer(Init, NotCopyInit); 15470 } 15471 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15472 DRSet.erase(E); 15473 return E; 15474 } 15475 bool AlwaysRebuild() { return false; } 15476 bool ReplacingOriginal() { return true; } 15477 } Transformer(SemaRef, Rec.ReferenceToConsteval, 15478 Rec.ImmediateInvocationCandidates, It); 15479 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 15480 assert(Res.isUsable()); 15481 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 15482 It->getPointer()->setSubExpr(Res.get()); 15483 } 15484 15485 static void 15486 HandleImmediateInvocations(Sema &SemaRef, 15487 Sema::ExpressionEvaluationContextRecord &Rec) { 15488 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 15489 Rec.ReferenceToConsteval.size() == 0) || 15490 SemaRef.RebuildingImmediateInvocation) 15491 return; 15492 15493 /// When we have more then 1 ImmediateInvocationCandidates we need to check 15494 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 15495 /// need to remove ReferenceToConsteval in the immediate invocation. 15496 if (Rec.ImmediateInvocationCandidates.size() > 1) { 15497 15498 /// Prevent sema calls during the tree transform from adding pointers that 15499 /// are already in the sets. 15500 llvm::SaveAndRestore<bool> DisableIITracking( 15501 SemaRef.RebuildingImmediateInvocation, true); 15502 15503 /// Prevent diagnostic during tree transfrom as they are duplicates 15504 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 15505 15506 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 15507 It != Rec.ImmediateInvocationCandidates.rend(); It++) 15508 if (!It->getInt()) 15509 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 15510 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 15511 Rec.ReferenceToConsteval.size()) { 15512 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 15513 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15514 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 15515 bool VisitDeclRefExpr(DeclRefExpr *E) { 15516 DRSet.erase(E); 15517 return DRSet.size(); 15518 } 15519 } Visitor(Rec.ReferenceToConsteval); 15520 Visitor.TraverseStmt( 15521 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 15522 } 15523 for (auto CE : Rec.ImmediateInvocationCandidates) 15524 if (!CE.getInt()) 15525 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 15526 for (auto DR : Rec.ReferenceToConsteval) { 15527 auto *FD = cast<FunctionDecl>(DR->getDecl()); 15528 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 15529 << FD; 15530 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 15531 } 15532 } 15533 15534 void Sema::PopExpressionEvaluationContext() { 15535 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15536 unsigned NumTypos = Rec.NumTypos; 15537 15538 if (!Rec.Lambdas.empty()) { 15539 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15540 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15541 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15542 unsigned D; 15543 if (Rec.isUnevaluated()) { 15544 // C++11 [expr.prim.lambda]p2: 15545 // A lambda-expression shall not appear in an unevaluated operand 15546 // (Clause 5). 15547 D = diag::err_lambda_unevaluated_operand; 15548 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15549 // C++1y [expr.const]p2: 15550 // A conditional-expression e is a core constant expression unless the 15551 // evaluation of e, following the rules of the abstract machine, would 15552 // evaluate [...] a lambda-expression. 15553 D = diag::err_lambda_in_constant_expression; 15554 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15555 // C++17 [expr.prim.lamda]p2: 15556 // A lambda-expression shall not appear [...] in a template-argument. 15557 D = diag::err_lambda_in_invalid_context; 15558 } else 15559 llvm_unreachable("Couldn't infer lambda error message."); 15560 15561 for (const auto *L : Rec.Lambdas) 15562 Diag(L->getBeginLoc(), D); 15563 } 15564 } 15565 15566 WarnOnPendingNoDerefs(Rec); 15567 HandleImmediateInvocations(*this, Rec); 15568 15569 // Warn on any volatile-qualified simple-assignments that are not discarded- 15570 // value expressions nor unevaluated operands (those cases get removed from 15571 // this list by CheckUnusedVolatileAssignment). 15572 for (auto *BO : Rec.VolatileAssignmentLHSs) 15573 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15574 << BO->getType(); 15575 15576 // When are coming out of an unevaluated context, clear out any 15577 // temporaries that we may have created as part of the evaluation of 15578 // the expression in that context: they aren't relevant because they 15579 // will never be constructed. 15580 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15581 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15582 ExprCleanupObjects.end()); 15583 Cleanup = Rec.ParentCleanup; 15584 CleanupVarDeclMarking(); 15585 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15586 // Otherwise, merge the contexts together. 15587 } else { 15588 Cleanup.mergeFrom(Rec.ParentCleanup); 15589 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15590 Rec.SavedMaybeODRUseExprs.end()); 15591 } 15592 15593 // Pop the current expression evaluation context off the stack. 15594 ExprEvalContexts.pop_back(); 15595 15596 // The global expression evaluation context record is never popped. 15597 ExprEvalContexts.back().NumTypos += NumTypos; 15598 } 15599 15600 void Sema::DiscardCleanupsInEvaluationContext() { 15601 ExprCleanupObjects.erase( 15602 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15603 ExprCleanupObjects.end()); 15604 Cleanup.reset(); 15605 MaybeODRUseExprs.clear(); 15606 } 15607 15608 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15609 ExprResult Result = CheckPlaceholderExpr(E); 15610 if (Result.isInvalid()) 15611 return ExprError(); 15612 E = Result.get(); 15613 if (!E->getType()->isVariablyModifiedType()) 15614 return E; 15615 return TransformToPotentiallyEvaluated(E); 15616 } 15617 15618 /// Are we in a context that is potentially constant evaluated per C++20 15619 /// [expr.const]p12? 15620 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15621 /// C++2a [expr.const]p12: 15622 // An expression or conversion is potentially constant evaluated if it is 15623 switch (SemaRef.ExprEvalContexts.back().Context) { 15624 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15625 // -- a manifestly constant-evaluated expression, 15626 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15627 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15628 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15629 // -- a potentially-evaluated expression, 15630 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15631 // -- an immediate subexpression of a braced-init-list, 15632 15633 // -- [FIXME] an expression of the form & cast-expression that occurs 15634 // within a templated entity 15635 // -- a subexpression of one of the above that is not a subexpression of 15636 // a nested unevaluated operand. 15637 return true; 15638 15639 case Sema::ExpressionEvaluationContext::Unevaluated: 15640 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15641 // Expressions in this context are never evaluated. 15642 return false; 15643 } 15644 llvm_unreachable("Invalid context"); 15645 } 15646 15647 /// Return true if this function has a calling convention that requires mangling 15648 /// in the size of the parameter pack. 15649 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15650 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15651 // we don't need parameter type sizes. 15652 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15653 if (!TT.isOSWindows() || !TT.isX86()) 15654 return false; 15655 15656 // If this is C++ and this isn't an extern "C" function, parameters do not 15657 // need to be complete. In this case, C++ mangling will apply, which doesn't 15658 // use the size of the parameters. 15659 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15660 return false; 15661 15662 // Stdcall, fastcall, and vectorcall need this special treatment. 15663 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15664 switch (CC) { 15665 case CC_X86StdCall: 15666 case CC_X86FastCall: 15667 case CC_X86VectorCall: 15668 return true; 15669 default: 15670 break; 15671 } 15672 return false; 15673 } 15674 15675 /// Require that all of the parameter types of function be complete. Normally, 15676 /// parameter types are only required to be complete when a function is called 15677 /// or defined, but to mangle functions with certain calling conventions, the 15678 /// mangler needs to know the size of the parameter list. In this situation, 15679 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15680 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15681 /// result in a linker error. Clang doesn't implement this behavior, and instead 15682 /// attempts to error at compile time. 15683 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15684 SourceLocation Loc) { 15685 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15686 FunctionDecl *FD; 15687 ParmVarDecl *Param; 15688 15689 public: 15690 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15691 : FD(FD), Param(Param) {} 15692 15693 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15694 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15695 StringRef CCName; 15696 switch (CC) { 15697 case CC_X86StdCall: 15698 CCName = "stdcall"; 15699 break; 15700 case CC_X86FastCall: 15701 CCName = "fastcall"; 15702 break; 15703 case CC_X86VectorCall: 15704 CCName = "vectorcall"; 15705 break; 15706 default: 15707 llvm_unreachable("CC does not need mangling"); 15708 } 15709 15710 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15711 << Param->getDeclName() << FD->getDeclName() << CCName; 15712 } 15713 }; 15714 15715 for (ParmVarDecl *Param : FD->parameters()) { 15716 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15717 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15718 } 15719 } 15720 15721 namespace { 15722 enum class OdrUseContext { 15723 /// Declarations in this context are not odr-used. 15724 None, 15725 /// Declarations in this context are formally odr-used, but this is a 15726 /// dependent context. 15727 Dependent, 15728 /// Declarations in this context are odr-used but not actually used (yet). 15729 FormallyOdrUsed, 15730 /// Declarations in this context are used. 15731 Used 15732 }; 15733 } 15734 15735 /// Are we within a context in which references to resolved functions or to 15736 /// variables result in odr-use? 15737 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15738 OdrUseContext Result; 15739 15740 switch (SemaRef.ExprEvalContexts.back().Context) { 15741 case Sema::ExpressionEvaluationContext::Unevaluated: 15742 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15743 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15744 return OdrUseContext::None; 15745 15746 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15747 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15748 Result = OdrUseContext::Used; 15749 break; 15750 15751 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15752 Result = OdrUseContext::FormallyOdrUsed; 15753 break; 15754 15755 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15756 // A default argument formally results in odr-use, but doesn't actually 15757 // result in a use in any real sense until it itself is used. 15758 Result = OdrUseContext::FormallyOdrUsed; 15759 break; 15760 } 15761 15762 if (SemaRef.CurContext->isDependentContext()) 15763 return OdrUseContext::Dependent; 15764 15765 return Result; 15766 } 15767 15768 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15769 return Func->isConstexpr() && 15770 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15771 } 15772 15773 /// Mark a function referenced, and check whether it is odr-used 15774 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15775 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15776 bool MightBeOdrUse) { 15777 assert(Func && "No function?"); 15778 15779 Func->setReferenced(); 15780 15781 // Recursive functions aren't really used until they're used from some other 15782 // context. 15783 bool IsRecursiveCall = CurContext == Func; 15784 15785 // C++11 [basic.def.odr]p3: 15786 // A function whose name appears as a potentially-evaluated expression is 15787 // odr-used if it is the unique lookup result or the selected member of a 15788 // set of overloaded functions [...]. 15789 // 15790 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15791 // can just check that here. 15792 OdrUseContext OdrUse = 15793 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15794 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15795 OdrUse = OdrUseContext::FormallyOdrUsed; 15796 15797 // Trivial default constructors and destructors are never actually used. 15798 // FIXME: What about other special members? 15799 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15800 OdrUse == OdrUseContext::Used) { 15801 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15802 if (Constructor->isDefaultConstructor()) 15803 OdrUse = OdrUseContext::FormallyOdrUsed; 15804 if (isa<CXXDestructorDecl>(Func)) 15805 OdrUse = OdrUseContext::FormallyOdrUsed; 15806 } 15807 15808 // C++20 [expr.const]p12: 15809 // A function [...] is needed for constant evaluation if it is [...] a 15810 // constexpr function that is named by an expression that is potentially 15811 // constant evaluated 15812 bool NeededForConstantEvaluation = 15813 isPotentiallyConstantEvaluatedContext(*this) && 15814 isImplicitlyDefinableConstexprFunction(Func); 15815 15816 // Determine whether we require a function definition to exist, per 15817 // C++11 [temp.inst]p3: 15818 // Unless a function template specialization has been explicitly 15819 // instantiated or explicitly specialized, the function template 15820 // specialization is implicitly instantiated when the specialization is 15821 // referenced in a context that requires a function definition to exist. 15822 // C++20 [temp.inst]p7: 15823 // The existence of a definition of a [...] function is considered to 15824 // affect the semantics of the program if the [...] function is needed for 15825 // constant evaluation by an expression 15826 // C++20 [basic.def.odr]p10: 15827 // Every program shall contain exactly one definition of every non-inline 15828 // function or variable that is odr-used in that program outside of a 15829 // discarded statement 15830 // C++20 [special]p1: 15831 // The implementation will implicitly define [defaulted special members] 15832 // if they are odr-used or needed for constant evaluation. 15833 // 15834 // Note that we skip the implicit instantiation of templates that are only 15835 // used in unused default arguments or by recursive calls to themselves. 15836 // This is formally non-conforming, but seems reasonable in practice. 15837 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15838 NeededForConstantEvaluation); 15839 15840 // C++14 [temp.expl.spec]p6: 15841 // If a template [...] is explicitly specialized then that specialization 15842 // shall be declared before the first use of that specialization that would 15843 // cause an implicit instantiation to take place, in every translation unit 15844 // in which such a use occurs 15845 if (NeedDefinition && 15846 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15847 Func->getMemberSpecializationInfo())) 15848 checkSpecializationVisibility(Loc, Func); 15849 15850 if (getLangOpts().CUDA) 15851 CheckCUDACall(Loc, Func); 15852 15853 // If we need a definition, try to create one. 15854 if (NeedDefinition && !Func->getBody()) { 15855 runWithSufficientStackSpace(Loc, [&] { 15856 if (CXXConstructorDecl *Constructor = 15857 dyn_cast<CXXConstructorDecl>(Func)) { 15858 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15859 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15860 if (Constructor->isDefaultConstructor()) { 15861 if (Constructor->isTrivial() && 15862 !Constructor->hasAttr<DLLExportAttr>()) 15863 return; 15864 DefineImplicitDefaultConstructor(Loc, Constructor); 15865 } else if (Constructor->isCopyConstructor()) { 15866 DefineImplicitCopyConstructor(Loc, Constructor); 15867 } else if (Constructor->isMoveConstructor()) { 15868 DefineImplicitMoveConstructor(Loc, Constructor); 15869 } 15870 } else if (Constructor->getInheritedConstructor()) { 15871 DefineInheritingConstructor(Loc, Constructor); 15872 } 15873 } else if (CXXDestructorDecl *Destructor = 15874 dyn_cast<CXXDestructorDecl>(Func)) { 15875 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15876 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15877 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15878 return; 15879 DefineImplicitDestructor(Loc, Destructor); 15880 } 15881 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15882 MarkVTableUsed(Loc, Destructor->getParent()); 15883 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15884 if (MethodDecl->isOverloadedOperator() && 15885 MethodDecl->getOverloadedOperator() == OO_Equal) { 15886 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15887 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15888 if (MethodDecl->isCopyAssignmentOperator()) 15889 DefineImplicitCopyAssignment(Loc, MethodDecl); 15890 else if (MethodDecl->isMoveAssignmentOperator()) 15891 DefineImplicitMoveAssignment(Loc, MethodDecl); 15892 } 15893 } else if (isa<CXXConversionDecl>(MethodDecl) && 15894 MethodDecl->getParent()->isLambda()) { 15895 CXXConversionDecl *Conversion = 15896 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15897 if (Conversion->isLambdaToBlockPointerConversion()) 15898 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15899 else 15900 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15901 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15902 MarkVTableUsed(Loc, MethodDecl->getParent()); 15903 } 15904 15905 if (Func->isDefaulted() && !Func->isDeleted()) { 15906 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 15907 if (DCK != DefaultedComparisonKind::None) 15908 DefineDefaultedComparison(Loc, Func, DCK); 15909 } 15910 15911 // Implicit instantiation of function templates and member functions of 15912 // class templates. 15913 if (Func->isImplicitlyInstantiable()) { 15914 TemplateSpecializationKind TSK = 15915 Func->getTemplateSpecializationKindForInstantiation(); 15916 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15917 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15918 if (FirstInstantiation) { 15919 PointOfInstantiation = Loc; 15920 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15921 } else if (TSK != TSK_ImplicitInstantiation) { 15922 // Use the point of use as the point of instantiation, instead of the 15923 // point of explicit instantiation (which we track as the actual point 15924 // of instantiation). This gives better backtraces in diagnostics. 15925 PointOfInstantiation = Loc; 15926 } 15927 15928 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15929 Func->isConstexpr()) { 15930 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15931 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15932 CodeSynthesisContexts.size()) 15933 PendingLocalImplicitInstantiations.push_back( 15934 std::make_pair(Func, PointOfInstantiation)); 15935 else if (Func->isConstexpr()) 15936 // Do not defer instantiations of constexpr functions, to avoid the 15937 // expression evaluator needing to call back into Sema if it sees a 15938 // call to such a function. 15939 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15940 else { 15941 Func->setInstantiationIsPending(true); 15942 PendingInstantiations.push_back( 15943 std::make_pair(Func, PointOfInstantiation)); 15944 // Notify the consumer that a function was implicitly instantiated. 15945 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15946 } 15947 } 15948 } else { 15949 // Walk redefinitions, as some of them may be instantiable. 15950 for (auto i : Func->redecls()) { 15951 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15952 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15953 } 15954 } 15955 }); 15956 } 15957 15958 // C++14 [except.spec]p17: 15959 // An exception-specification is considered to be needed when: 15960 // - the function is odr-used or, if it appears in an unevaluated operand, 15961 // would be odr-used if the expression were potentially-evaluated; 15962 // 15963 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15964 // function is a pure virtual function we're calling, and in that case the 15965 // function was selected by overload resolution and we need to resolve its 15966 // exception specification for a different reason. 15967 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15968 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15969 ResolveExceptionSpec(Loc, FPT); 15970 15971 // If this is the first "real" use, act on that. 15972 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15973 // Keep track of used but undefined functions. 15974 if (!Func->isDefined()) { 15975 if (mightHaveNonExternalLinkage(Func)) 15976 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15977 else if (Func->getMostRecentDecl()->isInlined() && 15978 !LangOpts.GNUInline && 15979 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15980 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15981 else if (isExternalWithNoLinkageType(Func)) 15982 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15983 } 15984 15985 // Some x86 Windows calling conventions mangle the size of the parameter 15986 // pack into the name. Computing the size of the parameters requires the 15987 // parameter types to be complete. Check that now. 15988 if (funcHasParameterSizeMangling(*this, Func)) 15989 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15990 15991 Func->markUsed(Context); 15992 } 15993 15994 if (LangOpts.OpenMP) { 15995 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15996 if (LangOpts.OpenMPIsDevice) 15997 checkOpenMPDeviceFunction(Loc, Func); 15998 else 15999 checkOpenMPHostFunction(Loc, Func); 16000 } 16001 } 16002 16003 /// Directly mark a variable odr-used. Given a choice, prefer to use 16004 /// MarkVariableReferenced since it does additional checks and then 16005 /// calls MarkVarDeclODRUsed. 16006 /// If the variable must be captured: 16007 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16008 /// - else capture it in the DeclContext that maps to the 16009 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16010 static void 16011 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16012 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16013 // Keep track of used but undefined variables. 16014 // FIXME: We shouldn't suppress this warning for static data members. 16015 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16016 (!Var->isExternallyVisible() || Var->isInline() || 16017 SemaRef.isExternalWithNoLinkageType(Var)) && 16018 !(Var->isStaticDataMember() && Var->hasInit())) { 16019 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16020 if (old.isInvalid()) 16021 old = Loc; 16022 } 16023 QualType CaptureType, DeclRefType; 16024 if (SemaRef.LangOpts.OpenMP) 16025 SemaRef.tryCaptureOpenMPLambdas(Var); 16026 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16027 /*EllipsisLoc*/ SourceLocation(), 16028 /*BuildAndDiagnose*/ true, 16029 CaptureType, DeclRefType, 16030 FunctionScopeIndexToStopAt); 16031 16032 Var->markUsed(SemaRef.Context); 16033 } 16034 16035 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16036 SourceLocation Loc, 16037 unsigned CapturingScopeIndex) { 16038 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16039 } 16040 16041 static void 16042 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16043 ValueDecl *var, DeclContext *DC) { 16044 DeclContext *VarDC = var->getDeclContext(); 16045 16046 // If the parameter still belongs to the translation unit, then 16047 // we're actually just using one parameter in the declaration of 16048 // the next. 16049 if (isa<ParmVarDecl>(var) && 16050 isa<TranslationUnitDecl>(VarDC)) 16051 return; 16052 16053 // For C code, don't diagnose about capture if we're not actually in code 16054 // right now; it's impossible to write a non-constant expression outside of 16055 // function context, so we'll get other (more useful) diagnostics later. 16056 // 16057 // For C++, things get a bit more nasty... it would be nice to suppress this 16058 // diagnostic for certain cases like using a local variable in an array bound 16059 // for a member of a local class, but the correct predicate is not obvious. 16060 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16061 return; 16062 16063 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16064 unsigned ContextKind = 3; // unknown 16065 if (isa<CXXMethodDecl>(VarDC) && 16066 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16067 ContextKind = 2; 16068 } else if (isa<FunctionDecl>(VarDC)) { 16069 ContextKind = 0; 16070 } else if (isa<BlockDecl>(VarDC)) { 16071 ContextKind = 1; 16072 } 16073 16074 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16075 << var << ValueKind << ContextKind << VarDC; 16076 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16077 << var; 16078 16079 // FIXME: Add additional diagnostic info about class etc. which prevents 16080 // capture. 16081 } 16082 16083 16084 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16085 bool &SubCapturesAreNested, 16086 QualType &CaptureType, 16087 QualType &DeclRefType) { 16088 // Check whether we've already captured it. 16089 if (CSI->CaptureMap.count(Var)) { 16090 // If we found a capture, any subcaptures are nested. 16091 SubCapturesAreNested = true; 16092 16093 // Retrieve the capture type for this variable. 16094 CaptureType = CSI->getCapture(Var).getCaptureType(); 16095 16096 // Compute the type of an expression that refers to this variable. 16097 DeclRefType = CaptureType.getNonReferenceType(); 16098 16099 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16100 // are mutable in the sense that user can change their value - they are 16101 // private instances of the captured declarations. 16102 const Capture &Cap = CSI->getCapture(Var); 16103 if (Cap.isCopyCapture() && 16104 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16105 !(isa<CapturedRegionScopeInfo>(CSI) && 16106 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16107 DeclRefType.addConst(); 16108 return true; 16109 } 16110 return false; 16111 } 16112 16113 // Only block literals, captured statements, and lambda expressions can 16114 // capture; other scopes don't work. 16115 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16116 SourceLocation Loc, 16117 const bool Diagnose, Sema &S) { 16118 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16119 return getLambdaAwareParentOfDeclContext(DC); 16120 else if (Var->hasLocalStorage()) { 16121 if (Diagnose) 16122 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16123 } 16124 return nullptr; 16125 } 16126 16127 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16128 // certain types of variables (unnamed, variably modified types etc.) 16129 // so check for eligibility. 16130 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16131 SourceLocation Loc, 16132 const bool Diagnose, Sema &S) { 16133 16134 bool IsBlock = isa<BlockScopeInfo>(CSI); 16135 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16136 16137 // Lambdas are not allowed to capture unnamed variables 16138 // (e.g. anonymous unions). 16139 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16140 // assuming that's the intent. 16141 if (IsLambda && !Var->getDeclName()) { 16142 if (Diagnose) { 16143 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16144 S.Diag(Var->getLocation(), diag::note_declared_at); 16145 } 16146 return false; 16147 } 16148 16149 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16150 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16151 if (Diagnose) { 16152 S.Diag(Loc, diag::err_ref_vm_type); 16153 S.Diag(Var->getLocation(), diag::note_previous_decl) 16154 << Var->getDeclName(); 16155 } 16156 return false; 16157 } 16158 // Prohibit structs with flexible array members too. 16159 // We cannot capture what is in the tail end of the struct. 16160 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16161 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16162 if (Diagnose) { 16163 if (IsBlock) 16164 S.Diag(Loc, diag::err_ref_flexarray_type); 16165 else 16166 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16167 << Var->getDeclName(); 16168 S.Diag(Var->getLocation(), diag::note_previous_decl) 16169 << Var->getDeclName(); 16170 } 16171 return false; 16172 } 16173 } 16174 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16175 // Lambdas and captured statements are not allowed to capture __block 16176 // variables; they don't support the expected semantics. 16177 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16178 if (Diagnose) { 16179 S.Diag(Loc, diag::err_capture_block_variable) 16180 << Var->getDeclName() << !IsLambda; 16181 S.Diag(Var->getLocation(), diag::note_previous_decl) 16182 << Var->getDeclName(); 16183 } 16184 return false; 16185 } 16186 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16187 if (S.getLangOpts().OpenCL && IsBlock && 16188 Var->getType()->isBlockPointerType()) { 16189 if (Diagnose) 16190 S.Diag(Loc, diag::err_opencl_block_ref_block); 16191 return false; 16192 } 16193 16194 return true; 16195 } 16196 16197 // Returns true if the capture by block was successful. 16198 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16199 SourceLocation Loc, 16200 const bool BuildAndDiagnose, 16201 QualType &CaptureType, 16202 QualType &DeclRefType, 16203 const bool Nested, 16204 Sema &S, bool Invalid) { 16205 bool ByRef = false; 16206 16207 // Blocks are not allowed to capture arrays, excepting OpenCL. 16208 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16209 // (decayed to pointers). 16210 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16211 if (BuildAndDiagnose) { 16212 S.Diag(Loc, diag::err_ref_array_type); 16213 S.Diag(Var->getLocation(), diag::note_previous_decl) 16214 << Var->getDeclName(); 16215 Invalid = true; 16216 } else { 16217 return false; 16218 } 16219 } 16220 16221 // Forbid the block-capture of autoreleasing variables. 16222 if (!Invalid && 16223 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16224 if (BuildAndDiagnose) { 16225 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16226 << /*block*/ 0; 16227 S.Diag(Var->getLocation(), diag::note_previous_decl) 16228 << Var->getDeclName(); 16229 Invalid = true; 16230 } else { 16231 return false; 16232 } 16233 } 16234 16235 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16236 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16237 QualType PointeeTy = PT->getPointeeType(); 16238 16239 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16240 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16241 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16242 if (BuildAndDiagnose) { 16243 SourceLocation VarLoc = Var->getLocation(); 16244 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16245 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16246 } 16247 } 16248 } 16249 16250 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16251 if (HasBlocksAttr || CaptureType->isReferenceType() || 16252 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16253 // Block capture by reference does not change the capture or 16254 // declaration reference types. 16255 ByRef = true; 16256 } else { 16257 // Block capture by copy introduces 'const'. 16258 CaptureType = CaptureType.getNonReferenceType().withConst(); 16259 DeclRefType = CaptureType; 16260 } 16261 16262 // Actually capture the variable. 16263 if (BuildAndDiagnose) 16264 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16265 CaptureType, Invalid); 16266 16267 return !Invalid; 16268 } 16269 16270 16271 /// Capture the given variable in the captured region. 16272 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16273 VarDecl *Var, 16274 SourceLocation Loc, 16275 const bool BuildAndDiagnose, 16276 QualType &CaptureType, 16277 QualType &DeclRefType, 16278 const bool RefersToCapturedVariable, 16279 Sema &S, bool Invalid) { 16280 // By default, capture variables by reference. 16281 bool ByRef = true; 16282 // Using an LValue reference type is consistent with Lambdas (see below). 16283 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16284 if (S.isOpenMPCapturedDecl(Var)) { 16285 bool HasConst = DeclRefType.isConstQualified(); 16286 DeclRefType = DeclRefType.getUnqualifiedType(); 16287 // Don't lose diagnostics about assignments to const. 16288 if (HasConst) 16289 DeclRefType.addConst(); 16290 } 16291 // Do not capture firstprivates in tasks. 16292 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 16293 OMPC_unknown) 16294 return true; 16295 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16296 RSI->OpenMPCaptureLevel); 16297 } 16298 16299 if (ByRef) 16300 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16301 else 16302 CaptureType = DeclRefType; 16303 16304 // Actually capture the variable. 16305 if (BuildAndDiagnose) 16306 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16307 Loc, SourceLocation(), CaptureType, Invalid); 16308 16309 return !Invalid; 16310 } 16311 16312 /// Capture the given variable in the lambda. 16313 static bool captureInLambda(LambdaScopeInfo *LSI, 16314 VarDecl *Var, 16315 SourceLocation Loc, 16316 const bool BuildAndDiagnose, 16317 QualType &CaptureType, 16318 QualType &DeclRefType, 16319 const bool RefersToCapturedVariable, 16320 const Sema::TryCaptureKind Kind, 16321 SourceLocation EllipsisLoc, 16322 const bool IsTopScope, 16323 Sema &S, bool Invalid) { 16324 // Determine whether we are capturing by reference or by value. 16325 bool ByRef = false; 16326 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16327 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16328 } else { 16329 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16330 } 16331 16332 // Compute the type of the field that will capture this variable. 16333 if (ByRef) { 16334 // C++11 [expr.prim.lambda]p15: 16335 // An entity is captured by reference if it is implicitly or 16336 // explicitly captured but not captured by copy. It is 16337 // unspecified whether additional unnamed non-static data 16338 // members are declared in the closure type for entities 16339 // captured by reference. 16340 // 16341 // FIXME: It is not clear whether we want to build an lvalue reference 16342 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16343 // to do the former, while EDG does the latter. Core issue 1249 will 16344 // clarify, but for now we follow GCC because it's a more permissive and 16345 // easily defensible position. 16346 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16347 } else { 16348 // C++11 [expr.prim.lambda]p14: 16349 // For each entity captured by copy, an unnamed non-static 16350 // data member is declared in the closure type. The 16351 // declaration order of these members is unspecified. The type 16352 // of such a data member is the type of the corresponding 16353 // captured entity if the entity is not a reference to an 16354 // object, or the referenced type otherwise. [Note: If the 16355 // captured entity is a reference to a function, the 16356 // corresponding data member is also a reference to a 16357 // function. - end note ] 16358 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16359 if (!RefType->getPointeeType()->isFunctionType()) 16360 CaptureType = RefType->getPointeeType(); 16361 } 16362 16363 // Forbid the lambda copy-capture of autoreleasing variables. 16364 if (!Invalid && 16365 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16366 if (BuildAndDiagnose) { 16367 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16368 S.Diag(Var->getLocation(), diag::note_previous_decl) 16369 << Var->getDeclName(); 16370 Invalid = true; 16371 } else { 16372 return false; 16373 } 16374 } 16375 16376 // Make sure that by-copy captures are of a complete and non-abstract type. 16377 if (!Invalid && BuildAndDiagnose) { 16378 if (!CaptureType->isDependentType() && 16379 S.RequireCompleteSizedType( 16380 Loc, CaptureType, 16381 diag::err_capture_of_incomplete_or_sizeless_type, 16382 Var->getDeclName())) 16383 Invalid = true; 16384 else if (S.RequireNonAbstractType(Loc, CaptureType, 16385 diag::err_capture_of_abstract_type)) 16386 Invalid = true; 16387 } 16388 } 16389 16390 // Compute the type of a reference to this captured variable. 16391 if (ByRef) 16392 DeclRefType = CaptureType.getNonReferenceType(); 16393 else { 16394 // C++ [expr.prim.lambda]p5: 16395 // The closure type for a lambda-expression has a public inline 16396 // function call operator [...]. This function call operator is 16397 // declared const (9.3.1) if and only if the lambda-expression's 16398 // parameter-declaration-clause is not followed by mutable. 16399 DeclRefType = CaptureType.getNonReferenceType(); 16400 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16401 DeclRefType.addConst(); 16402 } 16403 16404 // Add the capture. 16405 if (BuildAndDiagnose) 16406 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16407 Loc, EllipsisLoc, CaptureType, Invalid); 16408 16409 return !Invalid; 16410 } 16411 16412 bool Sema::tryCaptureVariable( 16413 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16414 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16415 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16416 // An init-capture is notionally from the context surrounding its 16417 // declaration, but its parent DC is the lambda class. 16418 DeclContext *VarDC = Var->getDeclContext(); 16419 if (Var->isInitCapture()) 16420 VarDC = VarDC->getParent(); 16421 16422 DeclContext *DC = CurContext; 16423 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16424 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16425 // We need to sync up the Declaration Context with the 16426 // FunctionScopeIndexToStopAt 16427 if (FunctionScopeIndexToStopAt) { 16428 unsigned FSIndex = FunctionScopes.size() - 1; 16429 while (FSIndex != MaxFunctionScopesIndex) { 16430 DC = getLambdaAwareParentOfDeclContext(DC); 16431 --FSIndex; 16432 } 16433 } 16434 16435 16436 // If the variable is declared in the current context, there is no need to 16437 // capture it. 16438 if (VarDC == DC) return true; 16439 16440 // Capture global variables if it is required to use private copy of this 16441 // variable. 16442 bool IsGlobal = !Var->hasLocalStorage(); 16443 if (IsGlobal && 16444 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16445 MaxFunctionScopesIndex))) 16446 return true; 16447 Var = Var->getCanonicalDecl(); 16448 16449 // Walk up the stack to determine whether we can capture the variable, 16450 // performing the "simple" checks that don't depend on type. We stop when 16451 // we've either hit the declared scope of the variable or find an existing 16452 // capture of that variable. We start from the innermost capturing-entity 16453 // (the DC) and ensure that all intervening capturing-entities 16454 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16455 // declcontext can either capture the variable or have already captured 16456 // the variable. 16457 CaptureType = Var->getType(); 16458 DeclRefType = CaptureType.getNonReferenceType(); 16459 bool Nested = false; 16460 bool Explicit = (Kind != TryCapture_Implicit); 16461 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16462 do { 16463 // Only block literals, captured statements, and lambda expressions can 16464 // capture; other scopes don't work. 16465 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16466 ExprLoc, 16467 BuildAndDiagnose, 16468 *this); 16469 // We need to check for the parent *first* because, if we *have* 16470 // private-captured a global variable, we need to recursively capture it in 16471 // intermediate blocks, lambdas, etc. 16472 if (!ParentDC) { 16473 if (IsGlobal) { 16474 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16475 break; 16476 } 16477 return true; 16478 } 16479 16480 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16481 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16482 16483 16484 // Check whether we've already captured it. 16485 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16486 DeclRefType)) { 16487 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16488 break; 16489 } 16490 // If we are instantiating a generic lambda call operator body, 16491 // we do not want to capture new variables. What was captured 16492 // during either a lambdas transformation or initial parsing 16493 // should be used. 16494 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16495 if (BuildAndDiagnose) { 16496 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16497 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16498 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16499 Diag(Var->getLocation(), diag::note_previous_decl) 16500 << Var->getDeclName(); 16501 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16502 } else 16503 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16504 } 16505 return true; 16506 } 16507 16508 // Try to capture variable-length arrays types. 16509 if (Var->getType()->isVariablyModifiedType()) { 16510 // We're going to walk down into the type and look for VLA 16511 // expressions. 16512 QualType QTy = Var->getType(); 16513 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16514 QTy = PVD->getOriginalType(); 16515 captureVariablyModifiedType(Context, QTy, CSI); 16516 } 16517 16518 if (getLangOpts().OpenMP) { 16519 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16520 // OpenMP private variables should not be captured in outer scope, so 16521 // just break here. Similarly, global variables that are captured in a 16522 // target region should not be captured outside the scope of the region. 16523 if (RSI->CapRegionKind == CR_OpenMP) { 16524 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 16525 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 16526 // If the variable is private (i.e. not captured) and has variably 16527 // modified type, we still need to capture the type for correct 16528 // codegen in all regions, associated with the construct. Currently, 16529 // it is captured in the innermost captured region only. 16530 if (IsOpenMPPrivateDecl != OMPC_unknown && 16531 Var->getType()->isVariablyModifiedType()) { 16532 QualType QTy = Var->getType(); 16533 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16534 QTy = PVD->getOriginalType(); 16535 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16536 I < E; ++I) { 16537 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16538 FunctionScopes[FunctionScopesIndex - I]); 16539 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16540 "Wrong number of captured regions associated with the " 16541 "OpenMP construct."); 16542 captureVariablyModifiedType(Context, QTy, OuterRSI); 16543 } 16544 } 16545 bool IsTargetCap = 16546 IsOpenMPPrivateDecl != OMPC_private && 16547 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 16548 RSI->OpenMPCaptureLevel); 16549 // Do not capture global if it is not privatized in outer regions. 16550 bool IsGlobalCap = 16551 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 16552 RSI->OpenMPCaptureLevel); 16553 16554 // When we detect target captures we are looking from inside the 16555 // target region, therefore we need to propagate the capture from the 16556 // enclosing region. Therefore, the capture is not initially nested. 16557 if (IsTargetCap) 16558 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16559 16560 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 16561 (IsGlobal && !IsGlobalCap)) { 16562 Nested = !IsTargetCap; 16563 DeclRefType = DeclRefType.getUnqualifiedType(); 16564 CaptureType = Context.getLValueReferenceType(DeclRefType); 16565 break; 16566 } 16567 } 16568 } 16569 } 16570 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16571 // No capture-default, and this is not an explicit capture 16572 // so cannot capture this variable. 16573 if (BuildAndDiagnose) { 16574 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16575 Diag(Var->getLocation(), diag::note_previous_decl) 16576 << Var->getDeclName(); 16577 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16578 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16579 diag::note_lambda_decl); 16580 // FIXME: If we error out because an outer lambda can not implicitly 16581 // capture a variable that an inner lambda explicitly captures, we 16582 // should have the inner lambda do the explicit capture - because 16583 // it makes for cleaner diagnostics later. This would purely be done 16584 // so that the diagnostic does not misleadingly claim that a variable 16585 // can not be captured by a lambda implicitly even though it is captured 16586 // explicitly. Suggestion: 16587 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16588 // at the function head 16589 // - cache the StartingDeclContext - this must be a lambda 16590 // - captureInLambda in the innermost lambda the variable. 16591 } 16592 return true; 16593 } 16594 16595 FunctionScopesIndex--; 16596 DC = ParentDC; 16597 Explicit = false; 16598 } while (!VarDC->Equals(DC)); 16599 16600 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16601 // computing the type of the capture at each step, checking type-specific 16602 // requirements, and adding captures if requested. 16603 // If the variable had already been captured previously, we start capturing 16604 // at the lambda nested within that one. 16605 bool Invalid = false; 16606 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16607 ++I) { 16608 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16609 16610 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16611 // certain types of variables (unnamed, variably modified types etc.) 16612 // so check for eligibility. 16613 if (!Invalid) 16614 Invalid = 16615 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16616 16617 // After encountering an error, if we're actually supposed to capture, keep 16618 // capturing in nested contexts to suppress any follow-on diagnostics. 16619 if (Invalid && !BuildAndDiagnose) 16620 return true; 16621 16622 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16623 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16624 DeclRefType, Nested, *this, Invalid); 16625 Nested = true; 16626 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16627 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16628 CaptureType, DeclRefType, Nested, 16629 *this, Invalid); 16630 Nested = true; 16631 } else { 16632 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16633 Invalid = 16634 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16635 DeclRefType, Nested, Kind, EllipsisLoc, 16636 /*IsTopScope*/ I == N - 1, *this, Invalid); 16637 Nested = true; 16638 } 16639 16640 if (Invalid && !BuildAndDiagnose) 16641 return true; 16642 } 16643 return Invalid; 16644 } 16645 16646 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16647 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16648 QualType CaptureType; 16649 QualType DeclRefType; 16650 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16651 /*BuildAndDiagnose=*/true, CaptureType, 16652 DeclRefType, nullptr); 16653 } 16654 16655 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16656 QualType CaptureType; 16657 QualType DeclRefType; 16658 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16659 /*BuildAndDiagnose=*/false, CaptureType, 16660 DeclRefType, nullptr); 16661 } 16662 16663 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16664 QualType CaptureType; 16665 QualType DeclRefType; 16666 16667 // Determine whether we can capture this variable. 16668 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16669 /*BuildAndDiagnose=*/false, CaptureType, 16670 DeclRefType, nullptr)) 16671 return QualType(); 16672 16673 return DeclRefType; 16674 } 16675 16676 namespace { 16677 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16678 // The produced TemplateArgumentListInfo* points to data stored within this 16679 // object, so should only be used in contexts where the pointer will not be 16680 // used after the CopiedTemplateArgs object is destroyed. 16681 class CopiedTemplateArgs { 16682 bool HasArgs; 16683 TemplateArgumentListInfo TemplateArgStorage; 16684 public: 16685 template<typename RefExpr> 16686 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16687 if (HasArgs) 16688 E->copyTemplateArgumentsInto(TemplateArgStorage); 16689 } 16690 operator TemplateArgumentListInfo*() 16691 #ifdef __has_cpp_attribute 16692 #if __has_cpp_attribute(clang::lifetimebound) 16693 [[clang::lifetimebound]] 16694 #endif 16695 #endif 16696 { 16697 return HasArgs ? &TemplateArgStorage : nullptr; 16698 } 16699 }; 16700 } 16701 16702 /// Walk the set of potential results of an expression and mark them all as 16703 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16704 /// 16705 /// \return A new expression if we found any potential results, ExprEmpty() if 16706 /// not, and ExprError() if we diagnosed an error. 16707 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16708 NonOdrUseReason NOUR) { 16709 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16710 // an object that satisfies the requirements for appearing in a 16711 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16712 // is immediately applied." This function handles the lvalue-to-rvalue 16713 // conversion part. 16714 // 16715 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16716 // transform it into the relevant kind of non-odr-use node and rebuild the 16717 // tree of nodes leading to it. 16718 // 16719 // This is a mini-TreeTransform that only transforms a restricted subset of 16720 // nodes (and only certain operands of them). 16721 16722 // Rebuild a subexpression. 16723 auto Rebuild = [&](Expr *Sub) { 16724 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16725 }; 16726 16727 // Check whether a potential result satisfies the requirements of NOUR. 16728 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16729 // Any entity other than a VarDecl is always odr-used whenever it's named 16730 // in a potentially-evaluated expression. 16731 auto *VD = dyn_cast<VarDecl>(D); 16732 if (!VD) 16733 return true; 16734 16735 // C++2a [basic.def.odr]p4: 16736 // A variable x whose name appears as a potentially-evalauted expression 16737 // e is odr-used by e unless 16738 // -- x is a reference that is usable in constant expressions, or 16739 // -- x is a variable of non-reference type that is usable in constant 16740 // expressions and has no mutable subobjects, and e is an element of 16741 // the set of potential results of an expression of 16742 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16743 // conversion is applied, or 16744 // -- x is a variable of non-reference type, and e is an element of the 16745 // set of potential results of a discarded-value expression to which 16746 // the lvalue-to-rvalue conversion is not applied 16747 // 16748 // We check the first bullet and the "potentially-evaluated" condition in 16749 // BuildDeclRefExpr. We check the type requirements in the second bullet 16750 // in CheckLValueToRValueConversionOperand below. 16751 switch (NOUR) { 16752 case NOUR_None: 16753 case NOUR_Unevaluated: 16754 llvm_unreachable("unexpected non-odr-use-reason"); 16755 16756 case NOUR_Constant: 16757 // Constant references were handled when they were built. 16758 if (VD->getType()->isReferenceType()) 16759 return true; 16760 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16761 if (RD->hasMutableFields()) 16762 return true; 16763 if (!VD->isUsableInConstantExpressions(S.Context)) 16764 return true; 16765 break; 16766 16767 case NOUR_Discarded: 16768 if (VD->getType()->isReferenceType()) 16769 return true; 16770 break; 16771 } 16772 return false; 16773 }; 16774 16775 // Mark that this expression does not constitute an odr-use. 16776 auto MarkNotOdrUsed = [&] { 16777 S.MaybeODRUseExprs.erase(E); 16778 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16779 LSI->markVariableExprAsNonODRUsed(E); 16780 }; 16781 16782 // C++2a [basic.def.odr]p2: 16783 // The set of potential results of an expression e is defined as follows: 16784 switch (E->getStmtClass()) { 16785 // -- If e is an id-expression, ... 16786 case Expr::DeclRefExprClass: { 16787 auto *DRE = cast<DeclRefExpr>(E); 16788 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16789 break; 16790 16791 // Rebuild as a non-odr-use DeclRefExpr. 16792 MarkNotOdrUsed(); 16793 return DeclRefExpr::Create( 16794 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16795 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16796 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16797 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16798 } 16799 16800 case Expr::FunctionParmPackExprClass: { 16801 auto *FPPE = cast<FunctionParmPackExpr>(E); 16802 // If any of the declarations in the pack is odr-used, then the expression 16803 // as a whole constitutes an odr-use. 16804 for (VarDecl *D : *FPPE) 16805 if (IsPotentialResultOdrUsed(D)) 16806 return ExprEmpty(); 16807 16808 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16809 // nothing cares about whether we marked this as an odr-use, but it might 16810 // be useful for non-compiler tools. 16811 MarkNotOdrUsed(); 16812 break; 16813 } 16814 16815 // -- If e is a subscripting operation with an array operand... 16816 case Expr::ArraySubscriptExprClass: { 16817 auto *ASE = cast<ArraySubscriptExpr>(E); 16818 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16819 if (!OldBase->getType()->isArrayType()) 16820 break; 16821 ExprResult Base = Rebuild(OldBase); 16822 if (!Base.isUsable()) 16823 return Base; 16824 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16825 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16826 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16827 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16828 ASE->getRBracketLoc()); 16829 } 16830 16831 case Expr::MemberExprClass: { 16832 auto *ME = cast<MemberExpr>(E); 16833 // -- If e is a class member access expression [...] naming a non-static 16834 // data member... 16835 if (isa<FieldDecl>(ME->getMemberDecl())) { 16836 ExprResult Base = Rebuild(ME->getBase()); 16837 if (!Base.isUsable()) 16838 return Base; 16839 return MemberExpr::Create( 16840 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16841 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16842 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16843 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16844 ME->getObjectKind(), ME->isNonOdrUse()); 16845 } 16846 16847 if (ME->getMemberDecl()->isCXXInstanceMember()) 16848 break; 16849 16850 // -- If e is a class member access expression naming a static data member, 16851 // ... 16852 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16853 break; 16854 16855 // Rebuild as a non-odr-use MemberExpr. 16856 MarkNotOdrUsed(); 16857 return MemberExpr::Create( 16858 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16859 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16860 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16861 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16862 return ExprEmpty(); 16863 } 16864 16865 case Expr::BinaryOperatorClass: { 16866 auto *BO = cast<BinaryOperator>(E); 16867 Expr *LHS = BO->getLHS(); 16868 Expr *RHS = BO->getRHS(); 16869 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16870 if (BO->getOpcode() == BO_PtrMemD) { 16871 ExprResult Sub = Rebuild(LHS); 16872 if (!Sub.isUsable()) 16873 return Sub; 16874 LHS = Sub.get(); 16875 // -- If e is a comma expression, ... 16876 } else if (BO->getOpcode() == BO_Comma) { 16877 ExprResult Sub = Rebuild(RHS); 16878 if (!Sub.isUsable()) 16879 return Sub; 16880 RHS = Sub.get(); 16881 } else { 16882 break; 16883 } 16884 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16885 LHS, RHS); 16886 } 16887 16888 // -- If e has the form (e1)... 16889 case Expr::ParenExprClass: { 16890 auto *PE = cast<ParenExpr>(E); 16891 ExprResult Sub = Rebuild(PE->getSubExpr()); 16892 if (!Sub.isUsable()) 16893 return Sub; 16894 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16895 } 16896 16897 // -- If e is a glvalue conditional expression, ... 16898 // We don't apply this to a binary conditional operator. FIXME: Should we? 16899 case Expr::ConditionalOperatorClass: { 16900 auto *CO = cast<ConditionalOperator>(E); 16901 ExprResult LHS = Rebuild(CO->getLHS()); 16902 if (LHS.isInvalid()) 16903 return ExprError(); 16904 ExprResult RHS = Rebuild(CO->getRHS()); 16905 if (RHS.isInvalid()) 16906 return ExprError(); 16907 if (!LHS.isUsable() && !RHS.isUsable()) 16908 return ExprEmpty(); 16909 if (!LHS.isUsable()) 16910 LHS = CO->getLHS(); 16911 if (!RHS.isUsable()) 16912 RHS = CO->getRHS(); 16913 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16914 CO->getCond(), LHS.get(), RHS.get()); 16915 } 16916 16917 // [Clang extension] 16918 // -- If e has the form __extension__ e1... 16919 case Expr::UnaryOperatorClass: { 16920 auto *UO = cast<UnaryOperator>(E); 16921 if (UO->getOpcode() != UO_Extension) 16922 break; 16923 ExprResult Sub = Rebuild(UO->getSubExpr()); 16924 if (!Sub.isUsable()) 16925 return Sub; 16926 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16927 Sub.get()); 16928 } 16929 16930 // [Clang extension] 16931 // -- If e has the form _Generic(...), the set of potential results is the 16932 // union of the sets of potential results of the associated expressions. 16933 case Expr::GenericSelectionExprClass: { 16934 auto *GSE = cast<GenericSelectionExpr>(E); 16935 16936 SmallVector<Expr *, 4> AssocExprs; 16937 bool AnyChanged = false; 16938 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16939 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16940 if (AssocExpr.isInvalid()) 16941 return ExprError(); 16942 if (AssocExpr.isUsable()) { 16943 AssocExprs.push_back(AssocExpr.get()); 16944 AnyChanged = true; 16945 } else { 16946 AssocExprs.push_back(OrigAssocExpr); 16947 } 16948 } 16949 16950 return AnyChanged ? S.CreateGenericSelectionExpr( 16951 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16952 GSE->getRParenLoc(), GSE->getControllingExpr(), 16953 GSE->getAssocTypeSourceInfos(), AssocExprs) 16954 : ExprEmpty(); 16955 } 16956 16957 // [Clang extension] 16958 // -- If e has the form __builtin_choose_expr(...), the set of potential 16959 // results is the union of the sets of potential results of the 16960 // second and third subexpressions. 16961 case Expr::ChooseExprClass: { 16962 auto *CE = cast<ChooseExpr>(E); 16963 16964 ExprResult LHS = Rebuild(CE->getLHS()); 16965 if (LHS.isInvalid()) 16966 return ExprError(); 16967 16968 ExprResult RHS = Rebuild(CE->getLHS()); 16969 if (RHS.isInvalid()) 16970 return ExprError(); 16971 16972 if (!LHS.get() && !RHS.get()) 16973 return ExprEmpty(); 16974 if (!LHS.isUsable()) 16975 LHS = CE->getLHS(); 16976 if (!RHS.isUsable()) 16977 RHS = CE->getRHS(); 16978 16979 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16980 RHS.get(), CE->getRParenLoc()); 16981 } 16982 16983 // Step through non-syntactic nodes. 16984 case Expr::ConstantExprClass: { 16985 auto *CE = cast<ConstantExpr>(E); 16986 ExprResult Sub = Rebuild(CE->getSubExpr()); 16987 if (!Sub.isUsable()) 16988 return Sub; 16989 return ConstantExpr::Create(S.Context, Sub.get()); 16990 } 16991 16992 // We could mostly rely on the recursive rebuilding to rebuild implicit 16993 // casts, but not at the top level, so rebuild them here. 16994 case Expr::ImplicitCastExprClass: { 16995 auto *ICE = cast<ImplicitCastExpr>(E); 16996 // Only step through the narrow set of cast kinds we expect to encounter. 16997 // Anything else suggests we've left the region in which potential results 16998 // can be found. 16999 switch (ICE->getCastKind()) { 17000 case CK_NoOp: 17001 case CK_DerivedToBase: 17002 case CK_UncheckedDerivedToBase: { 17003 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17004 if (!Sub.isUsable()) 17005 return Sub; 17006 CXXCastPath Path(ICE->path()); 17007 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17008 ICE->getValueKind(), &Path); 17009 } 17010 17011 default: 17012 break; 17013 } 17014 break; 17015 } 17016 17017 default: 17018 break; 17019 } 17020 17021 // Can't traverse through this node. Nothing to do. 17022 return ExprEmpty(); 17023 } 17024 17025 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17026 // Check whether the operand is or contains an object of non-trivial C union 17027 // type. 17028 if (E->getType().isVolatileQualified() && 17029 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17030 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17031 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17032 Sema::NTCUC_LValueToRValueVolatile, 17033 NTCUK_Destruct|NTCUK_Copy); 17034 17035 // C++2a [basic.def.odr]p4: 17036 // [...] an expression of non-volatile-qualified non-class type to which 17037 // the lvalue-to-rvalue conversion is applied [...] 17038 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17039 return E; 17040 17041 ExprResult Result = 17042 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17043 if (Result.isInvalid()) 17044 return ExprError(); 17045 return Result.get() ? Result : E; 17046 } 17047 17048 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17049 Res = CorrectDelayedTyposInExpr(Res); 17050 17051 if (!Res.isUsable()) 17052 return Res; 17053 17054 // If a constant-expression is a reference to a variable where we delay 17055 // deciding whether it is an odr-use, just assume we will apply the 17056 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17057 // (a non-type template argument), we have special handling anyway. 17058 return CheckLValueToRValueConversionOperand(Res.get()); 17059 } 17060 17061 void Sema::CleanupVarDeclMarking() { 17062 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17063 // call. 17064 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17065 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17066 17067 for (Expr *E : LocalMaybeODRUseExprs) { 17068 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17069 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17070 DRE->getLocation(), *this); 17071 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17072 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17073 *this); 17074 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17075 for (VarDecl *VD : *FP) 17076 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17077 } else { 17078 llvm_unreachable("Unexpected expression"); 17079 } 17080 } 17081 17082 assert(MaybeODRUseExprs.empty() && 17083 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17084 } 17085 17086 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17087 VarDecl *Var, Expr *E) { 17088 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17089 isa<FunctionParmPackExpr>(E)) && 17090 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17091 Var->setReferenced(); 17092 17093 if (Var->isInvalidDecl()) 17094 return; 17095 17096 auto *MSI = Var->getMemberSpecializationInfo(); 17097 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17098 : Var->getTemplateSpecializationKind(); 17099 17100 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17101 bool UsableInConstantExpr = 17102 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17103 17104 // C++20 [expr.const]p12: 17105 // A variable [...] is needed for constant evaluation if it is [...] a 17106 // variable whose name appears as a potentially constant evaluated 17107 // expression that is either a contexpr variable or is of non-volatile 17108 // const-qualified integral type or of reference type 17109 bool NeededForConstantEvaluation = 17110 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17111 17112 bool NeedDefinition = 17113 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17114 17115 VarTemplateSpecializationDecl *VarSpec = 17116 dyn_cast<VarTemplateSpecializationDecl>(Var); 17117 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17118 "Can't instantiate a partial template specialization."); 17119 17120 // If this might be a member specialization of a static data member, check 17121 // the specialization is visible. We already did the checks for variable 17122 // template specializations when we created them. 17123 if (NeedDefinition && TSK != TSK_Undeclared && 17124 !isa<VarTemplateSpecializationDecl>(Var)) 17125 SemaRef.checkSpecializationVisibility(Loc, Var); 17126 17127 // Perform implicit instantiation of static data members, static data member 17128 // templates of class templates, and variable template specializations. Delay 17129 // instantiations of variable templates, except for those that could be used 17130 // in a constant expression. 17131 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17132 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17133 // instantiation declaration if a variable is usable in a constant 17134 // expression (among other cases). 17135 bool TryInstantiating = 17136 TSK == TSK_ImplicitInstantiation || 17137 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17138 17139 if (TryInstantiating) { 17140 SourceLocation PointOfInstantiation = 17141 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17142 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17143 if (FirstInstantiation) { 17144 PointOfInstantiation = Loc; 17145 if (MSI) 17146 MSI->setPointOfInstantiation(PointOfInstantiation); 17147 else 17148 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17149 } 17150 17151 bool InstantiationDependent = false; 17152 bool IsNonDependent = 17153 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17154 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17155 : true; 17156 17157 // Do not instantiate specializations that are still type-dependent. 17158 if (IsNonDependent) { 17159 if (UsableInConstantExpr) { 17160 // Do not defer instantiations of variables that could be used in a 17161 // constant expression. 17162 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17163 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17164 }); 17165 } else if (FirstInstantiation || 17166 isa<VarTemplateSpecializationDecl>(Var)) { 17167 // FIXME: For a specialization of a variable template, we don't 17168 // distinguish between "declaration and type implicitly instantiated" 17169 // and "implicit instantiation of definition requested", so we have 17170 // no direct way to avoid enqueueing the pending instantiation 17171 // multiple times. 17172 SemaRef.PendingInstantiations 17173 .push_back(std::make_pair(Var, PointOfInstantiation)); 17174 } 17175 } 17176 } 17177 } 17178 17179 // C++2a [basic.def.odr]p4: 17180 // A variable x whose name appears as a potentially-evaluated expression e 17181 // is odr-used by e unless 17182 // -- x is a reference that is usable in constant expressions 17183 // -- x is a variable of non-reference type that is usable in constant 17184 // expressions and has no mutable subobjects [FIXME], and e is an 17185 // element of the set of potential results of an expression of 17186 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17187 // conversion is applied 17188 // -- x is a variable of non-reference type, and e is an element of the set 17189 // of potential results of a discarded-value expression to which the 17190 // lvalue-to-rvalue conversion is not applied [FIXME] 17191 // 17192 // We check the first part of the second bullet here, and 17193 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17194 // FIXME: To get the third bullet right, we need to delay this even for 17195 // variables that are not usable in constant expressions. 17196 17197 // If we already know this isn't an odr-use, there's nothing more to do. 17198 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17199 if (DRE->isNonOdrUse()) 17200 return; 17201 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17202 if (ME->isNonOdrUse()) 17203 return; 17204 17205 switch (OdrUse) { 17206 case OdrUseContext::None: 17207 assert((!E || isa<FunctionParmPackExpr>(E)) && 17208 "missing non-odr-use marking for unevaluated decl ref"); 17209 break; 17210 17211 case OdrUseContext::FormallyOdrUsed: 17212 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17213 // behavior. 17214 break; 17215 17216 case OdrUseContext::Used: 17217 // If we might later find that this expression isn't actually an odr-use, 17218 // delay the marking. 17219 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17220 SemaRef.MaybeODRUseExprs.insert(E); 17221 else 17222 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17223 break; 17224 17225 case OdrUseContext::Dependent: 17226 // If this is a dependent context, we don't need to mark variables as 17227 // odr-used, but we may still need to track them for lambda capture. 17228 // FIXME: Do we also need to do this inside dependent typeid expressions 17229 // (which are modeled as unevaluated at this point)? 17230 const bool RefersToEnclosingScope = 17231 (SemaRef.CurContext != Var->getDeclContext() && 17232 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17233 if (RefersToEnclosingScope) { 17234 LambdaScopeInfo *const LSI = 17235 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17236 if (LSI && (!LSI->CallOperator || 17237 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17238 // If a variable could potentially be odr-used, defer marking it so 17239 // until we finish analyzing the full expression for any 17240 // lvalue-to-rvalue 17241 // or discarded value conversions that would obviate odr-use. 17242 // Add it to the list of potential captures that will be analyzed 17243 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17244 // unless the variable is a reference that was initialized by a constant 17245 // expression (this will never need to be captured or odr-used). 17246 // 17247 // FIXME: We can simplify this a lot after implementing P0588R1. 17248 assert(E && "Capture variable should be used in an expression."); 17249 if (!Var->getType()->isReferenceType() || 17250 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17251 LSI->addPotentialCapture(E->IgnoreParens()); 17252 } 17253 } 17254 break; 17255 } 17256 } 17257 17258 /// Mark a variable referenced, and check whether it is odr-used 17259 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17260 /// used directly for normal expressions referring to VarDecl. 17261 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17262 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17263 } 17264 17265 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17266 Decl *D, Expr *E, bool MightBeOdrUse) { 17267 if (SemaRef.isInOpenMPDeclareTargetContext()) 17268 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17269 17270 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17271 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17272 return; 17273 } 17274 17275 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17276 17277 // If this is a call to a method via a cast, also mark the method in the 17278 // derived class used in case codegen can devirtualize the call. 17279 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17280 if (!ME) 17281 return; 17282 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17283 if (!MD) 17284 return; 17285 // Only attempt to devirtualize if this is truly a virtual call. 17286 bool IsVirtualCall = MD->isVirtual() && 17287 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17288 if (!IsVirtualCall) 17289 return; 17290 17291 // If it's possible to devirtualize the call, mark the called function 17292 // referenced. 17293 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17294 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17295 if (DM) 17296 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17297 } 17298 17299 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17300 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17301 // TODO: update this with DR# once a defect report is filed. 17302 // C++11 defect. The address of a pure member should not be an ODR use, even 17303 // if it's a qualified reference. 17304 bool OdrUse = true; 17305 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17306 if (Method->isVirtual() && 17307 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17308 OdrUse = false; 17309 17310 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17311 if (!isConstantEvaluated() && FD->isConsteval() && 17312 !RebuildingImmediateInvocation) 17313 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17314 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17315 } 17316 17317 /// Perform reference-marking and odr-use handling for a MemberExpr. 17318 void Sema::MarkMemberReferenced(MemberExpr *E) { 17319 // C++11 [basic.def.odr]p2: 17320 // A non-overloaded function whose name appears as a potentially-evaluated 17321 // expression or a member of a set of candidate functions, if selected by 17322 // overload resolution when referred to from a potentially-evaluated 17323 // expression, is odr-used, unless it is a pure virtual function and its 17324 // name is not explicitly qualified. 17325 bool MightBeOdrUse = true; 17326 if (E->performsVirtualDispatch(getLangOpts())) { 17327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17328 if (Method->isPure()) 17329 MightBeOdrUse = false; 17330 } 17331 SourceLocation Loc = 17332 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17333 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17334 } 17335 17336 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17337 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17338 for (VarDecl *VD : *E) 17339 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17340 } 17341 17342 /// Perform marking for a reference to an arbitrary declaration. It 17343 /// marks the declaration referenced, and performs odr-use checking for 17344 /// functions and variables. This method should not be used when building a 17345 /// normal expression which refers to a variable. 17346 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17347 bool MightBeOdrUse) { 17348 if (MightBeOdrUse) { 17349 if (auto *VD = dyn_cast<VarDecl>(D)) { 17350 MarkVariableReferenced(Loc, VD); 17351 return; 17352 } 17353 } 17354 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17355 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17356 return; 17357 } 17358 D->setReferenced(); 17359 } 17360 17361 namespace { 17362 // Mark all of the declarations used by a type as referenced. 17363 // FIXME: Not fully implemented yet! We need to have a better understanding 17364 // of when we're entering a context we should not recurse into. 17365 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17366 // TreeTransforms rebuilding the type in a new context. Rather than 17367 // duplicating the TreeTransform logic, we should consider reusing it here. 17368 // Currently that causes problems when rebuilding LambdaExprs. 17369 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17370 Sema &S; 17371 SourceLocation Loc; 17372 17373 public: 17374 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17375 17376 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17377 17378 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17379 }; 17380 } 17381 17382 bool MarkReferencedDecls::TraverseTemplateArgument( 17383 const TemplateArgument &Arg) { 17384 { 17385 // A non-type template argument is a constant-evaluated context. 17386 EnterExpressionEvaluationContext Evaluated( 17387 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17388 if (Arg.getKind() == TemplateArgument::Declaration) { 17389 if (Decl *D = Arg.getAsDecl()) 17390 S.MarkAnyDeclReferenced(Loc, D, true); 17391 } else if (Arg.getKind() == TemplateArgument::Expression) { 17392 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17393 } 17394 } 17395 17396 return Inherited::TraverseTemplateArgument(Arg); 17397 } 17398 17399 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17400 MarkReferencedDecls Marker(*this, Loc); 17401 Marker.TraverseType(T); 17402 } 17403 17404 namespace { 17405 /// Helper class that marks all of the declarations referenced by 17406 /// potentially-evaluated subexpressions as "referenced". 17407 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17408 Sema &S; 17409 bool SkipLocalVariables; 17410 17411 public: 17412 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17413 17414 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17415 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17416 17417 void VisitDeclRefExpr(DeclRefExpr *E) { 17418 // If we were asked not to visit local variables, don't. 17419 if (SkipLocalVariables) { 17420 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17421 if (VD->hasLocalStorage()) 17422 return; 17423 } 17424 17425 S.MarkDeclRefReferenced(E); 17426 } 17427 17428 void VisitMemberExpr(MemberExpr *E) { 17429 S.MarkMemberReferenced(E); 17430 Inherited::VisitMemberExpr(E); 17431 } 17432 17433 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17434 S.MarkFunctionReferenced( 17435 E->getBeginLoc(), 17436 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17437 Visit(E->getSubExpr()); 17438 } 17439 17440 void VisitCXXNewExpr(CXXNewExpr *E) { 17441 if (E->getOperatorNew()) 17442 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17443 if (E->getOperatorDelete()) 17444 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17445 Inherited::VisitCXXNewExpr(E); 17446 } 17447 17448 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17449 if (E->getOperatorDelete()) 17450 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17451 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17452 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17453 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17454 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17455 } 17456 17457 Inherited::VisitCXXDeleteExpr(E); 17458 } 17459 17460 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17461 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17462 Inherited::VisitCXXConstructExpr(E); 17463 } 17464 17465 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17466 Visit(E->getExpr()); 17467 } 17468 }; 17469 } 17470 17471 /// Mark any declarations that appear within this expression or any 17472 /// potentially-evaluated subexpressions as "referenced". 17473 /// 17474 /// \param SkipLocalVariables If true, don't mark local variables as 17475 /// 'referenced'. 17476 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17477 bool SkipLocalVariables) { 17478 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17479 } 17480 17481 /// Emit a diagnostic that describes an effect on the run-time behavior 17482 /// of the program being compiled. 17483 /// 17484 /// This routine emits the given diagnostic when the code currently being 17485 /// type-checked is "potentially evaluated", meaning that there is a 17486 /// possibility that the code will actually be executable. Code in sizeof() 17487 /// expressions, code used only during overload resolution, etc., are not 17488 /// potentially evaluated. This routine will suppress such diagnostics or, 17489 /// in the absolutely nutty case of potentially potentially evaluated 17490 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17491 /// later. 17492 /// 17493 /// This routine should be used for all diagnostics that describe the run-time 17494 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17495 /// Failure to do so will likely result in spurious diagnostics or failures 17496 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17497 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17498 const PartialDiagnostic &PD) { 17499 switch (ExprEvalContexts.back().Context) { 17500 case ExpressionEvaluationContext::Unevaluated: 17501 case ExpressionEvaluationContext::UnevaluatedList: 17502 case ExpressionEvaluationContext::UnevaluatedAbstract: 17503 case ExpressionEvaluationContext::DiscardedStatement: 17504 // The argument will never be evaluated, so don't complain. 17505 break; 17506 17507 case ExpressionEvaluationContext::ConstantEvaluated: 17508 // Relevant diagnostics should be produced by constant evaluation. 17509 break; 17510 17511 case ExpressionEvaluationContext::PotentiallyEvaluated: 17512 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17513 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17514 FunctionScopes.back()->PossiblyUnreachableDiags. 17515 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17516 return true; 17517 } 17518 17519 // The initializer of a constexpr variable or of the first declaration of a 17520 // static data member is not syntactically a constant evaluated constant, 17521 // but nonetheless is always required to be a constant expression, so we 17522 // can skip diagnosing. 17523 // FIXME: Using the mangling context here is a hack. 17524 if (auto *VD = dyn_cast_or_null<VarDecl>( 17525 ExprEvalContexts.back().ManglingContextDecl)) { 17526 if (VD->isConstexpr() || 17527 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17528 break; 17529 // FIXME: For any other kind of variable, we should build a CFG for its 17530 // initializer and check whether the context in question is reachable. 17531 } 17532 17533 Diag(Loc, PD); 17534 return true; 17535 } 17536 17537 return false; 17538 } 17539 17540 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17541 const PartialDiagnostic &PD) { 17542 return DiagRuntimeBehavior( 17543 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17544 } 17545 17546 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17547 CallExpr *CE, FunctionDecl *FD) { 17548 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17549 return false; 17550 17551 // If we're inside a decltype's expression, don't check for a valid return 17552 // type or construct temporaries until we know whether this is the last call. 17553 if (ExprEvalContexts.back().ExprContext == 17554 ExpressionEvaluationContextRecord::EK_Decltype) { 17555 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17556 return false; 17557 } 17558 17559 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17560 FunctionDecl *FD; 17561 CallExpr *CE; 17562 17563 public: 17564 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17565 : FD(FD), CE(CE) { } 17566 17567 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17568 if (!FD) { 17569 S.Diag(Loc, diag::err_call_incomplete_return) 17570 << T << CE->getSourceRange(); 17571 return; 17572 } 17573 17574 S.Diag(Loc, diag::err_call_function_incomplete_return) 17575 << CE->getSourceRange() << FD->getDeclName() << T; 17576 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17577 << FD->getDeclName(); 17578 } 17579 } Diagnoser(FD, CE); 17580 17581 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17582 return true; 17583 17584 return false; 17585 } 17586 17587 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17588 // will prevent this condition from triggering, which is what we want. 17589 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17590 SourceLocation Loc; 17591 17592 unsigned diagnostic = diag::warn_condition_is_assignment; 17593 bool IsOrAssign = false; 17594 17595 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17596 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17597 return; 17598 17599 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17600 17601 // Greylist some idioms by putting them into a warning subcategory. 17602 if (ObjCMessageExpr *ME 17603 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17604 Selector Sel = ME->getSelector(); 17605 17606 // self = [<foo> init...] 17607 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17608 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17609 17610 // <foo> = [<bar> nextObject] 17611 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17612 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17613 } 17614 17615 Loc = Op->getOperatorLoc(); 17616 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17617 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17618 return; 17619 17620 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17621 Loc = Op->getOperatorLoc(); 17622 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17623 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17624 else { 17625 // Not an assignment. 17626 return; 17627 } 17628 17629 Diag(Loc, diagnostic) << E->getSourceRange(); 17630 17631 SourceLocation Open = E->getBeginLoc(); 17632 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17633 Diag(Loc, diag::note_condition_assign_silence) 17634 << FixItHint::CreateInsertion(Open, "(") 17635 << FixItHint::CreateInsertion(Close, ")"); 17636 17637 if (IsOrAssign) 17638 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17639 << FixItHint::CreateReplacement(Loc, "!="); 17640 else 17641 Diag(Loc, diag::note_condition_assign_to_comparison) 17642 << FixItHint::CreateReplacement(Loc, "=="); 17643 } 17644 17645 /// Redundant parentheses over an equality comparison can indicate 17646 /// that the user intended an assignment used as condition. 17647 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17648 // Don't warn if the parens came from a macro. 17649 SourceLocation parenLoc = ParenE->getBeginLoc(); 17650 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17651 return; 17652 // Don't warn for dependent expressions. 17653 if (ParenE->isTypeDependent()) 17654 return; 17655 17656 Expr *E = ParenE->IgnoreParens(); 17657 17658 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17659 if (opE->getOpcode() == BO_EQ && 17660 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17661 == Expr::MLV_Valid) { 17662 SourceLocation Loc = opE->getOperatorLoc(); 17663 17664 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17665 SourceRange ParenERange = ParenE->getSourceRange(); 17666 Diag(Loc, diag::note_equality_comparison_silence) 17667 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17668 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17669 Diag(Loc, diag::note_equality_comparison_to_assign) 17670 << FixItHint::CreateReplacement(Loc, "="); 17671 } 17672 } 17673 17674 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17675 bool IsConstexpr) { 17676 DiagnoseAssignmentAsCondition(E); 17677 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17678 DiagnoseEqualityWithExtraParens(parenE); 17679 17680 ExprResult result = CheckPlaceholderExpr(E); 17681 if (result.isInvalid()) return ExprError(); 17682 E = result.get(); 17683 17684 if (!E->isTypeDependent()) { 17685 if (getLangOpts().CPlusPlus) 17686 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17687 17688 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17689 if (ERes.isInvalid()) 17690 return ExprError(); 17691 E = ERes.get(); 17692 17693 QualType T = E->getType(); 17694 if (!T->isScalarType()) { // C99 6.8.4.1p1 17695 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17696 << T << E->getSourceRange(); 17697 return ExprError(); 17698 } 17699 CheckBoolLikeConversion(E, Loc); 17700 } 17701 17702 return E; 17703 } 17704 17705 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17706 Expr *SubExpr, ConditionKind CK) { 17707 // Empty conditions are valid in for-statements. 17708 if (!SubExpr) 17709 return ConditionResult(); 17710 17711 ExprResult Cond; 17712 switch (CK) { 17713 case ConditionKind::Boolean: 17714 Cond = CheckBooleanCondition(Loc, SubExpr); 17715 break; 17716 17717 case ConditionKind::ConstexprIf: 17718 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17719 break; 17720 17721 case ConditionKind::Switch: 17722 Cond = CheckSwitchCondition(Loc, SubExpr); 17723 break; 17724 } 17725 if (Cond.isInvalid()) 17726 return ConditionError(); 17727 17728 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17729 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17730 if (!FullExpr.get()) 17731 return ConditionError(); 17732 17733 return ConditionResult(*this, nullptr, FullExpr, 17734 CK == ConditionKind::ConstexprIf); 17735 } 17736 17737 namespace { 17738 /// A visitor for rebuilding a call to an __unknown_any expression 17739 /// to have an appropriate type. 17740 struct RebuildUnknownAnyFunction 17741 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17742 17743 Sema &S; 17744 17745 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17746 17747 ExprResult VisitStmt(Stmt *S) { 17748 llvm_unreachable("unexpected statement!"); 17749 } 17750 17751 ExprResult VisitExpr(Expr *E) { 17752 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17753 << E->getSourceRange(); 17754 return ExprError(); 17755 } 17756 17757 /// Rebuild an expression which simply semantically wraps another 17758 /// expression which it shares the type and value kind of. 17759 template <class T> ExprResult rebuildSugarExpr(T *E) { 17760 ExprResult SubResult = Visit(E->getSubExpr()); 17761 if (SubResult.isInvalid()) return ExprError(); 17762 17763 Expr *SubExpr = SubResult.get(); 17764 E->setSubExpr(SubExpr); 17765 E->setType(SubExpr->getType()); 17766 E->setValueKind(SubExpr->getValueKind()); 17767 assert(E->getObjectKind() == OK_Ordinary); 17768 return E; 17769 } 17770 17771 ExprResult VisitParenExpr(ParenExpr *E) { 17772 return rebuildSugarExpr(E); 17773 } 17774 17775 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17776 return rebuildSugarExpr(E); 17777 } 17778 17779 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17780 ExprResult SubResult = Visit(E->getSubExpr()); 17781 if (SubResult.isInvalid()) return ExprError(); 17782 17783 Expr *SubExpr = SubResult.get(); 17784 E->setSubExpr(SubExpr); 17785 E->setType(S.Context.getPointerType(SubExpr->getType())); 17786 assert(E->getValueKind() == VK_RValue); 17787 assert(E->getObjectKind() == OK_Ordinary); 17788 return E; 17789 } 17790 17791 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17792 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17793 17794 E->setType(VD->getType()); 17795 17796 assert(E->getValueKind() == VK_RValue); 17797 if (S.getLangOpts().CPlusPlus && 17798 !(isa<CXXMethodDecl>(VD) && 17799 cast<CXXMethodDecl>(VD)->isInstance())) 17800 E->setValueKind(VK_LValue); 17801 17802 return E; 17803 } 17804 17805 ExprResult VisitMemberExpr(MemberExpr *E) { 17806 return resolveDecl(E, E->getMemberDecl()); 17807 } 17808 17809 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17810 return resolveDecl(E, E->getDecl()); 17811 } 17812 }; 17813 } 17814 17815 /// Given a function expression of unknown-any type, try to rebuild it 17816 /// to have a function type. 17817 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17818 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17819 if (Result.isInvalid()) return ExprError(); 17820 return S.DefaultFunctionArrayConversion(Result.get()); 17821 } 17822 17823 namespace { 17824 /// A visitor for rebuilding an expression of type __unknown_anytype 17825 /// into one which resolves the type directly on the referring 17826 /// expression. Strict preservation of the original source 17827 /// structure is not a goal. 17828 struct RebuildUnknownAnyExpr 17829 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17830 17831 Sema &S; 17832 17833 /// The current destination type. 17834 QualType DestType; 17835 17836 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17837 : S(S), DestType(CastType) {} 17838 17839 ExprResult VisitStmt(Stmt *S) { 17840 llvm_unreachable("unexpected statement!"); 17841 } 17842 17843 ExprResult VisitExpr(Expr *E) { 17844 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17845 << E->getSourceRange(); 17846 return ExprError(); 17847 } 17848 17849 ExprResult VisitCallExpr(CallExpr *E); 17850 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17851 17852 /// Rebuild an expression which simply semantically wraps another 17853 /// expression which it shares the type and value kind of. 17854 template <class T> ExprResult rebuildSugarExpr(T *E) { 17855 ExprResult SubResult = Visit(E->getSubExpr()); 17856 if (SubResult.isInvalid()) return ExprError(); 17857 Expr *SubExpr = SubResult.get(); 17858 E->setSubExpr(SubExpr); 17859 E->setType(SubExpr->getType()); 17860 E->setValueKind(SubExpr->getValueKind()); 17861 assert(E->getObjectKind() == OK_Ordinary); 17862 return E; 17863 } 17864 17865 ExprResult VisitParenExpr(ParenExpr *E) { 17866 return rebuildSugarExpr(E); 17867 } 17868 17869 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17870 return rebuildSugarExpr(E); 17871 } 17872 17873 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17874 const PointerType *Ptr = DestType->getAs<PointerType>(); 17875 if (!Ptr) { 17876 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17877 << E->getSourceRange(); 17878 return ExprError(); 17879 } 17880 17881 if (isa<CallExpr>(E->getSubExpr())) { 17882 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17883 << E->getSourceRange(); 17884 return ExprError(); 17885 } 17886 17887 assert(E->getValueKind() == VK_RValue); 17888 assert(E->getObjectKind() == OK_Ordinary); 17889 E->setType(DestType); 17890 17891 // Build the sub-expression as if it were an object of the pointee type. 17892 DestType = Ptr->getPointeeType(); 17893 ExprResult SubResult = Visit(E->getSubExpr()); 17894 if (SubResult.isInvalid()) return ExprError(); 17895 E->setSubExpr(SubResult.get()); 17896 return E; 17897 } 17898 17899 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17900 17901 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17902 17903 ExprResult VisitMemberExpr(MemberExpr *E) { 17904 return resolveDecl(E, E->getMemberDecl()); 17905 } 17906 17907 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17908 return resolveDecl(E, E->getDecl()); 17909 } 17910 }; 17911 } 17912 17913 /// Rebuilds a call expression which yielded __unknown_anytype. 17914 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17915 Expr *CalleeExpr = E->getCallee(); 17916 17917 enum FnKind { 17918 FK_MemberFunction, 17919 FK_FunctionPointer, 17920 FK_BlockPointer 17921 }; 17922 17923 FnKind Kind; 17924 QualType CalleeType = CalleeExpr->getType(); 17925 if (CalleeType == S.Context.BoundMemberTy) { 17926 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17927 Kind = FK_MemberFunction; 17928 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17929 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17930 CalleeType = Ptr->getPointeeType(); 17931 Kind = FK_FunctionPointer; 17932 } else { 17933 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17934 Kind = FK_BlockPointer; 17935 } 17936 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17937 17938 // Verify that this is a legal result type of a function. 17939 if (DestType->isArrayType() || DestType->isFunctionType()) { 17940 unsigned diagID = diag::err_func_returning_array_function; 17941 if (Kind == FK_BlockPointer) 17942 diagID = diag::err_block_returning_array_function; 17943 17944 S.Diag(E->getExprLoc(), diagID) 17945 << DestType->isFunctionType() << DestType; 17946 return ExprError(); 17947 } 17948 17949 // Otherwise, go ahead and set DestType as the call's result. 17950 E->setType(DestType.getNonLValueExprType(S.Context)); 17951 E->setValueKind(Expr::getValueKindForType(DestType)); 17952 assert(E->getObjectKind() == OK_Ordinary); 17953 17954 // Rebuild the function type, replacing the result type with DestType. 17955 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17956 if (Proto) { 17957 // __unknown_anytype(...) is a special case used by the debugger when 17958 // it has no idea what a function's signature is. 17959 // 17960 // We want to build this call essentially under the K&R 17961 // unprototyped rules, but making a FunctionNoProtoType in C++ 17962 // would foul up all sorts of assumptions. However, we cannot 17963 // simply pass all arguments as variadic arguments, nor can we 17964 // portably just call the function under a non-variadic type; see 17965 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17966 // However, it turns out that in practice it is generally safe to 17967 // call a function declared as "A foo(B,C,D);" under the prototype 17968 // "A foo(B,C,D,...);". The only known exception is with the 17969 // Windows ABI, where any variadic function is implicitly cdecl 17970 // regardless of its normal CC. Therefore we change the parameter 17971 // types to match the types of the arguments. 17972 // 17973 // This is a hack, but it is far superior to moving the 17974 // corresponding target-specific code from IR-gen to Sema/AST. 17975 17976 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17977 SmallVector<QualType, 8> ArgTypes; 17978 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17979 ArgTypes.reserve(E->getNumArgs()); 17980 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17981 Expr *Arg = E->getArg(i); 17982 QualType ArgType = Arg->getType(); 17983 if (E->isLValue()) { 17984 ArgType = S.Context.getLValueReferenceType(ArgType); 17985 } else if (E->isXValue()) { 17986 ArgType = S.Context.getRValueReferenceType(ArgType); 17987 } 17988 ArgTypes.push_back(ArgType); 17989 } 17990 ParamTypes = ArgTypes; 17991 } 17992 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17993 Proto->getExtProtoInfo()); 17994 } else { 17995 DestType = S.Context.getFunctionNoProtoType(DestType, 17996 FnType->getExtInfo()); 17997 } 17998 17999 // Rebuild the appropriate pointer-to-function type. 18000 switch (Kind) { 18001 case FK_MemberFunction: 18002 // Nothing to do. 18003 break; 18004 18005 case FK_FunctionPointer: 18006 DestType = S.Context.getPointerType(DestType); 18007 break; 18008 18009 case FK_BlockPointer: 18010 DestType = S.Context.getBlockPointerType(DestType); 18011 break; 18012 } 18013 18014 // Finally, we can recurse. 18015 ExprResult CalleeResult = Visit(CalleeExpr); 18016 if (!CalleeResult.isUsable()) return ExprError(); 18017 E->setCallee(CalleeResult.get()); 18018 18019 // Bind a temporary if necessary. 18020 return S.MaybeBindToTemporary(E); 18021 } 18022 18023 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18024 // Verify that this is a legal result type of a call. 18025 if (DestType->isArrayType() || DestType->isFunctionType()) { 18026 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18027 << DestType->isFunctionType() << DestType; 18028 return ExprError(); 18029 } 18030 18031 // Rewrite the method result type if available. 18032 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18033 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18034 Method->setReturnType(DestType); 18035 } 18036 18037 // Change the type of the message. 18038 E->setType(DestType.getNonReferenceType()); 18039 E->setValueKind(Expr::getValueKindForType(DestType)); 18040 18041 return S.MaybeBindToTemporary(E); 18042 } 18043 18044 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18045 // The only case we should ever see here is a function-to-pointer decay. 18046 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18047 assert(E->getValueKind() == VK_RValue); 18048 assert(E->getObjectKind() == OK_Ordinary); 18049 18050 E->setType(DestType); 18051 18052 // Rebuild the sub-expression as the pointee (function) type. 18053 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18054 18055 ExprResult Result = Visit(E->getSubExpr()); 18056 if (!Result.isUsable()) return ExprError(); 18057 18058 E->setSubExpr(Result.get()); 18059 return E; 18060 } else if (E->getCastKind() == CK_LValueToRValue) { 18061 assert(E->getValueKind() == VK_RValue); 18062 assert(E->getObjectKind() == OK_Ordinary); 18063 18064 assert(isa<BlockPointerType>(E->getType())); 18065 18066 E->setType(DestType); 18067 18068 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18069 DestType = S.Context.getLValueReferenceType(DestType); 18070 18071 ExprResult Result = Visit(E->getSubExpr()); 18072 if (!Result.isUsable()) return ExprError(); 18073 18074 E->setSubExpr(Result.get()); 18075 return E; 18076 } else { 18077 llvm_unreachable("Unhandled cast type!"); 18078 } 18079 } 18080 18081 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18082 ExprValueKind ValueKind = VK_LValue; 18083 QualType Type = DestType; 18084 18085 // We know how to make this work for certain kinds of decls: 18086 18087 // - functions 18088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18089 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18090 DestType = Ptr->getPointeeType(); 18091 ExprResult Result = resolveDecl(E, VD); 18092 if (Result.isInvalid()) return ExprError(); 18093 return S.ImpCastExprToType(Result.get(), Type, 18094 CK_FunctionToPointerDecay, VK_RValue); 18095 } 18096 18097 if (!Type->isFunctionType()) { 18098 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18099 << VD << E->getSourceRange(); 18100 return ExprError(); 18101 } 18102 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18103 // We must match the FunctionDecl's type to the hack introduced in 18104 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18105 // type. See the lengthy commentary in that routine. 18106 QualType FDT = FD->getType(); 18107 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18108 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18109 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18110 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18111 SourceLocation Loc = FD->getLocation(); 18112 FunctionDecl *NewFD = FunctionDecl::Create( 18113 S.Context, FD->getDeclContext(), Loc, Loc, 18114 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18115 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18116 /*ConstexprKind*/ CSK_unspecified); 18117 18118 if (FD->getQualifier()) 18119 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18120 18121 SmallVector<ParmVarDecl*, 16> Params; 18122 for (const auto &AI : FT->param_types()) { 18123 ParmVarDecl *Param = 18124 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18125 Param->setScopeInfo(0, Params.size()); 18126 Params.push_back(Param); 18127 } 18128 NewFD->setParams(Params); 18129 DRE->setDecl(NewFD); 18130 VD = DRE->getDecl(); 18131 } 18132 } 18133 18134 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18135 if (MD->isInstance()) { 18136 ValueKind = VK_RValue; 18137 Type = S.Context.BoundMemberTy; 18138 } 18139 18140 // Function references aren't l-values in C. 18141 if (!S.getLangOpts().CPlusPlus) 18142 ValueKind = VK_RValue; 18143 18144 // - variables 18145 } else if (isa<VarDecl>(VD)) { 18146 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18147 Type = RefTy->getPointeeType(); 18148 } else if (Type->isFunctionType()) { 18149 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18150 << VD << E->getSourceRange(); 18151 return ExprError(); 18152 } 18153 18154 // - nothing else 18155 } else { 18156 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18157 << VD << E->getSourceRange(); 18158 return ExprError(); 18159 } 18160 18161 // Modifying the declaration like this is friendly to IR-gen but 18162 // also really dangerous. 18163 VD->setType(DestType); 18164 E->setType(Type); 18165 E->setValueKind(ValueKind); 18166 return E; 18167 } 18168 18169 /// Check a cast of an unknown-any type. We intentionally only 18170 /// trigger this for C-style casts. 18171 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18172 Expr *CastExpr, CastKind &CastKind, 18173 ExprValueKind &VK, CXXCastPath &Path) { 18174 // The type we're casting to must be either void or complete. 18175 if (!CastType->isVoidType() && 18176 RequireCompleteType(TypeRange.getBegin(), CastType, 18177 diag::err_typecheck_cast_to_incomplete)) 18178 return ExprError(); 18179 18180 // Rewrite the casted expression from scratch. 18181 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18182 if (!result.isUsable()) return ExprError(); 18183 18184 CastExpr = result.get(); 18185 VK = CastExpr->getValueKind(); 18186 CastKind = CK_NoOp; 18187 18188 return CastExpr; 18189 } 18190 18191 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18192 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18193 } 18194 18195 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18196 Expr *arg, QualType ¶mType) { 18197 // If the syntactic form of the argument is not an explicit cast of 18198 // any sort, just do default argument promotion. 18199 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18200 if (!castArg) { 18201 ExprResult result = DefaultArgumentPromotion(arg); 18202 if (result.isInvalid()) return ExprError(); 18203 paramType = result.get()->getType(); 18204 return result; 18205 } 18206 18207 // Otherwise, use the type that was written in the explicit cast. 18208 assert(!arg->hasPlaceholderType()); 18209 paramType = castArg->getTypeAsWritten(); 18210 18211 // Copy-initialize a parameter of that type. 18212 InitializedEntity entity = 18213 InitializedEntity::InitializeParameter(Context, paramType, 18214 /*consumed*/ false); 18215 return PerformCopyInitialization(entity, callLoc, arg); 18216 } 18217 18218 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18219 Expr *orig = E; 18220 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18221 while (true) { 18222 E = E->IgnoreParenImpCasts(); 18223 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18224 E = call->getCallee(); 18225 diagID = diag::err_uncasted_call_of_unknown_any; 18226 } else { 18227 break; 18228 } 18229 } 18230 18231 SourceLocation loc; 18232 NamedDecl *d; 18233 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18234 loc = ref->getLocation(); 18235 d = ref->getDecl(); 18236 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18237 loc = mem->getMemberLoc(); 18238 d = mem->getMemberDecl(); 18239 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18240 diagID = diag::err_uncasted_call_of_unknown_any; 18241 loc = msg->getSelectorStartLoc(); 18242 d = msg->getMethodDecl(); 18243 if (!d) { 18244 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18245 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18246 << orig->getSourceRange(); 18247 return ExprError(); 18248 } 18249 } else { 18250 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18251 << E->getSourceRange(); 18252 return ExprError(); 18253 } 18254 18255 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18256 18257 // Never recoverable. 18258 return ExprError(); 18259 } 18260 18261 /// Check for operands with placeholder types and complain if found. 18262 /// Returns ExprError() if there was an error and no recovery was possible. 18263 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18264 if (!getLangOpts().CPlusPlus) { 18265 // C cannot handle TypoExpr nodes on either side of a binop because it 18266 // doesn't handle dependent types properly, so make sure any TypoExprs have 18267 // been dealt with before checking the operands. 18268 ExprResult Result = CorrectDelayedTyposInExpr(E); 18269 if (!Result.isUsable()) return ExprError(); 18270 E = Result.get(); 18271 } 18272 18273 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18274 if (!placeholderType) return E; 18275 18276 switch (placeholderType->getKind()) { 18277 18278 // Overloaded expressions. 18279 case BuiltinType::Overload: { 18280 // Try to resolve a single function template specialization. 18281 // This is obligatory. 18282 ExprResult Result = E; 18283 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18284 return Result; 18285 18286 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18287 // leaves Result unchanged on failure. 18288 Result = E; 18289 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18290 return Result; 18291 18292 // If that failed, try to recover with a call. 18293 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18294 /*complain*/ true); 18295 return Result; 18296 } 18297 18298 // Bound member functions. 18299 case BuiltinType::BoundMember: { 18300 ExprResult result = E; 18301 const Expr *BME = E->IgnoreParens(); 18302 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18303 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18304 if (isa<CXXPseudoDestructorExpr>(BME)) { 18305 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18306 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18307 if (ME->getMemberNameInfo().getName().getNameKind() == 18308 DeclarationName::CXXDestructorName) 18309 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18310 } 18311 tryToRecoverWithCall(result, PD, 18312 /*complain*/ true); 18313 return result; 18314 } 18315 18316 // ARC unbridged casts. 18317 case BuiltinType::ARCUnbridgedCast: { 18318 Expr *realCast = stripARCUnbridgedCast(E); 18319 diagnoseARCUnbridgedCast(realCast); 18320 return realCast; 18321 } 18322 18323 // Expressions of unknown type. 18324 case BuiltinType::UnknownAny: 18325 return diagnoseUnknownAnyExpr(*this, E); 18326 18327 // Pseudo-objects. 18328 case BuiltinType::PseudoObject: 18329 return checkPseudoObjectRValue(E); 18330 18331 case BuiltinType::BuiltinFn: { 18332 // Accept __noop without parens by implicitly converting it to a call expr. 18333 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18334 if (DRE) { 18335 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18336 if (FD->getBuiltinID() == Builtin::BI__noop) { 18337 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18338 CK_BuiltinFnToFnPtr) 18339 .get(); 18340 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18341 VK_RValue, SourceLocation()); 18342 } 18343 } 18344 18345 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18346 return ExprError(); 18347 } 18348 18349 // Expressions of unknown type. 18350 case BuiltinType::OMPArraySection: 18351 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18352 return ExprError(); 18353 18354 // Everything else should be impossible. 18355 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18356 case BuiltinType::Id: 18357 #include "clang/Basic/OpenCLImageTypes.def" 18358 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18359 case BuiltinType::Id: 18360 #include "clang/Basic/OpenCLExtensionTypes.def" 18361 #define SVE_TYPE(Name, Id, SingletonId) \ 18362 case BuiltinType::Id: 18363 #include "clang/Basic/AArch64SVEACLETypes.def" 18364 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18365 #define PLACEHOLDER_TYPE(Id, SingletonId) 18366 #include "clang/AST/BuiltinTypes.def" 18367 break; 18368 } 18369 18370 llvm_unreachable("invalid placeholder type!"); 18371 } 18372 18373 bool Sema::CheckCaseExpression(Expr *E) { 18374 if (E->isTypeDependent()) 18375 return true; 18376 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18377 return E->getType()->isIntegralOrEnumerationType(); 18378 return false; 18379 } 18380 18381 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18382 ExprResult 18383 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18384 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18385 "Unknown Objective-C Boolean value!"); 18386 QualType BoolT = Context.ObjCBuiltinBoolTy; 18387 if (!Context.getBOOLDecl()) { 18388 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18389 Sema::LookupOrdinaryName); 18390 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18391 NamedDecl *ND = Result.getFoundDecl(); 18392 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18393 Context.setBOOLDecl(TD); 18394 } 18395 } 18396 if (Context.getBOOLDecl()) 18397 BoolT = Context.getBOOLType(); 18398 return new (Context) 18399 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18400 } 18401 18402 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18403 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18404 SourceLocation RParen) { 18405 18406 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18407 18408 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18409 return Spec.getPlatform() == Platform; 18410 }); 18411 18412 VersionTuple Version; 18413 if (Spec != AvailSpecs.end()) 18414 Version = Spec->getVersion(); 18415 18416 // The use of `@available` in the enclosing function should be analyzed to 18417 // warn when it's used inappropriately (i.e. not if(@available)). 18418 if (getCurFunctionOrMethodDecl()) 18419 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18420 else if (getCurBlock() || getCurLambda()) 18421 getCurFunction()->HasPotentialAvailabilityViolations = true; 18422 18423 return new (Context) 18424 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18425 } 18426 18427 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18428 assert(E->isTypeDependent()); 18429 return isa<UnresolvedLookupExpr>(E); 18430 } 18431