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 (RequireCompleteType(E->getExprLoc(), 3973 Context.getBaseElementType(E->getType()), 3974 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3975 E->getSourceRange())) 3976 return true; 3977 } else { 3978 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3979 ExprKind, E->getSourceRange())) 3980 return true; 3981 } 3982 3983 // Completing the expression's type may have changed it. 3984 ExprTy = E->getType(); 3985 assert(!ExprTy->isReferenceType()); 3986 3987 if (ExprTy->isFunctionType()) { 3988 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3989 << ExprKind << E->getSourceRange(); 3990 return true; 3991 } 3992 3993 // The operand for sizeof and alignof is in an unevaluated expression context, 3994 // so side effects could result in unintended consequences. 3995 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3996 E->HasSideEffects(Context, false)) 3997 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3998 3999 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4000 E->getSourceRange(), ExprKind)) 4001 return true; 4002 4003 if (ExprKind == UETT_SizeOf) { 4004 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4005 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4006 QualType OType = PVD->getOriginalType(); 4007 QualType Type = PVD->getType(); 4008 if (Type->isPointerType() && OType->isArrayType()) { 4009 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4010 << Type << OType; 4011 Diag(PVD->getLocation(), diag::note_declared_at); 4012 } 4013 } 4014 } 4015 4016 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4017 // decays into a pointer and returns an unintended result. This is most 4018 // likely a typo for "sizeof(array) op x". 4019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4020 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4021 BO->getLHS()); 4022 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4023 BO->getRHS()); 4024 } 4025 } 4026 4027 return false; 4028 } 4029 4030 /// Check the constraints on operands to unary expression and type 4031 /// traits. 4032 /// 4033 /// This will complete any types necessary, and validate the various constraints 4034 /// on those operands. 4035 /// 4036 /// The UsualUnaryConversions() function is *not* called by this routine. 4037 /// C99 6.3.2.1p[2-4] all state: 4038 /// Except when it is the operand of the sizeof operator ... 4039 /// 4040 /// C++ [expr.sizeof]p4 4041 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4042 /// standard conversions are not applied to the operand of sizeof. 4043 /// 4044 /// This policy is followed for all of the unary trait expressions. 4045 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4046 SourceLocation OpLoc, 4047 SourceRange ExprRange, 4048 UnaryExprOrTypeTrait ExprKind) { 4049 if (ExprType->isDependentType()) 4050 return false; 4051 4052 // C++ [expr.sizeof]p2: 4053 // When applied to a reference or a reference type, the result 4054 // is the size of the referenced type. 4055 // C++11 [expr.alignof]p3: 4056 // When alignof is applied to a reference type, the result 4057 // shall be the alignment of the referenced type. 4058 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4059 ExprType = Ref->getPointeeType(); 4060 4061 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4062 // When alignof or _Alignof is applied to an array type, the result 4063 // is the alignment of the element type. 4064 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4065 ExprKind == UETT_OpenMPRequiredSimdAlign) 4066 ExprType = Context.getBaseElementType(ExprType); 4067 4068 if (ExprKind == UETT_VecStep) 4069 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4070 4071 // Whitelist some types as extensions 4072 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4073 ExprKind)) 4074 return false; 4075 4076 if (RequireCompleteType(OpLoc, ExprType, 4077 diag::err_sizeof_alignof_incomplete_type, 4078 ExprKind, ExprRange)) 4079 return true; 4080 4081 if (ExprType->isFunctionType()) { 4082 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4083 << ExprKind << ExprRange; 4084 return true; 4085 } 4086 4087 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4088 ExprKind)) 4089 return true; 4090 4091 return false; 4092 } 4093 4094 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4095 // Cannot know anything else if the expression is dependent. 4096 if (E->isTypeDependent()) 4097 return false; 4098 4099 if (E->getObjectKind() == OK_BitField) { 4100 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4101 << 1 << E->getSourceRange(); 4102 return true; 4103 } 4104 4105 ValueDecl *D = nullptr; 4106 Expr *Inner = E->IgnoreParens(); 4107 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4108 D = DRE->getDecl(); 4109 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4110 D = ME->getMemberDecl(); 4111 } 4112 4113 // If it's a field, require the containing struct to have a 4114 // complete definition so that we can compute the layout. 4115 // 4116 // This can happen in C++11 onwards, either by naming the member 4117 // in a way that is not transformed into a member access expression 4118 // (in an unevaluated operand, for instance), or by naming the member 4119 // in a trailing-return-type. 4120 // 4121 // For the record, since __alignof__ on expressions is a GCC 4122 // extension, GCC seems to permit this but always gives the 4123 // nonsensical answer 0. 4124 // 4125 // We don't really need the layout here --- we could instead just 4126 // directly check for all the appropriate alignment-lowing 4127 // attributes --- but that would require duplicating a lot of 4128 // logic that just isn't worth duplicating for such a marginal 4129 // use-case. 4130 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4131 // Fast path this check, since we at least know the record has a 4132 // definition if we can find a member of it. 4133 if (!FD->getParent()->isCompleteDefinition()) { 4134 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4135 << E->getSourceRange(); 4136 return true; 4137 } 4138 4139 // Otherwise, if it's a field, and the field doesn't have 4140 // reference type, then it must have a complete type (or be a 4141 // flexible array member, which we explicitly want to 4142 // white-list anyway), which makes the following checks trivial. 4143 if (!FD->getType()->isReferenceType()) 4144 return false; 4145 } 4146 4147 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4148 } 4149 4150 bool Sema::CheckVecStepExpr(Expr *E) { 4151 E = E->IgnoreParens(); 4152 4153 // Cannot know anything else if the expression is dependent. 4154 if (E->isTypeDependent()) 4155 return false; 4156 4157 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4158 } 4159 4160 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4161 CapturingScopeInfo *CSI) { 4162 assert(T->isVariablyModifiedType()); 4163 assert(CSI != nullptr); 4164 4165 // We're going to walk down into the type and look for VLA expressions. 4166 do { 4167 const Type *Ty = T.getTypePtr(); 4168 switch (Ty->getTypeClass()) { 4169 #define TYPE(Class, Base) 4170 #define ABSTRACT_TYPE(Class, Base) 4171 #define NON_CANONICAL_TYPE(Class, Base) 4172 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4173 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4174 #include "clang/AST/TypeNodes.inc" 4175 T = QualType(); 4176 break; 4177 // These types are never variably-modified. 4178 case Type::Builtin: 4179 case Type::Complex: 4180 case Type::Vector: 4181 case Type::ExtVector: 4182 case Type::Record: 4183 case Type::Enum: 4184 case Type::Elaborated: 4185 case Type::TemplateSpecialization: 4186 case Type::ObjCObject: 4187 case Type::ObjCInterface: 4188 case Type::ObjCObjectPointer: 4189 case Type::ObjCTypeParam: 4190 case Type::Pipe: 4191 llvm_unreachable("type class is never variably-modified!"); 4192 case Type::Adjusted: 4193 T = cast<AdjustedType>(Ty)->getOriginalType(); 4194 break; 4195 case Type::Decayed: 4196 T = cast<DecayedType>(Ty)->getPointeeType(); 4197 break; 4198 case Type::Pointer: 4199 T = cast<PointerType>(Ty)->getPointeeType(); 4200 break; 4201 case Type::BlockPointer: 4202 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4203 break; 4204 case Type::LValueReference: 4205 case Type::RValueReference: 4206 T = cast<ReferenceType>(Ty)->getPointeeType(); 4207 break; 4208 case Type::MemberPointer: 4209 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4210 break; 4211 case Type::ConstantArray: 4212 case Type::IncompleteArray: 4213 // Losing element qualification here is fine. 4214 T = cast<ArrayType>(Ty)->getElementType(); 4215 break; 4216 case Type::VariableArray: { 4217 // Losing element qualification here is fine. 4218 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4219 4220 // Unknown size indication requires no size computation. 4221 // Otherwise, evaluate and record it. 4222 auto Size = VAT->getSizeExpr(); 4223 if (Size && !CSI->isVLATypeCaptured(VAT) && 4224 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4225 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4226 4227 T = VAT->getElementType(); 4228 break; 4229 } 4230 case Type::FunctionProto: 4231 case Type::FunctionNoProto: 4232 T = cast<FunctionType>(Ty)->getReturnType(); 4233 break; 4234 case Type::Paren: 4235 case Type::TypeOf: 4236 case Type::UnaryTransform: 4237 case Type::Attributed: 4238 case Type::SubstTemplateTypeParm: 4239 case Type::PackExpansion: 4240 case Type::MacroQualified: 4241 // Keep walking after single level desugaring. 4242 T = T.getSingleStepDesugaredType(Context); 4243 break; 4244 case Type::Typedef: 4245 T = cast<TypedefType>(Ty)->desugar(); 4246 break; 4247 case Type::Decltype: 4248 T = cast<DecltypeType>(Ty)->desugar(); 4249 break; 4250 case Type::Auto: 4251 case Type::DeducedTemplateSpecialization: 4252 T = cast<DeducedType>(Ty)->getDeducedType(); 4253 break; 4254 case Type::TypeOfExpr: 4255 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4256 break; 4257 case Type::Atomic: 4258 T = cast<AtomicType>(Ty)->getValueType(); 4259 break; 4260 } 4261 } while (!T.isNull() && T->isVariablyModifiedType()); 4262 } 4263 4264 /// Build a sizeof or alignof expression given a type operand. 4265 ExprResult 4266 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4267 SourceLocation OpLoc, 4268 UnaryExprOrTypeTrait ExprKind, 4269 SourceRange R) { 4270 if (!TInfo) 4271 return ExprError(); 4272 4273 QualType T = TInfo->getType(); 4274 4275 if (!T->isDependentType() && 4276 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4277 return ExprError(); 4278 4279 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4280 if (auto *TT = T->getAs<TypedefType>()) { 4281 for (auto I = FunctionScopes.rbegin(), 4282 E = std::prev(FunctionScopes.rend()); 4283 I != E; ++I) { 4284 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4285 if (CSI == nullptr) 4286 break; 4287 DeclContext *DC = nullptr; 4288 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4289 DC = LSI->CallOperator; 4290 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4291 DC = CRSI->TheCapturedDecl; 4292 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4293 DC = BSI->TheDecl; 4294 if (DC) { 4295 if (DC->containsDecl(TT->getDecl())) 4296 break; 4297 captureVariablyModifiedType(Context, T, CSI); 4298 } 4299 } 4300 } 4301 } 4302 4303 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4304 return new (Context) UnaryExprOrTypeTraitExpr( 4305 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4306 } 4307 4308 /// Build a sizeof or alignof expression given an expression 4309 /// operand. 4310 ExprResult 4311 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4312 UnaryExprOrTypeTrait ExprKind) { 4313 ExprResult PE = CheckPlaceholderExpr(E); 4314 if (PE.isInvalid()) 4315 return ExprError(); 4316 4317 E = PE.get(); 4318 4319 // Verify that the operand is valid. 4320 bool isInvalid = false; 4321 if (E->isTypeDependent()) { 4322 // Delay type-checking for type-dependent expressions. 4323 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4324 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4325 } else if (ExprKind == UETT_VecStep) { 4326 isInvalid = CheckVecStepExpr(E); 4327 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4328 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4329 isInvalid = true; 4330 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4331 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4332 isInvalid = true; 4333 } else { 4334 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4335 } 4336 4337 if (isInvalid) 4338 return ExprError(); 4339 4340 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4341 PE = TransformToPotentiallyEvaluated(E); 4342 if (PE.isInvalid()) return ExprError(); 4343 E = PE.get(); 4344 } 4345 4346 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4347 return new (Context) UnaryExprOrTypeTraitExpr( 4348 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4349 } 4350 4351 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4352 /// expr and the same for @c alignof and @c __alignof 4353 /// Note that the ArgRange is invalid if isType is false. 4354 ExprResult 4355 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4356 UnaryExprOrTypeTrait ExprKind, bool IsType, 4357 void *TyOrEx, SourceRange ArgRange) { 4358 // If error parsing type, ignore. 4359 if (!TyOrEx) return ExprError(); 4360 4361 if (IsType) { 4362 TypeSourceInfo *TInfo; 4363 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4364 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4365 } 4366 4367 Expr *ArgEx = (Expr *)TyOrEx; 4368 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4369 return Result; 4370 } 4371 4372 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4373 bool IsReal) { 4374 if (V.get()->isTypeDependent()) 4375 return S.Context.DependentTy; 4376 4377 // _Real and _Imag are only l-values for normal l-values. 4378 if (V.get()->getObjectKind() != OK_Ordinary) { 4379 V = S.DefaultLvalueConversion(V.get()); 4380 if (V.isInvalid()) 4381 return QualType(); 4382 } 4383 4384 // These operators return the element type of a complex type. 4385 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4386 return CT->getElementType(); 4387 4388 // Otherwise they pass through real integer and floating point types here. 4389 if (V.get()->getType()->isArithmeticType()) 4390 return V.get()->getType(); 4391 4392 // Test for placeholders. 4393 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4394 if (PR.isInvalid()) return QualType(); 4395 if (PR.get() != V.get()) { 4396 V = PR; 4397 return CheckRealImagOperand(S, V, Loc, IsReal); 4398 } 4399 4400 // Reject anything else. 4401 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4402 << (IsReal ? "__real" : "__imag"); 4403 return QualType(); 4404 } 4405 4406 4407 4408 ExprResult 4409 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4410 tok::TokenKind Kind, Expr *Input) { 4411 UnaryOperatorKind Opc; 4412 switch (Kind) { 4413 default: llvm_unreachable("Unknown unary op!"); 4414 case tok::plusplus: Opc = UO_PostInc; break; 4415 case tok::minusminus: Opc = UO_PostDec; break; 4416 } 4417 4418 // Since this might is a postfix expression, get rid of ParenListExprs. 4419 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4420 if (Result.isInvalid()) return ExprError(); 4421 Input = Result.get(); 4422 4423 return BuildUnaryOp(S, OpLoc, Opc, Input); 4424 } 4425 4426 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4427 /// 4428 /// \return true on error 4429 static bool checkArithmeticOnObjCPointer(Sema &S, 4430 SourceLocation opLoc, 4431 Expr *op) { 4432 assert(op->getType()->isObjCObjectPointerType()); 4433 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4434 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4435 return false; 4436 4437 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4438 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4439 << op->getSourceRange(); 4440 return true; 4441 } 4442 4443 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4444 auto *BaseNoParens = Base->IgnoreParens(); 4445 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4446 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4447 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4448 } 4449 4450 ExprResult 4451 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4452 Expr *idx, SourceLocation rbLoc) { 4453 if (base && !base->getType().isNull() && 4454 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4455 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4456 /*Length=*/nullptr, rbLoc); 4457 4458 // Since this might be a postfix expression, get rid of ParenListExprs. 4459 if (isa<ParenListExpr>(base)) { 4460 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4461 if (result.isInvalid()) return ExprError(); 4462 base = result.get(); 4463 } 4464 4465 // A comma-expression as the index is deprecated in C++2a onwards. 4466 if (getLangOpts().CPlusPlus2a && 4467 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4468 (isa<CXXOperatorCallExpr>(idx) && 4469 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4470 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4471 << SourceRange(base->getBeginLoc(), rbLoc); 4472 } 4473 4474 // Handle any non-overload placeholder types in the base and index 4475 // expressions. We can't handle overloads here because the other 4476 // operand might be an overloadable type, in which case the overload 4477 // resolution for the operator overload should get the first crack 4478 // at the overload. 4479 bool IsMSPropertySubscript = false; 4480 if (base->getType()->isNonOverloadPlaceholderType()) { 4481 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4482 if (!IsMSPropertySubscript) { 4483 ExprResult result = CheckPlaceholderExpr(base); 4484 if (result.isInvalid()) 4485 return ExprError(); 4486 base = result.get(); 4487 } 4488 } 4489 if (idx->getType()->isNonOverloadPlaceholderType()) { 4490 ExprResult result = CheckPlaceholderExpr(idx); 4491 if (result.isInvalid()) return ExprError(); 4492 idx = result.get(); 4493 } 4494 4495 // Build an unanalyzed expression if either operand is type-dependent. 4496 if (getLangOpts().CPlusPlus && 4497 (base->isTypeDependent() || idx->isTypeDependent())) { 4498 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4499 VK_LValue, OK_Ordinary, rbLoc); 4500 } 4501 4502 // MSDN, property (C++) 4503 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4504 // This attribute can also be used in the declaration of an empty array in a 4505 // class or structure definition. For example: 4506 // __declspec(property(get=GetX, put=PutX)) int x[]; 4507 // The above statement indicates that x[] can be used with one or more array 4508 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4509 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4510 if (IsMSPropertySubscript) { 4511 // Build MS property subscript expression if base is MS property reference 4512 // or MS property subscript. 4513 return new (Context) MSPropertySubscriptExpr( 4514 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4515 } 4516 4517 // Use C++ overloaded-operator rules if either operand has record 4518 // type. The spec says to do this if either type is *overloadable*, 4519 // but enum types can't declare subscript operators or conversion 4520 // operators, so there's nothing interesting for overload resolution 4521 // to do if there aren't any record types involved. 4522 // 4523 // ObjC pointers have their own subscripting logic that is not tied 4524 // to overload resolution and so should not take this path. 4525 if (getLangOpts().CPlusPlus && 4526 (base->getType()->isRecordType() || 4527 (!base->getType()->isObjCObjectPointerType() && 4528 idx->getType()->isRecordType()))) { 4529 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4530 } 4531 4532 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4533 4534 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4535 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4536 4537 return Res; 4538 } 4539 4540 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4541 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4542 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4543 4544 // For expressions like `&(*s).b`, the base is recorded and what should be 4545 // checked. 4546 const MemberExpr *Member = nullptr; 4547 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4548 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4549 4550 LastRecord.PossibleDerefs.erase(StrippedExpr); 4551 } 4552 4553 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4554 QualType ResultTy = E->getType(); 4555 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4556 4557 // Bail if the element is an array since it is not memory access. 4558 if (isa<ArrayType>(ResultTy)) 4559 return; 4560 4561 if (ResultTy->hasAttr(attr::NoDeref)) { 4562 LastRecord.PossibleDerefs.insert(E); 4563 return; 4564 } 4565 4566 // Check if the base type is a pointer to a member access of a struct 4567 // marked with noderef. 4568 const Expr *Base = E->getBase(); 4569 QualType BaseTy = Base->getType(); 4570 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4571 // Not a pointer access 4572 return; 4573 4574 const MemberExpr *Member = nullptr; 4575 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4576 Member->isArrow()) 4577 Base = Member->getBase(); 4578 4579 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4580 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4581 LastRecord.PossibleDerefs.insert(E); 4582 } 4583 } 4584 4585 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4586 Expr *LowerBound, 4587 SourceLocation ColonLoc, Expr *Length, 4588 SourceLocation RBLoc) { 4589 if (Base->getType()->isPlaceholderType() && 4590 !Base->getType()->isSpecificPlaceholderType( 4591 BuiltinType::OMPArraySection)) { 4592 ExprResult Result = CheckPlaceholderExpr(Base); 4593 if (Result.isInvalid()) 4594 return ExprError(); 4595 Base = Result.get(); 4596 } 4597 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4598 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4599 if (Result.isInvalid()) 4600 return ExprError(); 4601 Result = DefaultLvalueConversion(Result.get()); 4602 if (Result.isInvalid()) 4603 return ExprError(); 4604 LowerBound = Result.get(); 4605 } 4606 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4607 ExprResult Result = CheckPlaceholderExpr(Length); 4608 if (Result.isInvalid()) 4609 return ExprError(); 4610 Result = DefaultLvalueConversion(Result.get()); 4611 if (Result.isInvalid()) 4612 return ExprError(); 4613 Length = Result.get(); 4614 } 4615 4616 // Build an unanalyzed expression if either operand is type-dependent. 4617 if (Base->isTypeDependent() || 4618 (LowerBound && 4619 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4620 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4621 return new (Context) 4622 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4623 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4624 } 4625 4626 // Perform default conversions. 4627 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4628 QualType ResultTy; 4629 if (OriginalTy->isAnyPointerType()) { 4630 ResultTy = OriginalTy->getPointeeType(); 4631 } else if (OriginalTy->isArrayType()) { 4632 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4633 } else { 4634 return ExprError( 4635 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4636 << Base->getSourceRange()); 4637 } 4638 // C99 6.5.2.1p1 4639 if (LowerBound) { 4640 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4641 LowerBound); 4642 if (Res.isInvalid()) 4643 return ExprError(Diag(LowerBound->getExprLoc(), 4644 diag::err_omp_typecheck_section_not_integer) 4645 << 0 << LowerBound->getSourceRange()); 4646 LowerBound = Res.get(); 4647 4648 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4649 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4650 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4651 << 0 << LowerBound->getSourceRange(); 4652 } 4653 if (Length) { 4654 auto Res = 4655 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4656 if (Res.isInvalid()) 4657 return ExprError(Diag(Length->getExprLoc(), 4658 diag::err_omp_typecheck_section_not_integer) 4659 << 1 << Length->getSourceRange()); 4660 Length = Res.get(); 4661 4662 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4663 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4664 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4665 << 1 << Length->getSourceRange(); 4666 } 4667 4668 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4669 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4670 // type. Note that functions are not objects, and that (in C99 parlance) 4671 // incomplete types are not object types. 4672 if (ResultTy->isFunctionType()) { 4673 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4674 << ResultTy << Base->getSourceRange(); 4675 return ExprError(); 4676 } 4677 4678 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4679 diag::err_omp_section_incomplete_type, Base)) 4680 return ExprError(); 4681 4682 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4683 Expr::EvalResult Result; 4684 if (LowerBound->EvaluateAsInt(Result, Context)) { 4685 // OpenMP 4.5, [2.4 Array Sections] 4686 // The array section must be a subset of the original array. 4687 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4688 if (LowerBoundValue.isNegative()) { 4689 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4690 << LowerBound->getSourceRange(); 4691 return ExprError(); 4692 } 4693 } 4694 } 4695 4696 if (Length) { 4697 Expr::EvalResult Result; 4698 if (Length->EvaluateAsInt(Result, Context)) { 4699 // OpenMP 4.5, [2.4 Array Sections] 4700 // The length must evaluate to non-negative integers. 4701 llvm::APSInt LengthValue = Result.Val.getInt(); 4702 if (LengthValue.isNegative()) { 4703 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4704 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4705 << Length->getSourceRange(); 4706 return ExprError(); 4707 } 4708 } 4709 } else if (ColonLoc.isValid() && 4710 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4711 !OriginalTy->isVariableArrayType()))) { 4712 // OpenMP 4.5, [2.4 Array Sections] 4713 // When the size of the array dimension is not known, the length must be 4714 // specified explicitly. 4715 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4716 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4717 return ExprError(); 4718 } 4719 4720 if (!Base->getType()->isSpecificPlaceholderType( 4721 BuiltinType::OMPArraySection)) { 4722 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4723 if (Result.isInvalid()) 4724 return ExprError(); 4725 Base = Result.get(); 4726 } 4727 return new (Context) 4728 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4729 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4730 } 4731 4732 ExprResult 4733 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4734 Expr *Idx, SourceLocation RLoc) { 4735 Expr *LHSExp = Base; 4736 Expr *RHSExp = Idx; 4737 4738 ExprValueKind VK = VK_LValue; 4739 ExprObjectKind OK = OK_Ordinary; 4740 4741 // Per C++ core issue 1213, the result is an xvalue if either operand is 4742 // a non-lvalue array, and an lvalue otherwise. 4743 if (getLangOpts().CPlusPlus11) { 4744 for (auto *Op : {LHSExp, RHSExp}) { 4745 Op = Op->IgnoreImplicit(); 4746 if (Op->getType()->isArrayType() && !Op->isLValue()) 4747 VK = VK_XValue; 4748 } 4749 } 4750 4751 // Perform default conversions. 4752 if (!LHSExp->getType()->getAs<VectorType>()) { 4753 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4754 if (Result.isInvalid()) 4755 return ExprError(); 4756 LHSExp = Result.get(); 4757 } 4758 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4759 if (Result.isInvalid()) 4760 return ExprError(); 4761 RHSExp = Result.get(); 4762 4763 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4764 4765 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4766 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4767 // in the subscript position. As a result, we need to derive the array base 4768 // and index from the expression types. 4769 Expr *BaseExpr, *IndexExpr; 4770 QualType ResultType; 4771 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4772 BaseExpr = LHSExp; 4773 IndexExpr = RHSExp; 4774 ResultType = Context.DependentTy; 4775 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4776 BaseExpr = LHSExp; 4777 IndexExpr = RHSExp; 4778 ResultType = PTy->getPointeeType(); 4779 } else if (const ObjCObjectPointerType *PTy = 4780 LHSTy->getAs<ObjCObjectPointerType>()) { 4781 BaseExpr = LHSExp; 4782 IndexExpr = RHSExp; 4783 4784 // Use custom logic if this should be the pseudo-object subscript 4785 // expression. 4786 if (!LangOpts.isSubscriptPointerArithmetic()) 4787 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4788 nullptr); 4789 4790 ResultType = PTy->getPointeeType(); 4791 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4792 // Handle the uncommon case of "123[Ptr]". 4793 BaseExpr = RHSExp; 4794 IndexExpr = LHSExp; 4795 ResultType = PTy->getPointeeType(); 4796 } else if (const ObjCObjectPointerType *PTy = 4797 RHSTy->getAs<ObjCObjectPointerType>()) { 4798 // Handle the uncommon case of "123[Ptr]". 4799 BaseExpr = RHSExp; 4800 IndexExpr = LHSExp; 4801 ResultType = PTy->getPointeeType(); 4802 if (!LangOpts.isSubscriptPointerArithmetic()) { 4803 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4804 << ResultType << BaseExpr->getSourceRange(); 4805 return ExprError(); 4806 } 4807 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4808 BaseExpr = LHSExp; // vectors: V[123] 4809 IndexExpr = RHSExp; 4810 // We apply C++ DR1213 to vector subscripting too. 4811 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4812 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4813 if (Materialized.isInvalid()) 4814 return ExprError(); 4815 LHSExp = Materialized.get(); 4816 } 4817 VK = LHSExp->getValueKind(); 4818 if (VK != VK_RValue) 4819 OK = OK_VectorComponent; 4820 4821 ResultType = VTy->getElementType(); 4822 QualType BaseType = BaseExpr->getType(); 4823 Qualifiers BaseQuals = BaseType.getQualifiers(); 4824 Qualifiers MemberQuals = ResultType.getQualifiers(); 4825 Qualifiers Combined = BaseQuals + MemberQuals; 4826 if (Combined != MemberQuals) 4827 ResultType = Context.getQualifiedType(ResultType, Combined); 4828 } else if (LHSTy->isArrayType()) { 4829 // If we see an array that wasn't promoted by 4830 // DefaultFunctionArrayLvalueConversion, it must be an array that 4831 // wasn't promoted because of the C90 rule that doesn't 4832 // allow promoting non-lvalue arrays. Warn, then 4833 // force the promotion here. 4834 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4835 << LHSExp->getSourceRange(); 4836 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4837 CK_ArrayToPointerDecay).get(); 4838 LHSTy = LHSExp->getType(); 4839 4840 BaseExpr = LHSExp; 4841 IndexExpr = RHSExp; 4842 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4843 } else if (RHSTy->isArrayType()) { 4844 // Same as previous, except for 123[f().a] case 4845 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4846 << RHSExp->getSourceRange(); 4847 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4848 CK_ArrayToPointerDecay).get(); 4849 RHSTy = RHSExp->getType(); 4850 4851 BaseExpr = RHSExp; 4852 IndexExpr = LHSExp; 4853 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4854 } else { 4855 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4856 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4857 } 4858 // C99 6.5.2.1p1 4859 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4860 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4861 << IndexExpr->getSourceRange()); 4862 4863 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4864 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4865 && !IndexExpr->isTypeDependent()) 4866 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4867 4868 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4869 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4870 // type. Note that Functions are not objects, and that (in C99 parlance) 4871 // incomplete types are not object types. 4872 if (ResultType->isFunctionType()) { 4873 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4874 << ResultType << BaseExpr->getSourceRange(); 4875 return ExprError(); 4876 } 4877 4878 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4879 // GNU extension: subscripting on pointer to void 4880 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4881 << BaseExpr->getSourceRange(); 4882 4883 // C forbids expressions of unqualified void type from being l-values. 4884 // See IsCForbiddenLValueType. 4885 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4886 } else if (!ResultType->isDependentType() && 4887 RequireCompleteType(LLoc, ResultType, 4888 diag::err_subscript_incomplete_type, BaseExpr)) 4889 return ExprError(); 4890 4891 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4892 !ResultType.isCForbiddenLValueType()); 4893 4894 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4895 FunctionScopes.size() > 1) { 4896 if (auto *TT = 4897 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4898 for (auto I = FunctionScopes.rbegin(), 4899 E = std::prev(FunctionScopes.rend()); 4900 I != E; ++I) { 4901 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4902 if (CSI == nullptr) 4903 break; 4904 DeclContext *DC = nullptr; 4905 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4906 DC = LSI->CallOperator; 4907 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4908 DC = CRSI->TheCapturedDecl; 4909 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4910 DC = BSI->TheDecl; 4911 if (DC) { 4912 if (DC->containsDecl(TT->getDecl())) 4913 break; 4914 captureVariablyModifiedType( 4915 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4916 } 4917 } 4918 } 4919 } 4920 4921 return new (Context) 4922 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4923 } 4924 4925 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4926 ParmVarDecl *Param) { 4927 if (Param->hasUnparsedDefaultArg()) { 4928 Diag(CallLoc, 4929 diag::err_use_of_default_argument_to_function_declared_later) << 4930 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4931 Diag(UnparsedDefaultArgLocs[Param], 4932 diag::note_default_argument_declared_here); 4933 return true; 4934 } 4935 4936 if (Param->hasUninstantiatedDefaultArg()) { 4937 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4938 4939 EnterExpressionEvaluationContext EvalContext( 4940 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4941 4942 // Instantiate the expression. 4943 // 4944 // FIXME: Pass in a correct Pattern argument, otherwise 4945 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4946 // 4947 // template<typename T> 4948 // struct A { 4949 // static int FooImpl(); 4950 // 4951 // template<typename Tp> 4952 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4953 // // template argument list [[T], [Tp]], should be [[Tp]]. 4954 // friend A<Tp> Foo(int a); 4955 // }; 4956 // 4957 // template<typename T> 4958 // A<T> Foo(int a = A<T>::FooImpl()); 4959 MultiLevelTemplateArgumentList MutiLevelArgList 4960 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4961 4962 InstantiatingTemplate Inst(*this, CallLoc, Param, 4963 MutiLevelArgList.getInnermost()); 4964 if (Inst.isInvalid()) 4965 return true; 4966 if (Inst.isAlreadyInstantiating()) { 4967 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4968 Param->setInvalidDecl(); 4969 return true; 4970 } 4971 4972 ExprResult Result; 4973 { 4974 // C++ [dcl.fct.default]p5: 4975 // The names in the [default argument] expression are bound, and 4976 // the semantic constraints are checked, at the point where the 4977 // default argument expression appears. 4978 ContextRAII SavedContext(*this, FD); 4979 LocalInstantiationScope Local(*this); 4980 runWithSufficientStackSpace(CallLoc, [&] { 4981 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4982 /*DirectInit*/false); 4983 }); 4984 } 4985 if (Result.isInvalid()) 4986 return true; 4987 4988 // Check the expression as an initializer for the parameter. 4989 InitializedEntity Entity 4990 = InitializedEntity::InitializeParameter(Context, Param); 4991 InitializationKind Kind = InitializationKind::CreateCopy( 4992 Param->getLocation(), 4993 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4994 Expr *ResultE = Result.getAs<Expr>(); 4995 4996 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4997 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4998 if (Result.isInvalid()) 4999 return true; 5000 5001 Result = 5002 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5003 /*DiscardedValue*/ false); 5004 if (Result.isInvalid()) 5005 return true; 5006 5007 // Remember the instantiated default argument. 5008 Param->setDefaultArg(Result.getAs<Expr>()); 5009 if (ASTMutationListener *L = getASTMutationListener()) { 5010 L->DefaultArgumentInstantiated(Param); 5011 } 5012 } 5013 5014 // If the default argument expression is not set yet, we are building it now. 5015 if (!Param->hasInit()) { 5016 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5017 Param->setInvalidDecl(); 5018 return true; 5019 } 5020 5021 // If the default expression creates temporaries, we need to 5022 // push them to the current stack of expression temporaries so they'll 5023 // be properly destroyed. 5024 // FIXME: We should really be rebuilding the default argument with new 5025 // bound temporaries; see the comment in PR5810. 5026 // We don't need to do that with block decls, though, because 5027 // blocks in default argument expression can never capture anything. 5028 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5029 // Set the "needs cleanups" bit regardless of whether there are 5030 // any explicit objects. 5031 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5032 5033 // Append all the objects to the cleanup list. Right now, this 5034 // should always be a no-op, because blocks in default argument 5035 // expressions should never be able to capture anything. 5036 assert(!Init->getNumObjects() && 5037 "default argument expression has capturing blocks?"); 5038 } 5039 5040 // We already type-checked the argument, so we know it works. 5041 // Just mark all of the declarations in this potentially-evaluated expression 5042 // as being "referenced". 5043 EnterExpressionEvaluationContext EvalContext( 5044 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5045 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5046 /*SkipLocalVariables=*/true); 5047 return false; 5048 } 5049 5050 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5051 FunctionDecl *FD, ParmVarDecl *Param) { 5052 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5053 return ExprError(); 5054 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5055 } 5056 5057 Sema::VariadicCallType 5058 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5059 Expr *Fn) { 5060 if (Proto && Proto->isVariadic()) { 5061 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5062 return VariadicConstructor; 5063 else if (Fn && Fn->getType()->isBlockPointerType()) 5064 return VariadicBlock; 5065 else if (FDecl) { 5066 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5067 if (Method->isInstance()) 5068 return VariadicMethod; 5069 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5070 return VariadicMethod; 5071 return VariadicFunction; 5072 } 5073 return VariadicDoesNotApply; 5074 } 5075 5076 namespace { 5077 class FunctionCallCCC final : public FunctionCallFilterCCC { 5078 public: 5079 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5080 unsigned NumArgs, MemberExpr *ME) 5081 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5082 FunctionName(FuncName) {} 5083 5084 bool ValidateCandidate(const TypoCorrection &candidate) override { 5085 if (!candidate.getCorrectionSpecifier() || 5086 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5087 return false; 5088 } 5089 5090 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5091 } 5092 5093 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5094 return std::make_unique<FunctionCallCCC>(*this); 5095 } 5096 5097 private: 5098 const IdentifierInfo *const FunctionName; 5099 }; 5100 } 5101 5102 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5103 FunctionDecl *FDecl, 5104 ArrayRef<Expr *> Args) { 5105 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5106 DeclarationName FuncName = FDecl->getDeclName(); 5107 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5108 5109 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5110 if (TypoCorrection Corrected = S.CorrectTypo( 5111 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5112 S.getScopeForContext(S.CurContext), nullptr, CCC, 5113 Sema::CTK_ErrorRecovery)) { 5114 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5115 if (Corrected.isOverloaded()) { 5116 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5117 OverloadCandidateSet::iterator Best; 5118 for (NamedDecl *CD : Corrected) { 5119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5120 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5121 OCS); 5122 } 5123 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5124 case OR_Success: 5125 ND = Best->FoundDecl; 5126 Corrected.setCorrectionDecl(ND); 5127 break; 5128 default: 5129 break; 5130 } 5131 } 5132 ND = ND->getUnderlyingDecl(); 5133 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5134 return Corrected; 5135 } 5136 } 5137 return TypoCorrection(); 5138 } 5139 5140 /// ConvertArgumentsForCall - Converts the arguments specified in 5141 /// Args/NumArgs to the parameter types of the function FDecl with 5142 /// function prototype Proto. Call is the call expression itself, and 5143 /// Fn is the function expression. For a C++ member function, this 5144 /// routine does not attempt to convert the object argument. Returns 5145 /// true if the call is ill-formed. 5146 bool 5147 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5148 FunctionDecl *FDecl, 5149 const FunctionProtoType *Proto, 5150 ArrayRef<Expr *> Args, 5151 SourceLocation RParenLoc, 5152 bool IsExecConfig) { 5153 // Bail out early if calling a builtin with custom typechecking. 5154 if (FDecl) 5155 if (unsigned ID = FDecl->getBuiltinID()) 5156 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5157 return false; 5158 5159 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5160 // assignment, to the types of the corresponding parameter, ... 5161 unsigned NumParams = Proto->getNumParams(); 5162 bool Invalid = false; 5163 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5164 unsigned FnKind = Fn->getType()->isBlockPointerType() 5165 ? 1 /* block */ 5166 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5167 : 0 /* function */); 5168 5169 // If too few arguments are available (and we don't have default 5170 // arguments for the remaining parameters), don't make the call. 5171 if (Args.size() < NumParams) { 5172 if (Args.size() < MinArgs) { 5173 TypoCorrection TC; 5174 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5175 unsigned diag_id = 5176 MinArgs == NumParams && !Proto->isVariadic() 5177 ? diag::err_typecheck_call_too_few_args_suggest 5178 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5179 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5180 << static_cast<unsigned>(Args.size()) 5181 << TC.getCorrectionRange()); 5182 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5183 Diag(RParenLoc, 5184 MinArgs == NumParams && !Proto->isVariadic() 5185 ? diag::err_typecheck_call_too_few_args_one 5186 : diag::err_typecheck_call_too_few_args_at_least_one) 5187 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5188 else 5189 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5190 ? diag::err_typecheck_call_too_few_args 5191 : diag::err_typecheck_call_too_few_args_at_least) 5192 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5193 << Fn->getSourceRange(); 5194 5195 // Emit the location of the prototype. 5196 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5197 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5198 5199 return true; 5200 } 5201 // We reserve space for the default arguments when we create 5202 // the call expression, before calling ConvertArgumentsForCall. 5203 assert((Call->getNumArgs() == NumParams) && 5204 "We should have reserved space for the default arguments before!"); 5205 } 5206 5207 // If too many are passed and not variadic, error on the extras and drop 5208 // them. 5209 if (Args.size() > NumParams) { 5210 if (!Proto->isVariadic()) { 5211 TypoCorrection TC; 5212 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5213 unsigned diag_id = 5214 MinArgs == NumParams && !Proto->isVariadic() 5215 ? diag::err_typecheck_call_too_many_args_suggest 5216 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5217 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5218 << static_cast<unsigned>(Args.size()) 5219 << TC.getCorrectionRange()); 5220 } else if (NumParams == 1 && FDecl && 5221 FDecl->getParamDecl(0)->getDeclName()) 5222 Diag(Args[NumParams]->getBeginLoc(), 5223 MinArgs == NumParams 5224 ? diag::err_typecheck_call_too_many_args_one 5225 : diag::err_typecheck_call_too_many_args_at_most_one) 5226 << FnKind << FDecl->getParamDecl(0) 5227 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5228 << SourceRange(Args[NumParams]->getBeginLoc(), 5229 Args.back()->getEndLoc()); 5230 else 5231 Diag(Args[NumParams]->getBeginLoc(), 5232 MinArgs == NumParams 5233 ? diag::err_typecheck_call_too_many_args 5234 : diag::err_typecheck_call_too_many_args_at_most) 5235 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5236 << Fn->getSourceRange() 5237 << SourceRange(Args[NumParams]->getBeginLoc(), 5238 Args.back()->getEndLoc()); 5239 5240 // Emit the location of the prototype. 5241 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5242 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5243 5244 // This deletes the extra arguments. 5245 Call->shrinkNumArgs(NumParams); 5246 return true; 5247 } 5248 } 5249 SmallVector<Expr *, 8> AllArgs; 5250 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5251 5252 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5253 AllArgs, CallType); 5254 if (Invalid) 5255 return true; 5256 unsigned TotalNumArgs = AllArgs.size(); 5257 for (unsigned i = 0; i < TotalNumArgs; ++i) 5258 Call->setArg(i, AllArgs[i]); 5259 5260 return false; 5261 } 5262 5263 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5264 const FunctionProtoType *Proto, 5265 unsigned FirstParam, ArrayRef<Expr *> Args, 5266 SmallVectorImpl<Expr *> &AllArgs, 5267 VariadicCallType CallType, bool AllowExplicit, 5268 bool IsListInitialization) { 5269 unsigned NumParams = Proto->getNumParams(); 5270 bool Invalid = false; 5271 size_t ArgIx = 0; 5272 // Continue to check argument types (even if we have too few/many args). 5273 for (unsigned i = FirstParam; i < NumParams; i++) { 5274 QualType ProtoArgType = Proto->getParamType(i); 5275 5276 Expr *Arg; 5277 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5278 if (ArgIx < Args.size()) { 5279 Arg = Args[ArgIx++]; 5280 5281 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5282 diag::err_call_incomplete_argument, Arg)) 5283 return true; 5284 5285 // Strip the unbridged-cast placeholder expression off, if applicable. 5286 bool CFAudited = false; 5287 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5288 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5289 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5290 Arg = stripARCUnbridgedCast(Arg); 5291 else if (getLangOpts().ObjCAutoRefCount && 5292 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5293 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5294 CFAudited = true; 5295 5296 if (Proto->getExtParameterInfo(i).isNoEscape()) 5297 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5298 BE->getBlockDecl()->setDoesNotEscape(); 5299 5300 InitializedEntity Entity = 5301 Param ? InitializedEntity::InitializeParameter(Context, Param, 5302 ProtoArgType) 5303 : InitializedEntity::InitializeParameter( 5304 Context, ProtoArgType, Proto->isParamConsumed(i)); 5305 5306 // Remember that parameter belongs to a CF audited API. 5307 if (CFAudited) 5308 Entity.setParameterCFAudited(); 5309 5310 ExprResult ArgE = PerformCopyInitialization( 5311 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5312 if (ArgE.isInvalid()) 5313 return true; 5314 5315 Arg = ArgE.getAs<Expr>(); 5316 } else { 5317 assert(Param && "can't use default arguments without a known callee"); 5318 5319 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5320 if (ArgExpr.isInvalid()) 5321 return true; 5322 5323 Arg = ArgExpr.getAs<Expr>(); 5324 } 5325 5326 // Check for array bounds violations for each argument to the call. This 5327 // check only triggers warnings when the argument isn't a more complex Expr 5328 // with its own checking, such as a BinaryOperator. 5329 CheckArrayAccess(Arg); 5330 5331 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5332 CheckStaticArrayArgument(CallLoc, Param, Arg); 5333 5334 AllArgs.push_back(Arg); 5335 } 5336 5337 // If this is a variadic call, handle args passed through "...". 5338 if (CallType != VariadicDoesNotApply) { 5339 // Assume that extern "C" functions with variadic arguments that 5340 // return __unknown_anytype aren't *really* variadic. 5341 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5342 FDecl->isExternC()) { 5343 for (Expr *A : Args.slice(ArgIx)) { 5344 QualType paramType; // ignored 5345 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5346 Invalid |= arg.isInvalid(); 5347 AllArgs.push_back(arg.get()); 5348 } 5349 5350 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5351 } else { 5352 for (Expr *A : Args.slice(ArgIx)) { 5353 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5354 Invalid |= Arg.isInvalid(); 5355 // Copy blocks to the heap. 5356 if (A->getType()->isBlockPointerType()) 5357 maybeExtendBlockObject(Arg); 5358 AllArgs.push_back(Arg.get()); 5359 } 5360 } 5361 5362 // Check for array bounds violations. 5363 for (Expr *A : Args.slice(ArgIx)) 5364 CheckArrayAccess(A); 5365 } 5366 return Invalid; 5367 } 5368 5369 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5370 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5371 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5372 TL = DTL.getOriginalLoc(); 5373 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5374 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5375 << ATL.getLocalSourceRange(); 5376 } 5377 5378 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5379 /// array parameter, check that it is non-null, and that if it is formed by 5380 /// array-to-pointer decay, the underlying array is sufficiently large. 5381 /// 5382 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5383 /// array type derivation, then for each call to the function, the value of the 5384 /// corresponding actual argument shall provide access to the first element of 5385 /// an array with at least as many elements as specified by the size expression. 5386 void 5387 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5388 ParmVarDecl *Param, 5389 const Expr *ArgExpr) { 5390 // Static array parameters are not supported in C++. 5391 if (!Param || getLangOpts().CPlusPlus) 5392 return; 5393 5394 QualType OrigTy = Param->getOriginalType(); 5395 5396 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5397 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5398 return; 5399 5400 if (ArgExpr->isNullPointerConstant(Context, 5401 Expr::NPC_NeverValueDependent)) { 5402 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5403 DiagnoseCalleeStaticArrayParam(*this, Param); 5404 return; 5405 } 5406 5407 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5408 if (!CAT) 5409 return; 5410 5411 const ConstantArrayType *ArgCAT = 5412 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5413 if (!ArgCAT) 5414 return; 5415 5416 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5417 ArgCAT->getElementType())) { 5418 if (ArgCAT->getSize().ult(CAT->getSize())) { 5419 Diag(CallLoc, diag::warn_static_array_too_small) 5420 << ArgExpr->getSourceRange() 5421 << (unsigned)ArgCAT->getSize().getZExtValue() 5422 << (unsigned)CAT->getSize().getZExtValue() << 0; 5423 DiagnoseCalleeStaticArrayParam(*this, Param); 5424 } 5425 return; 5426 } 5427 5428 Optional<CharUnits> ArgSize = 5429 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5430 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5431 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5432 Diag(CallLoc, diag::warn_static_array_too_small) 5433 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5434 << (unsigned)ParmSize->getQuantity() << 1; 5435 DiagnoseCalleeStaticArrayParam(*this, Param); 5436 } 5437 } 5438 5439 /// Given a function expression of unknown-any type, try to rebuild it 5440 /// to have a function type. 5441 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5442 5443 /// Is the given type a placeholder that we need to lower out 5444 /// immediately during argument processing? 5445 static bool isPlaceholderToRemoveAsArg(QualType type) { 5446 // Placeholders are never sugared. 5447 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5448 if (!placeholder) return false; 5449 5450 switch (placeholder->getKind()) { 5451 // Ignore all the non-placeholder types. 5452 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5453 case BuiltinType::Id: 5454 #include "clang/Basic/OpenCLImageTypes.def" 5455 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5456 case BuiltinType::Id: 5457 #include "clang/Basic/OpenCLExtensionTypes.def" 5458 // In practice we'll never use this, since all SVE types are sugared 5459 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5460 #define SVE_TYPE(Name, Id, SingletonId) \ 5461 case BuiltinType::Id: 5462 #include "clang/Basic/AArch64SVEACLETypes.def" 5463 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5464 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5465 #include "clang/AST/BuiltinTypes.def" 5466 return false; 5467 5468 // We cannot lower out overload sets; they might validly be resolved 5469 // by the call machinery. 5470 case BuiltinType::Overload: 5471 return false; 5472 5473 // Unbridged casts in ARC can be handled in some call positions and 5474 // should be left in place. 5475 case BuiltinType::ARCUnbridgedCast: 5476 return false; 5477 5478 // Pseudo-objects should be converted as soon as possible. 5479 case BuiltinType::PseudoObject: 5480 return true; 5481 5482 // The debugger mode could theoretically but currently does not try 5483 // to resolve unknown-typed arguments based on known parameter types. 5484 case BuiltinType::UnknownAny: 5485 return true; 5486 5487 // These are always invalid as call arguments and should be reported. 5488 case BuiltinType::BoundMember: 5489 case BuiltinType::BuiltinFn: 5490 case BuiltinType::OMPArraySection: 5491 return true; 5492 5493 } 5494 llvm_unreachable("bad builtin type kind"); 5495 } 5496 5497 /// Check an argument list for placeholders that we won't try to 5498 /// handle later. 5499 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5500 // Apply this processing to all the arguments at once instead of 5501 // dying at the first failure. 5502 bool hasInvalid = false; 5503 for (size_t i = 0, e = args.size(); i != e; i++) { 5504 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5505 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5506 if (result.isInvalid()) hasInvalid = true; 5507 else args[i] = result.get(); 5508 } else if (hasInvalid) { 5509 (void)S.CorrectDelayedTyposInExpr(args[i]); 5510 } 5511 } 5512 return hasInvalid; 5513 } 5514 5515 /// If a builtin function has a pointer argument with no explicit address 5516 /// space, then it should be able to accept a pointer to any address 5517 /// space as input. In order to do this, we need to replace the 5518 /// standard builtin declaration with one that uses the same address space 5519 /// as the call. 5520 /// 5521 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5522 /// it does not contain any pointer arguments without 5523 /// an address space qualifer. Otherwise the rewritten 5524 /// FunctionDecl is returned. 5525 /// TODO: Handle pointer return types. 5526 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5527 FunctionDecl *FDecl, 5528 MultiExprArg ArgExprs) { 5529 5530 QualType DeclType = FDecl->getType(); 5531 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5532 5533 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5534 ArgExprs.size() < FT->getNumParams()) 5535 return nullptr; 5536 5537 bool NeedsNewDecl = false; 5538 unsigned i = 0; 5539 SmallVector<QualType, 8> OverloadParams; 5540 5541 for (QualType ParamType : FT->param_types()) { 5542 5543 // Convert array arguments to pointer to simplify type lookup. 5544 ExprResult ArgRes = 5545 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5546 if (ArgRes.isInvalid()) 5547 return nullptr; 5548 Expr *Arg = ArgRes.get(); 5549 QualType ArgType = Arg->getType(); 5550 if (!ParamType->isPointerType() || 5551 ParamType.hasAddressSpace() || 5552 !ArgType->isPointerType() || 5553 !ArgType->getPointeeType().hasAddressSpace()) { 5554 OverloadParams.push_back(ParamType); 5555 continue; 5556 } 5557 5558 QualType PointeeType = ParamType->getPointeeType(); 5559 if (PointeeType.hasAddressSpace()) 5560 continue; 5561 5562 NeedsNewDecl = true; 5563 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5564 5565 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5566 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5567 } 5568 5569 if (!NeedsNewDecl) 5570 return nullptr; 5571 5572 FunctionProtoType::ExtProtoInfo EPI; 5573 EPI.Variadic = FT->isVariadic(); 5574 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5575 OverloadParams, EPI); 5576 DeclContext *Parent = FDecl->getParent(); 5577 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5578 FDecl->getLocation(), 5579 FDecl->getLocation(), 5580 FDecl->getIdentifier(), 5581 OverloadTy, 5582 /*TInfo=*/nullptr, 5583 SC_Extern, false, 5584 /*hasPrototype=*/true); 5585 SmallVector<ParmVarDecl*, 16> Params; 5586 FT = cast<FunctionProtoType>(OverloadTy); 5587 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5588 QualType ParamType = FT->getParamType(i); 5589 ParmVarDecl *Parm = 5590 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5591 SourceLocation(), nullptr, ParamType, 5592 /*TInfo=*/nullptr, SC_None, nullptr); 5593 Parm->setScopeInfo(0, i); 5594 Params.push_back(Parm); 5595 } 5596 OverloadDecl->setParams(Params); 5597 return OverloadDecl; 5598 } 5599 5600 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5601 FunctionDecl *Callee, 5602 MultiExprArg ArgExprs) { 5603 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5604 // similar attributes) really don't like it when functions are called with an 5605 // invalid number of args. 5606 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5607 /*PartialOverloading=*/false) && 5608 !Callee->isVariadic()) 5609 return; 5610 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5611 return; 5612 5613 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5614 S.Diag(Fn->getBeginLoc(), 5615 isa<CXXMethodDecl>(Callee) 5616 ? diag::err_ovl_no_viable_member_function_in_call 5617 : diag::err_ovl_no_viable_function_in_call) 5618 << Callee << Callee->getSourceRange(); 5619 S.Diag(Callee->getLocation(), 5620 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5621 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5622 return; 5623 } 5624 } 5625 5626 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5627 const UnresolvedMemberExpr *const UME, Sema &S) { 5628 5629 const auto GetFunctionLevelDCIfCXXClass = 5630 [](Sema &S) -> const CXXRecordDecl * { 5631 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5632 if (!DC || !DC->getParent()) 5633 return nullptr; 5634 5635 // If the call to some member function was made from within a member 5636 // function body 'M' return return 'M's parent. 5637 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5638 return MD->getParent()->getCanonicalDecl(); 5639 // else the call was made from within a default member initializer of a 5640 // class, so return the class. 5641 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5642 return RD->getCanonicalDecl(); 5643 return nullptr; 5644 }; 5645 // If our DeclContext is neither a member function nor a class (in the 5646 // case of a lambda in a default member initializer), we can't have an 5647 // enclosing 'this'. 5648 5649 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5650 if (!CurParentClass) 5651 return false; 5652 5653 // The naming class for implicit member functions call is the class in which 5654 // name lookup starts. 5655 const CXXRecordDecl *const NamingClass = 5656 UME->getNamingClass()->getCanonicalDecl(); 5657 assert(NamingClass && "Must have naming class even for implicit access"); 5658 5659 // If the unresolved member functions were found in a 'naming class' that is 5660 // related (either the same or derived from) to the class that contains the 5661 // member function that itself contained the implicit member access. 5662 5663 return CurParentClass == NamingClass || 5664 CurParentClass->isDerivedFrom(NamingClass); 5665 } 5666 5667 static void 5668 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5669 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5670 5671 if (!UME) 5672 return; 5673 5674 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5675 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5676 // already been captured, or if this is an implicit member function call (if 5677 // it isn't, an attempt to capture 'this' should already have been made). 5678 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5679 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5680 return; 5681 5682 // Check if the naming class in which the unresolved members were found is 5683 // related (same as or is a base of) to the enclosing class. 5684 5685 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5686 return; 5687 5688 5689 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5690 // If the enclosing function is not dependent, then this lambda is 5691 // capture ready, so if we can capture this, do so. 5692 if (!EnclosingFunctionCtx->isDependentContext()) { 5693 // If the current lambda and all enclosing lambdas can capture 'this' - 5694 // then go ahead and capture 'this' (since our unresolved overload set 5695 // contains at least one non-static member function). 5696 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5697 S.CheckCXXThisCapture(CallLoc); 5698 } else if (S.CurContext->isDependentContext()) { 5699 // ... since this is an implicit member reference, that might potentially 5700 // involve a 'this' capture, mark 'this' for potential capture in 5701 // enclosing lambdas. 5702 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5703 CurLSI->addPotentialThisCapture(CallLoc); 5704 } 5705 } 5706 5707 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5708 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5709 Expr *ExecConfig) { 5710 ExprResult Call = 5711 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5712 if (Call.isInvalid()) 5713 return Call; 5714 5715 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5716 // language modes. 5717 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5718 if (ULE->hasExplicitTemplateArgs() && 5719 ULE->decls_begin() == ULE->decls_end()) { 5720 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5721 ? diag::warn_cxx17_compat_adl_only_template_id 5722 : diag::ext_adl_only_template_id) 5723 << ULE->getName(); 5724 } 5725 } 5726 5727 return Call; 5728 } 5729 5730 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5731 /// This provides the location of the left/right parens and a list of comma 5732 /// locations. 5733 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5734 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5735 Expr *ExecConfig, bool IsExecConfig) { 5736 // Since this might be a postfix expression, get rid of ParenListExprs. 5737 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5738 if (Result.isInvalid()) return ExprError(); 5739 Fn = Result.get(); 5740 5741 if (checkArgsForPlaceholders(*this, ArgExprs)) 5742 return ExprError(); 5743 5744 if (getLangOpts().CPlusPlus) { 5745 // If this is a pseudo-destructor expression, build the call immediately. 5746 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5747 if (!ArgExprs.empty()) { 5748 // Pseudo-destructor calls should not have any arguments. 5749 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5750 << FixItHint::CreateRemoval( 5751 SourceRange(ArgExprs.front()->getBeginLoc(), 5752 ArgExprs.back()->getEndLoc())); 5753 } 5754 5755 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5756 VK_RValue, RParenLoc); 5757 } 5758 if (Fn->getType() == Context.PseudoObjectTy) { 5759 ExprResult result = CheckPlaceholderExpr(Fn); 5760 if (result.isInvalid()) return ExprError(); 5761 Fn = result.get(); 5762 } 5763 5764 // Determine whether this is a dependent call inside a C++ template, 5765 // in which case we won't do any semantic analysis now. 5766 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5767 if (ExecConfig) { 5768 return CUDAKernelCallExpr::Create( 5769 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5770 Context.DependentTy, VK_RValue, RParenLoc); 5771 } else { 5772 5773 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5774 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5775 Fn->getBeginLoc()); 5776 5777 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5778 VK_RValue, RParenLoc); 5779 } 5780 } 5781 5782 // Determine whether this is a call to an object (C++ [over.call.object]). 5783 if (Fn->getType()->isRecordType()) 5784 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5785 RParenLoc); 5786 5787 if (Fn->getType() == Context.UnknownAnyTy) { 5788 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5789 if (result.isInvalid()) return ExprError(); 5790 Fn = result.get(); 5791 } 5792 5793 if (Fn->getType() == Context.BoundMemberTy) { 5794 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5795 RParenLoc); 5796 } 5797 } 5798 5799 // Check for overloaded calls. This can happen even in C due to extensions. 5800 if (Fn->getType() == Context.OverloadTy) { 5801 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5802 5803 // We aren't supposed to apply this logic if there's an '&' involved. 5804 if (!find.HasFormOfMemberPointer) { 5805 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5806 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5807 VK_RValue, RParenLoc); 5808 OverloadExpr *ovl = find.Expression; 5809 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5810 return BuildOverloadedCallExpr( 5811 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5812 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5813 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5814 RParenLoc); 5815 } 5816 } 5817 5818 // If we're directly calling a function, get the appropriate declaration. 5819 if (Fn->getType() == Context.UnknownAnyTy) { 5820 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5821 if (result.isInvalid()) return ExprError(); 5822 Fn = result.get(); 5823 } 5824 5825 Expr *NakedFn = Fn->IgnoreParens(); 5826 5827 bool CallingNDeclIndirectly = false; 5828 NamedDecl *NDecl = nullptr; 5829 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5830 if (UnOp->getOpcode() == UO_AddrOf) { 5831 CallingNDeclIndirectly = true; 5832 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5833 } 5834 } 5835 5836 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5837 NDecl = DRE->getDecl(); 5838 5839 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5840 if (FDecl && FDecl->getBuiltinID()) { 5841 // Rewrite the function decl for this builtin by replacing parameters 5842 // with no explicit address space with the address space of the arguments 5843 // in ArgExprs. 5844 if ((FDecl = 5845 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5846 NDecl = FDecl; 5847 Fn = DeclRefExpr::Create( 5848 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5849 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5850 nullptr, DRE->isNonOdrUse()); 5851 } 5852 } 5853 } else if (isa<MemberExpr>(NakedFn)) 5854 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5855 5856 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5857 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5858 FD, /*Complain=*/true, Fn->getBeginLoc())) 5859 return ExprError(); 5860 5861 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5862 return ExprError(); 5863 5864 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5865 } 5866 5867 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5868 ExecConfig, IsExecConfig); 5869 } 5870 5871 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5872 /// 5873 /// __builtin_astype( value, dst type ) 5874 /// 5875 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5876 SourceLocation BuiltinLoc, 5877 SourceLocation RParenLoc) { 5878 ExprValueKind VK = VK_RValue; 5879 ExprObjectKind OK = OK_Ordinary; 5880 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5881 QualType SrcTy = E->getType(); 5882 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5883 return ExprError(Diag(BuiltinLoc, 5884 diag::err_invalid_astype_of_different_size) 5885 << DstTy 5886 << SrcTy 5887 << E->getSourceRange()); 5888 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5889 } 5890 5891 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5892 /// provided arguments. 5893 /// 5894 /// __builtin_convertvector( value, dst type ) 5895 /// 5896 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5897 SourceLocation BuiltinLoc, 5898 SourceLocation RParenLoc) { 5899 TypeSourceInfo *TInfo; 5900 GetTypeFromParser(ParsedDestTy, &TInfo); 5901 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5902 } 5903 5904 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5905 /// i.e. an expression not of \p OverloadTy. The expression should 5906 /// unary-convert to an expression of function-pointer or 5907 /// block-pointer type. 5908 /// 5909 /// \param NDecl the declaration being called, if available 5910 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5911 SourceLocation LParenLoc, 5912 ArrayRef<Expr *> Args, 5913 SourceLocation RParenLoc, Expr *Config, 5914 bool IsExecConfig, ADLCallKind UsesADL) { 5915 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5916 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5917 5918 // Functions with 'interrupt' attribute cannot be called directly. 5919 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5920 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5921 return ExprError(); 5922 } 5923 5924 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5925 // so there's some risk when calling out to non-interrupt handler functions 5926 // that the callee might not preserve them. This is easy to diagnose here, 5927 // but can be very challenging to debug. 5928 if (auto *Caller = getCurFunctionDecl()) 5929 if (Caller->hasAttr<ARMInterruptAttr>()) { 5930 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5931 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5932 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5933 } 5934 5935 // Promote the function operand. 5936 // We special-case function promotion here because we only allow promoting 5937 // builtin functions to function pointers in the callee of a call. 5938 ExprResult Result; 5939 QualType ResultTy; 5940 if (BuiltinID && 5941 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5942 // Extract the return type from the (builtin) function pointer type. 5943 // FIXME Several builtins still have setType in 5944 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5945 // Builtins.def to ensure they are correct before removing setType calls. 5946 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5947 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5948 ResultTy = FDecl->getCallResultType(); 5949 } else { 5950 Result = CallExprUnaryConversions(Fn); 5951 ResultTy = Context.BoolTy; 5952 } 5953 if (Result.isInvalid()) 5954 return ExprError(); 5955 Fn = Result.get(); 5956 5957 // Check for a valid function type, but only if it is not a builtin which 5958 // requires custom type checking. These will be handled by 5959 // CheckBuiltinFunctionCall below just after creation of the call expression. 5960 const FunctionType *FuncT = nullptr; 5961 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5962 retry: 5963 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5964 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5965 // have type pointer to function". 5966 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5967 if (!FuncT) 5968 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5969 << Fn->getType() << Fn->getSourceRange()); 5970 } else if (const BlockPointerType *BPT = 5971 Fn->getType()->getAs<BlockPointerType>()) { 5972 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5973 } else { 5974 // Handle calls to expressions of unknown-any type. 5975 if (Fn->getType() == Context.UnknownAnyTy) { 5976 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5977 if (rewrite.isInvalid()) 5978 return ExprError(); 5979 Fn = rewrite.get(); 5980 goto retry; 5981 } 5982 5983 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5984 << Fn->getType() << Fn->getSourceRange()); 5985 } 5986 } 5987 5988 // Get the number of parameters in the function prototype, if any. 5989 // We will allocate space for max(Args.size(), NumParams) arguments 5990 // in the call expression. 5991 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5992 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5993 5994 CallExpr *TheCall; 5995 if (Config) { 5996 assert(UsesADL == ADLCallKind::NotADL && 5997 "CUDAKernelCallExpr should not use ADL"); 5998 TheCall = 5999 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6000 ResultTy, VK_RValue, RParenLoc, NumParams); 6001 } else { 6002 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6003 RParenLoc, NumParams, UsesADL); 6004 } 6005 6006 if (!getLangOpts().CPlusPlus) { 6007 // Forget about the nulled arguments since typo correction 6008 // do not handle them well. 6009 TheCall->shrinkNumArgs(Args.size()); 6010 // C cannot always handle TypoExpr nodes in builtin calls and direct 6011 // function calls as their argument checking don't necessarily handle 6012 // dependent types properly, so make sure any TypoExprs have been 6013 // dealt with. 6014 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6015 if (!Result.isUsable()) return ExprError(); 6016 CallExpr *TheOldCall = TheCall; 6017 TheCall = dyn_cast<CallExpr>(Result.get()); 6018 bool CorrectedTypos = TheCall != TheOldCall; 6019 if (!TheCall) return Result; 6020 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6021 6022 // A new call expression node was created if some typos were corrected. 6023 // However it may not have been constructed with enough storage. In this 6024 // case, rebuild the node with enough storage. The waste of space is 6025 // immaterial since this only happens when some typos were corrected. 6026 if (CorrectedTypos && Args.size() < NumParams) { 6027 if (Config) 6028 TheCall = CUDAKernelCallExpr::Create( 6029 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6030 RParenLoc, NumParams); 6031 else 6032 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6033 RParenLoc, NumParams, UsesADL); 6034 } 6035 // We can now handle the nulled arguments for the default arguments. 6036 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6037 } 6038 6039 // Bail out early if calling a builtin with custom type checking. 6040 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6041 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6042 6043 if (getLangOpts().CUDA) { 6044 if (Config) { 6045 // CUDA: Kernel calls must be to global functions 6046 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6047 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6048 << FDecl << Fn->getSourceRange()); 6049 6050 // CUDA: Kernel function must have 'void' return type 6051 if (!FuncT->getReturnType()->isVoidType() && 6052 !FuncT->getReturnType()->getAs<AutoType>() && 6053 !FuncT->getReturnType()->isInstantiationDependentType()) 6054 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6055 << Fn->getType() << Fn->getSourceRange()); 6056 } else { 6057 // CUDA: Calls to global functions must be configured 6058 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6059 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6060 << FDecl << Fn->getSourceRange()); 6061 } 6062 } 6063 6064 // Check for a valid return type 6065 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6066 FDecl)) 6067 return ExprError(); 6068 6069 // We know the result type of the call, set it. 6070 TheCall->setType(FuncT->getCallResultType(Context)); 6071 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6072 6073 if (Proto) { 6074 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6075 IsExecConfig)) 6076 return ExprError(); 6077 } else { 6078 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6079 6080 if (FDecl) { 6081 // Check if we have too few/too many template arguments, based 6082 // on our knowledge of the function definition. 6083 const FunctionDecl *Def = nullptr; 6084 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6085 Proto = Def->getType()->getAs<FunctionProtoType>(); 6086 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6087 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6088 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6089 } 6090 6091 // If the function we're calling isn't a function prototype, but we have 6092 // a function prototype from a prior declaratiom, use that prototype. 6093 if (!FDecl->hasPrototype()) 6094 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6095 } 6096 6097 // Promote the arguments (C99 6.5.2.2p6). 6098 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6099 Expr *Arg = Args[i]; 6100 6101 if (Proto && i < Proto->getNumParams()) { 6102 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6103 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6104 ExprResult ArgE = 6105 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6106 if (ArgE.isInvalid()) 6107 return true; 6108 6109 Arg = ArgE.getAs<Expr>(); 6110 6111 } else { 6112 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6113 6114 if (ArgE.isInvalid()) 6115 return true; 6116 6117 Arg = ArgE.getAs<Expr>(); 6118 } 6119 6120 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6121 diag::err_call_incomplete_argument, Arg)) 6122 return ExprError(); 6123 6124 TheCall->setArg(i, Arg); 6125 } 6126 } 6127 6128 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6129 if (!Method->isStatic()) 6130 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6131 << Fn->getSourceRange()); 6132 6133 // Check for sentinels 6134 if (NDecl) 6135 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6136 6137 // Do special checking on direct calls to functions. 6138 if (FDecl) { 6139 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6140 return ExprError(); 6141 6142 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6143 6144 if (BuiltinID) 6145 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6146 } else if (NDecl) { 6147 if (CheckPointerCall(NDecl, TheCall, Proto)) 6148 return ExprError(); 6149 } else { 6150 if (CheckOtherCall(TheCall, Proto)) 6151 return ExprError(); 6152 } 6153 6154 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6155 } 6156 6157 ExprResult 6158 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6159 SourceLocation RParenLoc, Expr *InitExpr) { 6160 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6161 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6162 6163 TypeSourceInfo *TInfo; 6164 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6165 if (!TInfo) 6166 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6167 6168 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6169 } 6170 6171 ExprResult 6172 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6173 SourceLocation RParenLoc, Expr *LiteralExpr) { 6174 QualType literalType = TInfo->getType(); 6175 6176 if (literalType->isArrayType()) { 6177 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6178 diag::err_illegal_decl_array_incomplete_type, 6179 SourceRange(LParenLoc, 6180 LiteralExpr->getSourceRange().getEnd()))) 6181 return ExprError(); 6182 if (literalType->isVariableArrayType()) 6183 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6184 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6185 } else if (!literalType->isDependentType() && 6186 RequireCompleteType(LParenLoc, literalType, 6187 diag::err_typecheck_decl_incomplete_type, 6188 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6189 return ExprError(); 6190 6191 InitializedEntity Entity 6192 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6193 InitializationKind Kind 6194 = InitializationKind::CreateCStyleCast(LParenLoc, 6195 SourceRange(LParenLoc, RParenLoc), 6196 /*InitList=*/true); 6197 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6198 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6199 &literalType); 6200 if (Result.isInvalid()) 6201 return ExprError(); 6202 LiteralExpr = Result.get(); 6203 6204 bool isFileScope = !CurContext->isFunctionOrMethod(); 6205 6206 // In C, compound literals are l-values for some reason. 6207 // For GCC compatibility, in C++, file-scope array compound literals with 6208 // constant initializers are also l-values, and compound literals are 6209 // otherwise prvalues. 6210 // 6211 // (GCC also treats C++ list-initialized file-scope array prvalues with 6212 // constant initializers as l-values, but that's non-conforming, so we don't 6213 // follow it there.) 6214 // 6215 // FIXME: It would be better to handle the lvalue cases as materializing and 6216 // lifetime-extending a temporary object, but our materialized temporaries 6217 // representation only supports lifetime extension from a variable, not "out 6218 // of thin air". 6219 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6220 // is bound to the result of applying array-to-pointer decay to the compound 6221 // literal. 6222 // FIXME: GCC supports compound literals of reference type, which should 6223 // obviously have a value kind derived from the kind of reference involved. 6224 ExprValueKind VK = 6225 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6226 ? VK_RValue 6227 : VK_LValue; 6228 6229 if (isFileScope) 6230 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6231 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6232 Expr *Init = ILE->getInit(i); 6233 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6234 } 6235 6236 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6237 VK, LiteralExpr, isFileScope); 6238 if (isFileScope) { 6239 if (!LiteralExpr->isTypeDependent() && 6240 !LiteralExpr->isValueDependent() && 6241 !literalType->isDependentType()) // C99 6.5.2.5p3 6242 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6243 return ExprError(); 6244 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6245 literalType.getAddressSpace() != LangAS::Default) { 6246 // Embedded-C extensions to C99 6.5.2.5: 6247 // "If the compound literal occurs inside the body of a function, the 6248 // type name shall not be qualified by an address-space qualifier." 6249 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6250 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6251 return ExprError(); 6252 } 6253 6254 if (!isFileScope && !getLangOpts().CPlusPlus) { 6255 // Compound literals that have automatic storage duration are destroyed at 6256 // the end of the scope in C; in C++, they're just temporaries. 6257 6258 // Emit diagnostics if it is or contains a C union type that is non-trivial 6259 // to destruct. 6260 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6261 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6262 NTCUC_CompoundLiteral, NTCUK_Destruct); 6263 6264 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6265 if (literalType.isDestructedType()) { 6266 Cleanup.setExprNeedsCleanups(true); 6267 ExprCleanupObjects.push_back(E); 6268 getCurFunction()->setHasBranchProtectedScope(); 6269 } 6270 } 6271 6272 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6273 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6274 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6275 E->getInitializer()->getExprLoc()); 6276 6277 return MaybeBindToTemporary(E); 6278 } 6279 6280 ExprResult 6281 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6282 SourceLocation RBraceLoc) { 6283 // Only produce each kind of designated initialization diagnostic once. 6284 SourceLocation FirstDesignator; 6285 bool DiagnosedArrayDesignator = false; 6286 bool DiagnosedNestedDesignator = false; 6287 bool DiagnosedMixedDesignator = false; 6288 6289 // Check that any designated initializers are syntactically valid in the 6290 // current language mode. 6291 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6292 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6293 if (FirstDesignator.isInvalid()) 6294 FirstDesignator = DIE->getBeginLoc(); 6295 6296 if (!getLangOpts().CPlusPlus) 6297 break; 6298 6299 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6300 DiagnosedNestedDesignator = true; 6301 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6302 << DIE->getDesignatorsSourceRange(); 6303 } 6304 6305 for (auto &Desig : DIE->designators()) { 6306 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6307 DiagnosedArrayDesignator = true; 6308 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6309 << Desig.getSourceRange(); 6310 } 6311 } 6312 6313 if (!DiagnosedMixedDesignator && 6314 !isa<DesignatedInitExpr>(InitArgList[0])) { 6315 DiagnosedMixedDesignator = true; 6316 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6317 << DIE->getSourceRange(); 6318 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6319 << InitArgList[0]->getSourceRange(); 6320 } 6321 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6322 isa<DesignatedInitExpr>(InitArgList[0])) { 6323 DiagnosedMixedDesignator = true; 6324 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6325 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6326 << DIE->getSourceRange(); 6327 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6328 << InitArgList[I]->getSourceRange(); 6329 } 6330 } 6331 6332 if (FirstDesignator.isValid()) { 6333 // Only diagnose designated initiaization as a C++20 extension if we didn't 6334 // already diagnose use of (non-C++20) C99 designator syntax. 6335 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6336 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6337 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6338 ? diag::warn_cxx17_compat_designated_init 6339 : diag::ext_cxx_designated_init); 6340 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6341 Diag(FirstDesignator, diag::ext_designated_init); 6342 } 6343 } 6344 6345 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6346 } 6347 6348 ExprResult 6349 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6350 SourceLocation RBraceLoc) { 6351 // Semantic analysis for initializers is done by ActOnDeclarator() and 6352 // CheckInitializer() - it requires knowledge of the object being initialized. 6353 6354 // Immediately handle non-overload placeholders. Overloads can be 6355 // resolved contextually, but everything else here can't. 6356 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6357 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6358 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6359 6360 // Ignore failures; dropping the entire initializer list because 6361 // of one failure would be terrible for indexing/etc. 6362 if (result.isInvalid()) continue; 6363 6364 InitArgList[I] = result.get(); 6365 } 6366 } 6367 6368 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6369 RBraceLoc); 6370 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6371 return E; 6372 } 6373 6374 /// Do an explicit extend of the given block pointer if we're in ARC. 6375 void Sema::maybeExtendBlockObject(ExprResult &E) { 6376 assert(E.get()->getType()->isBlockPointerType()); 6377 assert(E.get()->isRValue()); 6378 6379 // Only do this in an r-value context. 6380 if (!getLangOpts().ObjCAutoRefCount) return; 6381 6382 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6383 CK_ARCExtendBlockObject, E.get(), 6384 /*base path*/ nullptr, VK_RValue); 6385 Cleanup.setExprNeedsCleanups(true); 6386 } 6387 6388 /// Prepare a conversion of the given expression to an ObjC object 6389 /// pointer type. 6390 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6391 QualType type = E.get()->getType(); 6392 if (type->isObjCObjectPointerType()) { 6393 return CK_BitCast; 6394 } else if (type->isBlockPointerType()) { 6395 maybeExtendBlockObject(E); 6396 return CK_BlockPointerToObjCPointerCast; 6397 } else { 6398 assert(type->isPointerType()); 6399 return CK_CPointerToObjCPointerCast; 6400 } 6401 } 6402 6403 /// Prepares for a scalar cast, performing all the necessary stages 6404 /// except the final cast and returning the kind required. 6405 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6406 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6407 // Also, callers should have filtered out the invalid cases with 6408 // pointers. Everything else should be possible. 6409 6410 QualType SrcTy = Src.get()->getType(); 6411 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6412 return CK_NoOp; 6413 6414 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6415 case Type::STK_MemberPointer: 6416 llvm_unreachable("member pointer type in C"); 6417 6418 case Type::STK_CPointer: 6419 case Type::STK_BlockPointer: 6420 case Type::STK_ObjCObjectPointer: 6421 switch (DestTy->getScalarTypeKind()) { 6422 case Type::STK_CPointer: { 6423 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6424 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6425 if (SrcAS != DestAS) 6426 return CK_AddressSpaceConversion; 6427 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6428 return CK_NoOp; 6429 return CK_BitCast; 6430 } 6431 case Type::STK_BlockPointer: 6432 return (SrcKind == Type::STK_BlockPointer 6433 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6434 case Type::STK_ObjCObjectPointer: 6435 if (SrcKind == Type::STK_ObjCObjectPointer) 6436 return CK_BitCast; 6437 if (SrcKind == Type::STK_CPointer) 6438 return CK_CPointerToObjCPointerCast; 6439 maybeExtendBlockObject(Src); 6440 return CK_BlockPointerToObjCPointerCast; 6441 case Type::STK_Bool: 6442 return CK_PointerToBoolean; 6443 case Type::STK_Integral: 6444 return CK_PointerToIntegral; 6445 case Type::STK_Floating: 6446 case Type::STK_FloatingComplex: 6447 case Type::STK_IntegralComplex: 6448 case Type::STK_MemberPointer: 6449 case Type::STK_FixedPoint: 6450 llvm_unreachable("illegal cast from pointer"); 6451 } 6452 llvm_unreachable("Should have returned before this"); 6453 6454 case Type::STK_FixedPoint: 6455 switch (DestTy->getScalarTypeKind()) { 6456 case Type::STK_FixedPoint: 6457 return CK_FixedPointCast; 6458 case Type::STK_Bool: 6459 return CK_FixedPointToBoolean; 6460 case Type::STK_Integral: 6461 return CK_FixedPointToIntegral; 6462 case Type::STK_Floating: 6463 case Type::STK_IntegralComplex: 6464 case Type::STK_FloatingComplex: 6465 Diag(Src.get()->getExprLoc(), 6466 diag::err_unimplemented_conversion_with_fixed_point_type) 6467 << DestTy; 6468 return CK_IntegralCast; 6469 case Type::STK_CPointer: 6470 case Type::STK_ObjCObjectPointer: 6471 case Type::STK_BlockPointer: 6472 case Type::STK_MemberPointer: 6473 llvm_unreachable("illegal cast to pointer type"); 6474 } 6475 llvm_unreachable("Should have returned before this"); 6476 6477 case Type::STK_Bool: // casting from bool is like casting from an integer 6478 case Type::STK_Integral: 6479 switch (DestTy->getScalarTypeKind()) { 6480 case Type::STK_CPointer: 6481 case Type::STK_ObjCObjectPointer: 6482 case Type::STK_BlockPointer: 6483 if (Src.get()->isNullPointerConstant(Context, 6484 Expr::NPC_ValueDependentIsNull)) 6485 return CK_NullToPointer; 6486 return CK_IntegralToPointer; 6487 case Type::STK_Bool: 6488 return CK_IntegralToBoolean; 6489 case Type::STK_Integral: 6490 return CK_IntegralCast; 6491 case Type::STK_Floating: 6492 return CK_IntegralToFloating; 6493 case Type::STK_IntegralComplex: 6494 Src = ImpCastExprToType(Src.get(), 6495 DestTy->castAs<ComplexType>()->getElementType(), 6496 CK_IntegralCast); 6497 return CK_IntegralRealToComplex; 6498 case Type::STK_FloatingComplex: 6499 Src = ImpCastExprToType(Src.get(), 6500 DestTy->castAs<ComplexType>()->getElementType(), 6501 CK_IntegralToFloating); 6502 return CK_FloatingRealToComplex; 6503 case Type::STK_MemberPointer: 6504 llvm_unreachable("member pointer type in C"); 6505 case Type::STK_FixedPoint: 6506 return CK_IntegralToFixedPoint; 6507 } 6508 llvm_unreachable("Should have returned before this"); 6509 6510 case Type::STK_Floating: 6511 switch (DestTy->getScalarTypeKind()) { 6512 case Type::STK_Floating: 6513 return CK_FloatingCast; 6514 case Type::STK_Bool: 6515 return CK_FloatingToBoolean; 6516 case Type::STK_Integral: 6517 return CK_FloatingToIntegral; 6518 case Type::STK_FloatingComplex: 6519 Src = ImpCastExprToType(Src.get(), 6520 DestTy->castAs<ComplexType>()->getElementType(), 6521 CK_FloatingCast); 6522 return CK_FloatingRealToComplex; 6523 case Type::STK_IntegralComplex: 6524 Src = ImpCastExprToType(Src.get(), 6525 DestTy->castAs<ComplexType>()->getElementType(), 6526 CK_FloatingToIntegral); 6527 return CK_IntegralRealToComplex; 6528 case Type::STK_CPointer: 6529 case Type::STK_ObjCObjectPointer: 6530 case Type::STK_BlockPointer: 6531 llvm_unreachable("valid float->pointer cast?"); 6532 case Type::STK_MemberPointer: 6533 llvm_unreachable("member pointer type in C"); 6534 case Type::STK_FixedPoint: 6535 Diag(Src.get()->getExprLoc(), 6536 diag::err_unimplemented_conversion_with_fixed_point_type) 6537 << SrcTy; 6538 return CK_IntegralCast; 6539 } 6540 llvm_unreachable("Should have returned before this"); 6541 6542 case Type::STK_FloatingComplex: 6543 switch (DestTy->getScalarTypeKind()) { 6544 case Type::STK_FloatingComplex: 6545 return CK_FloatingComplexCast; 6546 case Type::STK_IntegralComplex: 6547 return CK_FloatingComplexToIntegralComplex; 6548 case Type::STK_Floating: { 6549 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6550 if (Context.hasSameType(ET, DestTy)) 6551 return CK_FloatingComplexToReal; 6552 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6553 return CK_FloatingCast; 6554 } 6555 case Type::STK_Bool: 6556 return CK_FloatingComplexToBoolean; 6557 case Type::STK_Integral: 6558 Src = ImpCastExprToType(Src.get(), 6559 SrcTy->castAs<ComplexType>()->getElementType(), 6560 CK_FloatingComplexToReal); 6561 return CK_FloatingToIntegral; 6562 case Type::STK_CPointer: 6563 case Type::STK_ObjCObjectPointer: 6564 case Type::STK_BlockPointer: 6565 llvm_unreachable("valid complex float->pointer cast?"); 6566 case Type::STK_MemberPointer: 6567 llvm_unreachable("member pointer type in C"); 6568 case Type::STK_FixedPoint: 6569 Diag(Src.get()->getExprLoc(), 6570 diag::err_unimplemented_conversion_with_fixed_point_type) 6571 << SrcTy; 6572 return CK_IntegralCast; 6573 } 6574 llvm_unreachable("Should have returned before this"); 6575 6576 case Type::STK_IntegralComplex: 6577 switch (DestTy->getScalarTypeKind()) { 6578 case Type::STK_FloatingComplex: 6579 return CK_IntegralComplexToFloatingComplex; 6580 case Type::STK_IntegralComplex: 6581 return CK_IntegralComplexCast; 6582 case Type::STK_Integral: { 6583 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6584 if (Context.hasSameType(ET, DestTy)) 6585 return CK_IntegralComplexToReal; 6586 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6587 return CK_IntegralCast; 6588 } 6589 case Type::STK_Bool: 6590 return CK_IntegralComplexToBoolean; 6591 case Type::STK_Floating: 6592 Src = ImpCastExprToType(Src.get(), 6593 SrcTy->castAs<ComplexType>()->getElementType(), 6594 CK_IntegralComplexToReal); 6595 return CK_IntegralToFloating; 6596 case Type::STK_CPointer: 6597 case Type::STK_ObjCObjectPointer: 6598 case Type::STK_BlockPointer: 6599 llvm_unreachable("valid complex int->pointer cast?"); 6600 case Type::STK_MemberPointer: 6601 llvm_unreachable("member pointer type in C"); 6602 case Type::STK_FixedPoint: 6603 Diag(Src.get()->getExprLoc(), 6604 diag::err_unimplemented_conversion_with_fixed_point_type) 6605 << SrcTy; 6606 return CK_IntegralCast; 6607 } 6608 llvm_unreachable("Should have returned before this"); 6609 } 6610 6611 llvm_unreachable("Unhandled scalar cast"); 6612 } 6613 6614 static bool breakDownVectorType(QualType type, uint64_t &len, 6615 QualType &eltType) { 6616 // Vectors are simple. 6617 if (const VectorType *vecType = type->getAs<VectorType>()) { 6618 len = vecType->getNumElements(); 6619 eltType = vecType->getElementType(); 6620 assert(eltType->isScalarType()); 6621 return true; 6622 } 6623 6624 // We allow lax conversion to and from non-vector types, but only if 6625 // they're real types (i.e. non-complex, non-pointer scalar types). 6626 if (!type->isRealType()) return false; 6627 6628 len = 1; 6629 eltType = type; 6630 return true; 6631 } 6632 6633 /// Are the two types lax-compatible vector types? That is, given 6634 /// that one of them is a vector, do they have equal storage sizes, 6635 /// where the storage size is the number of elements times the element 6636 /// size? 6637 /// 6638 /// This will also return false if either of the types is neither a 6639 /// vector nor a real type. 6640 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6641 assert(destTy->isVectorType() || srcTy->isVectorType()); 6642 6643 // Disallow lax conversions between scalars and ExtVectors (these 6644 // conversions are allowed for other vector types because common headers 6645 // depend on them). Most scalar OP ExtVector cases are handled by the 6646 // splat path anyway, which does what we want (convert, not bitcast). 6647 // What this rules out for ExtVectors is crazy things like char4*float. 6648 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6649 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6650 6651 uint64_t srcLen, destLen; 6652 QualType srcEltTy, destEltTy; 6653 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6654 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6655 6656 // ASTContext::getTypeSize will return the size rounded up to a 6657 // power of 2, so instead of using that, we need to use the raw 6658 // element size multiplied by the element count. 6659 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6660 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6661 6662 return (srcLen * srcEltSize == destLen * destEltSize); 6663 } 6664 6665 /// Is this a legal conversion between two types, one of which is 6666 /// known to be a vector type? 6667 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6668 assert(destTy->isVectorType() || srcTy->isVectorType()); 6669 6670 switch (Context.getLangOpts().getLaxVectorConversions()) { 6671 case LangOptions::LaxVectorConversionKind::None: 6672 return false; 6673 6674 case LangOptions::LaxVectorConversionKind::Integer: 6675 if (!srcTy->isIntegralOrEnumerationType()) { 6676 auto *Vec = srcTy->getAs<VectorType>(); 6677 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6678 return false; 6679 } 6680 if (!destTy->isIntegralOrEnumerationType()) { 6681 auto *Vec = destTy->getAs<VectorType>(); 6682 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6683 return false; 6684 } 6685 // OK, integer (vector) -> integer (vector) bitcast. 6686 break; 6687 6688 case LangOptions::LaxVectorConversionKind::All: 6689 break; 6690 } 6691 6692 return areLaxCompatibleVectorTypes(srcTy, destTy); 6693 } 6694 6695 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6696 CastKind &Kind) { 6697 assert(VectorTy->isVectorType() && "Not a vector type!"); 6698 6699 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6700 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6701 return Diag(R.getBegin(), 6702 Ty->isVectorType() ? 6703 diag::err_invalid_conversion_between_vectors : 6704 diag::err_invalid_conversion_between_vector_and_integer) 6705 << VectorTy << Ty << R; 6706 } else 6707 return Diag(R.getBegin(), 6708 diag::err_invalid_conversion_between_vector_and_scalar) 6709 << VectorTy << Ty << R; 6710 6711 Kind = CK_BitCast; 6712 return false; 6713 } 6714 6715 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6716 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6717 6718 if (DestElemTy == SplattedExpr->getType()) 6719 return SplattedExpr; 6720 6721 assert(DestElemTy->isFloatingType() || 6722 DestElemTy->isIntegralOrEnumerationType()); 6723 6724 CastKind CK; 6725 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6726 // OpenCL requires that we convert `true` boolean expressions to -1, but 6727 // only when splatting vectors. 6728 if (DestElemTy->isFloatingType()) { 6729 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6730 // in two steps: boolean to signed integral, then to floating. 6731 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6732 CK_BooleanToSignedIntegral); 6733 SplattedExpr = CastExprRes.get(); 6734 CK = CK_IntegralToFloating; 6735 } else { 6736 CK = CK_BooleanToSignedIntegral; 6737 } 6738 } else { 6739 ExprResult CastExprRes = SplattedExpr; 6740 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6741 if (CastExprRes.isInvalid()) 6742 return ExprError(); 6743 SplattedExpr = CastExprRes.get(); 6744 } 6745 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6746 } 6747 6748 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6749 Expr *CastExpr, CastKind &Kind) { 6750 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6751 6752 QualType SrcTy = CastExpr->getType(); 6753 6754 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6755 // an ExtVectorType. 6756 // In OpenCL, casts between vectors of different types are not allowed. 6757 // (See OpenCL 6.2). 6758 if (SrcTy->isVectorType()) { 6759 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6760 (getLangOpts().OpenCL && 6761 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6762 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6763 << DestTy << SrcTy << R; 6764 return ExprError(); 6765 } 6766 Kind = CK_BitCast; 6767 return CastExpr; 6768 } 6769 6770 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6771 // conversion will take place first from scalar to elt type, and then 6772 // splat from elt type to vector. 6773 if (SrcTy->isPointerType()) 6774 return Diag(R.getBegin(), 6775 diag::err_invalid_conversion_between_vector_and_scalar) 6776 << DestTy << SrcTy << R; 6777 6778 Kind = CK_VectorSplat; 6779 return prepareVectorSplat(DestTy, CastExpr); 6780 } 6781 6782 ExprResult 6783 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6784 Declarator &D, ParsedType &Ty, 6785 SourceLocation RParenLoc, Expr *CastExpr) { 6786 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6787 "ActOnCastExpr(): missing type or expr"); 6788 6789 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6790 if (D.isInvalidType()) 6791 return ExprError(); 6792 6793 if (getLangOpts().CPlusPlus) { 6794 // Check that there are no default arguments (C++ only). 6795 CheckExtraCXXDefaultArguments(D); 6796 } else { 6797 // Make sure any TypoExprs have been dealt with. 6798 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6799 if (!Res.isUsable()) 6800 return ExprError(); 6801 CastExpr = Res.get(); 6802 } 6803 6804 checkUnusedDeclAttributes(D); 6805 6806 QualType castType = castTInfo->getType(); 6807 Ty = CreateParsedType(castType, castTInfo); 6808 6809 bool isVectorLiteral = false; 6810 6811 // Check for an altivec or OpenCL literal, 6812 // i.e. all the elements are integer constants. 6813 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6814 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6815 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6816 && castType->isVectorType() && (PE || PLE)) { 6817 if (PLE && PLE->getNumExprs() == 0) { 6818 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6819 return ExprError(); 6820 } 6821 if (PE || PLE->getNumExprs() == 1) { 6822 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6823 if (!E->getType()->isVectorType()) 6824 isVectorLiteral = true; 6825 } 6826 else 6827 isVectorLiteral = true; 6828 } 6829 6830 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6831 // then handle it as such. 6832 if (isVectorLiteral) 6833 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6834 6835 // If the Expr being casted is a ParenListExpr, handle it specially. 6836 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6837 // sequence of BinOp comma operators. 6838 if (isa<ParenListExpr>(CastExpr)) { 6839 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6840 if (Result.isInvalid()) return ExprError(); 6841 CastExpr = Result.get(); 6842 } 6843 6844 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6845 !getSourceManager().isInSystemMacro(LParenLoc)) 6846 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6847 6848 CheckTollFreeBridgeCast(castType, CastExpr); 6849 6850 CheckObjCBridgeRelatedCast(castType, CastExpr); 6851 6852 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6853 6854 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6855 } 6856 6857 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6858 SourceLocation RParenLoc, Expr *E, 6859 TypeSourceInfo *TInfo) { 6860 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6861 "Expected paren or paren list expression"); 6862 6863 Expr **exprs; 6864 unsigned numExprs; 6865 Expr *subExpr; 6866 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6867 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6868 LiteralLParenLoc = PE->getLParenLoc(); 6869 LiteralRParenLoc = PE->getRParenLoc(); 6870 exprs = PE->getExprs(); 6871 numExprs = PE->getNumExprs(); 6872 } else { // isa<ParenExpr> by assertion at function entrance 6873 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6874 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6875 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6876 exprs = &subExpr; 6877 numExprs = 1; 6878 } 6879 6880 QualType Ty = TInfo->getType(); 6881 assert(Ty->isVectorType() && "Expected vector type"); 6882 6883 SmallVector<Expr *, 8> initExprs; 6884 const VectorType *VTy = Ty->castAs<VectorType>(); 6885 unsigned numElems = VTy->getNumElements(); 6886 6887 // '(...)' form of vector initialization in AltiVec: the number of 6888 // initializers must be one or must match the size of the vector. 6889 // If a single value is specified in the initializer then it will be 6890 // replicated to all the components of the vector 6891 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6892 // The number of initializers must be one or must match the size of the 6893 // vector. If a single value is specified in the initializer then it will 6894 // be replicated to all the components of the vector 6895 if (numExprs == 1) { 6896 QualType ElemTy = VTy->getElementType(); 6897 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6898 if (Literal.isInvalid()) 6899 return ExprError(); 6900 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6901 PrepareScalarCast(Literal, ElemTy)); 6902 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6903 } 6904 else if (numExprs < numElems) { 6905 Diag(E->getExprLoc(), 6906 diag::err_incorrect_number_of_vector_initializers); 6907 return ExprError(); 6908 } 6909 else 6910 initExprs.append(exprs, exprs + numExprs); 6911 } 6912 else { 6913 // For OpenCL, when the number of initializers is a single value, 6914 // it will be replicated to all components of the vector. 6915 if (getLangOpts().OpenCL && 6916 VTy->getVectorKind() == VectorType::GenericVector && 6917 numExprs == 1) { 6918 QualType ElemTy = VTy->getElementType(); 6919 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6920 if (Literal.isInvalid()) 6921 return ExprError(); 6922 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6923 PrepareScalarCast(Literal, ElemTy)); 6924 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6925 } 6926 6927 initExprs.append(exprs, exprs + numExprs); 6928 } 6929 // FIXME: This means that pretty-printing the final AST will produce curly 6930 // braces instead of the original commas. 6931 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6932 initExprs, LiteralRParenLoc); 6933 initE->setType(Ty); 6934 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6935 } 6936 6937 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6938 /// the ParenListExpr into a sequence of comma binary operators. 6939 ExprResult 6940 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6941 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6942 if (!E) 6943 return OrigExpr; 6944 6945 ExprResult Result(E->getExpr(0)); 6946 6947 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6948 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6949 E->getExpr(i)); 6950 6951 if (Result.isInvalid()) return ExprError(); 6952 6953 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6954 } 6955 6956 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6957 SourceLocation R, 6958 MultiExprArg Val) { 6959 return ParenListExpr::Create(Context, L, Val, R); 6960 } 6961 6962 /// Emit a specialized diagnostic when one expression is a null pointer 6963 /// constant and the other is not a pointer. Returns true if a diagnostic is 6964 /// emitted. 6965 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6966 SourceLocation QuestionLoc) { 6967 Expr *NullExpr = LHSExpr; 6968 Expr *NonPointerExpr = RHSExpr; 6969 Expr::NullPointerConstantKind NullKind = 6970 NullExpr->isNullPointerConstant(Context, 6971 Expr::NPC_ValueDependentIsNotNull); 6972 6973 if (NullKind == Expr::NPCK_NotNull) { 6974 NullExpr = RHSExpr; 6975 NonPointerExpr = LHSExpr; 6976 NullKind = 6977 NullExpr->isNullPointerConstant(Context, 6978 Expr::NPC_ValueDependentIsNotNull); 6979 } 6980 6981 if (NullKind == Expr::NPCK_NotNull) 6982 return false; 6983 6984 if (NullKind == Expr::NPCK_ZeroExpression) 6985 return false; 6986 6987 if (NullKind == Expr::NPCK_ZeroLiteral) { 6988 // In this case, check to make sure that we got here from a "NULL" 6989 // string in the source code. 6990 NullExpr = NullExpr->IgnoreParenImpCasts(); 6991 SourceLocation loc = NullExpr->getExprLoc(); 6992 if (!findMacroSpelling(loc, "NULL")) 6993 return false; 6994 } 6995 6996 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6997 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6998 << NonPointerExpr->getType() << DiagType 6999 << NonPointerExpr->getSourceRange(); 7000 return true; 7001 } 7002 7003 /// Return false if the condition expression is valid, true otherwise. 7004 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7005 QualType CondTy = Cond->getType(); 7006 7007 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7008 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7009 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7010 << CondTy << Cond->getSourceRange(); 7011 return true; 7012 } 7013 7014 // C99 6.5.15p2 7015 if (CondTy->isScalarType()) return false; 7016 7017 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7018 << CondTy << Cond->getSourceRange(); 7019 return true; 7020 } 7021 7022 /// Handle when one or both operands are void type. 7023 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7024 ExprResult &RHS) { 7025 Expr *LHSExpr = LHS.get(); 7026 Expr *RHSExpr = RHS.get(); 7027 7028 if (!LHSExpr->getType()->isVoidType()) 7029 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7030 << RHSExpr->getSourceRange(); 7031 if (!RHSExpr->getType()->isVoidType()) 7032 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7033 << LHSExpr->getSourceRange(); 7034 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7035 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7036 return S.Context.VoidTy; 7037 } 7038 7039 /// Return false if the NullExpr can be promoted to PointerTy, 7040 /// true otherwise. 7041 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7042 QualType PointerTy) { 7043 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7044 !NullExpr.get()->isNullPointerConstant(S.Context, 7045 Expr::NPC_ValueDependentIsNull)) 7046 return true; 7047 7048 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7049 return false; 7050 } 7051 7052 /// Checks compatibility between two pointers and return the resulting 7053 /// type. 7054 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7055 ExprResult &RHS, 7056 SourceLocation Loc) { 7057 QualType LHSTy = LHS.get()->getType(); 7058 QualType RHSTy = RHS.get()->getType(); 7059 7060 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7061 // Two identical pointers types are always compatible. 7062 return LHSTy; 7063 } 7064 7065 QualType lhptee, rhptee; 7066 7067 // Get the pointee types. 7068 bool IsBlockPointer = false; 7069 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7070 lhptee = LHSBTy->getPointeeType(); 7071 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7072 IsBlockPointer = true; 7073 } else { 7074 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7075 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7076 } 7077 7078 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7079 // differently qualified versions of compatible types, the result type is 7080 // a pointer to an appropriately qualified version of the composite 7081 // type. 7082 7083 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7084 // clause doesn't make sense for our extensions. E.g. address space 2 should 7085 // be incompatible with address space 3: they may live on different devices or 7086 // anything. 7087 Qualifiers lhQual = lhptee.getQualifiers(); 7088 Qualifiers rhQual = rhptee.getQualifiers(); 7089 7090 LangAS ResultAddrSpace = LangAS::Default; 7091 LangAS LAddrSpace = lhQual.getAddressSpace(); 7092 LangAS RAddrSpace = rhQual.getAddressSpace(); 7093 7094 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7095 // spaces is disallowed. 7096 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7097 ResultAddrSpace = LAddrSpace; 7098 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7099 ResultAddrSpace = RAddrSpace; 7100 else { 7101 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7102 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7103 << RHS.get()->getSourceRange(); 7104 return QualType(); 7105 } 7106 7107 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7108 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7109 lhQual.removeCVRQualifiers(); 7110 rhQual.removeCVRQualifiers(); 7111 7112 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7113 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7114 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7115 // qual types are compatible iff 7116 // * corresponded types are compatible 7117 // * CVR qualifiers are equal 7118 // * address spaces are equal 7119 // Thus for conditional operator we merge CVR and address space unqualified 7120 // pointees and if there is a composite type we return a pointer to it with 7121 // merged qualifiers. 7122 LHSCastKind = 7123 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7124 RHSCastKind = 7125 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7126 lhQual.removeAddressSpace(); 7127 rhQual.removeAddressSpace(); 7128 7129 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7130 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7131 7132 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7133 7134 if (CompositeTy.isNull()) { 7135 // In this situation, we assume void* type. No especially good 7136 // reason, but this is what gcc does, and we do have to pick 7137 // to get a consistent AST. 7138 QualType incompatTy; 7139 incompatTy = S.Context.getPointerType( 7140 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7141 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7142 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7143 7144 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7145 // for casts between types with incompatible address space qualifiers. 7146 // For the following code the compiler produces casts between global and 7147 // local address spaces of the corresponded innermost pointees: 7148 // local int *global *a; 7149 // global int *global *b; 7150 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7151 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7152 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7153 << RHS.get()->getSourceRange(); 7154 7155 return incompatTy; 7156 } 7157 7158 // The pointer types are compatible. 7159 // In case of OpenCL ResultTy should have the address space qualifier 7160 // which is a superset of address spaces of both the 2nd and the 3rd 7161 // operands of the conditional operator. 7162 QualType ResultTy = [&, ResultAddrSpace]() { 7163 if (S.getLangOpts().OpenCL) { 7164 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7165 CompositeQuals.setAddressSpace(ResultAddrSpace); 7166 return S.Context 7167 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7168 .withCVRQualifiers(MergedCVRQual); 7169 } 7170 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7171 }(); 7172 if (IsBlockPointer) 7173 ResultTy = S.Context.getBlockPointerType(ResultTy); 7174 else 7175 ResultTy = S.Context.getPointerType(ResultTy); 7176 7177 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7178 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7179 return ResultTy; 7180 } 7181 7182 /// Return the resulting type when the operands are both block pointers. 7183 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7184 ExprResult &LHS, 7185 ExprResult &RHS, 7186 SourceLocation Loc) { 7187 QualType LHSTy = LHS.get()->getType(); 7188 QualType RHSTy = RHS.get()->getType(); 7189 7190 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7191 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7192 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7193 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7194 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7195 return destType; 7196 } 7197 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7198 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7199 << RHS.get()->getSourceRange(); 7200 return QualType(); 7201 } 7202 7203 // We have 2 block pointer types. 7204 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7205 } 7206 7207 /// Return the resulting type when the operands are both pointers. 7208 static QualType 7209 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7210 ExprResult &RHS, 7211 SourceLocation Loc) { 7212 // get the pointer types 7213 QualType LHSTy = LHS.get()->getType(); 7214 QualType RHSTy = RHS.get()->getType(); 7215 7216 // get the "pointed to" types 7217 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7218 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7219 7220 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7221 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7222 // Figure out necessary qualifiers (C99 6.5.15p6) 7223 QualType destPointee 7224 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7225 QualType destType = S.Context.getPointerType(destPointee); 7226 // Add qualifiers if necessary. 7227 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7228 // Promote to void*. 7229 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7230 return destType; 7231 } 7232 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7233 QualType destPointee 7234 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7235 QualType destType = S.Context.getPointerType(destPointee); 7236 // Add qualifiers if necessary. 7237 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7238 // Promote to void*. 7239 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7240 return destType; 7241 } 7242 7243 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7244 } 7245 7246 /// Return false if the first expression is not an integer and the second 7247 /// expression is not a pointer, true otherwise. 7248 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7249 Expr* PointerExpr, SourceLocation Loc, 7250 bool IsIntFirstExpr) { 7251 if (!PointerExpr->getType()->isPointerType() || 7252 !Int.get()->getType()->isIntegerType()) 7253 return false; 7254 7255 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7256 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7257 7258 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7259 << Expr1->getType() << Expr2->getType() 7260 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7261 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7262 CK_IntegralToPointer); 7263 return true; 7264 } 7265 7266 /// Simple conversion between integer and floating point types. 7267 /// 7268 /// Used when handling the OpenCL conditional operator where the 7269 /// condition is a vector while the other operands are scalar. 7270 /// 7271 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7272 /// types are either integer or floating type. Between the two 7273 /// operands, the type with the higher rank is defined as the "result 7274 /// type". The other operand needs to be promoted to the same type. No 7275 /// other type promotion is allowed. We cannot use 7276 /// UsualArithmeticConversions() for this purpose, since it always 7277 /// promotes promotable types. 7278 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7279 ExprResult &RHS, 7280 SourceLocation QuestionLoc) { 7281 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7282 if (LHS.isInvalid()) 7283 return QualType(); 7284 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7285 if (RHS.isInvalid()) 7286 return QualType(); 7287 7288 // For conversion purposes, we ignore any qualifiers. 7289 // For example, "const float" and "float" are equivalent. 7290 QualType LHSType = 7291 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7292 QualType RHSType = 7293 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7294 7295 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7296 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7297 << LHSType << LHS.get()->getSourceRange(); 7298 return QualType(); 7299 } 7300 7301 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7302 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7303 << RHSType << RHS.get()->getSourceRange(); 7304 return QualType(); 7305 } 7306 7307 // If both types are identical, no conversion is needed. 7308 if (LHSType == RHSType) 7309 return LHSType; 7310 7311 // Now handle "real" floating types (i.e. float, double, long double). 7312 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7313 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7314 /*IsCompAssign = */ false); 7315 7316 // Finally, we have two differing integer types. 7317 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7318 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7319 } 7320 7321 /// Convert scalar operands to a vector that matches the 7322 /// condition in length. 7323 /// 7324 /// Used when handling the OpenCL conditional operator where the 7325 /// condition is a vector while the other operands are scalar. 7326 /// 7327 /// We first compute the "result type" for the scalar operands 7328 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7329 /// into a vector of that type where the length matches the condition 7330 /// vector type. s6.11.6 requires that the element types of the result 7331 /// and the condition must have the same number of bits. 7332 static QualType 7333 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7334 QualType CondTy, SourceLocation QuestionLoc) { 7335 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7336 if (ResTy.isNull()) return QualType(); 7337 7338 const VectorType *CV = CondTy->getAs<VectorType>(); 7339 assert(CV); 7340 7341 // Determine the vector result type 7342 unsigned NumElements = CV->getNumElements(); 7343 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7344 7345 // Ensure that all types have the same number of bits 7346 if (S.Context.getTypeSize(CV->getElementType()) 7347 != S.Context.getTypeSize(ResTy)) { 7348 // Since VectorTy is created internally, it does not pretty print 7349 // with an OpenCL name. Instead, we just print a description. 7350 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7351 SmallString<64> Str; 7352 llvm::raw_svector_ostream OS(Str); 7353 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7354 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7355 << CondTy << OS.str(); 7356 return QualType(); 7357 } 7358 7359 // Convert operands to the vector result type 7360 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7361 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7362 7363 return VectorTy; 7364 } 7365 7366 /// Return false if this is a valid OpenCL condition vector 7367 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7368 SourceLocation QuestionLoc) { 7369 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7370 // integral type. 7371 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7372 assert(CondTy); 7373 QualType EleTy = CondTy->getElementType(); 7374 if (EleTy->isIntegerType()) return false; 7375 7376 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7377 << Cond->getType() << Cond->getSourceRange(); 7378 return true; 7379 } 7380 7381 /// Return false if the vector condition type and the vector 7382 /// result type are compatible. 7383 /// 7384 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7385 /// number of elements, and their element types have the same number 7386 /// of bits. 7387 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7388 SourceLocation QuestionLoc) { 7389 const VectorType *CV = CondTy->getAs<VectorType>(); 7390 const VectorType *RV = VecResTy->getAs<VectorType>(); 7391 assert(CV && RV); 7392 7393 if (CV->getNumElements() != RV->getNumElements()) { 7394 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7395 << CondTy << VecResTy; 7396 return true; 7397 } 7398 7399 QualType CVE = CV->getElementType(); 7400 QualType RVE = RV->getElementType(); 7401 7402 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7403 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7404 << CondTy << VecResTy; 7405 return true; 7406 } 7407 7408 return false; 7409 } 7410 7411 /// Return the resulting type for the conditional operator in 7412 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7413 /// s6.3.i) when the condition is a vector type. 7414 static QualType 7415 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7416 ExprResult &LHS, ExprResult &RHS, 7417 SourceLocation QuestionLoc) { 7418 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7419 if (Cond.isInvalid()) 7420 return QualType(); 7421 QualType CondTy = Cond.get()->getType(); 7422 7423 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7424 return QualType(); 7425 7426 // If either operand is a vector then find the vector type of the 7427 // result as specified in OpenCL v1.1 s6.3.i. 7428 if (LHS.get()->getType()->isVectorType() || 7429 RHS.get()->getType()->isVectorType()) { 7430 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7431 /*isCompAssign*/false, 7432 /*AllowBothBool*/true, 7433 /*AllowBoolConversions*/false); 7434 if (VecResTy.isNull()) return QualType(); 7435 // The result type must match the condition type as specified in 7436 // OpenCL v1.1 s6.11.6. 7437 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7438 return QualType(); 7439 return VecResTy; 7440 } 7441 7442 // Both operands are scalar. 7443 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7444 } 7445 7446 /// Return true if the Expr is block type 7447 static bool checkBlockType(Sema &S, const Expr *E) { 7448 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7449 QualType Ty = CE->getCallee()->getType(); 7450 if (Ty->isBlockPointerType()) { 7451 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7452 return true; 7453 } 7454 } 7455 return false; 7456 } 7457 7458 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7459 /// In that case, LHS = cond. 7460 /// C99 6.5.15 7461 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7462 ExprResult &RHS, ExprValueKind &VK, 7463 ExprObjectKind &OK, 7464 SourceLocation QuestionLoc) { 7465 7466 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7467 if (!LHSResult.isUsable()) return QualType(); 7468 LHS = LHSResult; 7469 7470 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7471 if (!RHSResult.isUsable()) return QualType(); 7472 RHS = RHSResult; 7473 7474 // C++ is sufficiently different to merit its own checker. 7475 if (getLangOpts().CPlusPlus) 7476 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7477 7478 VK = VK_RValue; 7479 OK = OK_Ordinary; 7480 7481 // The OpenCL operator with a vector condition is sufficiently 7482 // different to merit its own checker. 7483 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7484 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7485 7486 // First, check the condition. 7487 Cond = UsualUnaryConversions(Cond.get()); 7488 if (Cond.isInvalid()) 7489 return QualType(); 7490 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7491 return QualType(); 7492 7493 // Now check the two expressions. 7494 if (LHS.get()->getType()->isVectorType() || 7495 RHS.get()->getType()->isVectorType()) 7496 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7497 /*AllowBothBool*/true, 7498 /*AllowBoolConversions*/false); 7499 7500 QualType ResTy = 7501 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7502 if (LHS.isInvalid() || RHS.isInvalid()) 7503 return QualType(); 7504 7505 QualType LHSTy = LHS.get()->getType(); 7506 QualType RHSTy = RHS.get()->getType(); 7507 7508 // Diagnose attempts to convert between __float128 and long double where 7509 // such conversions currently can't be handled. 7510 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7511 Diag(QuestionLoc, 7512 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7513 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7514 return QualType(); 7515 } 7516 7517 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7518 // selection operator (?:). 7519 if (getLangOpts().OpenCL && 7520 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7521 return QualType(); 7522 } 7523 7524 // If both operands have arithmetic type, do the usual arithmetic conversions 7525 // to find a common type: C99 6.5.15p3,5. 7526 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7527 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7528 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7529 7530 return ResTy; 7531 } 7532 7533 // If both operands are the same structure or union type, the result is that 7534 // type. 7535 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7536 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7537 if (LHSRT->getDecl() == RHSRT->getDecl()) 7538 // "If both the operands have structure or union type, the result has 7539 // that type." This implies that CV qualifiers are dropped. 7540 return LHSTy.getUnqualifiedType(); 7541 // FIXME: Type of conditional expression must be complete in C mode. 7542 } 7543 7544 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7545 // The following || allows only one side to be void (a GCC-ism). 7546 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7547 return checkConditionalVoidType(*this, LHS, RHS); 7548 } 7549 7550 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7551 // the type of the other operand." 7552 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7553 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7554 7555 // All objective-c pointer type analysis is done here. 7556 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7557 QuestionLoc); 7558 if (LHS.isInvalid() || RHS.isInvalid()) 7559 return QualType(); 7560 if (!compositeType.isNull()) 7561 return compositeType; 7562 7563 7564 // Handle block pointer types. 7565 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7566 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7567 QuestionLoc); 7568 7569 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7570 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7571 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7572 QuestionLoc); 7573 7574 // GCC compatibility: soften pointer/integer mismatch. Note that 7575 // null pointers have been filtered out by this point. 7576 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7577 /*IsIntFirstExpr=*/true)) 7578 return RHSTy; 7579 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7580 /*IsIntFirstExpr=*/false)) 7581 return LHSTy; 7582 7583 // Emit a better diagnostic if one of the expressions is a null pointer 7584 // constant and the other is not a pointer type. In this case, the user most 7585 // likely forgot to take the address of the other expression. 7586 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7587 return QualType(); 7588 7589 // Otherwise, the operands are not compatible. 7590 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7591 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7592 << RHS.get()->getSourceRange(); 7593 return QualType(); 7594 } 7595 7596 /// FindCompositeObjCPointerType - Helper method to find composite type of 7597 /// two objective-c pointer types of the two input expressions. 7598 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7599 SourceLocation QuestionLoc) { 7600 QualType LHSTy = LHS.get()->getType(); 7601 QualType RHSTy = RHS.get()->getType(); 7602 7603 // Handle things like Class and struct objc_class*. Here we case the result 7604 // to the pseudo-builtin, because that will be implicitly cast back to the 7605 // redefinition type if an attempt is made to access its fields. 7606 if (LHSTy->isObjCClassType() && 7607 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7608 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7609 return LHSTy; 7610 } 7611 if (RHSTy->isObjCClassType() && 7612 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7613 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7614 return RHSTy; 7615 } 7616 // And the same for struct objc_object* / id 7617 if (LHSTy->isObjCIdType() && 7618 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7619 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7620 return LHSTy; 7621 } 7622 if (RHSTy->isObjCIdType() && 7623 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7624 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7625 return RHSTy; 7626 } 7627 // And the same for struct objc_selector* / SEL 7628 if (Context.isObjCSelType(LHSTy) && 7629 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7630 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7631 return LHSTy; 7632 } 7633 if (Context.isObjCSelType(RHSTy) && 7634 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7635 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7636 return RHSTy; 7637 } 7638 // Check constraints for Objective-C object pointers types. 7639 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7640 7641 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7642 // Two identical object pointer types are always compatible. 7643 return LHSTy; 7644 } 7645 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7646 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7647 QualType compositeType = LHSTy; 7648 7649 // If both operands are interfaces and either operand can be 7650 // assigned to the other, use that type as the composite 7651 // type. This allows 7652 // xxx ? (A*) a : (B*) b 7653 // where B is a subclass of A. 7654 // 7655 // Additionally, as for assignment, if either type is 'id' 7656 // allow silent coercion. Finally, if the types are 7657 // incompatible then make sure to use 'id' as the composite 7658 // type so the result is acceptable for sending messages to. 7659 7660 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7661 // It could return the composite type. 7662 if (!(compositeType = 7663 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7664 // Nothing more to do. 7665 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7666 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7667 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7668 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7669 } else if ((LHSOPT->isObjCQualifiedIdType() || 7670 RHSOPT->isObjCQualifiedIdType()) && 7671 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7672 true)) { 7673 // Need to handle "id<xx>" explicitly. 7674 // GCC allows qualified id and any Objective-C type to devolve to 7675 // id. Currently localizing to here until clear this should be 7676 // part of ObjCQualifiedIdTypesAreCompatible. 7677 compositeType = Context.getObjCIdType(); 7678 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7679 compositeType = Context.getObjCIdType(); 7680 } else { 7681 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7682 << LHSTy << RHSTy 7683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7684 QualType incompatTy = Context.getObjCIdType(); 7685 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7686 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7687 return incompatTy; 7688 } 7689 // The object pointer types are compatible. 7690 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7691 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7692 return compositeType; 7693 } 7694 // Check Objective-C object pointer types and 'void *' 7695 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7696 if (getLangOpts().ObjCAutoRefCount) { 7697 // ARC forbids the implicit conversion of object pointers to 'void *', 7698 // so these types are not compatible. 7699 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7700 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7701 LHS = RHS = true; 7702 return QualType(); 7703 } 7704 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7705 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7706 QualType destPointee 7707 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7708 QualType destType = Context.getPointerType(destPointee); 7709 // Add qualifiers if necessary. 7710 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7711 // Promote to void*. 7712 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7713 return destType; 7714 } 7715 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7716 if (getLangOpts().ObjCAutoRefCount) { 7717 // ARC forbids the implicit conversion of object pointers to 'void *', 7718 // so these types are not compatible. 7719 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7720 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7721 LHS = RHS = true; 7722 return QualType(); 7723 } 7724 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7725 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7726 QualType destPointee 7727 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7728 QualType destType = Context.getPointerType(destPointee); 7729 // Add qualifiers if necessary. 7730 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7731 // Promote to void*. 7732 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7733 return destType; 7734 } 7735 return QualType(); 7736 } 7737 7738 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7739 /// ParenRange in parentheses. 7740 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7741 const PartialDiagnostic &Note, 7742 SourceRange ParenRange) { 7743 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7744 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7745 EndLoc.isValid()) { 7746 Self.Diag(Loc, Note) 7747 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7748 << FixItHint::CreateInsertion(EndLoc, ")"); 7749 } else { 7750 // We can't display the parentheses, so just show the bare note. 7751 Self.Diag(Loc, Note) << ParenRange; 7752 } 7753 } 7754 7755 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7756 return BinaryOperator::isAdditiveOp(Opc) || 7757 BinaryOperator::isMultiplicativeOp(Opc) || 7758 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7759 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7760 // not any of the logical operators. Bitwise-xor is commonly used as a 7761 // logical-xor because there is no logical-xor operator. The logical 7762 // operators, including uses of xor, have a high false positive rate for 7763 // precedence warnings. 7764 } 7765 7766 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7767 /// expression, either using a built-in or overloaded operator, 7768 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7769 /// expression. 7770 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7771 Expr **RHSExprs) { 7772 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7773 E = E->IgnoreImpCasts(); 7774 E = E->IgnoreConversionOperator(); 7775 E = E->IgnoreImpCasts(); 7776 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7777 E = MTE->getSubExpr(); 7778 E = E->IgnoreImpCasts(); 7779 } 7780 7781 // Built-in binary operator. 7782 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7783 if (IsArithmeticOp(OP->getOpcode())) { 7784 *Opcode = OP->getOpcode(); 7785 *RHSExprs = OP->getRHS(); 7786 return true; 7787 } 7788 } 7789 7790 // Overloaded operator. 7791 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7792 if (Call->getNumArgs() != 2) 7793 return false; 7794 7795 // Make sure this is really a binary operator that is safe to pass into 7796 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7797 OverloadedOperatorKind OO = Call->getOperator(); 7798 if (OO < OO_Plus || OO > OO_Arrow || 7799 OO == OO_PlusPlus || OO == OO_MinusMinus) 7800 return false; 7801 7802 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7803 if (IsArithmeticOp(OpKind)) { 7804 *Opcode = OpKind; 7805 *RHSExprs = Call->getArg(1); 7806 return true; 7807 } 7808 } 7809 7810 return false; 7811 } 7812 7813 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7814 /// or is a logical expression such as (x==y) which has int type, but is 7815 /// commonly interpreted as boolean. 7816 static bool ExprLooksBoolean(Expr *E) { 7817 E = E->IgnoreParenImpCasts(); 7818 7819 if (E->getType()->isBooleanType()) 7820 return true; 7821 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7822 return OP->isComparisonOp() || OP->isLogicalOp(); 7823 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7824 return OP->getOpcode() == UO_LNot; 7825 if (E->getType()->isPointerType()) 7826 return true; 7827 // FIXME: What about overloaded operator calls returning "unspecified boolean 7828 // type"s (commonly pointer-to-members)? 7829 7830 return false; 7831 } 7832 7833 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7834 /// and binary operator are mixed in a way that suggests the programmer assumed 7835 /// the conditional operator has higher precedence, for example: 7836 /// "int x = a + someBinaryCondition ? 1 : 2". 7837 static void DiagnoseConditionalPrecedence(Sema &Self, 7838 SourceLocation OpLoc, 7839 Expr *Condition, 7840 Expr *LHSExpr, 7841 Expr *RHSExpr) { 7842 BinaryOperatorKind CondOpcode; 7843 Expr *CondRHS; 7844 7845 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7846 return; 7847 if (!ExprLooksBoolean(CondRHS)) 7848 return; 7849 7850 // The condition is an arithmetic binary expression, with a right- 7851 // hand side that looks boolean, so warn. 7852 7853 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7854 ? diag::warn_precedence_bitwise_conditional 7855 : diag::warn_precedence_conditional; 7856 7857 Self.Diag(OpLoc, DiagID) 7858 << Condition->getSourceRange() 7859 << BinaryOperator::getOpcodeStr(CondOpcode); 7860 7861 SuggestParentheses( 7862 Self, OpLoc, 7863 Self.PDiag(diag::note_precedence_silence) 7864 << BinaryOperator::getOpcodeStr(CondOpcode), 7865 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7866 7867 SuggestParentheses(Self, OpLoc, 7868 Self.PDiag(diag::note_precedence_conditional_first), 7869 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7870 } 7871 7872 /// Compute the nullability of a conditional expression. 7873 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7874 QualType LHSTy, QualType RHSTy, 7875 ASTContext &Ctx) { 7876 if (!ResTy->isAnyPointerType()) 7877 return ResTy; 7878 7879 auto GetNullability = [&Ctx](QualType Ty) { 7880 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7881 if (Kind) 7882 return *Kind; 7883 return NullabilityKind::Unspecified; 7884 }; 7885 7886 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7887 NullabilityKind MergedKind; 7888 7889 // Compute nullability of a binary conditional expression. 7890 if (IsBin) { 7891 if (LHSKind == NullabilityKind::NonNull) 7892 MergedKind = NullabilityKind::NonNull; 7893 else 7894 MergedKind = RHSKind; 7895 // Compute nullability of a normal conditional expression. 7896 } else { 7897 if (LHSKind == NullabilityKind::Nullable || 7898 RHSKind == NullabilityKind::Nullable) 7899 MergedKind = NullabilityKind::Nullable; 7900 else if (LHSKind == NullabilityKind::NonNull) 7901 MergedKind = RHSKind; 7902 else if (RHSKind == NullabilityKind::NonNull) 7903 MergedKind = LHSKind; 7904 else 7905 MergedKind = NullabilityKind::Unspecified; 7906 } 7907 7908 // Return if ResTy already has the correct nullability. 7909 if (GetNullability(ResTy) == MergedKind) 7910 return ResTy; 7911 7912 // Strip all nullability from ResTy. 7913 while (ResTy->getNullability(Ctx)) 7914 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7915 7916 // Create a new AttributedType with the new nullability kind. 7917 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7918 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7919 } 7920 7921 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7922 /// in the case of a the GNU conditional expr extension. 7923 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7924 SourceLocation ColonLoc, 7925 Expr *CondExpr, Expr *LHSExpr, 7926 Expr *RHSExpr) { 7927 if (!getLangOpts().CPlusPlus) { 7928 // C cannot handle TypoExpr nodes in the condition because it 7929 // doesn't handle dependent types properly, so make sure any TypoExprs have 7930 // been dealt with before checking the operands. 7931 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7932 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7933 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7934 7935 if (!CondResult.isUsable()) 7936 return ExprError(); 7937 7938 if (LHSExpr) { 7939 if (!LHSResult.isUsable()) 7940 return ExprError(); 7941 } 7942 7943 if (!RHSResult.isUsable()) 7944 return ExprError(); 7945 7946 CondExpr = CondResult.get(); 7947 LHSExpr = LHSResult.get(); 7948 RHSExpr = RHSResult.get(); 7949 } 7950 7951 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7952 // was the condition. 7953 OpaqueValueExpr *opaqueValue = nullptr; 7954 Expr *commonExpr = nullptr; 7955 if (!LHSExpr) { 7956 commonExpr = CondExpr; 7957 // Lower out placeholder types first. This is important so that we don't 7958 // try to capture a placeholder. This happens in few cases in C++; such 7959 // as Objective-C++'s dictionary subscripting syntax. 7960 if (commonExpr->hasPlaceholderType()) { 7961 ExprResult result = CheckPlaceholderExpr(commonExpr); 7962 if (!result.isUsable()) return ExprError(); 7963 commonExpr = result.get(); 7964 } 7965 // We usually want to apply unary conversions *before* saving, except 7966 // in the special case of a C++ l-value conditional. 7967 if (!(getLangOpts().CPlusPlus 7968 && !commonExpr->isTypeDependent() 7969 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7970 && commonExpr->isGLValue() 7971 && commonExpr->isOrdinaryOrBitFieldObject() 7972 && RHSExpr->isOrdinaryOrBitFieldObject() 7973 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7974 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7975 if (commonRes.isInvalid()) 7976 return ExprError(); 7977 commonExpr = commonRes.get(); 7978 } 7979 7980 // If the common expression is a class or array prvalue, materialize it 7981 // so that we can safely refer to it multiple times. 7982 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7983 commonExpr->getType()->isArrayType())) { 7984 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7985 if (MatExpr.isInvalid()) 7986 return ExprError(); 7987 commonExpr = MatExpr.get(); 7988 } 7989 7990 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7991 commonExpr->getType(), 7992 commonExpr->getValueKind(), 7993 commonExpr->getObjectKind(), 7994 commonExpr); 7995 LHSExpr = CondExpr = opaqueValue; 7996 } 7997 7998 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7999 ExprValueKind VK = VK_RValue; 8000 ExprObjectKind OK = OK_Ordinary; 8001 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8002 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8003 VK, OK, QuestionLoc); 8004 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8005 RHS.isInvalid()) 8006 return ExprError(); 8007 8008 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8009 RHS.get()); 8010 8011 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8012 8013 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8014 Context); 8015 8016 if (!commonExpr) 8017 return new (Context) 8018 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8019 RHS.get(), result, VK, OK); 8020 8021 return new (Context) BinaryConditionalOperator( 8022 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8023 ColonLoc, result, VK, OK); 8024 } 8025 8026 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8027 // being closely modeled after the C99 spec:-). The odd characteristic of this 8028 // routine is it effectively iqnores the qualifiers on the top level pointee. 8029 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8030 // FIXME: add a couple examples in this comment. 8031 static Sema::AssignConvertType 8032 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8033 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8034 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8035 8036 // get the "pointed to" type (ignoring qualifiers at the top level) 8037 const Type *lhptee, *rhptee; 8038 Qualifiers lhq, rhq; 8039 std::tie(lhptee, lhq) = 8040 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8041 std::tie(rhptee, rhq) = 8042 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8043 8044 Sema::AssignConvertType ConvTy = Sema::Compatible; 8045 8046 // C99 6.5.16.1p1: This following citation is common to constraints 8047 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8048 // qualifiers of the type *pointed to* by the right; 8049 8050 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8051 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8052 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8053 // Ignore lifetime for further calculation. 8054 lhq.removeObjCLifetime(); 8055 rhq.removeObjCLifetime(); 8056 } 8057 8058 if (!lhq.compatiblyIncludes(rhq)) { 8059 // Treat address-space mismatches as fatal. 8060 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8061 return Sema::IncompatiblePointerDiscardsQualifiers; 8062 8063 // It's okay to add or remove GC or lifetime qualifiers when converting to 8064 // and from void*. 8065 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8066 .compatiblyIncludes( 8067 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8068 && (lhptee->isVoidType() || rhptee->isVoidType())) 8069 ; // keep old 8070 8071 // Treat lifetime mismatches as fatal. 8072 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8073 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8074 8075 // For GCC/MS compatibility, other qualifier mismatches are treated 8076 // as still compatible in C. 8077 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8078 } 8079 8080 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8081 // incomplete type and the other is a pointer to a qualified or unqualified 8082 // version of void... 8083 if (lhptee->isVoidType()) { 8084 if (rhptee->isIncompleteOrObjectType()) 8085 return ConvTy; 8086 8087 // As an extension, we allow cast to/from void* to function pointer. 8088 assert(rhptee->isFunctionType()); 8089 return Sema::FunctionVoidPointer; 8090 } 8091 8092 if (rhptee->isVoidType()) { 8093 if (lhptee->isIncompleteOrObjectType()) 8094 return ConvTy; 8095 8096 // As an extension, we allow cast to/from void* to function pointer. 8097 assert(lhptee->isFunctionType()); 8098 return Sema::FunctionVoidPointer; 8099 } 8100 8101 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8102 // unqualified versions of compatible types, ... 8103 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8104 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8105 // Check if the pointee types are compatible ignoring the sign. 8106 // We explicitly check for char so that we catch "char" vs 8107 // "unsigned char" on systems where "char" is unsigned. 8108 if (lhptee->isCharType()) 8109 ltrans = S.Context.UnsignedCharTy; 8110 else if (lhptee->hasSignedIntegerRepresentation()) 8111 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8112 8113 if (rhptee->isCharType()) 8114 rtrans = S.Context.UnsignedCharTy; 8115 else if (rhptee->hasSignedIntegerRepresentation()) 8116 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8117 8118 if (ltrans == rtrans) { 8119 // Types are compatible ignoring the sign. Qualifier incompatibility 8120 // takes priority over sign incompatibility because the sign 8121 // warning can be disabled. 8122 if (ConvTy != Sema::Compatible) 8123 return ConvTy; 8124 8125 return Sema::IncompatiblePointerSign; 8126 } 8127 8128 // If we are a multi-level pointer, it's possible that our issue is simply 8129 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8130 // the eventual target type is the same and the pointers have the same 8131 // level of indirection, this must be the issue. 8132 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8133 do { 8134 std::tie(lhptee, lhq) = 8135 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8136 std::tie(rhptee, rhq) = 8137 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8138 8139 // Inconsistent address spaces at this point is invalid, even if the 8140 // address spaces would be compatible. 8141 // FIXME: This doesn't catch address space mismatches for pointers of 8142 // different nesting levels, like: 8143 // __local int *** a; 8144 // int ** b = a; 8145 // It's not clear how to actually determine when such pointers are 8146 // invalidly incompatible. 8147 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8148 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8149 8150 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8151 8152 if (lhptee == rhptee) 8153 return Sema::IncompatibleNestedPointerQualifiers; 8154 } 8155 8156 // General pointer incompatibility takes priority over qualifiers. 8157 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8158 return Sema::IncompatibleFunctionPointer; 8159 return Sema::IncompatiblePointer; 8160 } 8161 if (!S.getLangOpts().CPlusPlus && 8162 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8163 return Sema::IncompatibleFunctionPointer; 8164 return ConvTy; 8165 } 8166 8167 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8168 /// block pointer types are compatible or whether a block and normal pointer 8169 /// are compatible. It is more restrict than comparing two function pointer 8170 // types. 8171 static Sema::AssignConvertType 8172 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8173 QualType RHSType) { 8174 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8175 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8176 8177 QualType lhptee, rhptee; 8178 8179 // get the "pointed to" type (ignoring qualifiers at the top level) 8180 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8181 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8182 8183 // In C++, the types have to match exactly. 8184 if (S.getLangOpts().CPlusPlus) 8185 return Sema::IncompatibleBlockPointer; 8186 8187 Sema::AssignConvertType ConvTy = Sema::Compatible; 8188 8189 // For blocks we enforce that qualifiers are identical. 8190 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8191 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8192 if (S.getLangOpts().OpenCL) { 8193 LQuals.removeAddressSpace(); 8194 RQuals.removeAddressSpace(); 8195 } 8196 if (LQuals != RQuals) 8197 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8198 8199 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8200 // assignment. 8201 // The current behavior is similar to C++ lambdas. A block might be 8202 // assigned to a variable iff its return type and parameters are compatible 8203 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8204 // an assignment. Presumably it should behave in way that a function pointer 8205 // assignment does in C, so for each parameter and return type: 8206 // * CVR and address space of LHS should be a superset of CVR and address 8207 // space of RHS. 8208 // * unqualified types should be compatible. 8209 if (S.getLangOpts().OpenCL) { 8210 if (!S.Context.typesAreBlockPointerCompatible( 8211 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8212 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8213 return Sema::IncompatibleBlockPointer; 8214 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8215 return Sema::IncompatibleBlockPointer; 8216 8217 return ConvTy; 8218 } 8219 8220 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8221 /// for assignment compatibility. 8222 static Sema::AssignConvertType 8223 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8224 QualType RHSType) { 8225 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8226 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8227 8228 if (LHSType->isObjCBuiltinType()) { 8229 // Class is not compatible with ObjC object pointers. 8230 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8231 !RHSType->isObjCQualifiedClassType()) 8232 return Sema::IncompatiblePointer; 8233 return Sema::Compatible; 8234 } 8235 if (RHSType->isObjCBuiltinType()) { 8236 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8237 !LHSType->isObjCQualifiedClassType()) 8238 return Sema::IncompatiblePointer; 8239 return Sema::Compatible; 8240 } 8241 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8242 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8243 8244 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8245 // make an exception for id<P> 8246 !LHSType->isObjCQualifiedIdType()) 8247 return Sema::CompatiblePointerDiscardsQualifiers; 8248 8249 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8250 return Sema::Compatible; 8251 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8252 return Sema::IncompatibleObjCQualifiedId; 8253 return Sema::IncompatiblePointer; 8254 } 8255 8256 Sema::AssignConvertType 8257 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8258 QualType LHSType, QualType RHSType) { 8259 // Fake up an opaque expression. We don't actually care about what 8260 // cast operations are required, so if CheckAssignmentConstraints 8261 // adds casts to this they'll be wasted, but fortunately that doesn't 8262 // usually happen on valid code. 8263 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8264 ExprResult RHSPtr = &RHSExpr; 8265 CastKind K; 8266 8267 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8268 } 8269 8270 /// This helper function returns true if QT is a vector type that has element 8271 /// type ElementType. 8272 static bool isVector(QualType QT, QualType ElementType) { 8273 if (const VectorType *VT = QT->getAs<VectorType>()) 8274 return VT->getElementType() == ElementType; 8275 return false; 8276 } 8277 8278 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8279 /// has code to accommodate several GCC extensions when type checking 8280 /// pointers. Here are some objectionable examples that GCC considers warnings: 8281 /// 8282 /// int a, *pint; 8283 /// short *pshort; 8284 /// struct foo *pfoo; 8285 /// 8286 /// pint = pshort; // warning: assignment from incompatible pointer type 8287 /// a = pint; // warning: assignment makes integer from pointer without a cast 8288 /// pint = a; // warning: assignment makes pointer from integer without a cast 8289 /// pint = pfoo; // warning: assignment from incompatible pointer type 8290 /// 8291 /// As a result, the code for dealing with pointers is more complex than the 8292 /// C99 spec dictates. 8293 /// 8294 /// Sets 'Kind' for any result kind except Incompatible. 8295 Sema::AssignConvertType 8296 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8297 CastKind &Kind, bool ConvertRHS) { 8298 QualType RHSType = RHS.get()->getType(); 8299 QualType OrigLHSType = LHSType; 8300 8301 // Get canonical types. We're not formatting these types, just comparing 8302 // them. 8303 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8304 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8305 8306 // Common case: no conversion required. 8307 if (LHSType == RHSType) { 8308 Kind = CK_NoOp; 8309 return Compatible; 8310 } 8311 8312 // If we have an atomic type, try a non-atomic assignment, then just add an 8313 // atomic qualification step. 8314 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8315 Sema::AssignConvertType result = 8316 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8317 if (result != Compatible) 8318 return result; 8319 if (Kind != CK_NoOp && ConvertRHS) 8320 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8321 Kind = CK_NonAtomicToAtomic; 8322 return Compatible; 8323 } 8324 8325 // If the left-hand side is a reference type, then we are in a 8326 // (rare!) case where we've allowed the use of references in C, 8327 // e.g., as a parameter type in a built-in function. In this case, 8328 // just make sure that the type referenced is compatible with the 8329 // right-hand side type. The caller is responsible for adjusting 8330 // LHSType so that the resulting expression does not have reference 8331 // type. 8332 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8333 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8334 Kind = CK_LValueBitCast; 8335 return Compatible; 8336 } 8337 return Incompatible; 8338 } 8339 8340 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8341 // to the same ExtVector type. 8342 if (LHSType->isExtVectorType()) { 8343 if (RHSType->isExtVectorType()) 8344 return Incompatible; 8345 if (RHSType->isArithmeticType()) { 8346 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8347 if (ConvertRHS) 8348 RHS = prepareVectorSplat(LHSType, RHS.get()); 8349 Kind = CK_VectorSplat; 8350 return Compatible; 8351 } 8352 } 8353 8354 // Conversions to or from vector type. 8355 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8356 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8357 // Allow assignments of an AltiVec vector type to an equivalent GCC 8358 // vector type and vice versa 8359 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8360 Kind = CK_BitCast; 8361 return Compatible; 8362 } 8363 8364 // If we are allowing lax vector conversions, and LHS and RHS are both 8365 // vectors, the total size only needs to be the same. This is a bitcast; 8366 // no bits are changed but the result type is different. 8367 if (isLaxVectorConversion(RHSType, LHSType)) { 8368 Kind = CK_BitCast; 8369 return IncompatibleVectors; 8370 } 8371 } 8372 8373 // When the RHS comes from another lax conversion (e.g. binops between 8374 // scalars and vectors) the result is canonicalized as a vector. When the 8375 // LHS is also a vector, the lax is allowed by the condition above. Handle 8376 // the case where LHS is a scalar. 8377 if (LHSType->isScalarType()) { 8378 const VectorType *VecType = RHSType->getAs<VectorType>(); 8379 if (VecType && VecType->getNumElements() == 1 && 8380 isLaxVectorConversion(RHSType, LHSType)) { 8381 ExprResult *VecExpr = &RHS; 8382 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8383 Kind = CK_BitCast; 8384 return Compatible; 8385 } 8386 } 8387 8388 return Incompatible; 8389 } 8390 8391 // Diagnose attempts to convert between __float128 and long double where 8392 // such conversions currently can't be handled. 8393 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8394 return Incompatible; 8395 8396 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8397 // discards the imaginary part. 8398 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8399 !LHSType->getAs<ComplexType>()) 8400 return Incompatible; 8401 8402 // Arithmetic conversions. 8403 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8404 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8405 if (ConvertRHS) 8406 Kind = PrepareScalarCast(RHS, LHSType); 8407 return Compatible; 8408 } 8409 8410 // Conversions to normal pointers. 8411 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8412 // U* -> T* 8413 if (isa<PointerType>(RHSType)) { 8414 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8415 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8416 if (AddrSpaceL != AddrSpaceR) 8417 Kind = CK_AddressSpaceConversion; 8418 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8419 Kind = CK_NoOp; 8420 else 8421 Kind = CK_BitCast; 8422 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8423 } 8424 8425 // int -> T* 8426 if (RHSType->isIntegerType()) { 8427 Kind = CK_IntegralToPointer; // FIXME: null? 8428 return IntToPointer; 8429 } 8430 8431 // C pointers are not compatible with ObjC object pointers, 8432 // with two exceptions: 8433 if (isa<ObjCObjectPointerType>(RHSType)) { 8434 // - conversions to void* 8435 if (LHSPointer->getPointeeType()->isVoidType()) { 8436 Kind = CK_BitCast; 8437 return Compatible; 8438 } 8439 8440 // - conversions from 'Class' to the redefinition type 8441 if (RHSType->isObjCClassType() && 8442 Context.hasSameType(LHSType, 8443 Context.getObjCClassRedefinitionType())) { 8444 Kind = CK_BitCast; 8445 return Compatible; 8446 } 8447 8448 Kind = CK_BitCast; 8449 return IncompatiblePointer; 8450 } 8451 8452 // U^ -> void* 8453 if (RHSType->getAs<BlockPointerType>()) { 8454 if (LHSPointer->getPointeeType()->isVoidType()) { 8455 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8456 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8457 ->getPointeeType() 8458 .getAddressSpace(); 8459 Kind = 8460 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8461 return Compatible; 8462 } 8463 } 8464 8465 return Incompatible; 8466 } 8467 8468 // Conversions to block pointers. 8469 if (isa<BlockPointerType>(LHSType)) { 8470 // U^ -> T^ 8471 if (RHSType->isBlockPointerType()) { 8472 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8473 ->getPointeeType() 8474 .getAddressSpace(); 8475 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8476 ->getPointeeType() 8477 .getAddressSpace(); 8478 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8479 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8480 } 8481 8482 // int or null -> T^ 8483 if (RHSType->isIntegerType()) { 8484 Kind = CK_IntegralToPointer; // FIXME: null 8485 return IntToBlockPointer; 8486 } 8487 8488 // id -> T^ 8489 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8490 Kind = CK_AnyPointerToBlockPointerCast; 8491 return Compatible; 8492 } 8493 8494 // void* -> T^ 8495 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8496 if (RHSPT->getPointeeType()->isVoidType()) { 8497 Kind = CK_AnyPointerToBlockPointerCast; 8498 return Compatible; 8499 } 8500 8501 return Incompatible; 8502 } 8503 8504 // Conversions to Objective-C pointers. 8505 if (isa<ObjCObjectPointerType>(LHSType)) { 8506 // A* -> B* 8507 if (RHSType->isObjCObjectPointerType()) { 8508 Kind = CK_BitCast; 8509 Sema::AssignConvertType result = 8510 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8511 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8512 result == Compatible && 8513 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8514 result = IncompatibleObjCWeakRef; 8515 return result; 8516 } 8517 8518 // int or null -> A* 8519 if (RHSType->isIntegerType()) { 8520 Kind = CK_IntegralToPointer; // FIXME: null 8521 return IntToPointer; 8522 } 8523 8524 // In general, C pointers are not compatible with ObjC object pointers, 8525 // with two exceptions: 8526 if (isa<PointerType>(RHSType)) { 8527 Kind = CK_CPointerToObjCPointerCast; 8528 8529 // - conversions from 'void*' 8530 if (RHSType->isVoidPointerType()) { 8531 return Compatible; 8532 } 8533 8534 // - conversions to 'Class' from its redefinition type 8535 if (LHSType->isObjCClassType() && 8536 Context.hasSameType(RHSType, 8537 Context.getObjCClassRedefinitionType())) { 8538 return Compatible; 8539 } 8540 8541 return IncompatiblePointer; 8542 } 8543 8544 // Only under strict condition T^ is compatible with an Objective-C pointer. 8545 if (RHSType->isBlockPointerType() && 8546 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8547 if (ConvertRHS) 8548 maybeExtendBlockObject(RHS); 8549 Kind = CK_BlockPointerToObjCPointerCast; 8550 return Compatible; 8551 } 8552 8553 return Incompatible; 8554 } 8555 8556 // Conversions from pointers that are not covered by the above. 8557 if (isa<PointerType>(RHSType)) { 8558 // T* -> _Bool 8559 if (LHSType == Context.BoolTy) { 8560 Kind = CK_PointerToBoolean; 8561 return Compatible; 8562 } 8563 8564 // T* -> int 8565 if (LHSType->isIntegerType()) { 8566 Kind = CK_PointerToIntegral; 8567 return PointerToInt; 8568 } 8569 8570 return Incompatible; 8571 } 8572 8573 // Conversions from Objective-C pointers that are not covered by the above. 8574 if (isa<ObjCObjectPointerType>(RHSType)) { 8575 // T* -> _Bool 8576 if (LHSType == Context.BoolTy) { 8577 Kind = CK_PointerToBoolean; 8578 return Compatible; 8579 } 8580 8581 // T* -> int 8582 if (LHSType->isIntegerType()) { 8583 Kind = CK_PointerToIntegral; 8584 return PointerToInt; 8585 } 8586 8587 return Incompatible; 8588 } 8589 8590 // struct A -> struct B 8591 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8592 if (Context.typesAreCompatible(LHSType, RHSType)) { 8593 Kind = CK_NoOp; 8594 return Compatible; 8595 } 8596 } 8597 8598 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8599 Kind = CK_IntToOCLSampler; 8600 return Compatible; 8601 } 8602 8603 return Incompatible; 8604 } 8605 8606 /// Constructs a transparent union from an expression that is 8607 /// used to initialize the transparent union. 8608 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8609 ExprResult &EResult, QualType UnionType, 8610 FieldDecl *Field) { 8611 // Build an initializer list that designates the appropriate member 8612 // of the transparent union. 8613 Expr *E = EResult.get(); 8614 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8615 E, SourceLocation()); 8616 Initializer->setType(UnionType); 8617 Initializer->setInitializedFieldInUnion(Field); 8618 8619 // Build a compound literal constructing a value of the transparent 8620 // union type from this initializer list. 8621 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8622 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8623 VK_RValue, Initializer, false); 8624 } 8625 8626 Sema::AssignConvertType 8627 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8628 ExprResult &RHS) { 8629 QualType RHSType = RHS.get()->getType(); 8630 8631 // If the ArgType is a Union type, we want to handle a potential 8632 // transparent_union GCC extension. 8633 const RecordType *UT = ArgType->getAsUnionType(); 8634 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8635 return Incompatible; 8636 8637 // The field to initialize within the transparent union. 8638 RecordDecl *UD = UT->getDecl(); 8639 FieldDecl *InitField = nullptr; 8640 // It's compatible if the expression matches any of the fields. 8641 for (auto *it : UD->fields()) { 8642 if (it->getType()->isPointerType()) { 8643 // If the transparent union contains a pointer type, we allow: 8644 // 1) void pointer 8645 // 2) null pointer constant 8646 if (RHSType->isPointerType()) 8647 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8648 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8649 InitField = it; 8650 break; 8651 } 8652 8653 if (RHS.get()->isNullPointerConstant(Context, 8654 Expr::NPC_ValueDependentIsNull)) { 8655 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8656 CK_NullToPointer); 8657 InitField = it; 8658 break; 8659 } 8660 } 8661 8662 CastKind Kind; 8663 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8664 == Compatible) { 8665 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8666 InitField = it; 8667 break; 8668 } 8669 } 8670 8671 if (!InitField) 8672 return Incompatible; 8673 8674 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8675 return Compatible; 8676 } 8677 8678 Sema::AssignConvertType 8679 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8680 bool Diagnose, 8681 bool DiagnoseCFAudited, 8682 bool ConvertRHS) { 8683 // We need to be able to tell the caller whether we diagnosed a problem, if 8684 // they ask us to issue diagnostics. 8685 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8686 8687 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8688 // we can't avoid *all* modifications at the moment, so we need some somewhere 8689 // to put the updated value. 8690 ExprResult LocalRHS = CallerRHS; 8691 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8692 8693 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8694 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8695 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8696 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8697 Diag(RHS.get()->getExprLoc(), 8698 diag::warn_noderef_to_dereferenceable_pointer) 8699 << RHS.get()->getSourceRange(); 8700 } 8701 } 8702 } 8703 8704 if (getLangOpts().CPlusPlus) { 8705 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8706 // C++ 5.17p3: If the left operand is not of class type, the 8707 // expression is implicitly converted (C++ 4) to the 8708 // cv-unqualified type of the left operand. 8709 QualType RHSType = RHS.get()->getType(); 8710 if (Diagnose) { 8711 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8712 AA_Assigning); 8713 } else { 8714 ImplicitConversionSequence ICS = 8715 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8716 /*SuppressUserConversions=*/false, 8717 AllowedExplicit::None, 8718 /*InOverloadResolution=*/false, 8719 /*CStyle=*/false, 8720 /*AllowObjCWritebackConversion=*/false); 8721 if (ICS.isFailure()) 8722 return Incompatible; 8723 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8724 ICS, AA_Assigning); 8725 } 8726 if (RHS.isInvalid()) 8727 return Incompatible; 8728 Sema::AssignConvertType result = Compatible; 8729 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8730 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8731 result = IncompatibleObjCWeakRef; 8732 return result; 8733 } 8734 8735 // FIXME: Currently, we fall through and treat C++ classes like C 8736 // structures. 8737 // FIXME: We also fall through for atomics; not sure what should 8738 // happen there, though. 8739 } else if (RHS.get()->getType() == Context.OverloadTy) { 8740 // As a set of extensions to C, we support overloading on functions. These 8741 // functions need to be resolved here. 8742 DeclAccessPair DAP; 8743 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8744 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8745 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8746 else 8747 return Incompatible; 8748 } 8749 8750 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8751 // a null pointer constant. 8752 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8753 LHSType->isBlockPointerType()) && 8754 RHS.get()->isNullPointerConstant(Context, 8755 Expr::NPC_ValueDependentIsNull)) { 8756 if (Diagnose || ConvertRHS) { 8757 CastKind Kind; 8758 CXXCastPath Path; 8759 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8760 /*IgnoreBaseAccess=*/false, Diagnose); 8761 if (ConvertRHS) 8762 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8763 } 8764 return Compatible; 8765 } 8766 8767 // OpenCL queue_t type assignment. 8768 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8769 Context, Expr::NPC_ValueDependentIsNull)) { 8770 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8771 return Compatible; 8772 } 8773 8774 // This check seems unnatural, however it is necessary to ensure the proper 8775 // conversion of functions/arrays. If the conversion were done for all 8776 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8777 // expressions that suppress this implicit conversion (&, sizeof). 8778 // 8779 // Suppress this for references: C++ 8.5.3p5. 8780 if (!LHSType->isReferenceType()) { 8781 // FIXME: We potentially allocate here even if ConvertRHS is false. 8782 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8783 if (RHS.isInvalid()) 8784 return Incompatible; 8785 } 8786 CastKind Kind; 8787 Sema::AssignConvertType result = 8788 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8789 8790 // C99 6.5.16.1p2: The value of the right operand is converted to the 8791 // type of the assignment expression. 8792 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8793 // so that we can use references in built-in functions even in C. 8794 // The getNonReferenceType() call makes sure that the resulting expression 8795 // does not have reference type. 8796 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8797 QualType Ty = LHSType.getNonLValueExprType(Context); 8798 Expr *E = RHS.get(); 8799 8800 // Check for various Objective-C errors. If we are not reporting 8801 // diagnostics and just checking for errors, e.g., during overload 8802 // resolution, return Incompatible to indicate the failure. 8803 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8804 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8805 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8806 if (!Diagnose) 8807 return Incompatible; 8808 } 8809 if (getLangOpts().ObjC && 8810 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8811 E->getType(), E, Diagnose) || 8812 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8813 if (!Diagnose) 8814 return Incompatible; 8815 // Replace the expression with a corrected version and continue so we 8816 // can find further errors. 8817 RHS = E; 8818 return Compatible; 8819 } 8820 8821 if (ConvertRHS) 8822 RHS = ImpCastExprToType(E, Ty, Kind); 8823 } 8824 8825 return result; 8826 } 8827 8828 namespace { 8829 /// The original operand to an operator, prior to the application of the usual 8830 /// arithmetic conversions and converting the arguments of a builtin operator 8831 /// candidate. 8832 struct OriginalOperand { 8833 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8834 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8835 Op = MTE->getSubExpr(); 8836 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8837 Op = BTE->getSubExpr(); 8838 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8839 Orig = ICE->getSubExprAsWritten(); 8840 Conversion = ICE->getConversionFunction(); 8841 } 8842 } 8843 8844 QualType getType() const { return Orig->getType(); } 8845 8846 Expr *Orig; 8847 NamedDecl *Conversion; 8848 }; 8849 } 8850 8851 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8852 ExprResult &RHS) { 8853 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8854 8855 Diag(Loc, diag::err_typecheck_invalid_operands) 8856 << OrigLHS.getType() << OrigRHS.getType() 8857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8858 8859 // If a user-defined conversion was applied to either of the operands prior 8860 // to applying the built-in operator rules, tell the user about it. 8861 if (OrigLHS.Conversion) { 8862 Diag(OrigLHS.Conversion->getLocation(), 8863 diag::note_typecheck_invalid_operands_converted) 8864 << 0 << LHS.get()->getType(); 8865 } 8866 if (OrigRHS.Conversion) { 8867 Diag(OrigRHS.Conversion->getLocation(), 8868 diag::note_typecheck_invalid_operands_converted) 8869 << 1 << RHS.get()->getType(); 8870 } 8871 8872 return QualType(); 8873 } 8874 8875 // Diagnose cases where a scalar was implicitly converted to a vector and 8876 // diagnose the underlying types. Otherwise, diagnose the error 8877 // as invalid vector logical operands for non-C++ cases. 8878 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8879 ExprResult &RHS) { 8880 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8881 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8882 8883 bool LHSNatVec = LHSType->isVectorType(); 8884 bool RHSNatVec = RHSType->isVectorType(); 8885 8886 if (!(LHSNatVec && RHSNatVec)) { 8887 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8888 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8889 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8890 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8891 << Vector->getSourceRange(); 8892 return QualType(); 8893 } 8894 8895 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8896 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8897 << RHS.get()->getSourceRange(); 8898 8899 return QualType(); 8900 } 8901 8902 /// Try to convert a value of non-vector type to a vector type by converting 8903 /// the type to the element type of the vector and then performing a splat. 8904 /// If the language is OpenCL, we only use conversions that promote scalar 8905 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8906 /// for float->int. 8907 /// 8908 /// OpenCL V2.0 6.2.6.p2: 8909 /// An error shall occur if any scalar operand type has greater rank 8910 /// than the type of the vector element. 8911 /// 8912 /// \param scalar - if non-null, actually perform the conversions 8913 /// \return true if the operation fails (but without diagnosing the failure) 8914 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8915 QualType scalarTy, 8916 QualType vectorEltTy, 8917 QualType vectorTy, 8918 unsigned &DiagID) { 8919 // The conversion to apply to the scalar before splatting it, 8920 // if necessary. 8921 CastKind scalarCast = CK_NoOp; 8922 8923 if (vectorEltTy->isIntegralType(S.Context)) { 8924 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8925 (scalarTy->isIntegerType() && 8926 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8927 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8928 return true; 8929 } 8930 if (!scalarTy->isIntegralType(S.Context)) 8931 return true; 8932 scalarCast = CK_IntegralCast; 8933 } else if (vectorEltTy->isRealFloatingType()) { 8934 if (scalarTy->isRealFloatingType()) { 8935 if (S.getLangOpts().OpenCL && 8936 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8937 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8938 return true; 8939 } 8940 scalarCast = CK_FloatingCast; 8941 } 8942 else if (scalarTy->isIntegralType(S.Context)) 8943 scalarCast = CK_IntegralToFloating; 8944 else 8945 return true; 8946 } else { 8947 return true; 8948 } 8949 8950 // Adjust scalar if desired. 8951 if (scalar) { 8952 if (scalarCast != CK_NoOp) 8953 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8954 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8955 } 8956 return false; 8957 } 8958 8959 /// Convert vector E to a vector with the same number of elements but different 8960 /// element type. 8961 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8962 const auto *VecTy = E->getType()->getAs<VectorType>(); 8963 assert(VecTy && "Expression E must be a vector"); 8964 QualType NewVecTy = S.Context.getVectorType(ElementType, 8965 VecTy->getNumElements(), 8966 VecTy->getVectorKind()); 8967 8968 // Look through the implicit cast. Return the subexpression if its type is 8969 // NewVecTy. 8970 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8971 if (ICE->getSubExpr()->getType() == NewVecTy) 8972 return ICE->getSubExpr(); 8973 8974 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8975 return S.ImpCastExprToType(E, NewVecTy, Cast); 8976 } 8977 8978 /// Test if a (constant) integer Int can be casted to another integer type 8979 /// IntTy without losing precision. 8980 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8981 QualType OtherIntTy) { 8982 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8983 8984 // Reject cases where the value of the Int is unknown as that would 8985 // possibly cause truncation, but accept cases where the scalar can be 8986 // demoted without loss of precision. 8987 Expr::EvalResult EVResult; 8988 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8989 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8990 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8991 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8992 8993 if (CstInt) { 8994 // If the scalar is constant and is of a higher order and has more active 8995 // bits that the vector element type, reject it. 8996 llvm::APSInt Result = EVResult.Val.getInt(); 8997 unsigned NumBits = IntSigned 8998 ? (Result.isNegative() ? Result.getMinSignedBits() 8999 : Result.getActiveBits()) 9000 : Result.getActiveBits(); 9001 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9002 return true; 9003 9004 // If the signedness of the scalar type and the vector element type 9005 // differs and the number of bits is greater than that of the vector 9006 // element reject it. 9007 return (IntSigned != OtherIntSigned && 9008 NumBits > S.Context.getIntWidth(OtherIntTy)); 9009 } 9010 9011 // Reject cases where the value of the scalar is not constant and it's 9012 // order is greater than that of the vector element type. 9013 return (Order < 0); 9014 } 9015 9016 /// Test if a (constant) integer Int can be casted to floating point type 9017 /// FloatTy without losing precision. 9018 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9019 QualType FloatTy) { 9020 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9021 9022 // Determine if the integer constant can be expressed as a floating point 9023 // number of the appropriate type. 9024 Expr::EvalResult EVResult; 9025 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9026 9027 uint64_t Bits = 0; 9028 if (CstInt) { 9029 // Reject constants that would be truncated if they were converted to 9030 // the floating point type. Test by simple to/from conversion. 9031 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9032 // could be avoided if there was a convertFromAPInt method 9033 // which could signal back if implicit truncation occurred. 9034 llvm::APSInt Result = EVResult.Val.getInt(); 9035 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9036 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9037 llvm::APFloat::rmTowardZero); 9038 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9039 !IntTy->hasSignedIntegerRepresentation()); 9040 bool Ignored = false; 9041 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9042 &Ignored); 9043 if (Result != ConvertBack) 9044 return true; 9045 } else { 9046 // Reject types that cannot be fully encoded into the mantissa of 9047 // the float. 9048 Bits = S.Context.getTypeSize(IntTy); 9049 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9050 S.Context.getFloatTypeSemantics(FloatTy)); 9051 if (Bits > FloatPrec) 9052 return true; 9053 } 9054 9055 return false; 9056 } 9057 9058 /// Attempt to convert and splat Scalar into a vector whose types matches 9059 /// Vector following GCC conversion rules. The rule is that implicit 9060 /// conversion can occur when Scalar can be casted to match Vector's element 9061 /// type without causing truncation of Scalar. 9062 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9063 ExprResult *Vector) { 9064 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9065 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9066 const VectorType *VT = VectorTy->getAs<VectorType>(); 9067 9068 assert(!isa<ExtVectorType>(VT) && 9069 "ExtVectorTypes should not be handled here!"); 9070 9071 QualType VectorEltTy = VT->getElementType(); 9072 9073 // Reject cases where the vector element type or the scalar element type are 9074 // not integral or floating point types. 9075 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9076 return true; 9077 9078 // The conversion to apply to the scalar before splatting it, 9079 // if necessary. 9080 CastKind ScalarCast = CK_NoOp; 9081 9082 // Accept cases where the vector elements are integers and the scalar is 9083 // an integer. 9084 // FIXME: Notionally if the scalar was a floating point value with a precise 9085 // integral representation, we could cast it to an appropriate integer 9086 // type and then perform the rest of the checks here. GCC will perform 9087 // this conversion in some cases as determined by the input language. 9088 // We should accept it on a language independent basis. 9089 if (VectorEltTy->isIntegralType(S.Context) && 9090 ScalarTy->isIntegralType(S.Context) && 9091 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9092 9093 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9094 return true; 9095 9096 ScalarCast = CK_IntegralCast; 9097 } else if (VectorEltTy->isIntegralType(S.Context) && 9098 ScalarTy->isRealFloatingType()) { 9099 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9100 ScalarCast = CK_FloatingToIntegral; 9101 else 9102 return true; 9103 } else if (VectorEltTy->isRealFloatingType()) { 9104 if (ScalarTy->isRealFloatingType()) { 9105 9106 // Reject cases where the scalar type is not a constant and has a higher 9107 // Order than the vector element type. 9108 llvm::APFloat Result(0.0); 9109 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 9110 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9111 if (!CstScalar && Order < 0) 9112 return true; 9113 9114 // If the scalar cannot be safely casted to the vector element type, 9115 // reject it. 9116 if (CstScalar) { 9117 bool Truncated = false; 9118 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9119 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9120 if (Truncated) 9121 return true; 9122 } 9123 9124 ScalarCast = CK_FloatingCast; 9125 } else if (ScalarTy->isIntegralType(S.Context)) { 9126 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9127 return true; 9128 9129 ScalarCast = CK_IntegralToFloating; 9130 } else 9131 return true; 9132 } 9133 9134 // Adjust scalar if desired. 9135 if (Scalar) { 9136 if (ScalarCast != CK_NoOp) 9137 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9138 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9139 } 9140 return false; 9141 } 9142 9143 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9144 SourceLocation Loc, bool IsCompAssign, 9145 bool AllowBothBool, 9146 bool AllowBoolConversions) { 9147 if (!IsCompAssign) { 9148 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9149 if (LHS.isInvalid()) 9150 return QualType(); 9151 } 9152 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9153 if (RHS.isInvalid()) 9154 return QualType(); 9155 9156 // For conversion purposes, we ignore any qualifiers. 9157 // For example, "const float" and "float" are equivalent. 9158 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9159 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9160 9161 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9162 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9163 assert(LHSVecType || RHSVecType); 9164 9165 // AltiVec-style "vector bool op vector bool" combinations are allowed 9166 // for some operators but not others. 9167 if (!AllowBothBool && 9168 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9169 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9170 return InvalidOperands(Loc, LHS, RHS); 9171 9172 // If the vector types are identical, return. 9173 if (Context.hasSameType(LHSType, RHSType)) 9174 return LHSType; 9175 9176 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9177 if (LHSVecType && RHSVecType && 9178 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9179 if (isa<ExtVectorType>(LHSVecType)) { 9180 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9181 return LHSType; 9182 } 9183 9184 if (!IsCompAssign) 9185 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9186 return RHSType; 9187 } 9188 9189 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9190 // can be mixed, with the result being the non-bool type. The non-bool 9191 // operand must have integer element type. 9192 if (AllowBoolConversions && LHSVecType && RHSVecType && 9193 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9194 (Context.getTypeSize(LHSVecType->getElementType()) == 9195 Context.getTypeSize(RHSVecType->getElementType()))) { 9196 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9197 LHSVecType->getElementType()->isIntegerType() && 9198 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9199 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9200 return LHSType; 9201 } 9202 if (!IsCompAssign && 9203 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9204 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9205 RHSVecType->getElementType()->isIntegerType()) { 9206 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9207 return RHSType; 9208 } 9209 } 9210 9211 // If there's a vector type and a scalar, try to convert the scalar to 9212 // the vector element type and splat. 9213 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9214 if (!RHSVecType) { 9215 if (isa<ExtVectorType>(LHSVecType)) { 9216 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9217 LHSVecType->getElementType(), LHSType, 9218 DiagID)) 9219 return LHSType; 9220 } else { 9221 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9222 return LHSType; 9223 } 9224 } 9225 if (!LHSVecType) { 9226 if (isa<ExtVectorType>(RHSVecType)) { 9227 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9228 LHSType, RHSVecType->getElementType(), 9229 RHSType, DiagID)) 9230 return RHSType; 9231 } else { 9232 if (LHS.get()->getValueKind() == VK_LValue || 9233 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9234 return RHSType; 9235 } 9236 } 9237 9238 // FIXME: The code below also handles conversion between vectors and 9239 // non-scalars, we should break this down into fine grained specific checks 9240 // and emit proper diagnostics. 9241 QualType VecType = LHSVecType ? LHSType : RHSType; 9242 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9243 QualType OtherType = LHSVecType ? RHSType : LHSType; 9244 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9245 if (isLaxVectorConversion(OtherType, VecType)) { 9246 // If we're allowing lax vector conversions, only the total (data) size 9247 // needs to be the same. For non compound assignment, if one of the types is 9248 // scalar, the result is always the vector type. 9249 if (!IsCompAssign) { 9250 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9251 return VecType; 9252 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9253 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9254 // type. Note that this is already done by non-compound assignments in 9255 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9256 // <1 x T> -> T. The result is also a vector type. 9257 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9258 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9259 ExprResult *RHSExpr = &RHS; 9260 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9261 return VecType; 9262 } 9263 } 9264 9265 // Okay, the expression is invalid. 9266 9267 // If there's a non-vector, non-real operand, diagnose that. 9268 if ((!RHSVecType && !RHSType->isRealType()) || 9269 (!LHSVecType && !LHSType->isRealType())) { 9270 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9271 << LHSType << RHSType 9272 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9273 return QualType(); 9274 } 9275 9276 // OpenCL V1.1 6.2.6.p1: 9277 // If the operands are of more than one vector type, then an error shall 9278 // occur. Implicit conversions between vector types are not permitted, per 9279 // section 6.2.1. 9280 if (getLangOpts().OpenCL && 9281 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9282 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9283 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9284 << RHSType; 9285 return QualType(); 9286 } 9287 9288 9289 // If there is a vector type that is not a ExtVector and a scalar, we reach 9290 // this point if scalar could not be converted to the vector's element type 9291 // without truncation. 9292 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9293 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9294 QualType Scalar = LHSVecType ? RHSType : LHSType; 9295 QualType Vector = LHSVecType ? LHSType : RHSType; 9296 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9297 Diag(Loc, 9298 diag::err_typecheck_vector_not_convertable_implict_truncation) 9299 << ScalarOrVector << Scalar << Vector; 9300 9301 return QualType(); 9302 } 9303 9304 // Otherwise, use the generic diagnostic. 9305 Diag(Loc, DiagID) 9306 << LHSType << RHSType 9307 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9308 return QualType(); 9309 } 9310 9311 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9312 // expression. These are mainly cases where the null pointer is used as an 9313 // integer instead of a pointer. 9314 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9315 SourceLocation Loc, bool IsCompare) { 9316 // The canonical way to check for a GNU null is with isNullPointerConstant, 9317 // but we use a bit of a hack here for speed; this is a relatively 9318 // hot path, and isNullPointerConstant is slow. 9319 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9320 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9321 9322 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9323 9324 // Avoid analyzing cases where the result will either be invalid (and 9325 // diagnosed as such) or entirely valid and not something to warn about. 9326 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9327 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9328 return; 9329 9330 // Comparison operations would not make sense with a null pointer no matter 9331 // what the other expression is. 9332 if (!IsCompare) { 9333 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9334 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9335 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9336 return; 9337 } 9338 9339 // The rest of the operations only make sense with a null pointer 9340 // if the other expression is a pointer. 9341 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9342 NonNullType->canDecayToPointerType()) 9343 return; 9344 9345 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9346 << LHSNull /* LHS is NULL */ << NonNullType 9347 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9348 } 9349 9350 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9351 SourceLocation Loc) { 9352 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9353 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9354 if (!LUE || !RUE) 9355 return; 9356 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9357 RUE->getKind() != UETT_SizeOf) 9358 return; 9359 9360 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9361 QualType LHSTy = LHSArg->getType(); 9362 QualType RHSTy; 9363 9364 if (RUE->isArgumentType()) 9365 RHSTy = RUE->getArgumentType(); 9366 else 9367 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9368 9369 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9370 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9371 return; 9372 9373 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9374 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9375 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9376 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9377 << LHSArgDecl; 9378 } 9379 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9380 QualType ArrayElemTy = ArrayTy->getElementType(); 9381 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9382 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9383 ArrayElemTy->isCharType() || 9384 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9385 return; 9386 S.Diag(Loc, diag::warn_division_sizeof_array) 9387 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9388 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9389 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9390 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9391 << LHSArgDecl; 9392 } 9393 9394 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9395 } 9396 } 9397 9398 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9399 ExprResult &RHS, 9400 SourceLocation Loc, bool IsDiv) { 9401 // Check for division/remainder by zero. 9402 Expr::EvalResult RHSValue; 9403 if (!RHS.get()->isValueDependent() && 9404 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9405 RHSValue.Val.getInt() == 0) 9406 S.DiagRuntimeBehavior(Loc, RHS.get(), 9407 S.PDiag(diag::warn_remainder_division_by_zero) 9408 << IsDiv << RHS.get()->getSourceRange()); 9409 } 9410 9411 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9412 SourceLocation Loc, 9413 bool IsCompAssign, bool IsDiv) { 9414 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9415 9416 if (LHS.get()->getType()->isVectorType() || 9417 RHS.get()->getType()->isVectorType()) 9418 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9419 /*AllowBothBool*/getLangOpts().AltiVec, 9420 /*AllowBoolConversions*/false); 9421 9422 QualType compType = UsualArithmeticConversions( 9423 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9424 if (LHS.isInvalid() || RHS.isInvalid()) 9425 return QualType(); 9426 9427 9428 if (compType.isNull() || !compType->isArithmeticType()) 9429 return InvalidOperands(Loc, LHS, RHS); 9430 if (IsDiv) { 9431 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9432 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9433 } 9434 return compType; 9435 } 9436 9437 QualType Sema::CheckRemainderOperands( 9438 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9439 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9440 9441 if (LHS.get()->getType()->isVectorType() || 9442 RHS.get()->getType()->isVectorType()) { 9443 if (LHS.get()->getType()->hasIntegerRepresentation() && 9444 RHS.get()->getType()->hasIntegerRepresentation()) 9445 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9446 /*AllowBothBool*/getLangOpts().AltiVec, 9447 /*AllowBoolConversions*/false); 9448 return InvalidOperands(Loc, LHS, RHS); 9449 } 9450 9451 QualType compType = UsualArithmeticConversions( 9452 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9453 if (LHS.isInvalid() || RHS.isInvalid()) 9454 return QualType(); 9455 9456 if (compType.isNull() || !compType->isIntegerType()) 9457 return InvalidOperands(Loc, LHS, RHS); 9458 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9459 return compType; 9460 } 9461 9462 /// Diagnose invalid arithmetic on two void pointers. 9463 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9464 Expr *LHSExpr, Expr *RHSExpr) { 9465 S.Diag(Loc, S.getLangOpts().CPlusPlus 9466 ? diag::err_typecheck_pointer_arith_void_type 9467 : diag::ext_gnu_void_ptr) 9468 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9469 << RHSExpr->getSourceRange(); 9470 } 9471 9472 /// Diagnose invalid arithmetic on a void pointer. 9473 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9474 Expr *Pointer) { 9475 S.Diag(Loc, S.getLangOpts().CPlusPlus 9476 ? diag::err_typecheck_pointer_arith_void_type 9477 : diag::ext_gnu_void_ptr) 9478 << 0 /* one pointer */ << Pointer->getSourceRange(); 9479 } 9480 9481 /// Diagnose invalid arithmetic on a null pointer. 9482 /// 9483 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9484 /// idiom, which we recognize as a GNU extension. 9485 /// 9486 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9487 Expr *Pointer, bool IsGNUIdiom) { 9488 if (IsGNUIdiom) 9489 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9490 << Pointer->getSourceRange(); 9491 else 9492 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9493 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9494 } 9495 9496 /// Diagnose invalid arithmetic on two function pointers. 9497 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9498 Expr *LHS, Expr *RHS) { 9499 assert(LHS->getType()->isAnyPointerType()); 9500 assert(RHS->getType()->isAnyPointerType()); 9501 S.Diag(Loc, S.getLangOpts().CPlusPlus 9502 ? diag::err_typecheck_pointer_arith_function_type 9503 : diag::ext_gnu_ptr_func_arith) 9504 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9505 // We only show the second type if it differs from the first. 9506 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9507 RHS->getType()) 9508 << RHS->getType()->getPointeeType() 9509 << LHS->getSourceRange() << RHS->getSourceRange(); 9510 } 9511 9512 /// Diagnose invalid arithmetic on a function pointer. 9513 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9514 Expr *Pointer) { 9515 assert(Pointer->getType()->isAnyPointerType()); 9516 S.Diag(Loc, S.getLangOpts().CPlusPlus 9517 ? diag::err_typecheck_pointer_arith_function_type 9518 : diag::ext_gnu_ptr_func_arith) 9519 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9520 << 0 /* one pointer, so only one type */ 9521 << Pointer->getSourceRange(); 9522 } 9523 9524 /// Emit error if Operand is incomplete pointer type 9525 /// 9526 /// \returns True if pointer has incomplete type 9527 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9528 Expr *Operand) { 9529 QualType ResType = Operand->getType(); 9530 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9531 ResType = ResAtomicType->getValueType(); 9532 9533 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9534 QualType PointeeTy = ResType->getPointeeType(); 9535 return S.RequireCompleteType(Loc, PointeeTy, 9536 diag::err_typecheck_arithmetic_incomplete_type, 9537 PointeeTy, Operand->getSourceRange()); 9538 } 9539 9540 /// Check the validity of an arithmetic pointer operand. 9541 /// 9542 /// If the operand has pointer type, this code will check for pointer types 9543 /// which are invalid in arithmetic operations. These will be diagnosed 9544 /// appropriately, including whether or not the use is supported as an 9545 /// extension. 9546 /// 9547 /// \returns True when the operand is valid to use (even if as an extension). 9548 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9549 Expr *Operand) { 9550 QualType ResType = Operand->getType(); 9551 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9552 ResType = ResAtomicType->getValueType(); 9553 9554 if (!ResType->isAnyPointerType()) return true; 9555 9556 QualType PointeeTy = ResType->getPointeeType(); 9557 if (PointeeTy->isVoidType()) { 9558 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9559 return !S.getLangOpts().CPlusPlus; 9560 } 9561 if (PointeeTy->isFunctionType()) { 9562 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9563 return !S.getLangOpts().CPlusPlus; 9564 } 9565 9566 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9567 9568 return true; 9569 } 9570 9571 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9572 /// operands. 9573 /// 9574 /// This routine will diagnose any invalid arithmetic on pointer operands much 9575 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9576 /// for emitting a single diagnostic even for operations where both LHS and RHS 9577 /// are (potentially problematic) pointers. 9578 /// 9579 /// \returns True when the operand is valid to use (even if as an extension). 9580 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9581 Expr *LHSExpr, Expr *RHSExpr) { 9582 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9583 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9584 if (!isLHSPointer && !isRHSPointer) return true; 9585 9586 QualType LHSPointeeTy, RHSPointeeTy; 9587 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9588 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9589 9590 // if both are pointers check if operation is valid wrt address spaces 9591 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9592 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9593 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9594 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9595 S.Diag(Loc, 9596 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9597 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9598 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9599 return false; 9600 } 9601 } 9602 9603 // Check for arithmetic on pointers to incomplete types. 9604 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9605 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9606 if (isLHSVoidPtr || isRHSVoidPtr) { 9607 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9608 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9609 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9610 9611 return !S.getLangOpts().CPlusPlus; 9612 } 9613 9614 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9615 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9616 if (isLHSFuncPtr || isRHSFuncPtr) { 9617 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9618 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9619 RHSExpr); 9620 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9621 9622 return !S.getLangOpts().CPlusPlus; 9623 } 9624 9625 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9626 return false; 9627 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9628 return false; 9629 9630 return true; 9631 } 9632 9633 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9634 /// literal. 9635 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9636 Expr *LHSExpr, Expr *RHSExpr) { 9637 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9638 Expr* IndexExpr = RHSExpr; 9639 if (!StrExpr) { 9640 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9641 IndexExpr = LHSExpr; 9642 } 9643 9644 bool IsStringPlusInt = StrExpr && 9645 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9646 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9647 return; 9648 9649 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9650 Self.Diag(OpLoc, diag::warn_string_plus_int) 9651 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9652 9653 // Only print a fixit for "str" + int, not for int + "str". 9654 if (IndexExpr == RHSExpr) { 9655 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9656 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9657 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9658 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9659 << FixItHint::CreateInsertion(EndLoc, "]"); 9660 } else 9661 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9662 } 9663 9664 /// Emit a warning when adding a char literal to a string. 9665 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9666 Expr *LHSExpr, Expr *RHSExpr) { 9667 const Expr *StringRefExpr = LHSExpr; 9668 const CharacterLiteral *CharExpr = 9669 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9670 9671 if (!CharExpr) { 9672 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9673 StringRefExpr = RHSExpr; 9674 } 9675 9676 if (!CharExpr || !StringRefExpr) 9677 return; 9678 9679 const QualType StringType = StringRefExpr->getType(); 9680 9681 // Return if not a PointerType. 9682 if (!StringType->isAnyPointerType()) 9683 return; 9684 9685 // Return if not a CharacterType. 9686 if (!StringType->getPointeeType()->isAnyCharacterType()) 9687 return; 9688 9689 ASTContext &Ctx = Self.getASTContext(); 9690 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9691 9692 const QualType CharType = CharExpr->getType(); 9693 if (!CharType->isAnyCharacterType() && 9694 CharType->isIntegerType() && 9695 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9696 Self.Diag(OpLoc, diag::warn_string_plus_char) 9697 << DiagRange << Ctx.CharTy; 9698 } else { 9699 Self.Diag(OpLoc, diag::warn_string_plus_char) 9700 << DiagRange << CharExpr->getType(); 9701 } 9702 9703 // Only print a fixit for str + char, not for char + str. 9704 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9705 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9706 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9707 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9708 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9709 << FixItHint::CreateInsertion(EndLoc, "]"); 9710 } else { 9711 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9712 } 9713 } 9714 9715 /// Emit error when two pointers are incompatible. 9716 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9717 Expr *LHSExpr, Expr *RHSExpr) { 9718 assert(LHSExpr->getType()->isAnyPointerType()); 9719 assert(RHSExpr->getType()->isAnyPointerType()); 9720 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9721 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9722 << RHSExpr->getSourceRange(); 9723 } 9724 9725 // C99 6.5.6 9726 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9727 SourceLocation Loc, BinaryOperatorKind Opc, 9728 QualType* CompLHSTy) { 9729 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9730 9731 if (LHS.get()->getType()->isVectorType() || 9732 RHS.get()->getType()->isVectorType()) { 9733 QualType compType = CheckVectorOperands( 9734 LHS, RHS, Loc, CompLHSTy, 9735 /*AllowBothBool*/getLangOpts().AltiVec, 9736 /*AllowBoolConversions*/getLangOpts().ZVector); 9737 if (CompLHSTy) *CompLHSTy = compType; 9738 return compType; 9739 } 9740 9741 QualType compType = UsualArithmeticConversions( 9742 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9743 if (LHS.isInvalid() || RHS.isInvalid()) 9744 return QualType(); 9745 9746 // Diagnose "string literal" '+' int and string '+' "char literal". 9747 if (Opc == BO_Add) { 9748 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9749 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9750 } 9751 9752 // handle the common case first (both operands are arithmetic). 9753 if (!compType.isNull() && compType->isArithmeticType()) { 9754 if (CompLHSTy) *CompLHSTy = compType; 9755 return compType; 9756 } 9757 9758 // Type-checking. Ultimately the pointer's going to be in PExp; 9759 // note that we bias towards the LHS being the pointer. 9760 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9761 9762 bool isObjCPointer; 9763 if (PExp->getType()->isPointerType()) { 9764 isObjCPointer = false; 9765 } else if (PExp->getType()->isObjCObjectPointerType()) { 9766 isObjCPointer = true; 9767 } else { 9768 std::swap(PExp, IExp); 9769 if (PExp->getType()->isPointerType()) { 9770 isObjCPointer = false; 9771 } else if (PExp->getType()->isObjCObjectPointerType()) { 9772 isObjCPointer = true; 9773 } else { 9774 return InvalidOperands(Loc, LHS, RHS); 9775 } 9776 } 9777 assert(PExp->getType()->isAnyPointerType()); 9778 9779 if (!IExp->getType()->isIntegerType()) 9780 return InvalidOperands(Loc, LHS, RHS); 9781 9782 // Adding to a null pointer results in undefined behavior. 9783 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9784 Context, Expr::NPC_ValueDependentIsNotNull)) { 9785 // In C++ adding zero to a null pointer is defined. 9786 Expr::EvalResult KnownVal; 9787 if (!getLangOpts().CPlusPlus || 9788 (!IExp->isValueDependent() && 9789 (!IExp->EvaluateAsInt(KnownVal, Context) || 9790 KnownVal.Val.getInt() != 0))) { 9791 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9792 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9793 Context, BO_Add, PExp, IExp); 9794 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9795 } 9796 } 9797 9798 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9799 return QualType(); 9800 9801 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9802 return QualType(); 9803 9804 // Check array bounds for pointer arithemtic 9805 CheckArrayAccess(PExp, IExp); 9806 9807 if (CompLHSTy) { 9808 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9809 if (LHSTy.isNull()) { 9810 LHSTy = LHS.get()->getType(); 9811 if (LHSTy->isPromotableIntegerType()) 9812 LHSTy = Context.getPromotedIntegerType(LHSTy); 9813 } 9814 *CompLHSTy = LHSTy; 9815 } 9816 9817 return PExp->getType(); 9818 } 9819 9820 // C99 6.5.6 9821 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9822 SourceLocation Loc, 9823 QualType* CompLHSTy) { 9824 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9825 9826 if (LHS.get()->getType()->isVectorType() || 9827 RHS.get()->getType()->isVectorType()) { 9828 QualType compType = CheckVectorOperands( 9829 LHS, RHS, Loc, CompLHSTy, 9830 /*AllowBothBool*/getLangOpts().AltiVec, 9831 /*AllowBoolConversions*/getLangOpts().ZVector); 9832 if (CompLHSTy) *CompLHSTy = compType; 9833 return compType; 9834 } 9835 9836 QualType compType = UsualArithmeticConversions( 9837 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9838 if (LHS.isInvalid() || RHS.isInvalid()) 9839 return QualType(); 9840 9841 // Enforce type constraints: C99 6.5.6p3. 9842 9843 // Handle the common case first (both operands are arithmetic). 9844 if (!compType.isNull() && compType->isArithmeticType()) { 9845 if (CompLHSTy) *CompLHSTy = compType; 9846 return compType; 9847 } 9848 9849 // Either ptr - int or ptr - ptr. 9850 if (LHS.get()->getType()->isAnyPointerType()) { 9851 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9852 9853 // Diagnose bad cases where we step over interface counts. 9854 if (LHS.get()->getType()->isObjCObjectPointerType() && 9855 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9856 return QualType(); 9857 9858 // The result type of a pointer-int computation is the pointer type. 9859 if (RHS.get()->getType()->isIntegerType()) { 9860 // Subtracting from a null pointer should produce a warning. 9861 // The last argument to the diagnose call says this doesn't match the 9862 // GNU int-to-pointer idiom. 9863 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9864 Expr::NPC_ValueDependentIsNotNull)) { 9865 // In C++ adding zero to a null pointer is defined. 9866 Expr::EvalResult KnownVal; 9867 if (!getLangOpts().CPlusPlus || 9868 (!RHS.get()->isValueDependent() && 9869 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9870 KnownVal.Val.getInt() != 0))) { 9871 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9872 } 9873 } 9874 9875 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9876 return QualType(); 9877 9878 // Check array bounds for pointer arithemtic 9879 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9880 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9881 9882 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9883 return LHS.get()->getType(); 9884 } 9885 9886 // Handle pointer-pointer subtractions. 9887 if (const PointerType *RHSPTy 9888 = RHS.get()->getType()->getAs<PointerType>()) { 9889 QualType rpointee = RHSPTy->getPointeeType(); 9890 9891 if (getLangOpts().CPlusPlus) { 9892 // Pointee types must be the same: C++ [expr.add] 9893 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9894 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9895 } 9896 } else { 9897 // Pointee types must be compatible C99 6.5.6p3 9898 if (!Context.typesAreCompatible( 9899 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9900 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9901 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9902 return QualType(); 9903 } 9904 } 9905 9906 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9907 LHS.get(), RHS.get())) 9908 return QualType(); 9909 9910 // FIXME: Add warnings for nullptr - ptr. 9911 9912 // The pointee type may have zero size. As an extension, a structure or 9913 // union may have zero size or an array may have zero length. In this 9914 // case subtraction does not make sense. 9915 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9916 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9917 if (ElementSize.isZero()) { 9918 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9919 << rpointee.getUnqualifiedType() 9920 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9921 } 9922 } 9923 9924 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9925 return Context.getPointerDiffType(); 9926 } 9927 } 9928 9929 return InvalidOperands(Loc, LHS, RHS); 9930 } 9931 9932 static bool isScopedEnumerationType(QualType T) { 9933 if (const EnumType *ET = T->getAs<EnumType>()) 9934 return ET->getDecl()->isScoped(); 9935 return false; 9936 } 9937 9938 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9939 SourceLocation Loc, BinaryOperatorKind Opc, 9940 QualType LHSType) { 9941 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9942 // so skip remaining warnings as we don't want to modify values within Sema. 9943 if (S.getLangOpts().OpenCL) 9944 return; 9945 9946 // Check right/shifter operand 9947 Expr::EvalResult RHSResult; 9948 if (RHS.get()->isValueDependent() || 9949 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9950 return; 9951 llvm::APSInt Right = RHSResult.Val.getInt(); 9952 9953 if (Right.isNegative()) { 9954 S.DiagRuntimeBehavior(Loc, RHS.get(), 9955 S.PDiag(diag::warn_shift_negative) 9956 << RHS.get()->getSourceRange()); 9957 return; 9958 } 9959 llvm::APInt LeftBits(Right.getBitWidth(), 9960 S.Context.getTypeSize(LHS.get()->getType())); 9961 if (Right.uge(LeftBits)) { 9962 S.DiagRuntimeBehavior(Loc, RHS.get(), 9963 S.PDiag(diag::warn_shift_gt_typewidth) 9964 << RHS.get()->getSourceRange()); 9965 return; 9966 } 9967 if (Opc != BO_Shl) 9968 return; 9969 9970 // When left shifting an ICE which is signed, we can check for overflow which 9971 // according to C++ standards prior to C++2a has undefined behavior 9972 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9973 // more than the maximum value representable in the result type, so never 9974 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9975 // expression is still probably a bug.) 9976 Expr::EvalResult LHSResult; 9977 if (LHS.get()->isValueDependent() || 9978 LHSType->hasUnsignedIntegerRepresentation() || 9979 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9980 return; 9981 llvm::APSInt Left = LHSResult.Val.getInt(); 9982 9983 // If LHS does not have a signed type and non-negative value 9984 // then, the behavior is undefined before C++2a. Warn about it. 9985 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9986 !S.getLangOpts().CPlusPlus2a) { 9987 S.DiagRuntimeBehavior(Loc, LHS.get(), 9988 S.PDiag(diag::warn_shift_lhs_negative) 9989 << LHS.get()->getSourceRange()); 9990 return; 9991 } 9992 9993 llvm::APInt ResultBits = 9994 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9995 if (LeftBits.uge(ResultBits)) 9996 return; 9997 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9998 Result = Result.shl(Right); 9999 10000 // Print the bit representation of the signed integer as an unsigned 10001 // hexadecimal number. 10002 SmallString<40> HexResult; 10003 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10004 10005 // If we are only missing a sign bit, this is less likely to result in actual 10006 // bugs -- if the result is cast back to an unsigned type, it will have the 10007 // expected value. Thus we place this behind a different warning that can be 10008 // turned off separately if needed. 10009 if (LeftBits == ResultBits - 1) { 10010 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10011 << HexResult << LHSType 10012 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10013 return; 10014 } 10015 10016 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10017 << HexResult.str() << Result.getMinSignedBits() << LHSType 10018 << Left.getBitWidth() << LHS.get()->getSourceRange() 10019 << RHS.get()->getSourceRange(); 10020 } 10021 10022 /// Return the resulting type when a vector is shifted 10023 /// by a scalar or vector shift amount. 10024 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10025 SourceLocation Loc, bool IsCompAssign) { 10026 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10027 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10028 !LHS.get()->getType()->isVectorType()) { 10029 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10030 << RHS.get()->getType() << LHS.get()->getType() 10031 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10032 return QualType(); 10033 } 10034 10035 if (!IsCompAssign) { 10036 LHS = S.UsualUnaryConversions(LHS.get()); 10037 if (LHS.isInvalid()) return QualType(); 10038 } 10039 10040 RHS = S.UsualUnaryConversions(RHS.get()); 10041 if (RHS.isInvalid()) return QualType(); 10042 10043 QualType LHSType = LHS.get()->getType(); 10044 // Note that LHS might be a scalar because the routine calls not only in 10045 // OpenCL case. 10046 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10047 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10048 10049 // Note that RHS might not be a vector. 10050 QualType RHSType = RHS.get()->getType(); 10051 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10052 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10053 10054 // The operands need to be integers. 10055 if (!LHSEleType->isIntegerType()) { 10056 S.Diag(Loc, diag::err_typecheck_expect_int) 10057 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10058 return QualType(); 10059 } 10060 10061 if (!RHSEleType->isIntegerType()) { 10062 S.Diag(Loc, diag::err_typecheck_expect_int) 10063 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10064 return QualType(); 10065 } 10066 10067 if (!LHSVecTy) { 10068 assert(RHSVecTy); 10069 if (IsCompAssign) 10070 return RHSType; 10071 if (LHSEleType != RHSEleType) { 10072 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10073 LHSEleType = RHSEleType; 10074 } 10075 QualType VecTy = 10076 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10077 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10078 LHSType = VecTy; 10079 } else if (RHSVecTy) { 10080 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10081 // are applied component-wise. So if RHS is a vector, then ensure 10082 // that the number of elements is the same as LHS... 10083 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10084 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10085 << LHS.get()->getType() << RHS.get()->getType() 10086 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10087 return QualType(); 10088 } 10089 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10090 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10091 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10092 if (LHSBT != RHSBT && 10093 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10094 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10095 << LHS.get()->getType() << RHS.get()->getType() 10096 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10097 } 10098 } 10099 } else { 10100 // ...else expand RHS to match the number of elements in LHS. 10101 QualType VecTy = 10102 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10103 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10104 } 10105 10106 return LHSType; 10107 } 10108 10109 // C99 6.5.7 10110 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10111 SourceLocation Loc, BinaryOperatorKind Opc, 10112 bool IsCompAssign) { 10113 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10114 10115 // Vector shifts promote their scalar inputs to vector type. 10116 if (LHS.get()->getType()->isVectorType() || 10117 RHS.get()->getType()->isVectorType()) { 10118 if (LangOpts.ZVector) { 10119 // The shift operators for the z vector extensions work basically 10120 // like general shifts, except that neither the LHS nor the RHS is 10121 // allowed to be a "vector bool". 10122 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10123 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10124 return InvalidOperands(Loc, LHS, RHS); 10125 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10126 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10127 return InvalidOperands(Loc, LHS, RHS); 10128 } 10129 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10130 } 10131 10132 // Shifts don't perform usual arithmetic conversions, they just do integer 10133 // promotions on each operand. C99 6.5.7p3 10134 10135 // For the LHS, do usual unary conversions, but then reset them away 10136 // if this is a compound assignment. 10137 ExprResult OldLHS = LHS; 10138 LHS = UsualUnaryConversions(LHS.get()); 10139 if (LHS.isInvalid()) 10140 return QualType(); 10141 QualType LHSType = LHS.get()->getType(); 10142 if (IsCompAssign) LHS = OldLHS; 10143 10144 // The RHS is simpler. 10145 RHS = UsualUnaryConversions(RHS.get()); 10146 if (RHS.isInvalid()) 10147 return QualType(); 10148 QualType RHSType = RHS.get()->getType(); 10149 10150 // C99 6.5.7p2: Each of the operands shall have integer type. 10151 if (!LHSType->hasIntegerRepresentation() || 10152 !RHSType->hasIntegerRepresentation()) 10153 return InvalidOperands(Loc, LHS, RHS); 10154 10155 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10156 // hasIntegerRepresentation() above instead of this. 10157 if (isScopedEnumerationType(LHSType) || 10158 isScopedEnumerationType(RHSType)) { 10159 return InvalidOperands(Loc, LHS, RHS); 10160 } 10161 // Sanity-check shift operands 10162 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10163 10164 // "The type of the result is that of the promoted left operand." 10165 return LHSType; 10166 } 10167 10168 /// Diagnose bad pointer comparisons. 10169 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10170 ExprResult &LHS, ExprResult &RHS, 10171 bool IsError) { 10172 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10173 : diag::ext_typecheck_comparison_of_distinct_pointers) 10174 << LHS.get()->getType() << RHS.get()->getType() 10175 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10176 } 10177 10178 /// Returns false if the pointers are converted to a composite type, 10179 /// true otherwise. 10180 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10181 ExprResult &LHS, ExprResult &RHS) { 10182 // C++ [expr.rel]p2: 10183 // [...] Pointer conversions (4.10) and qualification 10184 // conversions (4.4) are performed on pointer operands (or on 10185 // a pointer operand and a null pointer constant) to bring 10186 // them to their composite pointer type. [...] 10187 // 10188 // C++ [expr.eq]p1 uses the same notion for (in)equality 10189 // comparisons of pointers. 10190 10191 QualType LHSType = LHS.get()->getType(); 10192 QualType RHSType = RHS.get()->getType(); 10193 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10194 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10195 10196 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10197 if (T.isNull()) { 10198 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10199 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10200 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10201 else 10202 S.InvalidOperands(Loc, LHS, RHS); 10203 return true; 10204 } 10205 10206 return false; 10207 } 10208 10209 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10210 ExprResult &LHS, 10211 ExprResult &RHS, 10212 bool IsError) { 10213 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10214 : diag::ext_typecheck_comparison_of_fptr_to_void) 10215 << LHS.get()->getType() << RHS.get()->getType() 10216 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10217 } 10218 10219 static bool isObjCObjectLiteral(ExprResult &E) { 10220 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10221 case Stmt::ObjCArrayLiteralClass: 10222 case Stmt::ObjCDictionaryLiteralClass: 10223 case Stmt::ObjCStringLiteralClass: 10224 case Stmt::ObjCBoxedExprClass: 10225 return true; 10226 default: 10227 // Note that ObjCBoolLiteral is NOT an object literal! 10228 return false; 10229 } 10230 } 10231 10232 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10233 const ObjCObjectPointerType *Type = 10234 LHS->getType()->getAs<ObjCObjectPointerType>(); 10235 10236 // If this is not actually an Objective-C object, bail out. 10237 if (!Type) 10238 return false; 10239 10240 // Get the LHS object's interface type. 10241 QualType InterfaceType = Type->getPointeeType(); 10242 10243 // If the RHS isn't an Objective-C object, bail out. 10244 if (!RHS->getType()->isObjCObjectPointerType()) 10245 return false; 10246 10247 // Try to find the -isEqual: method. 10248 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10249 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10250 InterfaceType, 10251 /*IsInstance=*/true); 10252 if (!Method) { 10253 if (Type->isObjCIdType()) { 10254 // For 'id', just check the global pool. 10255 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10256 /*receiverId=*/true); 10257 } else { 10258 // Check protocols. 10259 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10260 /*IsInstance=*/true); 10261 } 10262 } 10263 10264 if (!Method) 10265 return false; 10266 10267 QualType T = Method->parameters()[0]->getType(); 10268 if (!T->isObjCObjectPointerType()) 10269 return false; 10270 10271 QualType R = Method->getReturnType(); 10272 if (!R->isScalarType()) 10273 return false; 10274 10275 return true; 10276 } 10277 10278 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10279 FromE = FromE->IgnoreParenImpCasts(); 10280 switch (FromE->getStmtClass()) { 10281 default: 10282 break; 10283 case Stmt::ObjCStringLiteralClass: 10284 // "string literal" 10285 return LK_String; 10286 case Stmt::ObjCArrayLiteralClass: 10287 // "array literal" 10288 return LK_Array; 10289 case Stmt::ObjCDictionaryLiteralClass: 10290 // "dictionary literal" 10291 return LK_Dictionary; 10292 case Stmt::BlockExprClass: 10293 return LK_Block; 10294 case Stmt::ObjCBoxedExprClass: { 10295 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10296 switch (Inner->getStmtClass()) { 10297 case Stmt::IntegerLiteralClass: 10298 case Stmt::FloatingLiteralClass: 10299 case Stmt::CharacterLiteralClass: 10300 case Stmt::ObjCBoolLiteralExprClass: 10301 case Stmt::CXXBoolLiteralExprClass: 10302 // "numeric literal" 10303 return LK_Numeric; 10304 case Stmt::ImplicitCastExprClass: { 10305 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10306 // Boolean literals can be represented by implicit casts. 10307 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10308 return LK_Numeric; 10309 break; 10310 } 10311 default: 10312 break; 10313 } 10314 return LK_Boxed; 10315 } 10316 } 10317 return LK_None; 10318 } 10319 10320 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10321 ExprResult &LHS, ExprResult &RHS, 10322 BinaryOperator::Opcode Opc){ 10323 Expr *Literal; 10324 Expr *Other; 10325 if (isObjCObjectLiteral(LHS)) { 10326 Literal = LHS.get(); 10327 Other = RHS.get(); 10328 } else { 10329 Literal = RHS.get(); 10330 Other = LHS.get(); 10331 } 10332 10333 // Don't warn on comparisons against nil. 10334 Other = Other->IgnoreParenCasts(); 10335 if (Other->isNullPointerConstant(S.getASTContext(), 10336 Expr::NPC_ValueDependentIsNotNull)) 10337 return; 10338 10339 // This should be kept in sync with warn_objc_literal_comparison. 10340 // LK_String should always be after the other literals, since it has its own 10341 // warning flag. 10342 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10343 assert(LiteralKind != Sema::LK_Block); 10344 if (LiteralKind == Sema::LK_None) { 10345 llvm_unreachable("Unknown Objective-C object literal kind"); 10346 } 10347 10348 if (LiteralKind == Sema::LK_String) 10349 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10350 << Literal->getSourceRange(); 10351 else 10352 S.Diag(Loc, diag::warn_objc_literal_comparison) 10353 << LiteralKind << Literal->getSourceRange(); 10354 10355 if (BinaryOperator::isEqualityOp(Opc) && 10356 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10357 SourceLocation Start = LHS.get()->getBeginLoc(); 10358 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10359 CharSourceRange OpRange = 10360 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10361 10362 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10363 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10364 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10365 << FixItHint::CreateInsertion(End, "]"); 10366 } 10367 } 10368 10369 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10370 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10371 ExprResult &RHS, SourceLocation Loc, 10372 BinaryOperatorKind Opc) { 10373 // Check that left hand side is !something. 10374 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10375 if (!UO || UO->getOpcode() != UO_LNot) return; 10376 10377 // Only check if the right hand side is non-bool arithmetic type. 10378 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10379 10380 // Make sure that the something in !something is not bool. 10381 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10382 if (SubExpr->isKnownToHaveBooleanValue()) return; 10383 10384 // Emit warning. 10385 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10386 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10387 << Loc << IsBitwiseOp; 10388 10389 // First note suggest !(x < y) 10390 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10391 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10392 FirstClose = S.getLocForEndOfToken(FirstClose); 10393 if (FirstClose.isInvalid()) 10394 FirstOpen = SourceLocation(); 10395 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10396 << IsBitwiseOp 10397 << FixItHint::CreateInsertion(FirstOpen, "(") 10398 << FixItHint::CreateInsertion(FirstClose, ")"); 10399 10400 // Second note suggests (!x) < y 10401 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10402 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10403 SecondClose = S.getLocForEndOfToken(SecondClose); 10404 if (SecondClose.isInvalid()) 10405 SecondOpen = SourceLocation(); 10406 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10407 << FixItHint::CreateInsertion(SecondOpen, "(") 10408 << FixItHint::CreateInsertion(SecondClose, ")"); 10409 } 10410 10411 // Returns true if E refers to a non-weak array. 10412 static bool checkForArray(const Expr *E) { 10413 const ValueDecl *D = nullptr; 10414 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10415 D = DR->getDecl(); 10416 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10417 if (Mem->isImplicitAccess()) 10418 D = Mem->getMemberDecl(); 10419 } 10420 if (!D) 10421 return false; 10422 return D->getType()->isArrayType() && !D->isWeak(); 10423 } 10424 10425 /// Diagnose some forms of syntactically-obvious tautological comparison. 10426 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10427 Expr *LHS, Expr *RHS, 10428 BinaryOperatorKind Opc) { 10429 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10430 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10431 10432 QualType LHSType = LHS->getType(); 10433 QualType RHSType = RHS->getType(); 10434 if (LHSType->hasFloatingRepresentation() || 10435 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10436 S.inTemplateInstantiation()) 10437 return; 10438 10439 // Comparisons between two array types are ill-formed for operator<=>, so 10440 // we shouldn't emit any additional warnings about it. 10441 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10442 return; 10443 10444 // For non-floating point types, check for self-comparisons of the form 10445 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10446 // often indicate logic errors in the program. 10447 // 10448 // NOTE: Don't warn about comparison expressions resulting from macro 10449 // expansion. Also don't warn about comparisons which are only self 10450 // comparisons within a template instantiation. The warnings should catch 10451 // obvious cases in the definition of the template anyways. The idea is to 10452 // warn when the typed comparison operator will always evaluate to the same 10453 // result. 10454 10455 // Used for indexing into %select in warn_comparison_always 10456 enum { 10457 AlwaysConstant, 10458 AlwaysTrue, 10459 AlwaysFalse, 10460 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10461 }; 10462 10463 // C++2a [depr.array.comp]: 10464 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10465 // operands of array type are deprecated. 10466 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10467 RHSStripped->getType()->isArrayType()) { 10468 S.Diag(Loc, diag::warn_depr_array_comparison) 10469 << LHS->getSourceRange() << RHS->getSourceRange() 10470 << LHSStripped->getType() << RHSStripped->getType(); 10471 // Carry on to produce the tautological comparison warning, if this 10472 // expression is potentially-evaluated, we can resolve the array to a 10473 // non-weak declaration, and so on. 10474 } 10475 10476 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10477 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10478 unsigned Result; 10479 switch (Opc) { 10480 case BO_EQ: 10481 case BO_LE: 10482 case BO_GE: 10483 Result = AlwaysTrue; 10484 break; 10485 case BO_NE: 10486 case BO_LT: 10487 case BO_GT: 10488 Result = AlwaysFalse; 10489 break; 10490 case BO_Cmp: 10491 Result = AlwaysEqual; 10492 break; 10493 default: 10494 Result = AlwaysConstant; 10495 break; 10496 } 10497 S.DiagRuntimeBehavior(Loc, nullptr, 10498 S.PDiag(diag::warn_comparison_always) 10499 << 0 /*self-comparison*/ 10500 << Result); 10501 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10502 // What is it always going to evaluate to? 10503 unsigned Result; 10504 switch (Opc) { 10505 case BO_EQ: // e.g. array1 == array2 10506 Result = AlwaysFalse; 10507 break; 10508 case BO_NE: // e.g. array1 != array2 10509 Result = AlwaysTrue; 10510 break; 10511 default: // e.g. array1 <= array2 10512 // The best we can say is 'a constant' 10513 Result = AlwaysConstant; 10514 break; 10515 } 10516 S.DiagRuntimeBehavior(Loc, nullptr, 10517 S.PDiag(diag::warn_comparison_always) 10518 << 1 /*array comparison*/ 10519 << Result); 10520 } 10521 } 10522 10523 if (isa<CastExpr>(LHSStripped)) 10524 LHSStripped = LHSStripped->IgnoreParenCasts(); 10525 if (isa<CastExpr>(RHSStripped)) 10526 RHSStripped = RHSStripped->IgnoreParenCasts(); 10527 10528 // Warn about comparisons against a string constant (unless the other 10529 // operand is null); the user probably wants string comparison function. 10530 Expr *LiteralString = nullptr; 10531 Expr *LiteralStringStripped = nullptr; 10532 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10533 !RHSStripped->isNullPointerConstant(S.Context, 10534 Expr::NPC_ValueDependentIsNull)) { 10535 LiteralString = LHS; 10536 LiteralStringStripped = LHSStripped; 10537 } else if ((isa<StringLiteral>(RHSStripped) || 10538 isa<ObjCEncodeExpr>(RHSStripped)) && 10539 !LHSStripped->isNullPointerConstant(S.Context, 10540 Expr::NPC_ValueDependentIsNull)) { 10541 LiteralString = RHS; 10542 LiteralStringStripped = RHSStripped; 10543 } 10544 10545 if (LiteralString) { 10546 S.DiagRuntimeBehavior(Loc, nullptr, 10547 S.PDiag(diag::warn_stringcompare) 10548 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10549 << LiteralString->getSourceRange()); 10550 } 10551 } 10552 10553 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10554 switch (CK) { 10555 default: { 10556 #ifndef NDEBUG 10557 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10558 << "\n"; 10559 #endif 10560 llvm_unreachable("unhandled cast kind"); 10561 } 10562 case CK_UserDefinedConversion: 10563 return ICK_Identity; 10564 case CK_LValueToRValue: 10565 return ICK_Lvalue_To_Rvalue; 10566 case CK_ArrayToPointerDecay: 10567 return ICK_Array_To_Pointer; 10568 case CK_FunctionToPointerDecay: 10569 return ICK_Function_To_Pointer; 10570 case CK_IntegralCast: 10571 return ICK_Integral_Conversion; 10572 case CK_FloatingCast: 10573 return ICK_Floating_Conversion; 10574 case CK_IntegralToFloating: 10575 case CK_FloatingToIntegral: 10576 return ICK_Floating_Integral; 10577 case CK_IntegralComplexCast: 10578 case CK_FloatingComplexCast: 10579 case CK_FloatingComplexToIntegralComplex: 10580 case CK_IntegralComplexToFloatingComplex: 10581 return ICK_Complex_Conversion; 10582 case CK_FloatingComplexToReal: 10583 case CK_FloatingRealToComplex: 10584 case CK_IntegralComplexToReal: 10585 case CK_IntegralRealToComplex: 10586 return ICK_Complex_Real; 10587 } 10588 } 10589 10590 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10591 QualType FromType, 10592 SourceLocation Loc) { 10593 // Check for a narrowing implicit conversion. 10594 StandardConversionSequence SCS; 10595 SCS.setAsIdentityConversion(); 10596 SCS.setToType(0, FromType); 10597 SCS.setToType(1, ToType); 10598 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10599 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10600 10601 APValue PreNarrowingValue; 10602 QualType PreNarrowingType; 10603 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10604 PreNarrowingType, 10605 /*IgnoreFloatToIntegralConversion*/ true)) { 10606 case NK_Dependent_Narrowing: 10607 // Implicit conversion to a narrower type, but the expression is 10608 // value-dependent so we can't tell whether it's actually narrowing. 10609 case NK_Not_Narrowing: 10610 return false; 10611 10612 case NK_Constant_Narrowing: 10613 // Implicit conversion to a narrower type, and the value is not a constant 10614 // expression. 10615 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10616 << /*Constant*/ 1 10617 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10618 return true; 10619 10620 case NK_Variable_Narrowing: 10621 // Implicit conversion to a narrower type, and the value is not a constant 10622 // expression. 10623 case NK_Type_Narrowing: 10624 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10625 << /*Constant*/ 0 << FromType << ToType; 10626 // TODO: It's not a constant expression, but what if the user intended it 10627 // to be? Can we produce notes to help them figure out why it isn't? 10628 return true; 10629 } 10630 llvm_unreachable("unhandled case in switch"); 10631 } 10632 10633 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10634 ExprResult &LHS, 10635 ExprResult &RHS, 10636 SourceLocation Loc) { 10637 QualType LHSType = LHS.get()->getType(); 10638 QualType RHSType = RHS.get()->getType(); 10639 // Dig out the original argument type and expression before implicit casts 10640 // were applied. These are the types/expressions we need to check the 10641 // [expr.spaceship] requirements against. 10642 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10643 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10644 QualType LHSStrippedType = LHSStripped.get()->getType(); 10645 QualType RHSStrippedType = RHSStripped.get()->getType(); 10646 10647 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10648 // other is not, the program is ill-formed. 10649 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10650 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10651 return QualType(); 10652 } 10653 10654 // FIXME: Consider combining this with checkEnumArithmeticConversions. 10655 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10656 RHSStrippedType->isEnumeralType(); 10657 if (NumEnumArgs == 1) { 10658 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10659 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10660 if (OtherTy->hasFloatingRepresentation()) { 10661 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10662 return QualType(); 10663 } 10664 } 10665 if (NumEnumArgs == 2) { 10666 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10667 // type E, the operator yields the result of converting the operands 10668 // to the underlying type of E and applying <=> to the converted operands. 10669 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10670 S.InvalidOperands(Loc, LHS, RHS); 10671 return QualType(); 10672 } 10673 QualType IntType = 10674 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10675 assert(IntType->isArithmeticType()); 10676 10677 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10678 // promote the boolean type, and all other promotable integer types, to 10679 // avoid this. 10680 if (IntType->isPromotableIntegerType()) 10681 IntType = S.Context.getPromotedIntegerType(IntType); 10682 10683 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10684 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10685 LHSType = RHSType = IntType; 10686 } 10687 10688 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10689 // usual arithmetic conversions are applied to the operands. 10690 QualType Type = 10691 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10692 if (LHS.isInvalid() || RHS.isInvalid()) 10693 return QualType(); 10694 if (Type.isNull()) 10695 return S.InvalidOperands(Loc, LHS, RHS); 10696 10697 Optional<ComparisonCategoryType> CCT = 10698 getComparisonCategoryForBuiltinCmp(Type); 10699 if (!CCT) 10700 return S.InvalidOperands(Loc, LHS, RHS); 10701 10702 bool HasNarrowing = checkThreeWayNarrowingConversion( 10703 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10704 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10705 RHS.get()->getBeginLoc()); 10706 if (HasNarrowing) 10707 return QualType(); 10708 10709 assert(!Type.isNull() && "composite type for <=> has not been set"); 10710 10711 return S.CheckComparisonCategoryType( 10712 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 10713 } 10714 10715 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10716 ExprResult &RHS, 10717 SourceLocation Loc, 10718 BinaryOperatorKind Opc) { 10719 if (Opc == BO_Cmp) 10720 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10721 10722 // C99 6.5.8p3 / C99 6.5.9p4 10723 QualType Type = 10724 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10725 if (LHS.isInvalid() || RHS.isInvalid()) 10726 return QualType(); 10727 if (Type.isNull()) 10728 return S.InvalidOperands(Loc, LHS, RHS); 10729 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10730 10731 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10732 return S.InvalidOperands(Loc, LHS, RHS); 10733 10734 // Check for comparisons of floating point operands using != and ==. 10735 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10736 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10737 10738 // The result of comparisons is 'bool' in C++, 'int' in C. 10739 return S.Context.getLogicalOperationType(); 10740 } 10741 10742 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10743 if (!NullE.get()->getType()->isAnyPointerType()) 10744 return; 10745 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10746 if (!E.get()->getType()->isAnyPointerType() && 10747 E.get()->isNullPointerConstant(Context, 10748 Expr::NPC_ValueDependentIsNotNull) == 10749 Expr::NPCK_ZeroExpression) { 10750 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10751 if (CL->getValue() == 0) 10752 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10753 << NullValue 10754 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10755 NullValue ? "NULL" : "(void *)0"); 10756 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10757 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10758 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10759 if (T == Context.CharTy) 10760 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10761 << NullValue 10762 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10763 NullValue ? "NULL" : "(void *)0"); 10764 } 10765 } 10766 } 10767 10768 // C99 6.5.8, C++ [expr.rel] 10769 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10770 SourceLocation Loc, 10771 BinaryOperatorKind Opc) { 10772 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10773 bool IsThreeWay = Opc == BO_Cmp; 10774 bool IsOrdered = IsRelational || IsThreeWay; 10775 auto IsAnyPointerType = [](ExprResult E) { 10776 QualType Ty = E.get()->getType(); 10777 return Ty->isPointerType() || Ty->isMemberPointerType(); 10778 }; 10779 10780 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10781 // type, array-to-pointer, ..., conversions are performed on both operands to 10782 // bring them to their composite type. 10783 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10784 // any type-related checks. 10785 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10786 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10787 if (LHS.isInvalid()) 10788 return QualType(); 10789 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10790 if (RHS.isInvalid()) 10791 return QualType(); 10792 } else { 10793 LHS = DefaultLvalueConversion(LHS.get()); 10794 if (LHS.isInvalid()) 10795 return QualType(); 10796 RHS = DefaultLvalueConversion(RHS.get()); 10797 if (RHS.isInvalid()) 10798 return QualType(); 10799 } 10800 10801 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10802 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10803 CheckPtrComparisonWithNullChar(LHS, RHS); 10804 CheckPtrComparisonWithNullChar(RHS, LHS); 10805 } 10806 10807 // Handle vector comparisons separately. 10808 if (LHS.get()->getType()->isVectorType() || 10809 RHS.get()->getType()->isVectorType()) 10810 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10811 10812 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10813 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10814 10815 QualType LHSType = LHS.get()->getType(); 10816 QualType RHSType = RHS.get()->getType(); 10817 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10818 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10819 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10820 10821 const Expr::NullPointerConstantKind LHSNullKind = 10822 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10823 const Expr::NullPointerConstantKind RHSNullKind = 10824 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10825 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10826 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10827 10828 auto computeResultTy = [&]() { 10829 if (Opc != BO_Cmp) 10830 return Context.getLogicalOperationType(); 10831 assert(getLangOpts().CPlusPlus); 10832 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10833 10834 QualType CompositeTy = LHS.get()->getType(); 10835 assert(!CompositeTy->isReferenceType()); 10836 10837 Optional<ComparisonCategoryType> CCT = 10838 getComparisonCategoryForBuiltinCmp(CompositeTy); 10839 if (!CCT) 10840 return InvalidOperands(Loc, LHS, RHS); 10841 10842 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 10843 // P0946R0: Comparisons between a null pointer constant and an object 10844 // pointer result in std::strong_equality, which is ill-formed under 10845 // P1959R0. 10846 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 10847 << (LHSIsNull ? LHS.get()->getSourceRange() 10848 : RHS.get()->getSourceRange()); 10849 return QualType(); 10850 } 10851 10852 return CheckComparisonCategoryType( 10853 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 10854 }; 10855 10856 if (!IsOrdered && LHSIsNull != RHSIsNull) { 10857 bool IsEquality = Opc == BO_EQ; 10858 if (RHSIsNull) 10859 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10860 RHS.get()->getSourceRange()); 10861 else 10862 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10863 LHS.get()->getSourceRange()); 10864 } 10865 10866 if ((LHSType->isIntegerType() && !LHSIsNull) || 10867 (RHSType->isIntegerType() && !RHSIsNull)) { 10868 // Skip normal pointer conversion checks in this case; we have better 10869 // diagnostics for this below. 10870 } else if (getLangOpts().CPlusPlus) { 10871 // Equality comparison of a function pointer to a void pointer is invalid, 10872 // but we allow it as an extension. 10873 // FIXME: If we really want to allow this, should it be part of composite 10874 // pointer type computation so it works in conditionals too? 10875 if (!IsOrdered && 10876 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10877 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10878 // This is a gcc extension compatibility comparison. 10879 // In a SFINAE context, we treat this as a hard error to maintain 10880 // conformance with the C++ standard. 10881 diagnoseFunctionPointerToVoidComparison( 10882 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10883 10884 if (isSFINAEContext()) 10885 return QualType(); 10886 10887 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10888 return computeResultTy(); 10889 } 10890 10891 // C++ [expr.eq]p2: 10892 // If at least one operand is a pointer [...] bring them to their 10893 // composite pointer type. 10894 // C++ [expr.spaceship]p6 10895 // If at least one of the operands is of pointer type, [...] bring them 10896 // to their composite pointer type. 10897 // C++ [expr.rel]p2: 10898 // If both operands are pointers, [...] bring them to their composite 10899 // pointer type. 10900 // For <=>, the only valid non-pointer types are arrays and functions, and 10901 // we already decayed those, so this is really the same as the relational 10902 // comparison rule. 10903 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10904 (IsOrdered ? 2 : 1) && 10905 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10906 RHSType->isObjCObjectPointerType()))) { 10907 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10908 return QualType(); 10909 return computeResultTy(); 10910 } 10911 } else if (LHSType->isPointerType() && 10912 RHSType->isPointerType()) { // C99 6.5.8p2 10913 // All of the following pointer-related warnings are GCC extensions, except 10914 // when handling null pointer constants. 10915 QualType LCanPointeeTy = 10916 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10917 QualType RCanPointeeTy = 10918 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10919 10920 // C99 6.5.9p2 and C99 6.5.8p2 10921 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10922 RCanPointeeTy.getUnqualifiedType())) { 10923 // Valid unless a relational comparison of function pointers 10924 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10925 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10926 << LHSType << RHSType << LHS.get()->getSourceRange() 10927 << RHS.get()->getSourceRange(); 10928 } 10929 } else if (!IsRelational && 10930 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10931 // Valid unless comparison between non-null pointer and function pointer 10932 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10933 && !LHSIsNull && !RHSIsNull) 10934 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10935 /*isError*/false); 10936 } else { 10937 // Invalid 10938 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10939 } 10940 if (LCanPointeeTy != RCanPointeeTy) { 10941 // Treat NULL constant as a special case in OpenCL. 10942 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10943 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10944 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10945 Diag(Loc, 10946 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10947 << LHSType << RHSType << 0 /* comparison */ 10948 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10949 } 10950 } 10951 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10952 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10953 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10954 : CK_BitCast; 10955 if (LHSIsNull && !RHSIsNull) 10956 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10957 else 10958 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10959 } 10960 return computeResultTy(); 10961 } 10962 10963 if (getLangOpts().CPlusPlus) { 10964 // C++ [expr.eq]p4: 10965 // Two operands of type std::nullptr_t or one operand of type 10966 // std::nullptr_t and the other a null pointer constant compare equal. 10967 if (!IsOrdered && LHSIsNull && RHSIsNull) { 10968 if (LHSType->isNullPtrType()) { 10969 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10970 return computeResultTy(); 10971 } 10972 if (RHSType->isNullPtrType()) { 10973 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10974 return computeResultTy(); 10975 } 10976 } 10977 10978 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10979 // These aren't covered by the composite pointer type rules. 10980 if (!IsOrdered && RHSType->isNullPtrType() && 10981 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10982 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10983 return computeResultTy(); 10984 } 10985 if (!IsOrdered && LHSType->isNullPtrType() && 10986 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10987 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10988 return computeResultTy(); 10989 } 10990 10991 if (IsRelational && 10992 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10993 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10994 // HACK: Relational comparison of nullptr_t against a pointer type is 10995 // invalid per DR583, but we allow it within std::less<> and friends, 10996 // since otherwise common uses of it break. 10997 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10998 // friends to have std::nullptr_t overload candidates. 10999 DeclContext *DC = CurContext; 11000 if (isa<FunctionDecl>(DC)) 11001 DC = DC->getParent(); 11002 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11003 if (CTSD->isInStdNamespace() && 11004 llvm::StringSwitch<bool>(CTSD->getName()) 11005 .Cases("less", "less_equal", "greater", "greater_equal", true) 11006 .Default(false)) { 11007 if (RHSType->isNullPtrType()) 11008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11009 else 11010 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11011 return computeResultTy(); 11012 } 11013 } 11014 } 11015 11016 // C++ [expr.eq]p2: 11017 // If at least one operand is a pointer to member, [...] bring them to 11018 // their composite pointer type. 11019 if (!IsOrdered && 11020 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11021 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11022 return QualType(); 11023 else 11024 return computeResultTy(); 11025 } 11026 } 11027 11028 // Handle block pointer types. 11029 if (!IsOrdered && LHSType->isBlockPointerType() && 11030 RHSType->isBlockPointerType()) { 11031 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11032 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11033 11034 if (!LHSIsNull && !RHSIsNull && 11035 !Context.typesAreCompatible(lpointee, rpointee)) { 11036 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11037 << LHSType << RHSType << LHS.get()->getSourceRange() 11038 << RHS.get()->getSourceRange(); 11039 } 11040 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11041 return computeResultTy(); 11042 } 11043 11044 // Allow block pointers to be compared with null pointer constants. 11045 if (!IsOrdered 11046 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11047 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11048 if (!LHSIsNull && !RHSIsNull) { 11049 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11050 ->getPointeeType()->isVoidType()) 11051 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11052 ->getPointeeType()->isVoidType()))) 11053 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11054 << LHSType << RHSType << LHS.get()->getSourceRange() 11055 << RHS.get()->getSourceRange(); 11056 } 11057 if (LHSIsNull && !RHSIsNull) 11058 LHS = ImpCastExprToType(LHS.get(), RHSType, 11059 RHSType->isPointerType() ? CK_BitCast 11060 : CK_AnyPointerToBlockPointerCast); 11061 else 11062 RHS = ImpCastExprToType(RHS.get(), LHSType, 11063 LHSType->isPointerType() ? CK_BitCast 11064 : CK_AnyPointerToBlockPointerCast); 11065 return computeResultTy(); 11066 } 11067 11068 if (LHSType->isObjCObjectPointerType() || 11069 RHSType->isObjCObjectPointerType()) { 11070 const PointerType *LPT = LHSType->getAs<PointerType>(); 11071 const PointerType *RPT = RHSType->getAs<PointerType>(); 11072 if (LPT || RPT) { 11073 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11074 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11075 11076 if (!LPtrToVoid && !RPtrToVoid && 11077 !Context.typesAreCompatible(LHSType, RHSType)) { 11078 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11079 /*isError*/false); 11080 } 11081 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11082 // the RHS, but we have test coverage for this behavior. 11083 // FIXME: Consider using convertPointersToCompositeType in C++. 11084 if (LHSIsNull && !RHSIsNull) { 11085 Expr *E = LHS.get(); 11086 if (getLangOpts().ObjCAutoRefCount) 11087 CheckObjCConversion(SourceRange(), RHSType, E, 11088 CCK_ImplicitConversion); 11089 LHS = ImpCastExprToType(E, RHSType, 11090 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11091 } 11092 else { 11093 Expr *E = RHS.get(); 11094 if (getLangOpts().ObjCAutoRefCount) 11095 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11096 /*Diagnose=*/true, 11097 /*DiagnoseCFAudited=*/false, Opc); 11098 RHS = ImpCastExprToType(E, LHSType, 11099 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11100 } 11101 return computeResultTy(); 11102 } 11103 if (LHSType->isObjCObjectPointerType() && 11104 RHSType->isObjCObjectPointerType()) { 11105 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11106 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11107 /*isError*/false); 11108 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11109 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11110 11111 if (LHSIsNull && !RHSIsNull) 11112 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11113 else 11114 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11115 return computeResultTy(); 11116 } 11117 11118 if (!IsOrdered && LHSType->isBlockPointerType() && 11119 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11120 LHS = ImpCastExprToType(LHS.get(), RHSType, 11121 CK_BlockPointerToObjCPointerCast); 11122 return computeResultTy(); 11123 } else if (!IsOrdered && 11124 LHSType->isBlockCompatibleObjCPointerType(Context) && 11125 RHSType->isBlockPointerType()) { 11126 RHS = ImpCastExprToType(RHS.get(), LHSType, 11127 CK_BlockPointerToObjCPointerCast); 11128 return computeResultTy(); 11129 } 11130 } 11131 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11132 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11133 unsigned DiagID = 0; 11134 bool isError = false; 11135 if (LangOpts.DebuggerSupport) { 11136 // Under a debugger, allow the comparison of pointers to integers, 11137 // since users tend to want to compare addresses. 11138 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11139 (RHSIsNull && RHSType->isIntegerType())) { 11140 if (IsOrdered) { 11141 isError = getLangOpts().CPlusPlus; 11142 DiagID = 11143 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11144 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11145 } 11146 } else if (getLangOpts().CPlusPlus) { 11147 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11148 isError = true; 11149 } else if (IsOrdered) 11150 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11151 else 11152 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11153 11154 if (DiagID) { 11155 Diag(Loc, DiagID) 11156 << LHSType << RHSType << LHS.get()->getSourceRange() 11157 << RHS.get()->getSourceRange(); 11158 if (isError) 11159 return QualType(); 11160 } 11161 11162 if (LHSType->isIntegerType()) 11163 LHS = ImpCastExprToType(LHS.get(), RHSType, 11164 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11165 else 11166 RHS = ImpCastExprToType(RHS.get(), LHSType, 11167 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11168 return computeResultTy(); 11169 } 11170 11171 // Handle block pointers. 11172 if (!IsOrdered && RHSIsNull 11173 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11174 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11175 return computeResultTy(); 11176 } 11177 if (!IsOrdered && LHSIsNull 11178 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11179 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11180 return computeResultTy(); 11181 } 11182 11183 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11184 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11185 return computeResultTy(); 11186 } 11187 11188 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11189 return computeResultTy(); 11190 } 11191 11192 if (LHSIsNull && RHSType->isQueueT()) { 11193 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11194 return computeResultTy(); 11195 } 11196 11197 if (LHSType->isQueueT() && RHSIsNull) { 11198 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11199 return computeResultTy(); 11200 } 11201 } 11202 11203 return InvalidOperands(Loc, LHS, RHS); 11204 } 11205 11206 // Return a signed ext_vector_type that is of identical size and number of 11207 // elements. For floating point vectors, return an integer type of identical 11208 // size and number of elements. In the non ext_vector_type case, search from 11209 // the largest type to the smallest type to avoid cases where long long == long, 11210 // where long gets picked over long long. 11211 QualType Sema::GetSignedVectorType(QualType V) { 11212 const VectorType *VTy = V->castAs<VectorType>(); 11213 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11214 11215 if (isa<ExtVectorType>(VTy)) { 11216 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11217 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11218 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11219 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11220 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11221 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11222 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11223 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11224 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11225 "Unhandled vector element size in vector compare"); 11226 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11227 } 11228 11229 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11230 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11231 VectorType::GenericVector); 11232 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11233 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11234 VectorType::GenericVector); 11235 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11236 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11237 VectorType::GenericVector); 11238 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11239 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11240 VectorType::GenericVector); 11241 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11242 "Unhandled vector element size in vector compare"); 11243 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11244 VectorType::GenericVector); 11245 } 11246 11247 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11248 /// operates on extended vector types. Instead of producing an IntTy result, 11249 /// like a scalar comparison, a vector comparison produces a vector of integer 11250 /// types. 11251 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11252 SourceLocation Loc, 11253 BinaryOperatorKind Opc) { 11254 if (Opc == BO_Cmp) { 11255 Diag(Loc, diag::err_three_way_vector_comparison); 11256 return QualType(); 11257 } 11258 11259 // Check to make sure we're operating on vectors of the same type and width, 11260 // Allowing one side to be a scalar of element type. 11261 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11262 /*AllowBothBool*/true, 11263 /*AllowBoolConversions*/getLangOpts().ZVector); 11264 if (vType.isNull()) 11265 return vType; 11266 11267 QualType LHSType = LHS.get()->getType(); 11268 11269 // If AltiVec, the comparison results in a numeric type, i.e. 11270 // bool for C++, int for C 11271 if (getLangOpts().AltiVec && 11272 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11273 return Context.getLogicalOperationType(); 11274 11275 // For non-floating point types, check for self-comparisons of the form 11276 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11277 // often indicate logic errors in the program. 11278 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11279 11280 // Check for comparisons of floating point operands using != and ==. 11281 if (BinaryOperator::isEqualityOp(Opc) && 11282 LHSType->hasFloatingRepresentation()) { 11283 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11284 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11285 } 11286 11287 // Return a signed type for the vector. 11288 return GetSignedVectorType(vType); 11289 } 11290 11291 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11292 const ExprResult &XorRHS, 11293 const SourceLocation Loc) { 11294 // Do not diagnose macros. 11295 if (Loc.isMacroID()) 11296 return; 11297 11298 bool Negative = false; 11299 bool ExplicitPlus = false; 11300 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11301 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11302 11303 if (!LHSInt) 11304 return; 11305 if (!RHSInt) { 11306 // Check negative literals. 11307 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11308 UnaryOperatorKind Opc = UO->getOpcode(); 11309 if (Opc != UO_Minus && Opc != UO_Plus) 11310 return; 11311 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11312 if (!RHSInt) 11313 return; 11314 Negative = (Opc == UO_Minus); 11315 ExplicitPlus = !Negative; 11316 } else { 11317 return; 11318 } 11319 } 11320 11321 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11322 llvm::APInt RightSideValue = RHSInt->getValue(); 11323 if (LeftSideValue != 2 && LeftSideValue != 10) 11324 return; 11325 11326 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11327 return; 11328 11329 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11330 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11331 llvm::StringRef ExprStr = 11332 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11333 11334 CharSourceRange XorRange = 11335 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11336 llvm::StringRef XorStr = 11337 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11338 // Do not diagnose if xor keyword/macro is used. 11339 if (XorStr == "xor") 11340 return; 11341 11342 std::string LHSStr = std::string(Lexer::getSourceText( 11343 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11344 S.getSourceManager(), S.getLangOpts())); 11345 std::string RHSStr = std::string(Lexer::getSourceText( 11346 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11347 S.getSourceManager(), S.getLangOpts())); 11348 11349 if (Negative) { 11350 RightSideValue = -RightSideValue; 11351 RHSStr = "-" + RHSStr; 11352 } else if (ExplicitPlus) { 11353 RHSStr = "+" + RHSStr; 11354 } 11355 11356 StringRef LHSStrRef = LHSStr; 11357 StringRef RHSStrRef = RHSStr; 11358 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11359 // literals. 11360 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11361 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11362 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11363 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11364 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11365 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11366 LHSStrRef.find('\'') != StringRef::npos || 11367 RHSStrRef.find('\'') != StringRef::npos) 11368 return; 11369 11370 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11371 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11372 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11373 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11374 std::string SuggestedExpr = "1 << " + RHSStr; 11375 bool Overflow = false; 11376 llvm::APInt One = (LeftSideValue - 1); 11377 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11378 if (Overflow) { 11379 if (RightSideIntValue < 64) 11380 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11381 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11382 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11383 else if (RightSideIntValue == 64) 11384 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11385 else 11386 return; 11387 } else { 11388 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11389 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11390 << PowValue.toString(10, true) 11391 << FixItHint::CreateReplacement( 11392 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11393 } 11394 11395 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11396 } else if (LeftSideValue == 10) { 11397 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11398 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11399 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11400 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11401 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11402 } 11403 } 11404 11405 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11406 SourceLocation Loc) { 11407 // Ensure that either both operands are of the same vector type, or 11408 // one operand is of a vector type and the other is of its element type. 11409 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11410 /*AllowBothBool*/true, 11411 /*AllowBoolConversions*/false); 11412 if (vType.isNull()) 11413 return InvalidOperands(Loc, LHS, RHS); 11414 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11415 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11416 return InvalidOperands(Loc, LHS, RHS); 11417 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11418 // usage of the logical operators && and || with vectors in C. This 11419 // check could be notionally dropped. 11420 if (!getLangOpts().CPlusPlus && 11421 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11422 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11423 11424 return GetSignedVectorType(LHS.get()->getType()); 11425 } 11426 11427 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11428 SourceLocation Loc, 11429 BinaryOperatorKind Opc) { 11430 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11431 11432 bool IsCompAssign = 11433 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11434 11435 if (LHS.get()->getType()->isVectorType() || 11436 RHS.get()->getType()->isVectorType()) { 11437 if (LHS.get()->getType()->hasIntegerRepresentation() && 11438 RHS.get()->getType()->hasIntegerRepresentation()) 11439 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11440 /*AllowBothBool*/true, 11441 /*AllowBoolConversions*/getLangOpts().ZVector); 11442 return InvalidOperands(Loc, LHS, RHS); 11443 } 11444 11445 if (Opc == BO_And) 11446 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11447 11448 if (LHS.get()->getType()->hasFloatingRepresentation() || 11449 RHS.get()->getType()->hasFloatingRepresentation()) 11450 return InvalidOperands(Loc, LHS, RHS); 11451 11452 ExprResult LHSResult = LHS, RHSResult = RHS; 11453 QualType compType = UsualArithmeticConversions( 11454 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11455 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11456 return QualType(); 11457 LHS = LHSResult.get(); 11458 RHS = RHSResult.get(); 11459 11460 if (Opc == BO_Xor) 11461 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11462 11463 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11464 return compType; 11465 return InvalidOperands(Loc, LHS, RHS); 11466 } 11467 11468 // C99 6.5.[13,14] 11469 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11470 SourceLocation Loc, 11471 BinaryOperatorKind Opc) { 11472 // Check vector operands differently. 11473 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11474 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11475 11476 bool EnumConstantInBoolContext = false; 11477 for (const ExprResult &HS : {LHS, RHS}) { 11478 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11479 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11480 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11481 EnumConstantInBoolContext = true; 11482 } 11483 } 11484 11485 if (EnumConstantInBoolContext) 11486 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11487 11488 // Diagnose cases where the user write a logical and/or but probably meant a 11489 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11490 // is a constant. 11491 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11492 !LHS.get()->getType()->isBooleanType() && 11493 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11494 // Don't warn in macros or template instantiations. 11495 !Loc.isMacroID() && !inTemplateInstantiation()) { 11496 // If the RHS can be constant folded, and if it constant folds to something 11497 // that isn't 0 or 1 (which indicate a potential logical operation that 11498 // happened to fold to true/false) then warn. 11499 // Parens on the RHS are ignored. 11500 Expr::EvalResult EVResult; 11501 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11502 llvm::APSInt Result = EVResult.Val.getInt(); 11503 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11504 !RHS.get()->getExprLoc().isMacroID()) || 11505 (Result != 0 && Result != 1)) { 11506 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11507 << RHS.get()->getSourceRange() 11508 << (Opc == BO_LAnd ? "&&" : "||"); 11509 // Suggest replacing the logical operator with the bitwise version 11510 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11511 << (Opc == BO_LAnd ? "&" : "|") 11512 << FixItHint::CreateReplacement(SourceRange( 11513 Loc, getLocForEndOfToken(Loc)), 11514 Opc == BO_LAnd ? "&" : "|"); 11515 if (Opc == BO_LAnd) 11516 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11517 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11518 << FixItHint::CreateRemoval( 11519 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11520 RHS.get()->getEndLoc())); 11521 } 11522 } 11523 } 11524 11525 if (!Context.getLangOpts().CPlusPlus) { 11526 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11527 // not operate on the built-in scalar and vector float types. 11528 if (Context.getLangOpts().OpenCL && 11529 Context.getLangOpts().OpenCLVersion < 120) { 11530 if (LHS.get()->getType()->isFloatingType() || 11531 RHS.get()->getType()->isFloatingType()) 11532 return InvalidOperands(Loc, LHS, RHS); 11533 } 11534 11535 LHS = UsualUnaryConversions(LHS.get()); 11536 if (LHS.isInvalid()) 11537 return QualType(); 11538 11539 RHS = UsualUnaryConversions(RHS.get()); 11540 if (RHS.isInvalid()) 11541 return QualType(); 11542 11543 if (!LHS.get()->getType()->isScalarType() || 11544 !RHS.get()->getType()->isScalarType()) 11545 return InvalidOperands(Loc, LHS, RHS); 11546 11547 return Context.IntTy; 11548 } 11549 11550 // The following is safe because we only use this method for 11551 // non-overloadable operands. 11552 11553 // C++ [expr.log.and]p1 11554 // C++ [expr.log.or]p1 11555 // The operands are both contextually converted to type bool. 11556 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11557 if (LHSRes.isInvalid()) 11558 return InvalidOperands(Loc, LHS, RHS); 11559 LHS = LHSRes; 11560 11561 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11562 if (RHSRes.isInvalid()) 11563 return InvalidOperands(Loc, LHS, RHS); 11564 RHS = RHSRes; 11565 11566 // C++ [expr.log.and]p2 11567 // C++ [expr.log.or]p2 11568 // The result is a bool. 11569 return Context.BoolTy; 11570 } 11571 11572 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11573 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11574 if (!ME) return false; 11575 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11576 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11577 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11578 if (!Base) return false; 11579 return Base->getMethodDecl() != nullptr; 11580 } 11581 11582 /// Is the given expression (which must be 'const') a reference to a 11583 /// variable which was originally non-const, but which has become 11584 /// 'const' due to being captured within a block? 11585 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11586 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11587 assert(E->isLValue() && E->getType().isConstQualified()); 11588 E = E->IgnoreParens(); 11589 11590 // Must be a reference to a declaration from an enclosing scope. 11591 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11592 if (!DRE) return NCCK_None; 11593 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11594 11595 // The declaration must be a variable which is not declared 'const'. 11596 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11597 if (!var) return NCCK_None; 11598 if (var->getType().isConstQualified()) return NCCK_None; 11599 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11600 11601 // Decide whether the first capture was for a block or a lambda. 11602 DeclContext *DC = S.CurContext, *Prev = nullptr; 11603 // Decide whether the first capture was for a block or a lambda. 11604 while (DC) { 11605 // For init-capture, it is possible that the variable belongs to the 11606 // template pattern of the current context. 11607 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11608 if (var->isInitCapture() && 11609 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11610 break; 11611 if (DC == var->getDeclContext()) 11612 break; 11613 Prev = DC; 11614 DC = DC->getParent(); 11615 } 11616 // Unless we have an init-capture, we've gone one step too far. 11617 if (!var->isInitCapture()) 11618 DC = Prev; 11619 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11620 } 11621 11622 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11623 Ty = Ty.getNonReferenceType(); 11624 if (IsDereference && Ty->isPointerType()) 11625 Ty = Ty->getPointeeType(); 11626 return !Ty.isConstQualified(); 11627 } 11628 11629 // Update err_typecheck_assign_const and note_typecheck_assign_const 11630 // when this enum is changed. 11631 enum { 11632 ConstFunction, 11633 ConstVariable, 11634 ConstMember, 11635 ConstMethod, 11636 NestedConstMember, 11637 ConstUnknown, // Keep as last element 11638 }; 11639 11640 /// Emit the "read-only variable not assignable" error and print notes to give 11641 /// more information about why the variable is not assignable, such as pointing 11642 /// to the declaration of a const variable, showing that a method is const, or 11643 /// that the function is returning a const reference. 11644 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11645 SourceLocation Loc) { 11646 SourceRange ExprRange = E->getSourceRange(); 11647 11648 // Only emit one error on the first const found. All other consts will emit 11649 // a note to the error. 11650 bool DiagnosticEmitted = false; 11651 11652 // Track if the current expression is the result of a dereference, and if the 11653 // next checked expression is the result of a dereference. 11654 bool IsDereference = false; 11655 bool NextIsDereference = false; 11656 11657 // Loop to process MemberExpr chains. 11658 while (true) { 11659 IsDereference = NextIsDereference; 11660 11661 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11662 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11663 NextIsDereference = ME->isArrow(); 11664 const ValueDecl *VD = ME->getMemberDecl(); 11665 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11666 // Mutable fields can be modified even if the class is const. 11667 if (Field->isMutable()) { 11668 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11669 break; 11670 } 11671 11672 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11673 if (!DiagnosticEmitted) { 11674 S.Diag(Loc, diag::err_typecheck_assign_const) 11675 << ExprRange << ConstMember << false /*static*/ << Field 11676 << Field->getType(); 11677 DiagnosticEmitted = true; 11678 } 11679 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11680 << ConstMember << false /*static*/ << Field << Field->getType() 11681 << Field->getSourceRange(); 11682 } 11683 E = ME->getBase(); 11684 continue; 11685 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11686 if (VDecl->getType().isConstQualified()) { 11687 if (!DiagnosticEmitted) { 11688 S.Diag(Loc, diag::err_typecheck_assign_const) 11689 << ExprRange << ConstMember << true /*static*/ << VDecl 11690 << VDecl->getType(); 11691 DiagnosticEmitted = true; 11692 } 11693 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11694 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11695 << VDecl->getSourceRange(); 11696 } 11697 // Static fields do not inherit constness from parents. 11698 break; 11699 } 11700 break; // End MemberExpr 11701 } else if (const ArraySubscriptExpr *ASE = 11702 dyn_cast<ArraySubscriptExpr>(E)) { 11703 E = ASE->getBase()->IgnoreParenImpCasts(); 11704 continue; 11705 } else if (const ExtVectorElementExpr *EVE = 11706 dyn_cast<ExtVectorElementExpr>(E)) { 11707 E = EVE->getBase()->IgnoreParenImpCasts(); 11708 continue; 11709 } 11710 break; 11711 } 11712 11713 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11714 // Function calls 11715 const FunctionDecl *FD = CE->getDirectCallee(); 11716 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11717 if (!DiagnosticEmitted) { 11718 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11719 << ConstFunction << FD; 11720 DiagnosticEmitted = true; 11721 } 11722 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11723 diag::note_typecheck_assign_const) 11724 << ConstFunction << FD << FD->getReturnType() 11725 << FD->getReturnTypeSourceRange(); 11726 } 11727 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11728 // Point to variable declaration. 11729 if (const ValueDecl *VD = DRE->getDecl()) { 11730 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11731 if (!DiagnosticEmitted) { 11732 S.Diag(Loc, diag::err_typecheck_assign_const) 11733 << ExprRange << ConstVariable << VD << VD->getType(); 11734 DiagnosticEmitted = true; 11735 } 11736 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11737 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11738 } 11739 } 11740 } else if (isa<CXXThisExpr>(E)) { 11741 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11742 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11743 if (MD->isConst()) { 11744 if (!DiagnosticEmitted) { 11745 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11746 << ConstMethod << MD; 11747 DiagnosticEmitted = true; 11748 } 11749 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11750 << ConstMethod << MD << MD->getSourceRange(); 11751 } 11752 } 11753 } 11754 } 11755 11756 if (DiagnosticEmitted) 11757 return; 11758 11759 // Can't determine a more specific message, so display the generic error. 11760 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11761 } 11762 11763 enum OriginalExprKind { 11764 OEK_Variable, 11765 OEK_Member, 11766 OEK_LValue 11767 }; 11768 11769 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11770 const RecordType *Ty, 11771 SourceLocation Loc, SourceRange Range, 11772 OriginalExprKind OEK, 11773 bool &DiagnosticEmitted) { 11774 std::vector<const RecordType *> RecordTypeList; 11775 RecordTypeList.push_back(Ty); 11776 unsigned NextToCheckIndex = 0; 11777 // We walk the record hierarchy breadth-first to ensure that we print 11778 // diagnostics in field nesting order. 11779 while (RecordTypeList.size() > NextToCheckIndex) { 11780 bool IsNested = NextToCheckIndex > 0; 11781 for (const FieldDecl *Field : 11782 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11783 // First, check every field for constness. 11784 QualType FieldTy = Field->getType(); 11785 if (FieldTy.isConstQualified()) { 11786 if (!DiagnosticEmitted) { 11787 S.Diag(Loc, diag::err_typecheck_assign_const) 11788 << Range << NestedConstMember << OEK << VD 11789 << IsNested << Field; 11790 DiagnosticEmitted = true; 11791 } 11792 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11793 << NestedConstMember << IsNested << Field 11794 << FieldTy << Field->getSourceRange(); 11795 } 11796 11797 // Then we append it to the list to check next in order. 11798 FieldTy = FieldTy.getCanonicalType(); 11799 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11800 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11801 RecordTypeList.push_back(FieldRecTy); 11802 } 11803 } 11804 ++NextToCheckIndex; 11805 } 11806 } 11807 11808 /// Emit an error for the case where a record we are trying to assign to has a 11809 /// const-qualified field somewhere in its hierarchy. 11810 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11811 SourceLocation Loc) { 11812 QualType Ty = E->getType(); 11813 assert(Ty->isRecordType() && "lvalue was not record?"); 11814 SourceRange Range = E->getSourceRange(); 11815 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11816 bool DiagEmitted = false; 11817 11818 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11819 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11820 Range, OEK_Member, DiagEmitted); 11821 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11822 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11823 Range, OEK_Variable, DiagEmitted); 11824 else 11825 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11826 Range, OEK_LValue, DiagEmitted); 11827 if (!DiagEmitted) 11828 DiagnoseConstAssignment(S, E, Loc); 11829 } 11830 11831 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11832 /// emit an error and return true. If so, return false. 11833 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11834 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11835 11836 S.CheckShadowingDeclModification(E, Loc); 11837 11838 SourceLocation OrigLoc = Loc; 11839 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11840 &Loc); 11841 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11842 IsLV = Expr::MLV_InvalidMessageExpression; 11843 if (IsLV == Expr::MLV_Valid) 11844 return false; 11845 11846 unsigned DiagID = 0; 11847 bool NeedType = false; 11848 switch (IsLV) { // C99 6.5.16p2 11849 case Expr::MLV_ConstQualified: 11850 // Use a specialized diagnostic when we're assigning to an object 11851 // from an enclosing function or block. 11852 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11853 if (NCCK == NCCK_Block) 11854 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11855 else 11856 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11857 break; 11858 } 11859 11860 // In ARC, use some specialized diagnostics for occasions where we 11861 // infer 'const'. These are always pseudo-strong variables. 11862 if (S.getLangOpts().ObjCAutoRefCount) { 11863 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11864 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11865 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11866 11867 // Use the normal diagnostic if it's pseudo-__strong but the 11868 // user actually wrote 'const'. 11869 if (var->isARCPseudoStrong() && 11870 (!var->getTypeSourceInfo() || 11871 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11872 // There are three pseudo-strong cases: 11873 // - self 11874 ObjCMethodDecl *method = S.getCurMethodDecl(); 11875 if (method && var == method->getSelfDecl()) { 11876 DiagID = method->isClassMethod() 11877 ? diag::err_typecheck_arc_assign_self_class_method 11878 : diag::err_typecheck_arc_assign_self; 11879 11880 // - Objective-C externally_retained attribute. 11881 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11882 isa<ParmVarDecl>(var)) { 11883 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11884 11885 // - fast enumeration variables 11886 } else { 11887 DiagID = diag::err_typecheck_arr_assign_enumeration; 11888 } 11889 11890 SourceRange Assign; 11891 if (Loc != OrigLoc) 11892 Assign = SourceRange(OrigLoc, OrigLoc); 11893 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11894 // We need to preserve the AST regardless, so migration tool 11895 // can do its job. 11896 return false; 11897 } 11898 } 11899 } 11900 11901 // If none of the special cases above are triggered, then this is a 11902 // simple const assignment. 11903 if (DiagID == 0) { 11904 DiagnoseConstAssignment(S, E, Loc); 11905 return true; 11906 } 11907 11908 break; 11909 case Expr::MLV_ConstAddrSpace: 11910 DiagnoseConstAssignment(S, E, Loc); 11911 return true; 11912 case Expr::MLV_ConstQualifiedField: 11913 DiagnoseRecursiveConstFields(S, E, Loc); 11914 return true; 11915 case Expr::MLV_ArrayType: 11916 case Expr::MLV_ArrayTemporary: 11917 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11918 NeedType = true; 11919 break; 11920 case Expr::MLV_NotObjectType: 11921 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11922 NeedType = true; 11923 break; 11924 case Expr::MLV_LValueCast: 11925 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11926 break; 11927 case Expr::MLV_Valid: 11928 llvm_unreachable("did not take early return for MLV_Valid"); 11929 case Expr::MLV_InvalidExpression: 11930 case Expr::MLV_MemberFunction: 11931 case Expr::MLV_ClassTemporary: 11932 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11933 break; 11934 case Expr::MLV_IncompleteType: 11935 case Expr::MLV_IncompleteVoidType: 11936 return S.RequireCompleteType(Loc, E->getType(), 11937 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11938 case Expr::MLV_DuplicateVectorComponents: 11939 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11940 break; 11941 case Expr::MLV_NoSetterProperty: 11942 llvm_unreachable("readonly properties should be processed differently"); 11943 case Expr::MLV_InvalidMessageExpression: 11944 DiagID = diag::err_readonly_message_assignment; 11945 break; 11946 case Expr::MLV_SubObjCPropertySetting: 11947 DiagID = diag::err_no_subobject_property_setting; 11948 break; 11949 } 11950 11951 SourceRange Assign; 11952 if (Loc != OrigLoc) 11953 Assign = SourceRange(OrigLoc, OrigLoc); 11954 if (NeedType) 11955 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11956 else 11957 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11958 return true; 11959 } 11960 11961 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11962 SourceLocation Loc, 11963 Sema &Sema) { 11964 if (Sema.inTemplateInstantiation()) 11965 return; 11966 if (Sema.isUnevaluatedContext()) 11967 return; 11968 if (Loc.isInvalid() || Loc.isMacroID()) 11969 return; 11970 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11971 return; 11972 11973 // C / C++ fields 11974 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11975 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11976 if (ML && MR) { 11977 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11978 return; 11979 const ValueDecl *LHSDecl = 11980 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11981 const ValueDecl *RHSDecl = 11982 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11983 if (LHSDecl != RHSDecl) 11984 return; 11985 if (LHSDecl->getType().isVolatileQualified()) 11986 return; 11987 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11988 if (RefTy->getPointeeType().isVolatileQualified()) 11989 return; 11990 11991 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11992 } 11993 11994 // Objective-C instance variables 11995 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11996 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11997 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11998 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11999 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12000 if (RL && RR && RL->getDecl() == RR->getDecl()) 12001 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12002 } 12003 } 12004 12005 // C99 6.5.16.1 12006 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12007 SourceLocation Loc, 12008 QualType CompoundType) { 12009 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12010 12011 // Verify that LHS is a modifiable lvalue, and emit error if not. 12012 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12013 return QualType(); 12014 12015 QualType LHSType = LHSExpr->getType(); 12016 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12017 CompoundType; 12018 // OpenCL v1.2 s6.1.1.1 p2: 12019 // The half data type can only be used to declare a pointer to a buffer that 12020 // contains half values 12021 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12022 LHSType->isHalfType()) { 12023 Diag(Loc, diag::err_opencl_half_load_store) << 1 12024 << LHSType.getUnqualifiedType(); 12025 return QualType(); 12026 } 12027 12028 AssignConvertType ConvTy; 12029 if (CompoundType.isNull()) { 12030 Expr *RHSCheck = RHS.get(); 12031 12032 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12033 12034 QualType LHSTy(LHSType); 12035 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12036 if (RHS.isInvalid()) 12037 return QualType(); 12038 // Special case of NSObject attributes on c-style pointer types. 12039 if (ConvTy == IncompatiblePointer && 12040 ((Context.isObjCNSObjectType(LHSType) && 12041 RHSType->isObjCObjectPointerType()) || 12042 (Context.isObjCNSObjectType(RHSType) && 12043 LHSType->isObjCObjectPointerType()))) 12044 ConvTy = Compatible; 12045 12046 if (ConvTy == Compatible && 12047 LHSType->isObjCObjectType()) 12048 Diag(Loc, diag::err_objc_object_assignment) 12049 << LHSType; 12050 12051 // If the RHS is a unary plus or minus, check to see if they = and + are 12052 // right next to each other. If so, the user may have typo'd "x =+ 4" 12053 // instead of "x += 4". 12054 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12055 RHSCheck = ICE->getSubExpr(); 12056 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12057 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12058 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12059 // Only if the two operators are exactly adjacent. 12060 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12061 // And there is a space or other character before the subexpr of the 12062 // unary +/-. We don't want to warn on "x=-1". 12063 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12064 UO->getSubExpr()->getBeginLoc().isFileID()) { 12065 Diag(Loc, diag::warn_not_compound_assign) 12066 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12067 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12068 } 12069 } 12070 12071 if (ConvTy == Compatible) { 12072 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12073 // Warn about retain cycles where a block captures the LHS, but 12074 // not if the LHS is a simple variable into which the block is 12075 // being stored...unless that variable can be captured by reference! 12076 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12077 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12078 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12079 checkRetainCycles(LHSExpr, RHS.get()); 12080 } 12081 12082 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12083 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12084 // It is safe to assign a weak reference into a strong variable. 12085 // Although this code can still have problems: 12086 // id x = self.weakProp; 12087 // id y = self.weakProp; 12088 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12089 // paths through the function. This should be revisited if 12090 // -Wrepeated-use-of-weak is made flow-sensitive. 12091 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12092 // variable, which will be valid for the current autorelease scope. 12093 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12094 RHS.get()->getBeginLoc())) 12095 getCurFunction()->markSafeWeakUse(RHS.get()); 12096 12097 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12098 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12099 } 12100 } 12101 } else { 12102 // Compound assignment "x += y" 12103 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12104 } 12105 12106 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12107 RHS.get(), AA_Assigning)) 12108 return QualType(); 12109 12110 CheckForNullPointerDereference(*this, LHSExpr); 12111 12112 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12113 if (CompoundType.isNull()) { 12114 // C++2a [expr.ass]p5: 12115 // A simple-assignment whose left operand is of a volatile-qualified 12116 // type is deprecated unless the assignment is either a discarded-value 12117 // expression or an unevaluated operand 12118 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12119 } else { 12120 // C++2a [expr.ass]p6: 12121 // [Compound-assignment] expressions are deprecated if E1 has 12122 // volatile-qualified type 12123 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12124 } 12125 } 12126 12127 // C99 6.5.16p3: The type of an assignment expression is the type of the 12128 // left operand unless the left operand has qualified type, in which case 12129 // it is the unqualified version of the type of the left operand. 12130 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12131 // is converted to the type of the assignment expression (above). 12132 // C++ 5.17p1: the type of the assignment expression is that of its left 12133 // operand. 12134 return (getLangOpts().CPlusPlus 12135 ? LHSType : LHSType.getUnqualifiedType()); 12136 } 12137 12138 // Only ignore explicit casts to void. 12139 static bool IgnoreCommaOperand(const Expr *E) { 12140 E = E->IgnoreParens(); 12141 12142 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12143 if (CE->getCastKind() == CK_ToVoid) { 12144 return true; 12145 } 12146 12147 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12148 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12149 CE->getSubExpr()->getType()->isDependentType()) { 12150 return true; 12151 } 12152 } 12153 12154 return false; 12155 } 12156 12157 // Look for instances where it is likely the comma operator is confused with 12158 // another operator. There is a whitelist of acceptable expressions for the 12159 // left hand side of the comma operator, otherwise emit a warning. 12160 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12161 // No warnings in macros 12162 if (Loc.isMacroID()) 12163 return; 12164 12165 // Don't warn in template instantiations. 12166 if (inTemplateInstantiation()) 12167 return; 12168 12169 // Scope isn't fine-grained enough to whitelist the specific cases, so 12170 // instead, skip more than needed, then call back into here with the 12171 // CommaVisitor in SemaStmt.cpp. 12172 // The whitelisted locations are the initialization and increment portions 12173 // of a for loop. The additional checks are on the condition of 12174 // if statements, do/while loops, and for loops. 12175 // Differences in scope flags for C89 mode requires the extra logic. 12176 const unsigned ForIncrementFlags = 12177 getLangOpts().C99 || getLangOpts().CPlusPlus 12178 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12179 : Scope::ContinueScope | Scope::BreakScope; 12180 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12181 const unsigned ScopeFlags = getCurScope()->getFlags(); 12182 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12183 (ScopeFlags & ForInitFlags) == ForInitFlags) 12184 return; 12185 12186 // If there are multiple comma operators used together, get the RHS of the 12187 // of the comma operator as the LHS. 12188 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12189 if (BO->getOpcode() != BO_Comma) 12190 break; 12191 LHS = BO->getRHS(); 12192 } 12193 12194 // Only allow some expressions on LHS to not warn. 12195 if (IgnoreCommaOperand(LHS)) 12196 return; 12197 12198 Diag(Loc, diag::warn_comma_operator); 12199 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12200 << LHS->getSourceRange() 12201 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12202 LangOpts.CPlusPlus ? "static_cast<void>(" 12203 : "(void)(") 12204 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12205 ")"); 12206 } 12207 12208 // C99 6.5.17 12209 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12210 SourceLocation Loc) { 12211 LHS = S.CheckPlaceholderExpr(LHS.get()); 12212 RHS = S.CheckPlaceholderExpr(RHS.get()); 12213 if (LHS.isInvalid() || RHS.isInvalid()) 12214 return QualType(); 12215 12216 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12217 // operands, but not unary promotions. 12218 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12219 12220 // So we treat the LHS as a ignored value, and in C++ we allow the 12221 // containing site to determine what should be done with the RHS. 12222 LHS = S.IgnoredValueConversions(LHS.get()); 12223 if (LHS.isInvalid()) 12224 return QualType(); 12225 12226 S.DiagnoseUnusedExprResult(LHS.get()); 12227 12228 if (!S.getLangOpts().CPlusPlus) { 12229 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12230 if (RHS.isInvalid()) 12231 return QualType(); 12232 if (!RHS.get()->getType()->isVoidType()) 12233 S.RequireCompleteType(Loc, RHS.get()->getType(), 12234 diag::err_incomplete_type); 12235 } 12236 12237 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12238 S.DiagnoseCommaOperator(LHS.get(), Loc); 12239 12240 return RHS.get()->getType(); 12241 } 12242 12243 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12244 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12245 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12246 ExprValueKind &VK, 12247 ExprObjectKind &OK, 12248 SourceLocation OpLoc, 12249 bool IsInc, bool IsPrefix) { 12250 if (Op->isTypeDependent()) 12251 return S.Context.DependentTy; 12252 12253 QualType ResType = Op->getType(); 12254 // Atomic types can be used for increment / decrement where the non-atomic 12255 // versions can, so ignore the _Atomic() specifier for the purpose of 12256 // checking. 12257 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12258 ResType = ResAtomicType->getValueType(); 12259 12260 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12261 12262 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12263 // Decrement of bool is not allowed. 12264 if (!IsInc) { 12265 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12266 return QualType(); 12267 } 12268 // Increment of bool sets it to true, but is deprecated. 12269 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12270 : diag::warn_increment_bool) 12271 << Op->getSourceRange(); 12272 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12273 // Error on enum increments and decrements in C++ mode 12274 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12275 return QualType(); 12276 } else if (ResType->isRealType()) { 12277 // OK! 12278 } else if (ResType->isPointerType()) { 12279 // C99 6.5.2.4p2, 6.5.6p2 12280 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12281 return QualType(); 12282 } else if (ResType->isObjCObjectPointerType()) { 12283 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12284 // Otherwise, we just need a complete type. 12285 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12286 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12287 return QualType(); 12288 } else if (ResType->isAnyComplexType()) { 12289 // C99 does not support ++/-- on complex types, we allow as an extension. 12290 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12291 << ResType << Op->getSourceRange(); 12292 } else if (ResType->isPlaceholderType()) { 12293 ExprResult PR = S.CheckPlaceholderExpr(Op); 12294 if (PR.isInvalid()) return QualType(); 12295 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12296 IsInc, IsPrefix); 12297 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12298 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12299 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12300 (ResType->castAs<VectorType>()->getVectorKind() != 12301 VectorType::AltiVecBool)) { 12302 // The z vector extensions allow ++ and -- for non-bool vectors. 12303 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12304 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12305 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12306 } else { 12307 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12308 << ResType << int(IsInc) << Op->getSourceRange(); 12309 return QualType(); 12310 } 12311 // At this point, we know we have a real, complex or pointer type. 12312 // Now make sure the operand is a modifiable lvalue. 12313 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12314 return QualType(); 12315 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12316 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12317 // An operand with volatile-qualified type is deprecated 12318 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12319 << IsInc << ResType; 12320 } 12321 // In C++, a prefix increment is the same type as the operand. Otherwise 12322 // (in C or with postfix), the increment is the unqualified type of the 12323 // operand. 12324 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12325 VK = VK_LValue; 12326 OK = Op->getObjectKind(); 12327 return ResType; 12328 } else { 12329 VK = VK_RValue; 12330 return ResType.getUnqualifiedType(); 12331 } 12332 } 12333 12334 12335 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12336 /// This routine allows us to typecheck complex/recursive expressions 12337 /// where the declaration is needed for type checking. We only need to 12338 /// handle cases when the expression references a function designator 12339 /// or is an lvalue. Here are some examples: 12340 /// - &(x) => x 12341 /// - &*****f => f for f a function designator. 12342 /// - &s.xx => s 12343 /// - &s.zz[1].yy -> s, if zz is an array 12344 /// - *(x + 1) -> x, if x is an array 12345 /// - &"123"[2] -> 0 12346 /// - & __real__ x -> x 12347 static ValueDecl *getPrimaryDecl(Expr *E) { 12348 switch (E->getStmtClass()) { 12349 case Stmt::DeclRefExprClass: 12350 return cast<DeclRefExpr>(E)->getDecl(); 12351 case Stmt::MemberExprClass: 12352 // If this is an arrow operator, the address is an offset from 12353 // the base's value, so the object the base refers to is 12354 // irrelevant. 12355 if (cast<MemberExpr>(E)->isArrow()) 12356 return nullptr; 12357 // Otherwise, the expression refers to a part of the base 12358 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12359 case Stmt::ArraySubscriptExprClass: { 12360 // FIXME: This code shouldn't be necessary! We should catch the implicit 12361 // promotion of register arrays earlier. 12362 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12363 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12364 if (ICE->getSubExpr()->getType()->isArrayType()) 12365 return getPrimaryDecl(ICE->getSubExpr()); 12366 } 12367 return nullptr; 12368 } 12369 case Stmt::UnaryOperatorClass: { 12370 UnaryOperator *UO = cast<UnaryOperator>(E); 12371 12372 switch(UO->getOpcode()) { 12373 case UO_Real: 12374 case UO_Imag: 12375 case UO_Extension: 12376 return getPrimaryDecl(UO->getSubExpr()); 12377 default: 12378 return nullptr; 12379 } 12380 } 12381 case Stmt::ParenExprClass: 12382 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12383 case Stmt::ImplicitCastExprClass: 12384 // If the result of an implicit cast is an l-value, we care about 12385 // the sub-expression; otherwise, the result here doesn't matter. 12386 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12387 default: 12388 return nullptr; 12389 } 12390 } 12391 12392 namespace { 12393 enum { 12394 AO_Bit_Field = 0, 12395 AO_Vector_Element = 1, 12396 AO_Property_Expansion = 2, 12397 AO_Register_Variable = 3, 12398 AO_No_Error = 4 12399 }; 12400 } 12401 /// Diagnose invalid operand for address of operations. 12402 /// 12403 /// \param Type The type of operand which cannot have its address taken. 12404 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12405 Expr *E, unsigned Type) { 12406 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12407 } 12408 12409 /// CheckAddressOfOperand - The operand of & must be either a function 12410 /// designator or an lvalue designating an object. If it is an lvalue, the 12411 /// object cannot be declared with storage class register or be a bit field. 12412 /// Note: The usual conversions are *not* applied to the operand of the & 12413 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12414 /// In C++, the operand might be an overloaded function name, in which case 12415 /// we allow the '&' but retain the overloaded-function type. 12416 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12417 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12418 if (PTy->getKind() == BuiltinType::Overload) { 12419 Expr *E = OrigOp.get()->IgnoreParens(); 12420 if (!isa<OverloadExpr>(E)) { 12421 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12422 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12423 << OrigOp.get()->getSourceRange(); 12424 return QualType(); 12425 } 12426 12427 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12428 if (isa<UnresolvedMemberExpr>(Ovl)) 12429 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12430 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12431 << OrigOp.get()->getSourceRange(); 12432 return QualType(); 12433 } 12434 12435 return Context.OverloadTy; 12436 } 12437 12438 if (PTy->getKind() == BuiltinType::UnknownAny) 12439 return Context.UnknownAnyTy; 12440 12441 if (PTy->getKind() == BuiltinType::BoundMember) { 12442 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12443 << OrigOp.get()->getSourceRange(); 12444 return QualType(); 12445 } 12446 12447 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12448 if (OrigOp.isInvalid()) return QualType(); 12449 } 12450 12451 if (OrigOp.get()->isTypeDependent()) 12452 return Context.DependentTy; 12453 12454 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12455 12456 // Make sure to ignore parentheses in subsequent checks 12457 Expr *op = OrigOp.get()->IgnoreParens(); 12458 12459 // In OpenCL captures for blocks called as lambda functions 12460 // are located in the private address space. Blocks used in 12461 // enqueue_kernel can be located in a different address space 12462 // depending on a vendor implementation. Thus preventing 12463 // taking an address of the capture to avoid invalid AS casts. 12464 if (LangOpts.OpenCL) { 12465 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12466 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12467 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12468 return QualType(); 12469 } 12470 } 12471 12472 if (getLangOpts().C99) { 12473 // Implement C99-only parts of addressof rules. 12474 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12475 if (uOp->getOpcode() == UO_Deref) 12476 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12477 // (assuming the deref expression is valid). 12478 return uOp->getSubExpr()->getType(); 12479 } 12480 // Technically, there should be a check for array subscript 12481 // expressions here, but the result of one is always an lvalue anyway. 12482 } 12483 ValueDecl *dcl = getPrimaryDecl(op); 12484 12485 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12486 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12487 op->getBeginLoc())) 12488 return QualType(); 12489 12490 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12491 unsigned AddressOfError = AO_No_Error; 12492 12493 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12494 bool sfinae = (bool)isSFINAEContext(); 12495 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12496 : diag::ext_typecheck_addrof_temporary) 12497 << op->getType() << op->getSourceRange(); 12498 if (sfinae) 12499 return QualType(); 12500 // Materialize the temporary as an lvalue so that we can take its address. 12501 OrigOp = op = 12502 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12503 } else if (isa<ObjCSelectorExpr>(op)) { 12504 return Context.getPointerType(op->getType()); 12505 } else if (lval == Expr::LV_MemberFunction) { 12506 // If it's an instance method, make a member pointer. 12507 // The expression must have exactly the form &A::foo. 12508 12509 // If the underlying expression isn't a decl ref, give up. 12510 if (!isa<DeclRefExpr>(op)) { 12511 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12512 << OrigOp.get()->getSourceRange(); 12513 return QualType(); 12514 } 12515 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12516 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12517 12518 // The id-expression was parenthesized. 12519 if (OrigOp.get() != DRE) { 12520 Diag(OpLoc, diag::err_parens_pointer_member_function) 12521 << OrigOp.get()->getSourceRange(); 12522 12523 // The method was named without a qualifier. 12524 } else if (!DRE->getQualifier()) { 12525 if (MD->getParent()->getName().empty()) 12526 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12527 << op->getSourceRange(); 12528 else { 12529 SmallString<32> Str; 12530 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12531 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12532 << op->getSourceRange() 12533 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12534 } 12535 } 12536 12537 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12538 if (isa<CXXDestructorDecl>(MD)) 12539 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12540 12541 QualType MPTy = Context.getMemberPointerType( 12542 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12543 // Under the MS ABI, lock down the inheritance model now. 12544 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12545 (void)isCompleteType(OpLoc, MPTy); 12546 return MPTy; 12547 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12548 // C99 6.5.3.2p1 12549 // The operand must be either an l-value or a function designator 12550 if (!op->getType()->isFunctionType()) { 12551 // Use a special diagnostic for loads from property references. 12552 if (isa<PseudoObjectExpr>(op)) { 12553 AddressOfError = AO_Property_Expansion; 12554 } else { 12555 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12556 << op->getType() << op->getSourceRange(); 12557 return QualType(); 12558 } 12559 } 12560 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12561 // The operand cannot be a bit-field 12562 AddressOfError = AO_Bit_Field; 12563 } else if (op->getObjectKind() == OK_VectorComponent) { 12564 // The operand cannot be an element of a vector 12565 AddressOfError = AO_Vector_Element; 12566 } else if (dcl) { // C99 6.5.3.2p1 12567 // We have an lvalue with a decl. Make sure the decl is not declared 12568 // with the register storage-class specifier. 12569 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12570 // in C++ it is not error to take address of a register 12571 // variable (c++03 7.1.1P3) 12572 if (vd->getStorageClass() == SC_Register && 12573 !getLangOpts().CPlusPlus) { 12574 AddressOfError = AO_Register_Variable; 12575 } 12576 } else if (isa<MSPropertyDecl>(dcl)) { 12577 AddressOfError = AO_Property_Expansion; 12578 } else if (isa<FunctionTemplateDecl>(dcl)) { 12579 return Context.OverloadTy; 12580 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12581 // Okay: we can take the address of a field. 12582 // Could be a pointer to member, though, if there is an explicit 12583 // scope qualifier for the class. 12584 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12585 DeclContext *Ctx = dcl->getDeclContext(); 12586 if (Ctx && Ctx->isRecord()) { 12587 if (dcl->getType()->isReferenceType()) { 12588 Diag(OpLoc, 12589 diag::err_cannot_form_pointer_to_member_of_reference_type) 12590 << dcl->getDeclName() << dcl->getType(); 12591 return QualType(); 12592 } 12593 12594 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12595 Ctx = Ctx->getParent(); 12596 12597 QualType MPTy = Context.getMemberPointerType( 12598 op->getType(), 12599 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12600 // Under the MS ABI, lock down the inheritance model now. 12601 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12602 (void)isCompleteType(OpLoc, MPTy); 12603 return MPTy; 12604 } 12605 } 12606 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12607 !isa<BindingDecl>(dcl)) 12608 llvm_unreachable("Unknown/unexpected decl type"); 12609 } 12610 12611 if (AddressOfError != AO_No_Error) { 12612 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12613 return QualType(); 12614 } 12615 12616 if (lval == Expr::LV_IncompleteVoidType) { 12617 // Taking the address of a void variable is technically illegal, but we 12618 // allow it in cases which are otherwise valid. 12619 // Example: "extern void x; void* y = &x;". 12620 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12621 } 12622 12623 // If the operand has type "type", the result has type "pointer to type". 12624 if (op->getType()->isObjCObjectType()) 12625 return Context.getObjCObjectPointerType(op->getType()); 12626 12627 CheckAddressOfPackedMember(op); 12628 12629 return Context.getPointerType(op->getType()); 12630 } 12631 12632 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12633 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12634 if (!DRE) 12635 return; 12636 const Decl *D = DRE->getDecl(); 12637 if (!D) 12638 return; 12639 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12640 if (!Param) 12641 return; 12642 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12643 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12644 return; 12645 if (FunctionScopeInfo *FD = S.getCurFunction()) 12646 if (!FD->ModifiedNonNullParams.count(Param)) 12647 FD->ModifiedNonNullParams.insert(Param); 12648 } 12649 12650 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12651 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12652 SourceLocation OpLoc) { 12653 if (Op->isTypeDependent()) 12654 return S.Context.DependentTy; 12655 12656 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12657 if (ConvResult.isInvalid()) 12658 return QualType(); 12659 Op = ConvResult.get(); 12660 QualType OpTy = Op->getType(); 12661 QualType Result; 12662 12663 if (isa<CXXReinterpretCastExpr>(Op)) { 12664 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12665 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12666 Op->getSourceRange()); 12667 } 12668 12669 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12670 { 12671 Result = PT->getPointeeType(); 12672 } 12673 else if (const ObjCObjectPointerType *OPT = 12674 OpTy->getAs<ObjCObjectPointerType>()) 12675 Result = OPT->getPointeeType(); 12676 else { 12677 ExprResult PR = S.CheckPlaceholderExpr(Op); 12678 if (PR.isInvalid()) return QualType(); 12679 if (PR.get() != Op) 12680 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12681 } 12682 12683 if (Result.isNull()) { 12684 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12685 << OpTy << Op->getSourceRange(); 12686 return QualType(); 12687 } 12688 12689 // Note that per both C89 and C99, indirection is always legal, even if Result 12690 // is an incomplete type or void. It would be possible to warn about 12691 // dereferencing a void pointer, but it's completely well-defined, and such a 12692 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12693 // for pointers to 'void' but is fine for any other pointer type: 12694 // 12695 // C++ [expr.unary.op]p1: 12696 // [...] the expression to which [the unary * operator] is applied shall 12697 // be a pointer to an object type, or a pointer to a function type 12698 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12699 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12700 << OpTy << Op->getSourceRange(); 12701 12702 // Dereferences are usually l-values... 12703 VK = VK_LValue; 12704 12705 // ...except that certain expressions are never l-values in C. 12706 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12707 VK = VK_RValue; 12708 12709 return Result; 12710 } 12711 12712 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12713 BinaryOperatorKind Opc; 12714 switch (Kind) { 12715 default: llvm_unreachable("Unknown binop!"); 12716 case tok::periodstar: Opc = BO_PtrMemD; break; 12717 case tok::arrowstar: Opc = BO_PtrMemI; break; 12718 case tok::star: Opc = BO_Mul; break; 12719 case tok::slash: Opc = BO_Div; break; 12720 case tok::percent: Opc = BO_Rem; break; 12721 case tok::plus: Opc = BO_Add; break; 12722 case tok::minus: Opc = BO_Sub; break; 12723 case tok::lessless: Opc = BO_Shl; break; 12724 case tok::greatergreater: Opc = BO_Shr; break; 12725 case tok::lessequal: Opc = BO_LE; break; 12726 case tok::less: Opc = BO_LT; break; 12727 case tok::greaterequal: Opc = BO_GE; break; 12728 case tok::greater: Opc = BO_GT; break; 12729 case tok::exclaimequal: Opc = BO_NE; break; 12730 case tok::equalequal: Opc = BO_EQ; break; 12731 case tok::spaceship: Opc = BO_Cmp; break; 12732 case tok::amp: Opc = BO_And; break; 12733 case tok::caret: Opc = BO_Xor; break; 12734 case tok::pipe: Opc = BO_Or; break; 12735 case tok::ampamp: Opc = BO_LAnd; break; 12736 case tok::pipepipe: Opc = BO_LOr; break; 12737 case tok::equal: Opc = BO_Assign; break; 12738 case tok::starequal: Opc = BO_MulAssign; break; 12739 case tok::slashequal: Opc = BO_DivAssign; break; 12740 case tok::percentequal: Opc = BO_RemAssign; break; 12741 case tok::plusequal: Opc = BO_AddAssign; break; 12742 case tok::minusequal: Opc = BO_SubAssign; break; 12743 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12744 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12745 case tok::ampequal: Opc = BO_AndAssign; break; 12746 case tok::caretequal: Opc = BO_XorAssign; break; 12747 case tok::pipeequal: Opc = BO_OrAssign; break; 12748 case tok::comma: Opc = BO_Comma; break; 12749 } 12750 return Opc; 12751 } 12752 12753 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12754 tok::TokenKind Kind) { 12755 UnaryOperatorKind Opc; 12756 switch (Kind) { 12757 default: llvm_unreachable("Unknown unary op!"); 12758 case tok::plusplus: Opc = UO_PreInc; break; 12759 case tok::minusminus: Opc = UO_PreDec; break; 12760 case tok::amp: Opc = UO_AddrOf; break; 12761 case tok::star: Opc = UO_Deref; break; 12762 case tok::plus: Opc = UO_Plus; break; 12763 case tok::minus: Opc = UO_Minus; break; 12764 case tok::tilde: Opc = UO_Not; break; 12765 case tok::exclaim: Opc = UO_LNot; break; 12766 case tok::kw___real: Opc = UO_Real; break; 12767 case tok::kw___imag: Opc = UO_Imag; break; 12768 case tok::kw___extension__: Opc = UO_Extension; break; 12769 } 12770 return Opc; 12771 } 12772 12773 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12774 /// This warning suppressed in the event of macro expansions. 12775 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12776 SourceLocation OpLoc, bool IsBuiltin) { 12777 if (S.inTemplateInstantiation()) 12778 return; 12779 if (S.isUnevaluatedContext()) 12780 return; 12781 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12782 return; 12783 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12784 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12785 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12786 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12787 if (!LHSDeclRef || !RHSDeclRef || 12788 LHSDeclRef->getLocation().isMacroID() || 12789 RHSDeclRef->getLocation().isMacroID()) 12790 return; 12791 const ValueDecl *LHSDecl = 12792 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12793 const ValueDecl *RHSDecl = 12794 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12795 if (LHSDecl != RHSDecl) 12796 return; 12797 if (LHSDecl->getType().isVolatileQualified()) 12798 return; 12799 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12800 if (RefTy->getPointeeType().isVolatileQualified()) 12801 return; 12802 12803 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12804 : diag::warn_self_assignment_overloaded) 12805 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12806 << RHSExpr->getSourceRange(); 12807 } 12808 12809 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12810 /// is usually indicative of introspection within the Objective-C pointer. 12811 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12812 SourceLocation OpLoc) { 12813 if (!S.getLangOpts().ObjC) 12814 return; 12815 12816 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12817 const Expr *LHS = L.get(); 12818 const Expr *RHS = R.get(); 12819 12820 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12821 ObjCPointerExpr = LHS; 12822 OtherExpr = RHS; 12823 } 12824 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12825 ObjCPointerExpr = RHS; 12826 OtherExpr = LHS; 12827 } 12828 12829 // This warning is deliberately made very specific to reduce false 12830 // positives with logic that uses '&' for hashing. This logic mainly 12831 // looks for code trying to introspect into tagged pointers, which 12832 // code should generally never do. 12833 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12834 unsigned Diag = diag::warn_objc_pointer_masking; 12835 // Determine if we are introspecting the result of performSelectorXXX. 12836 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12837 // Special case messages to -performSelector and friends, which 12838 // can return non-pointer values boxed in a pointer value. 12839 // Some clients may wish to silence warnings in this subcase. 12840 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12841 Selector S = ME->getSelector(); 12842 StringRef SelArg0 = S.getNameForSlot(0); 12843 if (SelArg0.startswith("performSelector")) 12844 Diag = diag::warn_objc_pointer_masking_performSelector; 12845 } 12846 12847 S.Diag(OpLoc, Diag) 12848 << ObjCPointerExpr->getSourceRange(); 12849 } 12850 } 12851 12852 static NamedDecl *getDeclFromExpr(Expr *E) { 12853 if (!E) 12854 return nullptr; 12855 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12856 return DRE->getDecl(); 12857 if (auto *ME = dyn_cast<MemberExpr>(E)) 12858 return ME->getMemberDecl(); 12859 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12860 return IRE->getDecl(); 12861 return nullptr; 12862 } 12863 12864 // This helper function promotes a binary operator's operands (which are of a 12865 // half vector type) to a vector of floats and then truncates the result to 12866 // a vector of either half or short. 12867 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12868 BinaryOperatorKind Opc, QualType ResultTy, 12869 ExprValueKind VK, ExprObjectKind OK, 12870 bool IsCompAssign, SourceLocation OpLoc, 12871 FPOptions FPFeatures) { 12872 auto &Context = S.getASTContext(); 12873 assert((isVector(ResultTy, Context.HalfTy) || 12874 isVector(ResultTy, Context.ShortTy)) && 12875 "Result must be a vector of half or short"); 12876 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12877 isVector(RHS.get()->getType(), Context.HalfTy) && 12878 "both operands expected to be a half vector"); 12879 12880 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12881 QualType BinOpResTy = RHS.get()->getType(); 12882 12883 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12884 // change BinOpResTy to a vector of ints. 12885 if (isVector(ResultTy, Context.ShortTy)) 12886 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12887 12888 if (IsCompAssign) 12889 return new (Context) CompoundAssignOperator( 12890 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12891 OpLoc, FPFeatures); 12892 12893 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12894 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12895 VK, OK, OpLoc, FPFeatures); 12896 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12897 } 12898 12899 static std::pair<ExprResult, ExprResult> 12900 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12901 Expr *RHSExpr) { 12902 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12903 if (!S.getLangOpts().CPlusPlus) { 12904 // C cannot handle TypoExpr nodes on either side of a binop because it 12905 // doesn't handle dependent types properly, so make sure any TypoExprs have 12906 // been dealt with before checking the operands. 12907 LHS = S.CorrectDelayedTyposInExpr(LHS); 12908 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12909 if (Opc != BO_Assign) 12910 return ExprResult(E); 12911 // Avoid correcting the RHS to the same Expr as the LHS. 12912 Decl *D = getDeclFromExpr(E); 12913 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12914 }); 12915 } 12916 return std::make_pair(LHS, RHS); 12917 } 12918 12919 /// Returns true if conversion between vectors of halfs and vectors of floats 12920 /// is needed. 12921 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12922 QualType SrcType) { 12923 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12924 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12925 isVector(SrcType, Ctx.HalfTy); 12926 } 12927 12928 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12929 /// operator @p Opc at location @c TokLoc. This routine only supports 12930 /// built-in operations; ActOnBinOp handles overloaded operators. 12931 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12932 BinaryOperatorKind Opc, 12933 Expr *LHSExpr, Expr *RHSExpr) { 12934 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12935 // The syntax only allows initializer lists on the RHS of assignment, 12936 // so we don't need to worry about accepting invalid code for 12937 // non-assignment operators. 12938 // C++11 5.17p9: 12939 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12940 // of x = {} is x = T(). 12941 InitializationKind Kind = InitializationKind::CreateDirectList( 12942 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12943 InitializedEntity Entity = 12944 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12945 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12946 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12947 if (Init.isInvalid()) 12948 return Init; 12949 RHSExpr = Init.get(); 12950 } 12951 12952 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12953 QualType ResultTy; // Result type of the binary operator. 12954 // The following two variables are used for compound assignment operators 12955 QualType CompLHSTy; // Type of LHS after promotions for computation 12956 QualType CompResultTy; // Type of computation result 12957 ExprValueKind VK = VK_RValue; 12958 ExprObjectKind OK = OK_Ordinary; 12959 bool ConvertHalfVec = false; 12960 12961 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12962 if (!LHS.isUsable() || !RHS.isUsable()) 12963 return ExprError(); 12964 12965 if (getLangOpts().OpenCL) { 12966 QualType LHSTy = LHSExpr->getType(); 12967 QualType RHSTy = RHSExpr->getType(); 12968 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12969 // the ATOMIC_VAR_INIT macro. 12970 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12971 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12972 if (BO_Assign == Opc) 12973 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12974 else 12975 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12976 return ExprError(); 12977 } 12978 12979 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12980 // only with a builtin functions and therefore should be disallowed here. 12981 if (LHSTy->isImageType() || RHSTy->isImageType() || 12982 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12983 LHSTy->isPipeType() || RHSTy->isPipeType() || 12984 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12985 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12986 return ExprError(); 12987 } 12988 } 12989 12990 // Diagnose operations on the unsupported types for OpenMP device compilation. 12991 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12992 if (Opc != BO_Assign && Opc != BO_Comma) { 12993 checkOpenMPDeviceExpr(LHSExpr); 12994 checkOpenMPDeviceExpr(RHSExpr); 12995 } 12996 } 12997 12998 switch (Opc) { 12999 case BO_Assign: 13000 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13001 if (getLangOpts().CPlusPlus && 13002 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13003 VK = LHS.get()->getValueKind(); 13004 OK = LHS.get()->getObjectKind(); 13005 } 13006 if (!ResultTy.isNull()) { 13007 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13008 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13009 13010 // Avoid copying a block to the heap if the block is assigned to a local 13011 // auto variable that is declared in the same scope as the block. This 13012 // optimization is unsafe if the local variable is declared in an outer 13013 // scope. For example: 13014 // 13015 // BlockTy b; 13016 // { 13017 // b = ^{...}; 13018 // } 13019 // // It is unsafe to invoke the block here if it wasn't copied to the 13020 // // heap. 13021 // b(); 13022 13023 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13024 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13025 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13026 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13027 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13028 13029 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13030 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13031 NTCUC_Assignment, NTCUK_Copy); 13032 } 13033 RecordModifiableNonNullParam(*this, LHS.get()); 13034 break; 13035 case BO_PtrMemD: 13036 case BO_PtrMemI: 13037 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13038 Opc == BO_PtrMemI); 13039 break; 13040 case BO_Mul: 13041 case BO_Div: 13042 ConvertHalfVec = true; 13043 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13044 Opc == BO_Div); 13045 break; 13046 case BO_Rem: 13047 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13048 break; 13049 case BO_Add: 13050 ConvertHalfVec = true; 13051 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13052 break; 13053 case BO_Sub: 13054 ConvertHalfVec = true; 13055 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13056 break; 13057 case BO_Shl: 13058 case BO_Shr: 13059 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13060 break; 13061 case BO_LE: 13062 case BO_LT: 13063 case BO_GE: 13064 case BO_GT: 13065 ConvertHalfVec = true; 13066 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13067 break; 13068 case BO_EQ: 13069 case BO_NE: 13070 ConvertHalfVec = true; 13071 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13072 break; 13073 case BO_Cmp: 13074 ConvertHalfVec = true; 13075 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13076 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13077 break; 13078 case BO_And: 13079 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13080 LLVM_FALLTHROUGH; 13081 case BO_Xor: 13082 case BO_Or: 13083 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13084 break; 13085 case BO_LAnd: 13086 case BO_LOr: 13087 ConvertHalfVec = true; 13088 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13089 break; 13090 case BO_MulAssign: 13091 case BO_DivAssign: 13092 ConvertHalfVec = true; 13093 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13094 Opc == BO_DivAssign); 13095 CompLHSTy = CompResultTy; 13096 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13097 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13098 break; 13099 case BO_RemAssign: 13100 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13101 CompLHSTy = CompResultTy; 13102 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13103 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13104 break; 13105 case BO_AddAssign: 13106 ConvertHalfVec = true; 13107 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13108 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13109 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13110 break; 13111 case BO_SubAssign: 13112 ConvertHalfVec = true; 13113 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13114 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13115 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13116 break; 13117 case BO_ShlAssign: 13118 case BO_ShrAssign: 13119 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13120 CompLHSTy = CompResultTy; 13121 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13122 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13123 break; 13124 case BO_AndAssign: 13125 case BO_OrAssign: // fallthrough 13126 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13127 LLVM_FALLTHROUGH; 13128 case BO_XorAssign: 13129 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13130 CompLHSTy = CompResultTy; 13131 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13132 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13133 break; 13134 case BO_Comma: 13135 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13136 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13137 VK = RHS.get()->getValueKind(); 13138 OK = RHS.get()->getObjectKind(); 13139 } 13140 break; 13141 } 13142 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13143 return ExprError(); 13144 13145 if (ResultTy->isRealFloatingType() && 13146 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13147 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13148 // Mark the current function as usng floating point constrained intrinsics 13149 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13150 F->setUsesFPIntrin(true); 13151 } 13152 13153 // Some of the binary operations require promoting operands of half vector to 13154 // float vectors and truncating the result back to half vector. For now, we do 13155 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13156 // arm64). 13157 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13158 isVector(LHS.get()->getType(), Context.HalfTy) && 13159 "both sides are half vectors or neither sides are"); 13160 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13161 LHS.get()->getType()); 13162 13163 // Check for array bounds violations for both sides of the BinaryOperator 13164 CheckArrayAccess(LHS.get()); 13165 CheckArrayAccess(RHS.get()); 13166 13167 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13168 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13169 &Context.Idents.get("object_setClass"), 13170 SourceLocation(), LookupOrdinaryName); 13171 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13172 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13173 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13174 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13175 "object_setClass(") 13176 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13177 ",") 13178 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13179 } 13180 else 13181 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13182 } 13183 else if (const ObjCIvarRefExpr *OIRE = 13184 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13185 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13186 13187 // Opc is not a compound assignment if CompResultTy is null. 13188 if (CompResultTy.isNull()) { 13189 if (ConvertHalfVec) 13190 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13191 OpLoc, FPFeatures); 13192 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13193 OK, OpLoc, FPFeatures); 13194 } 13195 13196 // Handle compound assignments. 13197 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13198 OK_ObjCProperty) { 13199 VK = VK_LValue; 13200 OK = LHS.get()->getObjectKind(); 13201 } 13202 13203 if (ConvertHalfVec) 13204 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13205 OpLoc, FPFeatures); 13206 13207 return new (Context) CompoundAssignOperator( 13208 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13209 OpLoc, FPFeatures); 13210 } 13211 13212 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13213 /// operators are mixed in a way that suggests that the programmer forgot that 13214 /// comparison operators have higher precedence. The most typical example of 13215 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13216 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13217 SourceLocation OpLoc, Expr *LHSExpr, 13218 Expr *RHSExpr) { 13219 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13220 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13221 13222 // Check that one of the sides is a comparison operator and the other isn't. 13223 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13224 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13225 if (isLeftComp == isRightComp) 13226 return; 13227 13228 // Bitwise operations are sometimes used as eager logical ops. 13229 // Don't diagnose this. 13230 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13231 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13232 if (isLeftBitwise || isRightBitwise) 13233 return; 13234 13235 SourceRange DiagRange = isLeftComp 13236 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13237 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13238 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13239 SourceRange ParensRange = 13240 isLeftComp 13241 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13242 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13243 13244 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13245 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13246 SuggestParentheses(Self, OpLoc, 13247 Self.PDiag(diag::note_precedence_silence) << OpStr, 13248 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13249 SuggestParentheses(Self, OpLoc, 13250 Self.PDiag(diag::note_precedence_bitwise_first) 13251 << BinaryOperator::getOpcodeStr(Opc), 13252 ParensRange); 13253 } 13254 13255 /// It accepts a '&&' expr that is inside a '||' one. 13256 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13257 /// in parentheses. 13258 static void 13259 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13260 BinaryOperator *Bop) { 13261 assert(Bop->getOpcode() == BO_LAnd); 13262 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13263 << Bop->getSourceRange() << OpLoc; 13264 SuggestParentheses(Self, Bop->getOperatorLoc(), 13265 Self.PDiag(diag::note_precedence_silence) 13266 << Bop->getOpcodeStr(), 13267 Bop->getSourceRange()); 13268 } 13269 13270 /// Returns true if the given expression can be evaluated as a constant 13271 /// 'true'. 13272 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13273 bool Res; 13274 return !E->isValueDependent() && 13275 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13276 } 13277 13278 /// Returns true if the given expression can be evaluated as a constant 13279 /// 'false'. 13280 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13281 bool Res; 13282 return !E->isValueDependent() && 13283 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13284 } 13285 13286 /// Look for '&&' in the left hand of a '||' expr. 13287 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13288 Expr *LHSExpr, Expr *RHSExpr) { 13289 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13290 if (Bop->getOpcode() == BO_LAnd) { 13291 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13292 if (EvaluatesAsFalse(S, RHSExpr)) 13293 return; 13294 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13295 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13296 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13297 } else if (Bop->getOpcode() == BO_LOr) { 13298 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13299 // If it's "a || b && 1 || c" we didn't warn earlier for 13300 // "a || b && 1", but warn now. 13301 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13302 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13303 } 13304 } 13305 } 13306 } 13307 13308 /// Look for '&&' in the right hand of a '||' expr. 13309 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13310 Expr *LHSExpr, Expr *RHSExpr) { 13311 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13312 if (Bop->getOpcode() == BO_LAnd) { 13313 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13314 if (EvaluatesAsFalse(S, LHSExpr)) 13315 return; 13316 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13317 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13318 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13319 } 13320 } 13321 } 13322 13323 /// Look for bitwise op in the left or right hand of a bitwise op with 13324 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13325 /// the '&' expression in parentheses. 13326 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13327 SourceLocation OpLoc, Expr *SubExpr) { 13328 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13329 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13330 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13331 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13332 << Bop->getSourceRange() << OpLoc; 13333 SuggestParentheses(S, Bop->getOperatorLoc(), 13334 S.PDiag(diag::note_precedence_silence) 13335 << Bop->getOpcodeStr(), 13336 Bop->getSourceRange()); 13337 } 13338 } 13339 } 13340 13341 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13342 Expr *SubExpr, StringRef Shift) { 13343 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13344 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13345 StringRef Op = Bop->getOpcodeStr(); 13346 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13347 << Bop->getSourceRange() << OpLoc << Shift << Op; 13348 SuggestParentheses(S, Bop->getOperatorLoc(), 13349 S.PDiag(diag::note_precedence_silence) << Op, 13350 Bop->getSourceRange()); 13351 } 13352 } 13353 } 13354 13355 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13356 Expr *LHSExpr, Expr *RHSExpr) { 13357 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13358 if (!OCE) 13359 return; 13360 13361 FunctionDecl *FD = OCE->getDirectCallee(); 13362 if (!FD || !FD->isOverloadedOperator()) 13363 return; 13364 13365 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13366 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13367 return; 13368 13369 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13370 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13371 << (Kind == OO_LessLess); 13372 SuggestParentheses(S, OCE->getOperatorLoc(), 13373 S.PDiag(diag::note_precedence_silence) 13374 << (Kind == OO_LessLess ? "<<" : ">>"), 13375 OCE->getSourceRange()); 13376 SuggestParentheses( 13377 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13378 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13379 } 13380 13381 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13382 /// precedence. 13383 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13384 SourceLocation OpLoc, Expr *LHSExpr, 13385 Expr *RHSExpr){ 13386 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13387 if (BinaryOperator::isBitwiseOp(Opc)) 13388 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13389 13390 // Diagnose "arg1 & arg2 | arg3" 13391 if ((Opc == BO_Or || Opc == BO_Xor) && 13392 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13393 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13394 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13395 } 13396 13397 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13398 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13399 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13400 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13401 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13402 } 13403 13404 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13405 || Opc == BO_Shr) { 13406 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13407 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13408 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13409 } 13410 13411 // Warn on overloaded shift operators and comparisons, such as: 13412 // cout << 5 == 4; 13413 if (BinaryOperator::isComparisonOp(Opc)) 13414 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13415 } 13416 13417 // Binary Operators. 'Tok' is the token for the operator. 13418 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13419 tok::TokenKind Kind, 13420 Expr *LHSExpr, Expr *RHSExpr) { 13421 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13422 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13423 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13424 13425 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13426 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13427 13428 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13429 } 13430 13431 /// Build an overloaded binary operator expression in the given scope. 13432 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13433 BinaryOperatorKind Opc, 13434 Expr *LHS, Expr *RHS) { 13435 switch (Opc) { 13436 case BO_Assign: 13437 case BO_DivAssign: 13438 case BO_RemAssign: 13439 case BO_SubAssign: 13440 case BO_AndAssign: 13441 case BO_OrAssign: 13442 case BO_XorAssign: 13443 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13444 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13445 break; 13446 default: 13447 break; 13448 } 13449 13450 // Find all of the overloaded operators visible from this 13451 // point. We perform both an operator-name lookup from the local 13452 // scope and an argument-dependent lookup based on the types of 13453 // the arguments. 13454 UnresolvedSet<16> Functions; 13455 OverloadedOperatorKind OverOp 13456 = BinaryOperator::getOverloadedOperator(Opc); 13457 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13458 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13459 RHS->getType(), Functions); 13460 13461 // In C++20 onwards, we may have a second operator to look up. 13462 if (S.getLangOpts().CPlusPlus2a) { 13463 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13464 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13465 RHS->getType(), Functions); 13466 } 13467 13468 // Build the (potentially-overloaded, potentially-dependent) 13469 // binary operation. 13470 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13471 } 13472 13473 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13474 BinaryOperatorKind Opc, 13475 Expr *LHSExpr, Expr *RHSExpr) { 13476 ExprResult LHS, RHS; 13477 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13478 if (!LHS.isUsable() || !RHS.isUsable()) 13479 return ExprError(); 13480 LHSExpr = LHS.get(); 13481 RHSExpr = RHS.get(); 13482 13483 // We want to end up calling one of checkPseudoObjectAssignment 13484 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13485 // both expressions are overloadable or either is type-dependent), 13486 // or CreateBuiltinBinOp (in any other case). We also want to get 13487 // any placeholder types out of the way. 13488 13489 // Handle pseudo-objects in the LHS. 13490 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13491 // Assignments with a pseudo-object l-value need special analysis. 13492 if (pty->getKind() == BuiltinType::PseudoObject && 13493 BinaryOperator::isAssignmentOp(Opc)) 13494 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13495 13496 // Don't resolve overloads if the other type is overloadable. 13497 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13498 // We can't actually test that if we still have a placeholder, 13499 // though. Fortunately, none of the exceptions we see in that 13500 // code below are valid when the LHS is an overload set. Note 13501 // that an overload set can be dependently-typed, but it never 13502 // instantiates to having an overloadable type. 13503 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13504 if (resolvedRHS.isInvalid()) return ExprError(); 13505 RHSExpr = resolvedRHS.get(); 13506 13507 if (RHSExpr->isTypeDependent() || 13508 RHSExpr->getType()->isOverloadableType()) 13509 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13510 } 13511 13512 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13513 // template, diagnose the missing 'template' keyword instead of diagnosing 13514 // an invalid use of a bound member function. 13515 // 13516 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13517 // to C++1z [over.over]/1.4, but we already checked for that case above. 13518 if (Opc == BO_LT && inTemplateInstantiation() && 13519 (pty->getKind() == BuiltinType::BoundMember || 13520 pty->getKind() == BuiltinType::Overload)) { 13521 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13522 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13523 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13524 return isa<FunctionTemplateDecl>(ND); 13525 })) { 13526 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13527 : OE->getNameLoc(), 13528 diag::err_template_kw_missing) 13529 << OE->getName().getAsString() << ""; 13530 return ExprError(); 13531 } 13532 } 13533 13534 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13535 if (LHS.isInvalid()) return ExprError(); 13536 LHSExpr = LHS.get(); 13537 } 13538 13539 // Handle pseudo-objects in the RHS. 13540 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13541 // An overload in the RHS can potentially be resolved by the type 13542 // being assigned to. 13543 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13544 if (getLangOpts().CPlusPlus && 13545 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13546 LHSExpr->getType()->isOverloadableType())) 13547 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13548 13549 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13550 } 13551 13552 // Don't resolve overloads if the other type is overloadable. 13553 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13554 LHSExpr->getType()->isOverloadableType()) 13555 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13556 13557 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13558 if (!resolvedRHS.isUsable()) return ExprError(); 13559 RHSExpr = resolvedRHS.get(); 13560 } 13561 13562 if (getLangOpts().CPlusPlus) { 13563 // If either expression is type-dependent, always build an 13564 // overloaded op. 13565 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13566 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13567 13568 // Otherwise, build an overloaded op if either expression has an 13569 // overloadable type. 13570 if (LHSExpr->getType()->isOverloadableType() || 13571 RHSExpr->getType()->isOverloadableType()) 13572 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13573 } 13574 13575 // Build a built-in binary operation. 13576 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13577 } 13578 13579 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13580 if (T.isNull() || T->isDependentType()) 13581 return false; 13582 13583 if (!T->isPromotableIntegerType()) 13584 return true; 13585 13586 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13587 } 13588 13589 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13590 UnaryOperatorKind Opc, 13591 Expr *InputExpr) { 13592 ExprResult Input = InputExpr; 13593 ExprValueKind VK = VK_RValue; 13594 ExprObjectKind OK = OK_Ordinary; 13595 QualType resultType; 13596 bool CanOverflow = false; 13597 13598 bool ConvertHalfVec = false; 13599 if (getLangOpts().OpenCL) { 13600 QualType Ty = InputExpr->getType(); 13601 // The only legal unary operation for atomics is '&'. 13602 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13603 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13604 // only with a builtin functions and therefore should be disallowed here. 13605 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13606 || Ty->isBlockPointerType())) { 13607 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13608 << InputExpr->getType() 13609 << Input.get()->getSourceRange()); 13610 } 13611 } 13612 // Diagnose operations on the unsupported types for OpenMP device compilation. 13613 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13614 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13615 UnaryOperator::isArithmeticOp(Opc)) 13616 checkOpenMPDeviceExpr(InputExpr); 13617 } 13618 13619 switch (Opc) { 13620 case UO_PreInc: 13621 case UO_PreDec: 13622 case UO_PostInc: 13623 case UO_PostDec: 13624 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13625 OpLoc, 13626 Opc == UO_PreInc || 13627 Opc == UO_PostInc, 13628 Opc == UO_PreInc || 13629 Opc == UO_PreDec); 13630 CanOverflow = isOverflowingIntegerType(Context, resultType); 13631 break; 13632 case UO_AddrOf: 13633 resultType = CheckAddressOfOperand(Input, OpLoc); 13634 CheckAddressOfNoDeref(InputExpr); 13635 RecordModifiableNonNullParam(*this, InputExpr); 13636 break; 13637 case UO_Deref: { 13638 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13639 if (Input.isInvalid()) return ExprError(); 13640 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13641 break; 13642 } 13643 case UO_Plus: 13644 case UO_Minus: 13645 CanOverflow = Opc == UO_Minus && 13646 isOverflowingIntegerType(Context, Input.get()->getType()); 13647 Input = UsualUnaryConversions(Input.get()); 13648 if (Input.isInvalid()) return ExprError(); 13649 // Unary plus and minus require promoting an operand of half vector to a 13650 // float vector and truncating the result back to a half vector. For now, we 13651 // do this only when HalfArgsAndReturns is set (that is, when the target is 13652 // arm or arm64). 13653 ConvertHalfVec = 13654 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13655 13656 // If the operand is a half vector, promote it to a float vector. 13657 if (ConvertHalfVec) 13658 Input = convertVector(Input.get(), Context.FloatTy, *this); 13659 resultType = Input.get()->getType(); 13660 if (resultType->isDependentType()) 13661 break; 13662 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13663 break; 13664 else if (resultType->isVectorType() && 13665 // The z vector extensions don't allow + or - with bool vectors. 13666 (!Context.getLangOpts().ZVector || 13667 resultType->castAs<VectorType>()->getVectorKind() != 13668 VectorType::AltiVecBool)) 13669 break; 13670 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13671 Opc == UO_Plus && 13672 resultType->isPointerType()) 13673 break; 13674 13675 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13676 << resultType << Input.get()->getSourceRange()); 13677 13678 case UO_Not: // bitwise complement 13679 Input = UsualUnaryConversions(Input.get()); 13680 if (Input.isInvalid()) 13681 return ExprError(); 13682 resultType = Input.get()->getType(); 13683 if (resultType->isDependentType()) 13684 break; 13685 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13686 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13687 // C99 does not support '~' for complex conjugation. 13688 Diag(OpLoc, diag::ext_integer_complement_complex) 13689 << resultType << Input.get()->getSourceRange(); 13690 else if (resultType->hasIntegerRepresentation()) 13691 break; 13692 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13693 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13694 // on vector float types. 13695 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13696 if (!T->isIntegerType()) 13697 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13698 << resultType << Input.get()->getSourceRange()); 13699 } else { 13700 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13701 << resultType << Input.get()->getSourceRange()); 13702 } 13703 break; 13704 13705 case UO_LNot: // logical negation 13706 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13707 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13708 if (Input.isInvalid()) return ExprError(); 13709 resultType = Input.get()->getType(); 13710 13711 // Though we still have to promote half FP to float... 13712 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13713 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13714 resultType = Context.FloatTy; 13715 } 13716 13717 if (resultType->isDependentType()) 13718 break; 13719 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13720 // C99 6.5.3.3p1: ok, fallthrough; 13721 if (Context.getLangOpts().CPlusPlus) { 13722 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13723 // operand contextually converted to bool. 13724 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13725 ScalarTypeToBooleanCastKind(resultType)); 13726 } else if (Context.getLangOpts().OpenCL && 13727 Context.getLangOpts().OpenCLVersion < 120) { 13728 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13729 // operate on scalar float types. 13730 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13731 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13732 << resultType << Input.get()->getSourceRange()); 13733 } 13734 } else if (resultType->isExtVectorType()) { 13735 if (Context.getLangOpts().OpenCL && 13736 Context.getLangOpts().OpenCLVersion < 120 && 13737 !Context.getLangOpts().OpenCLCPlusPlus) { 13738 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13739 // operate on vector float types. 13740 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13741 if (!T->isIntegerType()) 13742 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13743 << resultType << Input.get()->getSourceRange()); 13744 } 13745 // Vector logical not returns the signed variant of the operand type. 13746 resultType = GetSignedVectorType(resultType); 13747 break; 13748 } else { 13749 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13750 // type in C++. We should allow that here too. 13751 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13752 << resultType << Input.get()->getSourceRange()); 13753 } 13754 13755 // LNot always has type int. C99 6.5.3.3p5. 13756 // In C++, it's bool. C++ 5.3.1p8 13757 resultType = Context.getLogicalOperationType(); 13758 break; 13759 case UO_Real: 13760 case UO_Imag: 13761 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13762 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13763 // complex l-values to ordinary l-values and all other values to r-values. 13764 if (Input.isInvalid()) return ExprError(); 13765 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13766 if (Input.get()->getValueKind() != VK_RValue && 13767 Input.get()->getObjectKind() == OK_Ordinary) 13768 VK = Input.get()->getValueKind(); 13769 } else if (!getLangOpts().CPlusPlus) { 13770 // In C, a volatile scalar is read by __imag. In C++, it is not. 13771 Input = DefaultLvalueConversion(Input.get()); 13772 } 13773 break; 13774 case UO_Extension: 13775 resultType = Input.get()->getType(); 13776 VK = Input.get()->getValueKind(); 13777 OK = Input.get()->getObjectKind(); 13778 break; 13779 case UO_Coawait: 13780 // It's unnecessary to represent the pass-through operator co_await in the 13781 // AST; just return the input expression instead. 13782 assert(!Input.get()->getType()->isDependentType() && 13783 "the co_await expression must be non-dependant before " 13784 "building operator co_await"); 13785 return Input; 13786 } 13787 if (resultType.isNull() || Input.isInvalid()) 13788 return ExprError(); 13789 13790 // Check for array bounds violations in the operand of the UnaryOperator, 13791 // except for the '*' and '&' operators that have to be handled specially 13792 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13793 // that are explicitly defined as valid by the standard). 13794 if (Opc != UO_AddrOf && Opc != UO_Deref) 13795 CheckArrayAccess(Input.get()); 13796 13797 auto *UO = new (Context) 13798 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13799 13800 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13801 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13802 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13803 13804 // Convert the result back to a half vector. 13805 if (ConvertHalfVec) 13806 return convertVector(UO, Context.HalfTy, *this); 13807 return UO; 13808 } 13809 13810 /// Determine whether the given expression is a qualified member 13811 /// access expression, of a form that could be turned into a pointer to member 13812 /// with the address-of operator. 13813 bool Sema::isQualifiedMemberAccess(Expr *E) { 13814 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13815 if (!DRE->getQualifier()) 13816 return false; 13817 13818 ValueDecl *VD = DRE->getDecl(); 13819 if (!VD->isCXXClassMember()) 13820 return false; 13821 13822 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13823 return true; 13824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13825 return Method->isInstance(); 13826 13827 return false; 13828 } 13829 13830 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13831 if (!ULE->getQualifier()) 13832 return false; 13833 13834 for (NamedDecl *D : ULE->decls()) { 13835 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13836 if (Method->isInstance()) 13837 return true; 13838 } else { 13839 // Overload set does not contain methods. 13840 break; 13841 } 13842 } 13843 13844 return false; 13845 } 13846 13847 return false; 13848 } 13849 13850 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13851 UnaryOperatorKind Opc, Expr *Input) { 13852 // First things first: handle placeholders so that the 13853 // overloaded-operator check considers the right type. 13854 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13855 // Increment and decrement of pseudo-object references. 13856 if (pty->getKind() == BuiltinType::PseudoObject && 13857 UnaryOperator::isIncrementDecrementOp(Opc)) 13858 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13859 13860 // extension is always a builtin operator. 13861 if (Opc == UO_Extension) 13862 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13863 13864 // & gets special logic for several kinds of placeholder. 13865 // The builtin code knows what to do. 13866 if (Opc == UO_AddrOf && 13867 (pty->getKind() == BuiltinType::Overload || 13868 pty->getKind() == BuiltinType::UnknownAny || 13869 pty->getKind() == BuiltinType::BoundMember)) 13870 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13871 13872 // Anything else needs to be handled now. 13873 ExprResult Result = CheckPlaceholderExpr(Input); 13874 if (Result.isInvalid()) return ExprError(); 13875 Input = Result.get(); 13876 } 13877 13878 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13879 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13880 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13881 // Find all of the overloaded operators visible from this 13882 // point. We perform both an operator-name lookup from the local 13883 // scope and an argument-dependent lookup based on the types of 13884 // the arguments. 13885 UnresolvedSet<16> Functions; 13886 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13887 if (S && OverOp != OO_None) 13888 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13889 Functions); 13890 13891 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13892 } 13893 13894 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13895 } 13896 13897 // Unary Operators. 'Tok' is the token for the operator. 13898 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13899 tok::TokenKind Op, Expr *Input) { 13900 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13901 } 13902 13903 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13904 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13905 LabelDecl *TheDecl) { 13906 TheDecl->markUsed(Context); 13907 // Create the AST node. The address of a label always has type 'void*'. 13908 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13909 Context.getPointerType(Context.VoidTy)); 13910 } 13911 13912 void Sema::ActOnStartStmtExpr() { 13913 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13914 } 13915 13916 void Sema::ActOnStmtExprError() { 13917 // Note that function is also called by TreeTransform when leaving a 13918 // StmtExpr scope without rebuilding anything. 13919 13920 DiscardCleanupsInEvaluationContext(); 13921 PopExpressionEvaluationContext(); 13922 } 13923 13924 ExprResult 13925 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13926 SourceLocation RPLoc) { // "({..})" 13927 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13928 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13929 13930 if (hasAnyUnrecoverableErrorsInThisFunction()) 13931 DiscardCleanupsInEvaluationContext(); 13932 assert(!Cleanup.exprNeedsCleanups() && 13933 "cleanups within StmtExpr not correctly bound!"); 13934 PopExpressionEvaluationContext(); 13935 13936 // FIXME: there are a variety of strange constraints to enforce here, for 13937 // example, it is not possible to goto into a stmt expression apparently. 13938 // More semantic analysis is needed. 13939 13940 // If there are sub-stmts in the compound stmt, take the type of the last one 13941 // as the type of the stmtexpr. 13942 QualType Ty = Context.VoidTy; 13943 bool StmtExprMayBindToTemp = false; 13944 if (!Compound->body_empty()) { 13945 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13946 if (const auto *LastStmt = 13947 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13948 if (const Expr *Value = LastStmt->getExprStmt()) { 13949 StmtExprMayBindToTemp = true; 13950 Ty = Value->getType(); 13951 } 13952 } 13953 } 13954 13955 // FIXME: Check that expression type is complete/non-abstract; statement 13956 // expressions are not lvalues. 13957 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13958 if (StmtExprMayBindToTemp) 13959 return MaybeBindToTemporary(ResStmtExpr); 13960 return ResStmtExpr; 13961 } 13962 13963 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13964 if (ER.isInvalid()) 13965 return ExprError(); 13966 13967 // Do function/array conversion on the last expression, but not 13968 // lvalue-to-rvalue. However, initialize an unqualified type. 13969 ER = DefaultFunctionArrayConversion(ER.get()); 13970 if (ER.isInvalid()) 13971 return ExprError(); 13972 Expr *E = ER.get(); 13973 13974 if (E->isTypeDependent()) 13975 return E; 13976 13977 // In ARC, if the final expression ends in a consume, splice 13978 // the consume out and bind it later. In the alternate case 13979 // (when dealing with a retainable type), the result 13980 // initialization will create a produce. In both cases the 13981 // result will be +1, and we'll need to balance that out with 13982 // a bind. 13983 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13984 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13985 return Cast->getSubExpr(); 13986 13987 // FIXME: Provide a better location for the initialization. 13988 return PerformCopyInitialization( 13989 InitializedEntity::InitializeStmtExprResult( 13990 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13991 SourceLocation(), E); 13992 } 13993 13994 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13995 TypeSourceInfo *TInfo, 13996 ArrayRef<OffsetOfComponent> Components, 13997 SourceLocation RParenLoc) { 13998 QualType ArgTy = TInfo->getType(); 13999 bool Dependent = ArgTy->isDependentType(); 14000 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14001 14002 // We must have at least one component that refers to the type, and the first 14003 // one is known to be a field designator. Verify that the ArgTy represents 14004 // a struct/union/class. 14005 if (!Dependent && !ArgTy->isRecordType()) 14006 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14007 << ArgTy << TypeRange); 14008 14009 // Type must be complete per C99 7.17p3 because a declaring a variable 14010 // with an incomplete type would be ill-formed. 14011 if (!Dependent 14012 && RequireCompleteType(BuiltinLoc, ArgTy, 14013 diag::err_offsetof_incomplete_type, TypeRange)) 14014 return ExprError(); 14015 14016 bool DidWarnAboutNonPOD = false; 14017 QualType CurrentType = ArgTy; 14018 SmallVector<OffsetOfNode, 4> Comps; 14019 SmallVector<Expr*, 4> Exprs; 14020 for (const OffsetOfComponent &OC : Components) { 14021 if (OC.isBrackets) { 14022 // Offset of an array sub-field. TODO: Should we allow vector elements? 14023 if (!CurrentType->isDependentType()) { 14024 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14025 if(!AT) 14026 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14027 << CurrentType); 14028 CurrentType = AT->getElementType(); 14029 } else 14030 CurrentType = Context.DependentTy; 14031 14032 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14033 if (IdxRval.isInvalid()) 14034 return ExprError(); 14035 Expr *Idx = IdxRval.get(); 14036 14037 // The expression must be an integral expression. 14038 // FIXME: An integral constant expression? 14039 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14040 !Idx->getType()->isIntegerType()) 14041 return ExprError( 14042 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14043 << Idx->getSourceRange()); 14044 14045 // Record this array index. 14046 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14047 Exprs.push_back(Idx); 14048 continue; 14049 } 14050 14051 // Offset of a field. 14052 if (CurrentType->isDependentType()) { 14053 // We have the offset of a field, but we can't look into the dependent 14054 // type. Just record the identifier of the field. 14055 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14056 CurrentType = Context.DependentTy; 14057 continue; 14058 } 14059 14060 // We need to have a complete type to look into. 14061 if (RequireCompleteType(OC.LocStart, CurrentType, 14062 diag::err_offsetof_incomplete_type)) 14063 return ExprError(); 14064 14065 // Look for the designated field. 14066 const RecordType *RC = CurrentType->getAs<RecordType>(); 14067 if (!RC) 14068 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14069 << CurrentType); 14070 RecordDecl *RD = RC->getDecl(); 14071 14072 // C++ [lib.support.types]p5: 14073 // The macro offsetof accepts a restricted set of type arguments in this 14074 // International Standard. type shall be a POD structure or a POD union 14075 // (clause 9). 14076 // C++11 [support.types]p4: 14077 // If type is not a standard-layout class (Clause 9), the results are 14078 // undefined. 14079 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14080 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14081 unsigned DiagID = 14082 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14083 : diag::ext_offsetof_non_pod_type; 14084 14085 if (!IsSafe && !DidWarnAboutNonPOD && 14086 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14087 PDiag(DiagID) 14088 << SourceRange(Components[0].LocStart, OC.LocEnd) 14089 << CurrentType)) 14090 DidWarnAboutNonPOD = true; 14091 } 14092 14093 // Look for the field. 14094 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14095 LookupQualifiedName(R, RD); 14096 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14097 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14098 if (!MemberDecl) { 14099 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14100 MemberDecl = IndirectMemberDecl->getAnonField(); 14101 } 14102 14103 if (!MemberDecl) 14104 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14105 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14106 OC.LocEnd)); 14107 14108 // C99 7.17p3: 14109 // (If the specified member is a bit-field, the behavior is undefined.) 14110 // 14111 // We diagnose this as an error. 14112 if (MemberDecl->isBitField()) { 14113 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14114 << MemberDecl->getDeclName() 14115 << SourceRange(BuiltinLoc, RParenLoc); 14116 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14117 return ExprError(); 14118 } 14119 14120 RecordDecl *Parent = MemberDecl->getParent(); 14121 if (IndirectMemberDecl) 14122 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14123 14124 // If the member was found in a base class, introduce OffsetOfNodes for 14125 // the base class indirections. 14126 CXXBasePaths Paths; 14127 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14128 Paths)) { 14129 if (Paths.getDetectedVirtual()) { 14130 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14131 << MemberDecl->getDeclName() 14132 << SourceRange(BuiltinLoc, RParenLoc); 14133 return ExprError(); 14134 } 14135 14136 CXXBasePath &Path = Paths.front(); 14137 for (const CXXBasePathElement &B : Path) 14138 Comps.push_back(OffsetOfNode(B.Base)); 14139 } 14140 14141 if (IndirectMemberDecl) { 14142 for (auto *FI : IndirectMemberDecl->chain()) { 14143 assert(isa<FieldDecl>(FI)); 14144 Comps.push_back(OffsetOfNode(OC.LocStart, 14145 cast<FieldDecl>(FI), OC.LocEnd)); 14146 } 14147 } else 14148 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14149 14150 CurrentType = MemberDecl->getType().getNonReferenceType(); 14151 } 14152 14153 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14154 Comps, Exprs, RParenLoc); 14155 } 14156 14157 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14158 SourceLocation BuiltinLoc, 14159 SourceLocation TypeLoc, 14160 ParsedType ParsedArgTy, 14161 ArrayRef<OffsetOfComponent> Components, 14162 SourceLocation RParenLoc) { 14163 14164 TypeSourceInfo *ArgTInfo; 14165 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14166 if (ArgTy.isNull()) 14167 return ExprError(); 14168 14169 if (!ArgTInfo) 14170 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14171 14172 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14173 } 14174 14175 14176 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14177 Expr *CondExpr, 14178 Expr *LHSExpr, Expr *RHSExpr, 14179 SourceLocation RPLoc) { 14180 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14181 14182 ExprValueKind VK = VK_RValue; 14183 ExprObjectKind OK = OK_Ordinary; 14184 QualType resType; 14185 bool ValueDependent = false; 14186 bool CondIsTrue = false; 14187 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14188 resType = Context.DependentTy; 14189 ValueDependent = true; 14190 } else { 14191 // The conditional expression is required to be a constant expression. 14192 llvm::APSInt condEval(32); 14193 ExprResult CondICE 14194 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14195 diag::err_typecheck_choose_expr_requires_constant, false); 14196 if (CondICE.isInvalid()) 14197 return ExprError(); 14198 CondExpr = CondICE.get(); 14199 CondIsTrue = condEval.getZExtValue(); 14200 14201 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14202 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14203 14204 resType = ActiveExpr->getType(); 14205 ValueDependent = ActiveExpr->isValueDependent(); 14206 VK = ActiveExpr->getValueKind(); 14207 OK = ActiveExpr->getObjectKind(); 14208 } 14209 14210 return new (Context) 14211 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14212 CondIsTrue, resType->isDependentType(), ValueDependent); 14213 } 14214 14215 //===----------------------------------------------------------------------===// 14216 // Clang Extensions. 14217 //===----------------------------------------------------------------------===// 14218 14219 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14220 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14221 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14222 14223 if (LangOpts.CPlusPlus) { 14224 MangleNumberingContext *MCtx; 14225 Decl *ManglingContextDecl; 14226 std::tie(MCtx, ManglingContextDecl) = 14227 getCurrentMangleNumberContext(Block->getDeclContext()); 14228 if (MCtx) { 14229 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14230 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14231 } 14232 } 14233 14234 PushBlockScope(CurScope, Block); 14235 CurContext->addDecl(Block); 14236 if (CurScope) 14237 PushDeclContext(CurScope, Block); 14238 else 14239 CurContext = Block; 14240 14241 getCurBlock()->HasImplicitReturnType = true; 14242 14243 // Enter a new evaluation context to insulate the block from any 14244 // cleanups from the enclosing full-expression. 14245 PushExpressionEvaluationContext( 14246 ExpressionEvaluationContext::PotentiallyEvaluated); 14247 } 14248 14249 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14250 Scope *CurScope) { 14251 assert(ParamInfo.getIdentifier() == nullptr && 14252 "block-id should have no identifier!"); 14253 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14254 BlockScopeInfo *CurBlock = getCurBlock(); 14255 14256 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14257 QualType T = Sig->getType(); 14258 14259 // FIXME: We should allow unexpanded parameter packs here, but that would, 14260 // in turn, make the block expression contain unexpanded parameter packs. 14261 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14262 // Drop the parameters. 14263 FunctionProtoType::ExtProtoInfo EPI; 14264 EPI.HasTrailingReturn = false; 14265 EPI.TypeQuals.addConst(); 14266 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14267 Sig = Context.getTrivialTypeSourceInfo(T); 14268 } 14269 14270 // GetTypeForDeclarator always produces a function type for a block 14271 // literal signature. Furthermore, it is always a FunctionProtoType 14272 // unless the function was written with a typedef. 14273 assert(T->isFunctionType() && 14274 "GetTypeForDeclarator made a non-function block signature"); 14275 14276 // Look for an explicit signature in that function type. 14277 FunctionProtoTypeLoc ExplicitSignature; 14278 14279 if ((ExplicitSignature = Sig->getTypeLoc() 14280 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14281 14282 // Check whether that explicit signature was synthesized by 14283 // GetTypeForDeclarator. If so, don't save that as part of the 14284 // written signature. 14285 if (ExplicitSignature.getLocalRangeBegin() == 14286 ExplicitSignature.getLocalRangeEnd()) { 14287 // This would be much cheaper if we stored TypeLocs instead of 14288 // TypeSourceInfos. 14289 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14290 unsigned Size = Result.getFullDataSize(); 14291 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14292 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14293 14294 ExplicitSignature = FunctionProtoTypeLoc(); 14295 } 14296 } 14297 14298 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14299 CurBlock->FunctionType = T; 14300 14301 const FunctionType *Fn = T->getAs<FunctionType>(); 14302 QualType RetTy = Fn->getReturnType(); 14303 bool isVariadic = 14304 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14305 14306 CurBlock->TheDecl->setIsVariadic(isVariadic); 14307 14308 // Context.DependentTy is used as a placeholder for a missing block 14309 // return type. TODO: what should we do with declarators like: 14310 // ^ * { ... } 14311 // If the answer is "apply template argument deduction".... 14312 if (RetTy != Context.DependentTy) { 14313 CurBlock->ReturnType = RetTy; 14314 CurBlock->TheDecl->setBlockMissingReturnType(false); 14315 CurBlock->HasImplicitReturnType = false; 14316 } 14317 14318 // Push block parameters from the declarator if we had them. 14319 SmallVector<ParmVarDecl*, 8> Params; 14320 if (ExplicitSignature) { 14321 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14322 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14323 if (Param->getIdentifier() == nullptr && 14324 !Param->isImplicit() && 14325 !Param->isInvalidDecl() && 14326 !getLangOpts().CPlusPlus) 14327 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14328 Params.push_back(Param); 14329 } 14330 14331 // Fake up parameter variables if we have a typedef, like 14332 // ^ fntype { ... } 14333 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14334 for (const auto &I : Fn->param_types()) { 14335 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14336 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14337 Params.push_back(Param); 14338 } 14339 } 14340 14341 // Set the parameters on the block decl. 14342 if (!Params.empty()) { 14343 CurBlock->TheDecl->setParams(Params); 14344 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14345 /*CheckParameterNames=*/false); 14346 } 14347 14348 // Finally we can process decl attributes. 14349 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14350 14351 // Put the parameter variables in scope. 14352 for (auto AI : CurBlock->TheDecl->parameters()) { 14353 AI->setOwningFunction(CurBlock->TheDecl); 14354 14355 // If this has an identifier, add it to the scope stack. 14356 if (AI->getIdentifier()) { 14357 CheckShadow(CurBlock->TheScope, AI); 14358 14359 PushOnScopeChains(AI, CurBlock->TheScope); 14360 } 14361 } 14362 } 14363 14364 /// ActOnBlockError - If there is an error parsing a block, this callback 14365 /// is invoked to pop the information about the block from the action impl. 14366 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14367 // Leave the expression-evaluation context. 14368 DiscardCleanupsInEvaluationContext(); 14369 PopExpressionEvaluationContext(); 14370 14371 // Pop off CurBlock, handle nested blocks. 14372 PopDeclContext(); 14373 PopFunctionScopeInfo(); 14374 } 14375 14376 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14377 /// literal was successfully completed. ^(int x){...} 14378 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14379 Stmt *Body, Scope *CurScope) { 14380 // If blocks are disabled, emit an error. 14381 if (!LangOpts.Blocks) 14382 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14383 14384 // Leave the expression-evaluation context. 14385 if (hasAnyUnrecoverableErrorsInThisFunction()) 14386 DiscardCleanupsInEvaluationContext(); 14387 assert(!Cleanup.exprNeedsCleanups() && 14388 "cleanups within block not correctly bound!"); 14389 PopExpressionEvaluationContext(); 14390 14391 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14392 BlockDecl *BD = BSI->TheDecl; 14393 14394 if (BSI->HasImplicitReturnType) 14395 deduceClosureReturnType(*BSI); 14396 14397 QualType RetTy = Context.VoidTy; 14398 if (!BSI->ReturnType.isNull()) 14399 RetTy = BSI->ReturnType; 14400 14401 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14402 QualType BlockTy; 14403 14404 // If the user wrote a function type in some form, try to use that. 14405 if (!BSI->FunctionType.isNull()) { 14406 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14407 14408 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14409 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14410 14411 // Turn protoless block types into nullary block types. 14412 if (isa<FunctionNoProtoType>(FTy)) { 14413 FunctionProtoType::ExtProtoInfo EPI; 14414 EPI.ExtInfo = Ext; 14415 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14416 14417 // Otherwise, if we don't need to change anything about the function type, 14418 // preserve its sugar structure. 14419 } else if (FTy->getReturnType() == RetTy && 14420 (!NoReturn || FTy->getNoReturnAttr())) { 14421 BlockTy = BSI->FunctionType; 14422 14423 // Otherwise, make the minimal modifications to the function type. 14424 } else { 14425 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14426 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14427 EPI.TypeQuals = Qualifiers(); 14428 EPI.ExtInfo = Ext; 14429 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14430 } 14431 14432 // If we don't have a function type, just build one from nothing. 14433 } else { 14434 FunctionProtoType::ExtProtoInfo EPI; 14435 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14436 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14437 } 14438 14439 DiagnoseUnusedParameters(BD->parameters()); 14440 BlockTy = Context.getBlockPointerType(BlockTy); 14441 14442 // If needed, diagnose invalid gotos and switches in the block. 14443 if (getCurFunction()->NeedsScopeChecking() && 14444 !PP.isCodeCompletionEnabled()) 14445 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14446 14447 BD->setBody(cast<CompoundStmt>(Body)); 14448 14449 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14450 DiagnoseUnguardedAvailabilityViolations(BD); 14451 14452 // Try to apply the named return value optimization. We have to check again 14453 // if we can do this, though, because blocks keep return statements around 14454 // to deduce an implicit return type. 14455 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14456 !BD->isDependentContext()) 14457 computeNRVO(Body, BSI); 14458 14459 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14460 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14461 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14462 NTCUK_Destruct|NTCUK_Copy); 14463 14464 PopDeclContext(); 14465 14466 // Pop the block scope now but keep it alive to the end of this function. 14467 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14468 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14469 14470 // Set the captured variables on the block. 14471 SmallVector<BlockDecl::Capture, 4> Captures; 14472 for (Capture &Cap : BSI->Captures) { 14473 if (Cap.isInvalid() || Cap.isThisCapture()) 14474 continue; 14475 14476 VarDecl *Var = Cap.getVariable(); 14477 Expr *CopyExpr = nullptr; 14478 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14479 if (const RecordType *Record = 14480 Cap.getCaptureType()->getAs<RecordType>()) { 14481 // The capture logic needs the destructor, so make sure we mark it. 14482 // Usually this is unnecessary because most local variables have 14483 // their destructors marked at declaration time, but parameters are 14484 // an exception because it's technically only the call site that 14485 // actually requires the destructor. 14486 if (isa<ParmVarDecl>(Var)) 14487 FinalizeVarWithDestructor(Var, Record); 14488 14489 // Enter a separate potentially-evaluated context while building block 14490 // initializers to isolate their cleanups from those of the block 14491 // itself. 14492 // FIXME: Is this appropriate even when the block itself occurs in an 14493 // unevaluated operand? 14494 EnterExpressionEvaluationContext EvalContext( 14495 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14496 14497 SourceLocation Loc = Cap.getLocation(); 14498 14499 ExprResult Result = BuildDeclarationNameExpr( 14500 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14501 14502 // According to the blocks spec, the capture of a variable from 14503 // the stack requires a const copy constructor. This is not true 14504 // of the copy/move done to move a __block variable to the heap. 14505 if (!Result.isInvalid() && 14506 !Result.get()->getType().isConstQualified()) { 14507 Result = ImpCastExprToType(Result.get(), 14508 Result.get()->getType().withConst(), 14509 CK_NoOp, VK_LValue); 14510 } 14511 14512 if (!Result.isInvalid()) { 14513 Result = PerformCopyInitialization( 14514 InitializedEntity::InitializeBlock(Var->getLocation(), 14515 Cap.getCaptureType(), false), 14516 Loc, Result.get()); 14517 } 14518 14519 // Build a full-expression copy expression if initialization 14520 // succeeded and used a non-trivial constructor. Recover from 14521 // errors by pretending that the copy isn't necessary. 14522 if (!Result.isInvalid() && 14523 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14524 ->isTrivial()) { 14525 Result = MaybeCreateExprWithCleanups(Result); 14526 CopyExpr = Result.get(); 14527 } 14528 } 14529 } 14530 14531 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14532 CopyExpr); 14533 Captures.push_back(NewCap); 14534 } 14535 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14536 14537 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14538 14539 // If the block isn't obviously global, i.e. it captures anything at 14540 // all, then we need to do a few things in the surrounding context: 14541 if (Result->getBlockDecl()->hasCaptures()) { 14542 // First, this expression has a new cleanup object. 14543 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14544 Cleanup.setExprNeedsCleanups(true); 14545 14546 // It also gets a branch-protected scope if any of the captured 14547 // variables needs destruction. 14548 for (const auto &CI : Result->getBlockDecl()->captures()) { 14549 const VarDecl *var = CI.getVariable(); 14550 if (var->getType().isDestructedType() != QualType::DK_none) { 14551 setFunctionHasBranchProtectedScope(); 14552 break; 14553 } 14554 } 14555 } 14556 14557 if (getCurFunction()) 14558 getCurFunction()->addBlock(BD); 14559 14560 return Result; 14561 } 14562 14563 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14564 SourceLocation RPLoc) { 14565 TypeSourceInfo *TInfo; 14566 GetTypeFromParser(Ty, &TInfo); 14567 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14568 } 14569 14570 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14571 Expr *E, TypeSourceInfo *TInfo, 14572 SourceLocation RPLoc) { 14573 Expr *OrigExpr = E; 14574 bool IsMS = false; 14575 14576 // CUDA device code does not support varargs. 14577 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14578 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14579 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14580 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14581 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14582 } 14583 } 14584 14585 // NVPTX does not support va_arg expression. 14586 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14587 Context.getTargetInfo().getTriple().isNVPTX()) 14588 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14589 14590 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14591 // as Microsoft ABI on an actual Microsoft platform, where 14592 // __builtin_ms_va_list and __builtin_va_list are the same.) 14593 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14594 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14595 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14596 if (Context.hasSameType(MSVaListType, E->getType())) { 14597 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14598 return ExprError(); 14599 IsMS = true; 14600 } 14601 } 14602 14603 // Get the va_list type 14604 QualType VaListType = Context.getBuiltinVaListType(); 14605 if (!IsMS) { 14606 if (VaListType->isArrayType()) { 14607 // Deal with implicit array decay; for example, on x86-64, 14608 // va_list is an array, but it's supposed to decay to 14609 // a pointer for va_arg. 14610 VaListType = Context.getArrayDecayedType(VaListType); 14611 // Make sure the input expression also decays appropriately. 14612 ExprResult Result = UsualUnaryConversions(E); 14613 if (Result.isInvalid()) 14614 return ExprError(); 14615 E = Result.get(); 14616 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14617 // If va_list is a record type and we are compiling in C++ mode, 14618 // check the argument using reference binding. 14619 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14620 Context, Context.getLValueReferenceType(VaListType), false); 14621 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14622 if (Init.isInvalid()) 14623 return ExprError(); 14624 E = Init.getAs<Expr>(); 14625 } else { 14626 // Otherwise, the va_list argument must be an l-value because 14627 // it is modified by va_arg. 14628 if (!E->isTypeDependent() && 14629 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14630 return ExprError(); 14631 } 14632 } 14633 14634 if (!IsMS && !E->isTypeDependent() && 14635 !Context.hasSameType(VaListType, E->getType())) 14636 return ExprError( 14637 Diag(E->getBeginLoc(), 14638 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14639 << OrigExpr->getType() << E->getSourceRange()); 14640 14641 if (!TInfo->getType()->isDependentType()) { 14642 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14643 diag::err_second_parameter_to_va_arg_incomplete, 14644 TInfo->getTypeLoc())) 14645 return ExprError(); 14646 14647 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14648 TInfo->getType(), 14649 diag::err_second_parameter_to_va_arg_abstract, 14650 TInfo->getTypeLoc())) 14651 return ExprError(); 14652 14653 if (!TInfo->getType().isPODType(Context)) { 14654 Diag(TInfo->getTypeLoc().getBeginLoc(), 14655 TInfo->getType()->isObjCLifetimeType() 14656 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14657 : diag::warn_second_parameter_to_va_arg_not_pod) 14658 << TInfo->getType() 14659 << TInfo->getTypeLoc().getSourceRange(); 14660 } 14661 14662 // Check for va_arg where arguments of the given type will be promoted 14663 // (i.e. this va_arg is guaranteed to have undefined behavior). 14664 QualType PromoteType; 14665 if (TInfo->getType()->isPromotableIntegerType()) { 14666 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14667 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14668 PromoteType = QualType(); 14669 } 14670 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14671 PromoteType = Context.DoubleTy; 14672 if (!PromoteType.isNull()) 14673 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14674 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14675 << TInfo->getType() 14676 << PromoteType 14677 << TInfo->getTypeLoc().getSourceRange()); 14678 } 14679 14680 QualType T = TInfo->getType().getNonLValueExprType(Context); 14681 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14682 } 14683 14684 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14685 // The type of __null will be int or long, depending on the size of 14686 // pointers on the target. 14687 QualType Ty; 14688 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14689 if (pw == Context.getTargetInfo().getIntWidth()) 14690 Ty = Context.IntTy; 14691 else if (pw == Context.getTargetInfo().getLongWidth()) 14692 Ty = Context.LongTy; 14693 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14694 Ty = Context.LongLongTy; 14695 else { 14696 llvm_unreachable("I don't know size of pointer!"); 14697 } 14698 14699 return new (Context) GNUNullExpr(Ty, TokenLoc); 14700 } 14701 14702 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14703 SourceLocation BuiltinLoc, 14704 SourceLocation RPLoc) { 14705 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14706 } 14707 14708 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14709 SourceLocation BuiltinLoc, 14710 SourceLocation RPLoc, 14711 DeclContext *ParentContext) { 14712 return new (Context) 14713 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14714 } 14715 14716 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14717 bool Diagnose) { 14718 if (!getLangOpts().ObjC) 14719 return false; 14720 14721 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14722 if (!PT) 14723 return false; 14724 14725 if (!PT->isObjCIdType()) { 14726 // Check if the destination is the 'NSString' interface. 14727 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14728 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14729 return false; 14730 } 14731 14732 // Ignore any parens, implicit casts (should only be 14733 // array-to-pointer decays), and not-so-opaque values. The last is 14734 // important for making this trigger for property assignments. 14735 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14736 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14737 if (OV->getSourceExpr()) 14738 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14739 14740 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14741 if (!SL || !SL->isAscii()) 14742 return false; 14743 if (Diagnose) { 14744 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14745 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14746 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14747 } 14748 return true; 14749 } 14750 14751 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14752 const Expr *SrcExpr) { 14753 if (!DstType->isFunctionPointerType() || 14754 !SrcExpr->getType()->isFunctionType()) 14755 return false; 14756 14757 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14758 if (!DRE) 14759 return false; 14760 14761 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14762 if (!FD) 14763 return false; 14764 14765 return !S.checkAddressOfFunctionIsAvailable(FD, 14766 /*Complain=*/true, 14767 SrcExpr->getBeginLoc()); 14768 } 14769 14770 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14771 SourceLocation Loc, 14772 QualType DstType, QualType SrcType, 14773 Expr *SrcExpr, AssignmentAction Action, 14774 bool *Complained) { 14775 if (Complained) 14776 *Complained = false; 14777 14778 // Decode the result (notice that AST's are still created for extensions). 14779 bool CheckInferredResultType = false; 14780 bool isInvalid = false; 14781 unsigned DiagKind = 0; 14782 FixItHint Hint; 14783 ConversionFixItGenerator ConvHints; 14784 bool MayHaveConvFixit = false; 14785 bool MayHaveFunctionDiff = false; 14786 const ObjCInterfaceDecl *IFace = nullptr; 14787 const ObjCProtocolDecl *PDecl = nullptr; 14788 14789 switch (ConvTy) { 14790 case Compatible: 14791 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14792 return false; 14793 14794 case PointerToInt: 14795 if (getLangOpts().CPlusPlus) { 14796 DiagKind = diag::err_typecheck_convert_pointer_int; 14797 isInvalid = true; 14798 } else { 14799 DiagKind = diag::ext_typecheck_convert_pointer_int; 14800 } 14801 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14802 MayHaveConvFixit = true; 14803 break; 14804 case IntToPointer: 14805 if (getLangOpts().CPlusPlus) { 14806 DiagKind = diag::err_typecheck_convert_int_pointer; 14807 isInvalid = true; 14808 } else { 14809 DiagKind = diag::ext_typecheck_convert_int_pointer; 14810 } 14811 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14812 MayHaveConvFixit = true; 14813 break; 14814 case IncompatibleFunctionPointer: 14815 if (getLangOpts().CPlusPlus) { 14816 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 14817 isInvalid = true; 14818 } else { 14819 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14820 } 14821 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14822 MayHaveConvFixit = true; 14823 break; 14824 case IncompatiblePointer: 14825 if (Action == AA_Passing_CFAudited) { 14826 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14827 } else if (getLangOpts().CPlusPlus) { 14828 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 14829 isInvalid = true; 14830 } else { 14831 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14832 } 14833 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14834 SrcType->isObjCObjectPointerType(); 14835 if (Hint.isNull() && !CheckInferredResultType) { 14836 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14837 } 14838 else if (CheckInferredResultType) { 14839 SrcType = SrcType.getUnqualifiedType(); 14840 DstType = DstType.getUnqualifiedType(); 14841 } 14842 MayHaveConvFixit = true; 14843 break; 14844 case IncompatiblePointerSign: 14845 if (getLangOpts().CPlusPlus) { 14846 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 14847 isInvalid = true; 14848 } else { 14849 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14850 } 14851 break; 14852 case FunctionVoidPointer: 14853 if (getLangOpts().CPlusPlus) { 14854 DiagKind = diag::err_typecheck_convert_pointer_void_func; 14855 isInvalid = true; 14856 } else { 14857 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14858 } 14859 break; 14860 case IncompatiblePointerDiscardsQualifiers: { 14861 // Perform array-to-pointer decay if necessary. 14862 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14863 14864 isInvalid = true; 14865 14866 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14867 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14868 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14869 DiagKind = diag::err_typecheck_incompatible_address_space; 14870 break; 14871 14872 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14873 DiagKind = diag::err_typecheck_incompatible_ownership; 14874 break; 14875 } 14876 14877 llvm_unreachable("unknown error case for discarding qualifiers!"); 14878 // fallthrough 14879 } 14880 case CompatiblePointerDiscardsQualifiers: 14881 // If the qualifiers lost were because we were applying the 14882 // (deprecated) C++ conversion from a string literal to a char* 14883 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14884 // Ideally, this check would be performed in 14885 // checkPointerTypesForAssignment. However, that would require a 14886 // bit of refactoring (so that the second argument is an 14887 // expression, rather than a type), which should be done as part 14888 // of a larger effort to fix checkPointerTypesForAssignment for 14889 // C++ semantics. 14890 if (getLangOpts().CPlusPlus && 14891 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14892 return false; 14893 if (getLangOpts().CPlusPlus) { 14894 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 14895 isInvalid = true; 14896 } else { 14897 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14898 } 14899 14900 break; 14901 case IncompatibleNestedPointerQualifiers: 14902 if (getLangOpts().CPlusPlus) { 14903 isInvalid = true; 14904 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 14905 } else { 14906 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14907 } 14908 break; 14909 case IncompatibleNestedPointerAddressSpaceMismatch: 14910 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14911 isInvalid = true; 14912 break; 14913 case IntToBlockPointer: 14914 DiagKind = diag::err_int_to_block_pointer; 14915 isInvalid = true; 14916 break; 14917 case IncompatibleBlockPointer: 14918 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14919 isInvalid = true; 14920 break; 14921 case IncompatibleObjCQualifiedId: { 14922 if (SrcType->isObjCQualifiedIdType()) { 14923 const ObjCObjectPointerType *srcOPT = 14924 SrcType->castAs<ObjCObjectPointerType>(); 14925 for (auto *srcProto : srcOPT->quals()) { 14926 PDecl = srcProto; 14927 break; 14928 } 14929 if (const ObjCInterfaceType *IFaceT = 14930 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14931 IFace = IFaceT->getDecl(); 14932 } 14933 else if (DstType->isObjCQualifiedIdType()) { 14934 const ObjCObjectPointerType *dstOPT = 14935 DstType->castAs<ObjCObjectPointerType>(); 14936 for (auto *dstProto : dstOPT->quals()) { 14937 PDecl = dstProto; 14938 break; 14939 } 14940 if (const ObjCInterfaceType *IFaceT = 14941 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14942 IFace = IFaceT->getDecl(); 14943 } 14944 if (getLangOpts().CPlusPlus) { 14945 DiagKind = diag::err_incompatible_qualified_id; 14946 isInvalid = true; 14947 } else { 14948 DiagKind = diag::warn_incompatible_qualified_id; 14949 } 14950 break; 14951 } 14952 case IncompatibleVectors: 14953 if (getLangOpts().CPlusPlus) { 14954 DiagKind = diag::err_incompatible_vectors; 14955 isInvalid = true; 14956 } else { 14957 DiagKind = diag::warn_incompatible_vectors; 14958 } 14959 break; 14960 case IncompatibleObjCWeakRef: 14961 DiagKind = diag::err_arc_weak_unavailable_assign; 14962 isInvalid = true; 14963 break; 14964 case Incompatible: 14965 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14966 if (Complained) 14967 *Complained = true; 14968 return true; 14969 } 14970 14971 DiagKind = diag::err_typecheck_convert_incompatible; 14972 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14973 MayHaveConvFixit = true; 14974 isInvalid = true; 14975 MayHaveFunctionDiff = true; 14976 break; 14977 } 14978 14979 QualType FirstType, SecondType; 14980 switch (Action) { 14981 case AA_Assigning: 14982 case AA_Initializing: 14983 // The destination type comes first. 14984 FirstType = DstType; 14985 SecondType = SrcType; 14986 break; 14987 14988 case AA_Returning: 14989 case AA_Passing: 14990 case AA_Passing_CFAudited: 14991 case AA_Converting: 14992 case AA_Sending: 14993 case AA_Casting: 14994 // The source type comes first. 14995 FirstType = SrcType; 14996 SecondType = DstType; 14997 break; 14998 } 14999 15000 PartialDiagnostic FDiag = PDiag(DiagKind); 15001 if (Action == AA_Passing_CFAudited) 15002 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15003 else 15004 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15005 15006 // If we can fix the conversion, suggest the FixIts. 15007 assert(ConvHints.isNull() || Hint.isNull()); 15008 if (!ConvHints.isNull()) { 15009 for (FixItHint &H : ConvHints.Hints) 15010 FDiag << H; 15011 } else { 15012 FDiag << Hint; 15013 } 15014 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15015 15016 if (MayHaveFunctionDiff) 15017 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15018 15019 Diag(Loc, FDiag); 15020 if ((DiagKind == diag::warn_incompatible_qualified_id || 15021 DiagKind == diag::err_incompatible_qualified_id) && 15022 PDecl && IFace && !IFace->hasDefinition()) 15023 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15024 << IFace << PDecl; 15025 15026 if (SecondType == Context.OverloadTy) 15027 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15028 FirstType, /*TakingAddress=*/true); 15029 15030 if (CheckInferredResultType) 15031 EmitRelatedResultTypeNote(SrcExpr); 15032 15033 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15034 EmitRelatedResultTypeNoteForReturn(DstType); 15035 15036 if (Complained) 15037 *Complained = true; 15038 return isInvalid; 15039 } 15040 15041 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15042 llvm::APSInt *Result) { 15043 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15044 public: 15045 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15046 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15047 } 15048 } Diagnoser; 15049 15050 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15051 } 15052 15053 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15054 llvm::APSInt *Result, 15055 unsigned DiagID, 15056 bool AllowFold) { 15057 class IDDiagnoser : public VerifyICEDiagnoser { 15058 unsigned DiagID; 15059 15060 public: 15061 IDDiagnoser(unsigned DiagID) 15062 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15063 15064 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15065 S.Diag(Loc, DiagID) << SR; 15066 } 15067 } Diagnoser(DiagID); 15068 15069 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15070 } 15071 15072 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15073 SourceRange SR) { 15074 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15075 } 15076 15077 ExprResult 15078 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15079 VerifyICEDiagnoser &Diagnoser, 15080 bool AllowFold) { 15081 SourceLocation DiagLoc = E->getBeginLoc(); 15082 15083 if (getLangOpts().CPlusPlus11) { 15084 // C++11 [expr.const]p5: 15085 // If an expression of literal class type is used in a context where an 15086 // integral constant expression is required, then that class type shall 15087 // have a single non-explicit conversion function to an integral or 15088 // unscoped enumeration type 15089 ExprResult Converted; 15090 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15091 public: 15092 CXX11ConvertDiagnoser(bool Silent) 15093 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15094 Silent, true) {} 15095 15096 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15097 QualType T) override { 15098 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15099 } 15100 15101 SemaDiagnosticBuilder diagnoseIncomplete( 15102 Sema &S, SourceLocation Loc, QualType T) override { 15103 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15104 } 15105 15106 SemaDiagnosticBuilder diagnoseExplicitConv( 15107 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15108 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15109 } 15110 15111 SemaDiagnosticBuilder noteExplicitConv( 15112 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15113 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15114 << ConvTy->isEnumeralType() << ConvTy; 15115 } 15116 15117 SemaDiagnosticBuilder diagnoseAmbiguous( 15118 Sema &S, SourceLocation Loc, QualType T) override { 15119 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15120 } 15121 15122 SemaDiagnosticBuilder noteAmbiguous( 15123 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15124 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15125 << ConvTy->isEnumeralType() << ConvTy; 15126 } 15127 15128 SemaDiagnosticBuilder diagnoseConversion( 15129 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15130 llvm_unreachable("conversion functions are permitted"); 15131 } 15132 } ConvertDiagnoser(Diagnoser.Suppress); 15133 15134 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15135 ConvertDiagnoser); 15136 if (Converted.isInvalid()) 15137 return Converted; 15138 E = Converted.get(); 15139 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15140 return ExprError(); 15141 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15142 // An ICE must be of integral or unscoped enumeration type. 15143 if (!Diagnoser.Suppress) 15144 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15145 return ExprError(); 15146 } 15147 15148 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15149 // in the non-ICE case. 15150 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15151 if (Result) 15152 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15153 if (!isa<ConstantExpr>(E)) 15154 E = ConstantExpr::Create(Context, E); 15155 return E; 15156 } 15157 15158 Expr::EvalResult EvalResult; 15159 SmallVector<PartialDiagnosticAt, 8> Notes; 15160 EvalResult.Diag = &Notes; 15161 15162 // Try to evaluate the expression, and produce diagnostics explaining why it's 15163 // not a constant expression as a side-effect. 15164 bool Folded = 15165 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15166 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15167 15168 if (!isa<ConstantExpr>(E)) 15169 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15170 15171 // In C++11, we can rely on diagnostics being produced for any expression 15172 // which is not a constant expression. If no diagnostics were produced, then 15173 // this is a constant expression. 15174 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15175 if (Result) 15176 *Result = EvalResult.Val.getInt(); 15177 return E; 15178 } 15179 15180 // If our only note is the usual "invalid subexpression" note, just point 15181 // the caret at its location rather than producing an essentially 15182 // redundant note. 15183 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15184 diag::note_invalid_subexpr_in_const_expr) { 15185 DiagLoc = Notes[0].first; 15186 Notes.clear(); 15187 } 15188 15189 if (!Folded || !AllowFold) { 15190 if (!Diagnoser.Suppress) { 15191 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15192 for (const PartialDiagnosticAt &Note : Notes) 15193 Diag(Note.first, Note.second); 15194 } 15195 15196 return ExprError(); 15197 } 15198 15199 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15200 for (const PartialDiagnosticAt &Note : Notes) 15201 Diag(Note.first, Note.second); 15202 15203 if (Result) 15204 *Result = EvalResult.Val.getInt(); 15205 return E; 15206 } 15207 15208 namespace { 15209 // Handle the case where we conclude a expression which we speculatively 15210 // considered to be unevaluated is actually evaluated. 15211 class TransformToPE : public TreeTransform<TransformToPE> { 15212 typedef TreeTransform<TransformToPE> BaseTransform; 15213 15214 public: 15215 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15216 15217 // Make sure we redo semantic analysis 15218 bool AlwaysRebuild() { return true; } 15219 bool ReplacingOriginal() { return true; } 15220 15221 // We need to special-case DeclRefExprs referring to FieldDecls which 15222 // are not part of a member pointer formation; normal TreeTransforming 15223 // doesn't catch this case because of the way we represent them in the AST. 15224 // FIXME: This is a bit ugly; is it really the best way to handle this 15225 // case? 15226 // 15227 // Error on DeclRefExprs referring to FieldDecls. 15228 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15229 if (isa<FieldDecl>(E->getDecl()) && 15230 !SemaRef.isUnevaluatedContext()) 15231 return SemaRef.Diag(E->getLocation(), 15232 diag::err_invalid_non_static_member_use) 15233 << E->getDecl() << E->getSourceRange(); 15234 15235 return BaseTransform::TransformDeclRefExpr(E); 15236 } 15237 15238 // Exception: filter out member pointer formation 15239 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15240 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15241 return E; 15242 15243 return BaseTransform::TransformUnaryOperator(E); 15244 } 15245 15246 // The body of a lambda-expression is in a separate expression evaluation 15247 // context so never needs to be transformed. 15248 // FIXME: Ideally we wouldn't transform the closure type either, and would 15249 // just recreate the capture expressions and lambda expression. 15250 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15251 return SkipLambdaBody(E, Body); 15252 } 15253 }; 15254 } 15255 15256 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15257 assert(isUnevaluatedContext() && 15258 "Should only transform unevaluated expressions"); 15259 ExprEvalContexts.back().Context = 15260 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15261 if (isUnevaluatedContext()) 15262 return E; 15263 return TransformToPE(*this).TransformExpr(E); 15264 } 15265 15266 void 15267 Sema::PushExpressionEvaluationContext( 15268 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15269 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15270 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15271 LambdaContextDecl, ExprContext); 15272 Cleanup.reset(); 15273 if (!MaybeODRUseExprs.empty()) 15274 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15275 } 15276 15277 void 15278 Sema::PushExpressionEvaluationContext( 15279 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15280 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15281 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15282 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15283 } 15284 15285 namespace { 15286 15287 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15288 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15289 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15290 if (E->getOpcode() == UO_Deref) 15291 return CheckPossibleDeref(S, E->getSubExpr()); 15292 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15293 return CheckPossibleDeref(S, E->getBase()); 15294 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15295 return CheckPossibleDeref(S, E->getBase()); 15296 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15297 QualType Inner; 15298 QualType Ty = E->getType(); 15299 if (const auto *Ptr = Ty->getAs<PointerType>()) 15300 Inner = Ptr->getPointeeType(); 15301 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15302 Inner = Arr->getElementType(); 15303 else 15304 return nullptr; 15305 15306 if (Inner->hasAttr(attr::NoDeref)) 15307 return E; 15308 } 15309 return nullptr; 15310 } 15311 15312 } // namespace 15313 15314 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15315 for (const Expr *E : Rec.PossibleDerefs) { 15316 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15317 if (DeclRef) { 15318 const ValueDecl *Decl = DeclRef->getDecl(); 15319 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15320 << Decl->getName() << E->getSourceRange(); 15321 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15322 } else { 15323 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15324 << E->getSourceRange(); 15325 } 15326 } 15327 Rec.PossibleDerefs.clear(); 15328 } 15329 15330 /// Check whether E, which is either a discarded-value expression or an 15331 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15332 /// and if so, remove it from the list of volatile-qualified assignments that 15333 /// we are going to warn are deprecated. 15334 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15335 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15336 return; 15337 15338 // Note: ignoring parens here is not justified by the standard rules, but 15339 // ignoring parentheses seems like a more reasonable approach, and this only 15340 // drives a deprecation warning so doesn't affect conformance. 15341 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15342 if (BO->getOpcode() == BO_Assign) { 15343 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15344 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15345 LHSs.end()); 15346 } 15347 } 15348 } 15349 15350 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15351 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15352 RebuildingImmediateInvocation) 15353 return E; 15354 15355 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15356 /// It's OK if this fails; we'll also remove this in 15357 /// HandleImmediateInvocations, but catching it here allows us to avoid 15358 /// walking the AST looking for it in simple cases. 15359 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15360 if (auto *DeclRef = 15361 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15362 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15363 15364 E = MaybeCreateExprWithCleanups(E); 15365 15366 ConstantExpr *Res = ConstantExpr::Create( 15367 getASTContext(), E.get(), 15368 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15369 getASTContext()), 15370 /*IsImmediateInvocation*/ true); 15371 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15372 return Res; 15373 } 15374 15375 static void EvaluateAndDiagnoseImmediateInvocation( 15376 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15377 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15378 Expr::EvalResult Eval; 15379 Eval.Diag = &Notes; 15380 ConstantExpr *CE = Candidate.getPointer(); 15381 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15382 SemaRef.getASTContext(), true); 15383 if (!Result || !Notes.empty()) { 15384 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15385 FunctionDecl *FD = nullptr; 15386 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15387 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15388 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15389 FD = Call->getConstructor(); 15390 else 15391 llvm_unreachable("unhandled decl kind"); 15392 assert(FD->isConsteval()); 15393 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15394 for (auto &Note : Notes) 15395 SemaRef.Diag(Note.first, Note.second); 15396 return; 15397 } 15398 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15399 } 15400 15401 static void RemoveNestedImmediateInvocation( 15402 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15403 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15404 struct ComplexRemove : TreeTransform<ComplexRemove> { 15405 using Base = TreeTransform<ComplexRemove>; 15406 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15407 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15408 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15409 CurrentII; 15410 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15411 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15412 SmallVector<Sema::ImmediateInvocationCandidate, 15413 4>::reverse_iterator Current) 15414 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15415 void RemoveImmediateInvocation(ConstantExpr* E) { 15416 auto It = std::find_if(CurrentII, IISet.rend(), 15417 [E](Sema::ImmediateInvocationCandidate Elem) { 15418 return Elem.getPointer() == E; 15419 }); 15420 assert(It != IISet.rend() && 15421 "ConstantExpr marked IsImmediateInvocation should " 15422 "be present"); 15423 It->setInt(1); // Mark as deleted 15424 } 15425 ExprResult TransformConstantExpr(ConstantExpr *E) { 15426 if (!E->isImmediateInvocation()) 15427 return Base::TransformConstantExpr(E); 15428 RemoveImmediateInvocation(E); 15429 return Base::TransformExpr(E->getSubExpr()); 15430 } 15431 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15432 /// we need to remove its DeclRefExpr from the DRSet. 15433 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15434 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15435 return Base::TransformCXXOperatorCallExpr(E); 15436 } 15437 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15438 /// here. 15439 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15440 if (!Init) 15441 return Init; 15442 /// ConstantExpr are the first layer of implicit node to be removed so if 15443 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15444 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 15445 if (CE->isImmediateInvocation()) 15446 RemoveImmediateInvocation(CE); 15447 return Base::TransformInitializer(Init, NotCopyInit); 15448 } 15449 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15450 DRSet.erase(E); 15451 return E; 15452 } 15453 bool AlwaysRebuild() { return false; } 15454 bool ReplacingOriginal() { return true; } 15455 } Transformer(SemaRef, Rec.ReferenceToConsteval, 15456 Rec.ImmediateInvocationCandidates, It); 15457 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 15458 assert(Res.isUsable()); 15459 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 15460 It->getPointer()->setSubExpr(Res.get()); 15461 } 15462 15463 static void 15464 HandleImmediateInvocations(Sema &SemaRef, 15465 Sema::ExpressionEvaluationContextRecord &Rec) { 15466 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 15467 Rec.ReferenceToConsteval.size() == 0) || 15468 SemaRef.RebuildingImmediateInvocation) 15469 return; 15470 15471 /// When we have more then 1 ImmediateInvocationCandidates we need to check 15472 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 15473 /// need to remove ReferenceToConsteval in the immediate invocation. 15474 if (Rec.ImmediateInvocationCandidates.size() > 1) { 15475 15476 /// Prevent sema calls during the tree transform from adding pointers that 15477 /// are already in the sets. 15478 llvm::SaveAndRestore<bool> DisableIITracking( 15479 SemaRef.RebuildingImmediateInvocation, true); 15480 15481 /// Prevent diagnostic during tree transfrom as they are duplicates 15482 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 15483 15484 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 15485 It != Rec.ImmediateInvocationCandidates.rend(); It++) 15486 if (!It->getInt()) 15487 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 15488 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 15489 Rec.ReferenceToConsteval.size()) { 15490 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 15491 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15492 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 15493 bool VisitDeclRefExpr(DeclRefExpr *E) { 15494 DRSet.erase(E); 15495 return DRSet.size(); 15496 } 15497 } Visitor(Rec.ReferenceToConsteval); 15498 Visitor.TraverseStmt( 15499 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 15500 } 15501 for (auto CE : Rec.ImmediateInvocationCandidates) 15502 if (!CE.getInt()) 15503 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 15504 for (auto DR : Rec.ReferenceToConsteval) { 15505 auto *FD = cast<FunctionDecl>(DR->getDecl()); 15506 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 15507 << FD; 15508 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 15509 } 15510 } 15511 15512 void Sema::PopExpressionEvaluationContext() { 15513 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15514 unsigned NumTypos = Rec.NumTypos; 15515 15516 if (!Rec.Lambdas.empty()) { 15517 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15518 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15519 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15520 unsigned D; 15521 if (Rec.isUnevaluated()) { 15522 // C++11 [expr.prim.lambda]p2: 15523 // A lambda-expression shall not appear in an unevaluated operand 15524 // (Clause 5). 15525 D = diag::err_lambda_unevaluated_operand; 15526 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15527 // C++1y [expr.const]p2: 15528 // A conditional-expression e is a core constant expression unless the 15529 // evaluation of e, following the rules of the abstract machine, would 15530 // evaluate [...] a lambda-expression. 15531 D = diag::err_lambda_in_constant_expression; 15532 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15533 // C++17 [expr.prim.lamda]p2: 15534 // A lambda-expression shall not appear [...] in a template-argument. 15535 D = diag::err_lambda_in_invalid_context; 15536 } else 15537 llvm_unreachable("Couldn't infer lambda error message."); 15538 15539 for (const auto *L : Rec.Lambdas) 15540 Diag(L->getBeginLoc(), D); 15541 } 15542 } 15543 15544 WarnOnPendingNoDerefs(Rec); 15545 HandleImmediateInvocations(*this, Rec); 15546 15547 // Warn on any volatile-qualified simple-assignments that are not discarded- 15548 // value expressions nor unevaluated operands (those cases get removed from 15549 // this list by CheckUnusedVolatileAssignment). 15550 for (auto *BO : Rec.VolatileAssignmentLHSs) 15551 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15552 << BO->getType(); 15553 15554 // When are coming out of an unevaluated context, clear out any 15555 // temporaries that we may have created as part of the evaluation of 15556 // the expression in that context: they aren't relevant because they 15557 // will never be constructed. 15558 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15559 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15560 ExprCleanupObjects.end()); 15561 Cleanup = Rec.ParentCleanup; 15562 CleanupVarDeclMarking(); 15563 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15564 // Otherwise, merge the contexts together. 15565 } else { 15566 Cleanup.mergeFrom(Rec.ParentCleanup); 15567 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15568 Rec.SavedMaybeODRUseExprs.end()); 15569 } 15570 15571 // Pop the current expression evaluation context off the stack. 15572 ExprEvalContexts.pop_back(); 15573 15574 // The global expression evaluation context record is never popped. 15575 ExprEvalContexts.back().NumTypos += NumTypos; 15576 } 15577 15578 void Sema::DiscardCleanupsInEvaluationContext() { 15579 ExprCleanupObjects.erase( 15580 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15581 ExprCleanupObjects.end()); 15582 Cleanup.reset(); 15583 MaybeODRUseExprs.clear(); 15584 } 15585 15586 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15587 ExprResult Result = CheckPlaceholderExpr(E); 15588 if (Result.isInvalid()) 15589 return ExprError(); 15590 E = Result.get(); 15591 if (!E->getType()->isVariablyModifiedType()) 15592 return E; 15593 return TransformToPotentiallyEvaluated(E); 15594 } 15595 15596 /// Are we in a context that is potentially constant evaluated per C++20 15597 /// [expr.const]p12? 15598 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15599 /// C++2a [expr.const]p12: 15600 // An expression or conversion is potentially constant evaluated if it is 15601 switch (SemaRef.ExprEvalContexts.back().Context) { 15602 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15603 // -- a manifestly constant-evaluated expression, 15604 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15605 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15606 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15607 // -- a potentially-evaluated expression, 15608 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15609 // -- an immediate subexpression of a braced-init-list, 15610 15611 // -- [FIXME] an expression of the form & cast-expression that occurs 15612 // within a templated entity 15613 // -- a subexpression of one of the above that is not a subexpression of 15614 // a nested unevaluated operand. 15615 return true; 15616 15617 case Sema::ExpressionEvaluationContext::Unevaluated: 15618 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15619 // Expressions in this context are never evaluated. 15620 return false; 15621 } 15622 llvm_unreachable("Invalid context"); 15623 } 15624 15625 /// Return true if this function has a calling convention that requires mangling 15626 /// in the size of the parameter pack. 15627 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15628 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15629 // we don't need parameter type sizes. 15630 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15631 if (!TT.isOSWindows() || !TT.isX86()) 15632 return false; 15633 15634 // If this is C++ and this isn't an extern "C" function, parameters do not 15635 // need to be complete. In this case, C++ mangling will apply, which doesn't 15636 // use the size of the parameters. 15637 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15638 return false; 15639 15640 // Stdcall, fastcall, and vectorcall need this special treatment. 15641 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15642 switch (CC) { 15643 case CC_X86StdCall: 15644 case CC_X86FastCall: 15645 case CC_X86VectorCall: 15646 return true; 15647 default: 15648 break; 15649 } 15650 return false; 15651 } 15652 15653 /// Require that all of the parameter types of function be complete. Normally, 15654 /// parameter types are only required to be complete when a function is called 15655 /// or defined, but to mangle functions with certain calling conventions, the 15656 /// mangler needs to know the size of the parameter list. In this situation, 15657 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15658 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15659 /// result in a linker error. Clang doesn't implement this behavior, and instead 15660 /// attempts to error at compile time. 15661 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15662 SourceLocation Loc) { 15663 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15664 FunctionDecl *FD; 15665 ParmVarDecl *Param; 15666 15667 public: 15668 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15669 : FD(FD), Param(Param) {} 15670 15671 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15672 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15673 StringRef CCName; 15674 switch (CC) { 15675 case CC_X86StdCall: 15676 CCName = "stdcall"; 15677 break; 15678 case CC_X86FastCall: 15679 CCName = "fastcall"; 15680 break; 15681 case CC_X86VectorCall: 15682 CCName = "vectorcall"; 15683 break; 15684 default: 15685 llvm_unreachable("CC does not need mangling"); 15686 } 15687 15688 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15689 << Param->getDeclName() << FD->getDeclName() << CCName; 15690 } 15691 }; 15692 15693 for (ParmVarDecl *Param : FD->parameters()) { 15694 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15695 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15696 } 15697 } 15698 15699 namespace { 15700 enum class OdrUseContext { 15701 /// Declarations in this context are not odr-used. 15702 None, 15703 /// Declarations in this context are formally odr-used, but this is a 15704 /// dependent context. 15705 Dependent, 15706 /// Declarations in this context are odr-used but not actually used (yet). 15707 FormallyOdrUsed, 15708 /// Declarations in this context are used. 15709 Used 15710 }; 15711 } 15712 15713 /// Are we within a context in which references to resolved functions or to 15714 /// variables result in odr-use? 15715 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15716 OdrUseContext Result; 15717 15718 switch (SemaRef.ExprEvalContexts.back().Context) { 15719 case Sema::ExpressionEvaluationContext::Unevaluated: 15720 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15721 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15722 return OdrUseContext::None; 15723 15724 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15725 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15726 Result = OdrUseContext::Used; 15727 break; 15728 15729 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15730 Result = OdrUseContext::FormallyOdrUsed; 15731 break; 15732 15733 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15734 // A default argument formally results in odr-use, but doesn't actually 15735 // result in a use in any real sense until it itself is used. 15736 Result = OdrUseContext::FormallyOdrUsed; 15737 break; 15738 } 15739 15740 if (SemaRef.CurContext->isDependentContext()) 15741 return OdrUseContext::Dependent; 15742 15743 return Result; 15744 } 15745 15746 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15747 return Func->isConstexpr() && 15748 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15749 } 15750 15751 /// Mark a function referenced, and check whether it is odr-used 15752 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15753 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15754 bool MightBeOdrUse) { 15755 assert(Func && "No function?"); 15756 15757 Func->setReferenced(); 15758 15759 // Recursive functions aren't really used until they're used from some other 15760 // context. 15761 bool IsRecursiveCall = CurContext == Func; 15762 15763 // C++11 [basic.def.odr]p3: 15764 // A function whose name appears as a potentially-evaluated expression is 15765 // odr-used if it is the unique lookup result or the selected member of a 15766 // set of overloaded functions [...]. 15767 // 15768 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15769 // can just check that here. 15770 OdrUseContext OdrUse = 15771 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15772 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15773 OdrUse = OdrUseContext::FormallyOdrUsed; 15774 15775 // Trivial default constructors and destructors are never actually used. 15776 // FIXME: What about other special members? 15777 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15778 OdrUse == OdrUseContext::Used) { 15779 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15780 if (Constructor->isDefaultConstructor()) 15781 OdrUse = OdrUseContext::FormallyOdrUsed; 15782 if (isa<CXXDestructorDecl>(Func)) 15783 OdrUse = OdrUseContext::FormallyOdrUsed; 15784 } 15785 15786 // C++20 [expr.const]p12: 15787 // A function [...] is needed for constant evaluation if it is [...] a 15788 // constexpr function that is named by an expression that is potentially 15789 // constant evaluated 15790 bool NeededForConstantEvaluation = 15791 isPotentiallyConstantEvaluatedContext(*this) && 15792 isImplicitlyDefinableConstexprFunction(Func); 15793 15794 // Determine whether we require a function definition to exist, per 15795 // C++11 [temp.inst]p3: 15796 // Unless a function template specialization has been explicitly 15797 // instantiated or explicitly specialized, the function template 15798 // specialization is implicitly instantiated when the specialization is 15799 // referenced in a context that requires a function definition to exist. 15800 // C++20 [temp.inst]p7: 15801 // The existence of a definition of a [...] function is considered to 15802 // affect the semantics of the program if the [...] function is needed for 15803 // constant evaluation by an expression 15804 // C++20 [basic.def.odr]p10: 15805 // Every program shall contain exactly one definition of every non-inline 15806 // function or variable that is odr-used in that program outside of a 15807 // discarded statement 15808 // C++20 [special]p1: 15809 // The implementation will implicitly define [defaulted special members] 15810 // if they are odr-used or needed for constant evaluation. 15811 // 15812 // Note that we skip the implicit instantiation of templates that are only 15813 // used in unused default arguments or by recursive calls to themselves. 15814 // This is formally non-conforming, but seems reasonable in practice. 15815 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15816 NeededForConstantEvaluation); 15817 15818 // C++14 [temp.expl.spec]p6: 15819 // If a template [...] is explicitly specialized then that specialization 15820 // shall be declared before the first use of that specialization that would 15821 // cause an implicit instantiation to take place, in every translation unit 15822 // in which such a use occurs 15823 if (NeedDefinition && 15824 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15825 Func->getMemberSpecializationInfo())) 15826 checkSpecializationVisibility(Loc, Func); 15827 15828 if (getLangOpts().CUDA) 15829 CheckCUDACall(Loc, Func); 15830 15831 // If we need a definition, try to create one. 15832 if (NeedDefinition && !Func->getBody()) { 15833 runWithSufficientStackSpace(Loc, [&] { 15834 if (CXXConstructorDecl *Constructor = 15835 dyn_cast<CXXConstructorDecl>(Func)) { 15836 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15837 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15838 if (Constructor->isDefaultConstructor()) { 15839 if (Constructor->isTrivial() && 15840 !Constructor->hasAttr<DLLExportAttr>()) 15841 return; 15842 DefineImplicitDefaultConstructor(Loc, Constructor); 15843 } else if (Constructor->isCopyConstructor()) { 15844 DefineImplicitCopyConstructor(Loc, Constructor); 15845 } else if (Constructor->isMoveConstructor()) { 15846 DefineImplicitMoveConstructor(Loc, Constructor); 15847 } 15848 } else if (Constructor->getInheritedConstructor()) { 15849 DefineInheritingConstructor(Loc, Constructor); 15850 } 15851 } else if (CXXDestructorDecl *Destructor = 15852 dyn_cast<CXXDestructorDecl>(Func)) { 15853 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15854 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15855 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15856 return; 15857 DefineImplicitDestructor(Loc, Destructor); 15858 } 15859 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15860 MarkVTableUsed(Loc, Destructor->getParent()); 15861 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15862 if (MethodDecl->isOverloadedOperator() && 15863 MethodDecl->getOverloadedOperator() == OO_Equal) { 15864 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15865 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15866 if (MethodDecl->isCopyAssignmentOperator()) 15867 DefineImplicitCopyAssignment(Loc, MethodDecl); 15868 else if (MethodDecl->isMoveAssignmentOperator()) 15869 DefineImplicitMoveAssignment(Loc, MethodDecl); 15870 } 15871 } else if (isa<CXXConversionDecl>(MethodDecl) && 15872 MethodDecl->getParent()->isLambda()) { 15873 CXXConversionDecl *Conversion = 15874 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15875 if (Conversion->isLambdaToBlockPointerConversion()) 15876 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15877 else 15878 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15879 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15880 MarkVTableUsed(Loc, MethodDecl->getParent()); 15881 } 15882 15883 if (Func->isDefaulted() && !Func->isDeleted()) { 15884 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 15885 if (DCK != DefaultedComparisonKind::None) 15886 DefineDefaultedComparison(Loc, Func, DCK); 15887 } 15888 15889 // Implicit instantiation of function templates and member functions of 15890 // class templates. 15891 if (Func->isImplicitlyInstantiable()) { 15892 TemplateSpecializationKind TSK = 15893 Func->getTemplateSpecializationKindForInstantiation(); 15894 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15895 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15896 if (FirstInstantiation) { 15897 PointOfInstantiation = Loc; 15898 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15899 } else if (TSK != TSK_ImplicitInstantiation) { 15900 // Use the point of use as the point of instantiation, instead of the 15901 // point of explicit instantiation (which we track as the actual point 15902 // of instantiation). This gives better backtraces in diagnostics. 15903 PointOfInstantiation = Loc; 15904 } 15905 15906 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15907 Func->isConstexpr()) { 15908 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15909 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15910 CodeSynthesisContexts.size()) 15911 PendingLocalImplicitInstantiations.push_back( 15912 std::make_pair(Func, PointOfInstantiation)); 15913 else if (Func->isConstexpr()) 15914 // Do not defer instantiations of constexpr functions, to avoid the 15915 // expression evaluator needing to call back into Sema if it sees a 15916 // call to such a function. 15917 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15918 else { 15919 Func->setInstantiationIsPending(true); 15920 PendingInstantiations.push_back( 15921 std::make_pair(Func, PointOfInstantiation)); 15922 // Notify the consumer that a function was implicitly instantiated. 15923 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15924 } 15925 } 15926 } else { 15927 // Walk redefinitions, as some of them may be instantiable. 15928 for (auto i : Func->redecls()) { 15929 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15930 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15931 } 15932 } 15933 }); 15934 } 15935 15936 // C++14 [except.spec]p17: 15937 // An exception-specification is considered to be needed when: 15938 // - the function is odr-used or, if it appears in an unevaluated operand, 15939 // would be odr-used if the expression were potentially-evaluated; 15940 // 15941 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15942 // function is a pure virtual function we're calling, and in that case the 15943 // function was selected by overload resolution and we need to resolve its 15944 // exception specification for a different reason. 15945 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15946 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15947 ResolveExceptionSpec(Loc, FPT); 15948 15949 // If this is the first "real" use, act on that. 15950 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15951 // Keep track of used but undefined functions. 15952 if (!Func->isDefined()) { 15953 if (mightHaveNonExternalLinkage(Func)) 15954 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15955 else if (Func->getMostRecentDecl()->isInlined() && 15956 !LangOpts.GNUInline && 15957 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15958 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15959 else if (isExternalWithNoLinkageType(Func)) 15960 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15961 } 15962 15963 // Some x86 Windows calling conventions mangle the size of the parameter 15964 // pack into the name. Computing the size of the parameters requires the 15965 // parameter types to be complete. Check that now. 15966 if (funcHasParameterSizeMangling(*this, Func)) 15967 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15968 15969 Func->markUsed(Context); 15970 } 15971 15972 if (LangOpts.OpenMP) { 15973 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15974 if (LangOpts.OpenMPIsDevice) 15975 checkOpenMPDeviceFunction(Loc, Func); 15976 else 15977 checkOpenMPHostFunction(Loc, Func); 15978 } 15979 } 15980 15981 /// Directly mark a variable odr-used. Given a choice, prefer to use 15982 /// MarkVariableReferenced since it does additional checks and then 15983 /// calls MarkVarDeclODRUsed. 15984 /// If the variable must be captured: 15985 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15986 /// - else capture it in the DeclContext that maps to the 15987 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15988 static void 15989 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15990 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15991 // Keep track of used but undefined variables. 15992 // FIXME: We shouldn't suppress this warning for static data members. 15993 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15994 (!Var->isExternallyVisible() || Var->isInline() || 15995 SemaRef.isExternalWithNoLinkageType(Var)) && 15996 !(Var->isStaticDataMember() && Var->hasInit())) { 15997 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15998 if (old.isInvalid()) 15999 old = Loc; 16000 } 16001 QualType CaptureType, DeclRefType; 16002 if (SemaRef.LangOpts.OpenMP) 16003 SemaRef.tryCaptureOpenMPLambdas(Var); 16004 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16005 /*EllipsisLoc*/ SourceLocation(), 16006 /*BuildAndDiagnose*/ true, 16007 CaptureType, DeclRefType, 16008 FunctionScopeIndexToStopAt); 16009 16010 Var->markUsed(SemaRef.Context); 16011 } 16012 16013 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16014 SourceLocation Loc, 16015 unsigned CapturingScopeIndex) { 16016 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16017 } 16018 16019 static void 16020 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16021 ValueDecl *var, DeclContext *DC) { 16022 DeclContext *VarDC = var->getDeclContext(); 16023 16024 // If the parameter still belongs to the translation unit, then 16025 // we're actually just using one parameter in the declaration of 16026 // the next. 16027 if (isa<ParmVarDecl>(var) && 16028 isa<TranslationUnitDecl>(VarDC)) 16029 return; 16030 16031 // For C code, don't diagnose about capture if we're not actually in code 16032 // right now; it's impossible to write a non-constant expression outside of 16033 // function context, so we'll get other (more useful) diagnostics later. 16034 // 16035 // For C++, things get a bit more nasty... it would be nice to suppress this 16036 // diagnostic for certain cases like using a local variable in an array bound 16037 // for a member of a local class, but the correct predicate is not obvious. 16038 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16039 return; 16040 16041 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16042 unsigned ContextKind = 3; // unknown 16043 if (isa<CXXMethodDecl>(VarDC) && 16044 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16045 ContextKind = 2; 16046 } else if (isa<FunctionDecl>(VarDC)) { 16047 ContextKind = 0; 16048 } else if (isa<BlockDecl>(VarDC)) { 16049 ContextKind = 1; 16050 } 16051 16052 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16053 << var << ValueKind << ContextKind << VarDC; 16054 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16055 << var; 16056 16057 // FIXME: Add additional diagnostic info about class etc. which prevents 16058 // capture. 16059 } 16060 16061 16062 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16063 bool &SubCapturesAreNested, 16064 QualType &CaptureType, 16065 QualType &DeclRefType) { 16066 // Check whether we've already captured it. 16067 if (CSI->CaptureMap.count(Var)) { 16068 // If we found a capture, any subcaptures are nested. 16069 SubCapturesAreNested = true; 16070 16071 // Retrieve the capture type for this variable. 16072 CaptureType = CSI->getCapture(Var).getCaptureType(); 16073 16074 // Compute the type of an expression that refers to this variable. 16075 DeclRefType = CaptureType.getNonReferenceType(); 16076 16077 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16078 // are mutable in the sense that user can change their value - they are 16079 // private instances of the captured declarations. 16080 const Capture &Cap = CSI->getCapture(Var); 16081 if (Cap.isCopyCapture() && 16082 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16083 !(isa<CapturedRegionScopeInfo>(CSI) && 16084 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16085 DeclRefType.addConst(); 16086 return true; 16087 } 16088 return false; 16089 } 16090 16091 // Only block literals, captured statements, and lambda expressions can 16092 // capture; other scopes don't work. 16093 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16094 SourceLocation Loc, 16095 const bool Diagnose, Sema &S) { 16096 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16097 return getLambdaAwareParentOfDeclContext(DC); 16098 else if (Var->hasLocalStorage()) { 16099 if (Diagnose) 16100 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16101 } 16102 return nullptr; 16103 } 16104 16105 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16106 // certain types of variables (unnamed, variably modified types etc.) 16107 // so check for eligibility. 16108 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16109 SourceLocation Loc, 16110 const bool Diagnose, Sema &S) { 16111 16112 bool IsBlock = isa<BlockScopeInfo>(CSI); 16113 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16114 16115 // Lambdas are not allowed to capture unnamed variables 16116 // (e.g. anonymous unions). 16117 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16118 // assuming that's the intent. 16119 if (IsLambda && !Var->getDeclName()) { 16120 if (Diagnose) { 16121 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16122 S.Diag(Var->getLocation(), diag::note_declared_at); 16123 } 16124 return false; 16125 } 16126 16127 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16128 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16129 if (Diagnose) { 16130 S.Diag(Loc, diag::err_ref_vm_type); 16131 S.Diag(Var->getLocation(), diag::note_previous_decl) 16132 << Var->getDeclName(); 16133 } 16134 return false; 16135 } 16136 // Prohibit structs with flexible array members too. 16137 // We cannot capture what is in the tail end of the struct. 16138 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16139 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16140 if (Diagnose) { 16141 if (IsBlock) 16142 S.Diag(Loc, diag::err_ref_flexarray_type); 16143 else 16144 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16145 << Var->getDeclName(); 16146 S.Diag(Var->getLocation(), diag::note_previous_decl) 16147 << Var->getDeclName(); 16148 } 16149 return false; 16150 } 16151 } 16152 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16153 // Lambdas and captured statements are not allowed to capture __block 16154 // variables; they don't support the expected semantics. 16155 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16156 if (Diagnose) { 16157 S.Diag(Loc, diag::err_capture_block_variable) 16158 << Var->getDeclName() << !IsLambda; 16159 S.Diag(Var->getLocation(), diag::note_previous_decl) 16160 << Var->getDeclName(); 16161 } 16162 return false; 16163 } 16164 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16165 if (S.getLangOpts().OpenCL && IsBlock && 16166 Var->getType()->isBlockPointerType()) { 16167 if (Diagnose) 16168 S.Diag(Loc, diag::err_opencl_block_ref_block); 16169 return false; 16170 } 16171 16172 return true; 16173 } 16174 16175 // Returns true if the capture by block was successful. 16176 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16177 SourceLocation Loc, 16178 const bool BuildAndDiagnose, 16179 QualType &CaptureType, 16180 QualType &DeclRefType, 16181 const bool Nested, 16182 Sema &S, bool Invalid) { 16183 bool ByRef = false; 16184 16185 // Blocks are not allowed to capture arrays, excepting OpenCL. 16186 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16187 // (decayed to pointers). 16188 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16189 if (BuildAndDiagnose) { 16190 S.Diag(Loc, diag::err_ref_array_type); 16191 S.Diag(Var->getLocation(), diag::note_previous_decl) 16192 << Var->getDeclName(); 16193 Invalid = true; 16194 } else { 16195 return false; 16196 } 16197 } 16198 16199 // Forbid the block-capture of autoreleasing variables. 16200 if (!Invalid && 16201 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16202 if (BuildAndDiagnose) { 16203 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16204 << /*block*/ 0; 16205 S.Diag(Var->getLocation(), diag::note_previous_decl) 16206 << Var->getDeclName(); 16207 Invalid = true; 16208 } else { 16209 return false; 16210 } 16211 } 16212 16213 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16214 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16215 QualType PointeeTy = PT->getPointeeType(); 16216 16217 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16218 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16219 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16220 if (BuildAndDiagnose) { 16221 SourceLocation VarLoc = Var->getLocation(); 16222 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16223 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16224 } 16225 } 16226 } 16227 16228 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16229 if (HasBlocksAttr || CaptureType->isReferenceType() || 16230 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16231 // Block capture by reference does not change the capture or 16232 // declaration reference types. 16233 ByRef = true; 16234 } else { 16235 // Block capture by copy introduces 'const'. 16236 CaptureType = CaptureType.getNonReferenceType().withConst(); 16237 DeclRefType = CaptureType; 16238 } 16239 16240 // Actually capture the variable. 16241 if (BuildAndDiagnose) 16242 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16243 CaptureType, Invalid); 16244 16245 return !Invalid; 16246 } 16247 16248 16249 /// Capture the given variable in the captured region. 16250 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16251 VarDecl *Var, 16252 SourceLocation Loc, 16253 const bool BuildAndDiagnose, 16254 QualType &CaptureType, 16255 QualType &DeclRefType, 16256 const bool RefersToCapturedVariable, 16257 Sema &S, bool Invalid) { 16258 // By default, capture variables by reference. 16259 bool ByRef = true; 16260 // Using an LValue reference type is consistent with Lambdas (see below). 16261 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16262 if (S.isOpenMPCapturedDecl(Var)) { 16263 bool HasConst = DeclRefType.isConstQualified(); 16264 DeclRefType = DeclRefType.getUnqualifiedType(); 16265 // Don't lose diagnostics about assignments to const. 16266 if (HasConst) 16267 DeclRefType.addConst(); 16268 } 16269 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16270 RSI->OpenMPCaptureLevel); 16271 } 16272 16273 if (ByRef) 16274 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16275 else 16276 CaptureType = DeclRefType; 16277 16278 // Actually capture the variable. 16279 if (BuildAndDiagnose) 16280 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16281 Loc, SourceLocation(), CaptureType, Invalid); 16282 16283 return !Invalid; 16284 } 16285 16286 /// Capture the given variable in the lambda. 16287 static bool captureInLambda(LambdaScopeInfo *LSI, 16288 VarDecl *Var, 16289 SourceLocation Loc, 16290 const bool BuildAndDiagnose, 16291 QualType &CaptureType, 16292 QualType &DeclRefType, 16293 const bool RefersToCapturedVariable, 16294 const Sema::TryCaptureKind Kind, 16295 SourceLocation EllipsisLoc, 16296 const bool IsTopScope, 16297 Sema &S, bool Invalid) { 16298 // Determine whether we are capturing by reference or by value. 16299 bool ByRef = false; 16300 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16301 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16302 } else { 16303 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16304 } 16305 16306 // Compute the type of the field that will capture this variable. 16307 if (ByRef) { 16308 // C++11 [expr.prim.lambda]p15: 16309 // An entity is captured by reference if it is implicitly or 16310 // explicitly captured but not captured by copy. It is 16311 // unspecified whether additional unnamed non-static data 16312 // members are declared in the closure type for entities 16313 // captured by reference. 16314 // 16315 // FIXME: It is not clear whether we want to build an lvalue reference 16316 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16317 // to do the former, while EDG does the latter. Core issue 1249 will 16318 // clarify, but for now we follow GCC because it's a more permissive and 16319 // easily defensible position. 16320 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16321 } else { 16322 // C++11 [expr.prim.lambda]p14: 16323 // For each entity captured by copy, an unnamed non-static 16324 // data member is declared in the closure type. The 16325 // declaration order of these members is unspecified. The type 16326 // of such a data member is the type of the corresponding 16327 // captured entity if the entity is not a reference to an 16328 // object, or the referenced type otherwise. [Note: If the 16329 // captured entity is a reference to a function, the 16330 // corresponding data member is also a reference to a 16331 // function. - end note ] 16332 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16333 if (!RefType->getPointeeType()->isFunctionType()) 16334 CaptureType = RefType->getPointeeType(); 16335 } 16336 16337 // Forbid the lambda copy-capture of autoreleasing variables. 16338 if (!Invalid && 16339 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16340 if (BuildAndDiagnose) { 16341 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16342 S.Diag(Var->getLocation(), diag::note_previous_decl) 16343 << Var->getDeclName(); 16344 Invalid = true; 16345 } else { 16346 return false; 16347 } 16348 } 16349 16350 // Make sure that by-copy captures are of a complete and non-abstract type. 16351 if (!Invalid && BuildAndDiagnose) { 16352 if (!CaptureType->isDependentType() && 16353 S.RequireCompleteType(Loc, CaptureType, 16354 diag::err_capture_of_incomplete_type, 16355 Var->getDeclName())) 16356 Invalid = true; 16357 else if (S.RequireNonAbstractType(Loc, CaptureType, 16358 diag::err_capture_of_abstract_type)) 16359 Invalid = true; 16360 } 16361 } 16362 16363 // Compute the type of a reference to this captured variable. 16364 if (ByRef) 16365 DeclRefType = CaptureType.getNonReferenceType(); 16366 else { 16367 // C++ [expr.prim.lambda]p5: 16368 // The closure type for a lambda-expression has a public inline 16369 // function call operator [...]. This function call operator is 16370 // declared const (9.3.1) if and only if the lambda-expression's 16371 // parameter-declaration-clause is not followed by mutable. 16372 DeclRefType = CaptureType.getNonReferenceType(); 16373 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16374 DeclRefType.addConst(); 16375 } 16376 16377 // Add the capture. 16378 if (BuildAndDiagnose) 16379 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16380 Loc, EllipsisLoc, CaptureType, Invalid); 16381 16382 return !Invalid; 16383 } 16384 16385 bool Sema::tryCaptureVariable( 16386 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16387 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16388 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16389 // An init-capture is notionally from the context surrounding its 16390 // declaration, but its parent DC is the lambda class. 16391 DeclContext *VarDC = Var->getDeclContext(); 16392 if (Var->isInitCapture()) 16393 VarDC = VarDC->getParent(); 16394 16395 DeclContext *DC = CurContext; 16396 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16397 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16398 // We need to sync up the Declaration Context with the 16399 // FunctionScopeIndexToStopAt 16400 if (FunctionScopeIndexToStopAt) { 16401 unsigned FSIndex = FunctionScopes.size() - 1; 16402 while (FSIndex != MaxFunctionScopesIndex) { 16403 DC = getLambdaAwareParentOfDeclContext(DC); 16404 --FSIndex; 16405 } 16406 } 16407 16408 16409 // If the variable is declared in the current context, there is no need to 16410 // capture it. 16411 if (VarDC == DC) return true; 16412 16413 // Capture global variables if it is required to use private copy of this 16414 // variable. 16415 bool IsGlobal = !Var->hasLocalStorage(); 16416 if (IsGlobal && 16417 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16418 MaxFunctionScopesIndex))) 16419 return true; 16420 Var = Var->getCanonicalDecl(); 16421 16422 // Walk up the stack to determine whether we can capture the variable, 16423 // performing the "simple" checks that don't depend on type. We stop when 16424 // we've either hit the declared scope of the variable or find an existing 16425 // capture of that variable. We start from the innermost capturing-entity 16426 // (the DC) and ensure that all intervening capturing-entities 16427 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16428 // declcontext can either capture the variable or have already captured 16429 // the variable. 16430 CaptureType = Var->getType(); 16431 DeclRefType = CaptureType.getNonReferenceType(); 16432 bool Nested = false; 16433 bool Explicit = (Kind != TryCapture_Implicit); 16434 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16435 do { 16436 // Only block literals, captured statements, and lambda expressions can 16437 // capture; other scopes don't work. 16438 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16439 ExprLoc, 16440 BuildAndDiagnose, 16441 *this); 16442 // We need to check for the parent *first* because, if we *have* 16443 // private-captured a global variable, we need to recursively capture it in 16444 // intermediate blocks, lambdas, etc. 16445 if (!ParentDC) { 16446 if (IsGlobal) { 16447 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16448 break; 16449 } 16450 return true; 16451 } 16452 16453 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16454 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16455 16456 16457 // Check whether we've already captured it. 16458 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16459 DeclRefType)) { 16460 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16461 break; 16462 } 16463 // If we are instantiating a generic lambda call operator body, 16464 // we do not want to capture new variables. What was captured 16465 // during either a lambdas transformation or initial parsing 16466 // should be used. 16467 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16468 if (BuildAndDiagnose) { 16469 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16470 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16471 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16472 Diag(Var->getLocation(), diag::note_previous_decl) 16473 << Var->getDeclName(); 16474 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16475 } else 16476 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16477 } 16478 return true; 16479 } 16480 16481 // Try to capture variable-length arrays types. 16482 if (Var->getType()->isVariablyModifiedType()) { 16483 // We're going to walk down into the type and look for VLA 16484 // expressions. 16485 QualType QTy = Var->getType(); 16486 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16487 QTy = PVD->getOriginalType(); 16488 captureVariablyModifiedType(Context, QTy, CSI); 16489 } 16490 16491 if (getLangOpts().OpenMP) { 16492 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16493 // OpenMP private variables should not be captured in outer scope, so 16494 // just break here. Similarly, global variables that are captured in a 16495 // target region should not be captured outside the scope of the region. 16496 if (RSI->CapRegionKind == CR_OpenMP) { 16497 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16498 // If the variable is private (i.e. not captured) and has variably 16499 // modified type, we still need to capture the type for correct 16500 // codegen in all regions, associated with the construct. Currently, 16501 // it is captured in the innermost captured region only. 16502 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16503 QualType QTy = Var->getType(); 16504 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16505 QTy = PVD->getOriginalType(); 16506 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16507 I < E; ++I) { 16508 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16509 FunctionScopes[FunctionScopesIndex - I]); 16510 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16511 "Wrong number of captured regions associated with the " 16512 "OpenMP construct."); 16513 captureVariablyModifiedType(Context, QTy, OuterRSI); 16514 } 16515 } 16516 bool IsTargetCap = 16517 !IsOpenMPPrivateDecl && 16518 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 16519 RSI->OpenMPCaptureLevel); 16520 // When we detect target captures we are looking from inside the 16521 // target region, therefore we need to propagate the capture from the 16522 // enclosing region. Therefore, the capture is not initially nested. 16523 if (IsTargetCap) 16524 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16525 16526 if (IsTargetCap || IsOpenMPPrivateDecl) { 16527 Nested = !IsTargetCap; 16528 DeclRefType = DeclRefType.getUnqualifiedType(); 16529 CaptureType = Context.getLValueReferenceType(DeclRefType); 16530 break; 16531 } 16532 } 16533 } 16534 } 16535 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16536 // No capture-default, and this is not an explicit capture 16537 // so cannot capture this variable. 16538 if (BuildAndDiagnose) { 16539 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16540 Diag(Var->getLocation(), diag::note_previous_decl) 16541 << Var->getDeclName(); 16542 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16543 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16544 diag::note_lambda_decl); 16545 // FIXME: If we error out because an outer lambda can not implicitly 16546 // capture a variable that an inner lambda explicitly captures, we 16547 // should have the inner lambda do the explicit capture - because 16548 // it makes for cleaner diagnostics later. This would purely be done 16549 // so that the diagnostic does not misleadingly claim that a variable 16550 // can not be captured by a lambda implicitly even though it is captured 16551 // explicitly. Suggestion: 16552 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16553 // at the function head 16554 // - cache the StartingDeclContext - this must be a lambda 16555 // - captureInLambda in the innermost lambda the variable. 16556 } 16557 return true; 16558 } 16559 16560 FunctionScopesIndex--; 16561 DC = ParentDC; 16562 Explicit = false; 16563 } while (!VarDC->Equals(DC)); 16564 16565 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16566 // computing the type of the capture at each step, checking type-specific 16567 // requirements, and adding captures if requested. 16568 // If the variable had already been captured previously, we start capturing 16569 // at the lambda nested within that one. 16570 bool Invalid = false; 16571 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16572 ++I) { 16573 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16574 16575 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16576 // certain types of variables (unnamed, variably modified types etc.) 16577 // so check for eligibility. 16578 if (!Invalid) 16579 Invalid = 16580 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16581 16582 // After encountering an error, if we're actually supposed to capture, keep 16583 // capturing in nested contexts to suppress any follow-on diagnostics. 16584 if (Invalid && !BuildAndDiagnose) 16585 return true; 16586 16587 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16588 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16589 DeclRefType, Nested, *this, Invalid); 16590 Nested = true; 16591 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16592 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16593 CaptureType, DeclRefType, Nested, 16594 *this, Invalid); 16595 Nested = true; 16596 } else { 16597 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16598 Invalid = 16599 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16600 DeclRefType, Nested, Kind, EllipsisLoc, 16601 /*IsTopScope*/ I == N - 1, *this, Invalid); 16602 Nested = true; 16603 } 16604 16605 if (Invalid && !BuildAndDiagnose) 16606 return true; 16607 } 16608 return Invalid; 16609 } 16610 16611 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16612 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16613 QualType CaptureType; 16614 QualType DeclRefType; 16615 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16616 /*BuildAndDiagnose=*/true, CaptureType, 16617 DeclRefType, nullptr); 16618 } 16619 16620 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16621 QualType CaptureType; 16622 QualType DeclRefType; 16623 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16624 /*BuildAndDiagnose=*/false, CaptureType, 16625 DeclRefType, nullptr); 16626 } 16627 16628 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16629 QualType CaptureType; 16630 QualType DeclRefType; 16631 16632 // Determine whether we can capture this variable. 16633 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16634 /*BuildAndDiagnose=*/false, CaptureType, 16635 DeclRefType, nullptr)) 16636 return QualType(); 16637 16638 return DeclRefType; 16639 } 16640 16641 namespace { 16642 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16643 // The produced TemplateArgumentListInfo* points to data stored within this 16644 // object, so should only be used in contexts where the pointer will not be 16645 // used after the CopiedTemplateArgs object is destroyed. 16646 class CopiedTemplateArgs { 16647 bool HasArgs; 16648 TemplateArgumentListInfo TemplateArgStorage; 16649 public: 16650 template<typename RefExpr> 16651 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16652 if (HasArgs) 16653 E->copyTemplateArgumentsInto(TemplateArgStorage); 16654 } 16655 operator TemplateArgumentListInfo*() 16656 #ifdef __has_cpp_attribute 16657 #if __has_cpp_attribute(clang::lifetimebound) 16658 [[clang::lifetimebound]] 16659 #endif 16660 #endif 16661 { 16662 return HasArgs ? &TemplateArgStorage : nullptr; 16663 } 16664 }; 16665 } 16666 16667 /// Walk the set of potential results of an expression and mark them all as 16668 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16669 /// 16670 /// \return A new expression if we found any potential results, ExprEmpty() if 16671 /// not, and ExprError() if we diagnosed an error. 16672 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16673 NonOdrUseReason NOUR) { 16674 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16675 // an object that satisfies the requirements for appearing in a 16676 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16677 // is immediately applied." This function handles the lvalue-to-rvalue 16678 // conversion part. 16679 // 16680 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16681 // transform it into the relevant kind of non-odr-use node and rebuild the 16682 // tree of nodes leading to it. 16683 // 16684 // This is a mini-TreeTransform that only transforms a restricted subset of 16685 // nodes (and only certain operands of them). 16686 16687 // Rebuild a subexpression. 16688 auto Rebuild = [&](Expr *Sub) { 16689 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16690 }; 16691 16692 // Check whether a potential result satisfies the requirements of NOUR. 16693 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16694 // Any entity other than a VarDecl is always odr-used whenever it's named 16695 // in a potentially-evaluated expression. 16696 auto *VD = dyn_cast<VarDecl>(D); 16697 if (!VD) 16698 return true; 16699 16700 // C++2a [basic.def.odr]p4: 16701 // A variable x whose name appears as a potentially-evalauted expression 16702 // e is odr-used by e unless 16703 // -- x is a reference that is usable in constant expressions, or 16704 // -- x is a variable of non-reference type that is usable in constant 16705 // expressions and has no mutable subobjects, and e is an element of 16706 // the set of potential results of an expression of 16707 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16708 // conversion is applied, or 16709 // -- x is a variable of non-reference type, and e is an element of the 16710 // set of potential results of a discarded-value expression to which 16711 // the lvalue-to-rvalue conversion is not applied 16712 // 16713 // We check the first bullet and the "potentially-evaluated" condition in 16714 // BuildDeclRefExpr. We check the type requirements in the second bullet 16715 // in CheckLValueToRValueConversionOperand below. 16716 switch (NOUR) { 16717 case NOUR_None: 16718 case NOUR_Unevaluated: 16719 llvm_unreachable("unexpected non-odr-use-reason"); 16720 16721 case NOUR_Constant: 16722 // Constant references were handled when they were built. 16723 if (VD->getType()->isReferenceType()) 16724 return true; 16725 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16726 if (RD->hasMutableFields()) 16727 return true; 16728 if (!VD->isUsableInConstantExpressions(S.Context)) 16729 return true; 16730 break; 16731 16732 case NOUR_Discarded: 16733 if (VD->getType()->isReferenceType()) 16734 return true; 16735 break; 16736 } 16737 return false; 16738 }; 16739 16740 // Mark that this expression does not constitute an odr-use. 16741 auto MarkNotOdrUsed = [&] { 16742 S.MaybeODRUseExprs.erase(E); 16743 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16744 LSI->markVariableExprAsNonODRUsed(E); 16745 }; 16746 16747 // C++2a [basic.def.odr]p2: 16748 // The set of potential results of an expression e is defined as follows: 16749 switch (E->getStmtClass()) { 16750 // -- If e is an id-expression, ... 16751 case Expr::DeclRefExprClass: { 16752 auto *DRE = cast<DeclRefExpr>(E); 16753 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16754 break; 16755 16756 // Rebuild as a non-odr-use DeclRefExpr. 16757 MarkNotOdrUsed(); 16758 return DeclRefExpr::Create( 16759 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16760 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16761 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16762 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16763 } 16764 16765 case Expr::FunctionParmPackExprClass: { 16766 auto *FPPE = cast<FunctionParmPackExpr>(E); 16767 // If any of the declarations in the pack is odr-used, then the expression 16768 // as a whole constitutes an odr-use. 16769 for (VarDecl *D : *FPPE) 16770 if (IsPotentialResultOdrUsed(D)) 16771 return ExprEmpty(); 16772 16773 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16774 // nothing cares about whether we marked this as an odr-use, but it might 16775 // be useful for non-compiler tools. 16776 MarkNotOdrUsed(); 16777 break; 16778 } 16779 16780 // -- If e is a subscripting operation with an array operand... 16781 case Expr::ArraySubscriptExprClass: { 16782 auto *ASE = cast<ArraySubscriptExpr>(E); 16783 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16784 if (!OldBase->getType()->isArrayType()) 16785 break; 16786 ExprResult Base = Rebuild(OldBase); 16787 if (!Base.isUsable()) 16788 return Base; 16789 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16790 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16791 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16792 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16793 ASE->getRBracketLoc()); 16794 } 16795 16796 case Expr::MemberExprClass: { 16797 auto *ME = cast<MemberExpr>(E); 16798 // -- If e is a class member access expression [...] naming a non-static 16799 // data member... 16800 if (isa<FieldDecl>(ME->getMemberDecl())) { 16801 ExprResult Base = Rebuild(ME->getBase()); 16802 if (!Base.isUsable()) 16803 return Base; 16804 return MemberExpr::Create( 16805 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16806 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16807 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16808 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16809 ME->getObjectKind(), ME->isNonOdrUse()); 16810 } 16811 16812 if (ME->getMemberDecl()->isCXXInstanceMember()) 16813 break; 16814 16815 // -- If e is a class member access expression naming a static data member, 16816 // ... 16817 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16818 break; 16819 16820 // Rebuild as a non-odr-use MemberExpr. 16821 MarkNotOdrUsed(); 16822 return MemberExpr::Create( 16823 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16824 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16825 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16826 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16827 return ExprEmpty(); 16828 } 16829 16830 case Expr::BinaryOperatorClass: { 16831 auto *BO = cast<BinaryOperator>(E); 16832 Expr *LHS = BO->getLHS(); 16833 Expr *RHS = BO->getRHS(); 16834 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16835 if (BO->getOpcode() == BO_PtrMemD) { 16836 ExprResult Sub = Rebuild(LHS); 16837 if (!Sub.isUsable()) 16838 return Sub; 16839 LHS = Sub.get(); 16840 // -- If e is a comma expression, ... 16841 } else if (BO->getOpcode() == BO_Comma) { 16842 ExprResult Sub = Rebuild(RHS); 16843 if (!Sub.isUsable()) 16844 return Sub; 16845 RHS = Sub.get(); 16846 } else { 16847 break; 16848 } 16849 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16850 LHS, RHS); 16851 } 16852 16853 // -- If e has the form (e1)... 16854 case Expr::ParenExprClass: { 16855 auto *PE = cast<ParenExpr>(E); 16856 ExprResult Sub = Rebuild(PE->getSubExpr()); 16857 if (!Sub.isUsable()) 16858 return Sub; 16859 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16860 } 16861 16862 // -- If e is a glvalue conditional expression, ... 16863 // We don't apply this to a binary conditional operator. FIXME: Should we? 16864 case Expr::ConditionalOperatorClass: { 16865 auto *CO = cast<ConditionalOperator>(E); 16866 ExprResult LHS = Rebuild(CO->getLHS()); 16867 if (LHS.isInvalid()) 16868 return ExprError(); 16869 ExprResult RHS = Rebuild(CO->getRHS()); 16870 if (RHS.isInvalid()) 16871 return ExprError(); 16872 if (!LHS.isUsable() && !RHS.isUsable()) 16873 return ExprEmpty(); 16874 if (!LHS.isUsable()) 16875 LHS = CO->getLHS(); 16876 if (!RHS.isUsable()) 16877 RHS = CO->getRHS(); 16878 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16879 CO->getCond(), LHS.get(), RHS.get()); 16880 } 16881 16882 // [Clang extension] 16883 // -- If e has the form __extension__ e1... 16884 case Expr::UnaryOperatorClass: { 16885 auto *UO = cast<UnaryOperator>(E); 16886 if (UO->getOpcode() != UO_Extension) 16887 break; 16888 ExprResult Sub = Rebuild(UO->getSubExpr()); 16889 if (!Sub.isUsable()) 16890 return Sub; 16891 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16892 Sub.get()); 16893 } 16894 16895 // [Clang extension] 16896 // -- If e has the form _Generic(...), the set of potential results is the 16897 // union of the sets of potential results of the associated expressions. 16898 case Expr::GenericSelectionExprClass: { 16899 auto *GSE = cast<GenericSelectionExpr>(E); 16900 16901 SmallVector<Expr *, 4> AssocExprs; 16902 bool AnyChanged = false; 16903 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16904 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16905 if (AssocExpr.isInvalid()) 16906 return ExprError(); 16907 if (AssocExpr.isUsable()) { 16908 AssocExprs.push_back(AssocExpr.get()); 16909 AnyChanged = true; 16910 } else { 16911 AssocExprs.push_back(OrigAssocExpr); 16912 } 16913 } 16914 16915 return AnyChanged ? S.CreateGenericSelectionExpr( 16916 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16917 GSE->getRParenLoc(), GSE->getControllingExpr(), 16918 GSE->getAssocTypeSourceInfos(), AssocExprs) 16919 : ExprEmpty(); 16920 } 16921 16922 // [Clang extension] 16923 // -- If e has the form __builtin_choose_expr(...), the set of potential 16924 // results is the union of the sets of potential results of the 16925 // second and third subexpressions. 16926 case Expr::ChooseExprClass: { 16927 auto *CE = cast<ChooseExpr>(E); 16928 16929 ExprResult LHS = Rebuild(CE->getLHS()); 16930 if (LHS.isInvalid()) 16931 return ExprError(); 16932 16933 ExprResult RHS = Rebuild(CE->getLHS()); 16934 if (RHS.isInvalid()) 16935 return ExprError(); 16936 16937 if (!LHS.get() && !RHS.get()) 16938 return ExprEmpty(); 16939 if (!LHS.isUsable()) 16940 LHS = CE->getLHS(); 16941 if (!RHS.isUsable()) 16942 RHS = CE->getRHS(); 16943 16944 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16945 RHS.get(), CE->getRParenLoc()); 16946 } 16947 16948 // Step through non-syntactic nodes. 16949 case Expr::ConstantExprClass: { 16950 auto *CE = cast<ConstantExpr>(E); 16951 ExprResult Sub = Rebuild(CE->getSubExpr()); 16952 if (!Sub.isUsable()) 16953 return Sub; 16954 return ConstantExpr::Create(S.Context, Sub.get()); 16955 } 16956 16957 // We could mostly rely on the recursive rebuilding to rebuild implicit 16958 // casts, but not at the top level, so rebuild them here. 16959 case Expr::ImplicitCastExprClass: { 16960 auto *ICE = cast<ImplicitCastExpr>(E); 16961 // Only step through the narrow set of cast kinds we expect to encounter. 16962 // Anything else suggests we've left the region in which potential results 16963 // can be found. 16964 switch (ICE->getCastKind()) { 16965 case CK_NoOp: 16966 case CK_DerivedToBase: 16967 case CK_UncheckedDerivedToBase: { 16968 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16969 if (!Sub.isUsable()) 16970 return Sub; 16971 CXXCastPath Path(ICE->path()); 16972 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16973 ICE->getValueKind(), &Path); 16974 } 16975 16976 default: 16977 break; 16978 } 16979 break; 16980 } 16981 16982 default: 16983 break; 16984 } 16985 16986 // Can't traverse through this node. Nothing to do. 16987 return ExprEmpty(); 16988 } 16989 16990 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16991 // Check whether the operand is or contains an object of non-trivial C union 16992 // type. 16993 if (E->getType().isVolatileQualified() && 16994 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16995 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16996 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16997 Sema::NTCUC_LValueToRValueVolatile, 16998 NTCUK_Destruct|NTCUK_Copy); 16999 17000 // C++2a [basic.def.odr]p4: 17001 // [...] an expression of non-volatile-qualified non-class type to which 17002 // the lvalue-to-rvalue conversion is applied [...] 17003 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17004 return E; 17005 17006 ExprResult Result = 17007 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17008 if (Result.isInvalid()) 17009 return ExprError(); 17010 return Result.get() ? Result : E; 17011 } 17012 17013 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17014 Res = CorrectDelayedTyposInExpr(Res); 17015 17016 if (!Res.isUsable()) 17017 return Res; 17018 17019 // If a constant-expression is a reference to a variable where we delay 17020 // deciding whether it is an odr-use, just assume we will apply the 17021 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17022 // (a non-type template argument), we have special handling anyway. 17023 return CheckLValueToRValueConversionOperand(Res.get()); 17024 } 17025 17026 void Sema::CleanupVarDeclMarking() { 17027 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17028 // call. 17029 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17030 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17031 17032 for (Expr *E : LocalMaybeODRUseExprs) { 17033 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17034 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17035 DRE->getLocation(), *this); 17036 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17037 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17038 *this); 17039 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17040 for (VarDecl *VD : *FP) 17041 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17042 } else { 17043 llvm_unreachable("Unexpected expression"); 17044 } 17045 } 17046 17047 assert(MaybeODRUseExprs.empty() && 17048 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17049 } 17050 17051 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17052 VarDecl *Var, Expr *E) { 17053 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17054 isa<FunctionParmPackExpr>(E)) && 17055 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17056 Var->setReferenced(); 17057 17058 if (Var->isInvalidDecl()) 17059 return; 17060 17061 auto *MSI = Var->getMemberSpecializationInfo(); 17062 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17063 : Var->getTemplateSpecializationKind(); 17064 17065 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17066 bool UsableInConstantExpr = 17067 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17068 17069 // C++20 [expr.const]p12: 17070 // A variable [...] is needed for constant evaluation if it is [...] a 17071 // variable whose name appears as a potentially constant evaluated 17072 // expression that is either a contexpr variable or is of non-volatile 17073 // const-qualified integral type or of reference type 17074 bool NeededForConstantEvaluation = 17075 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17076 17077 bool NeedDefinition = 17078 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17079 17080 VarTemplateSpecializationDecl *VarSpec = 17081 dyn_cast<VarTemplateSpecializationDecl>(Var); 17082 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17083 "Can't instantiate a partial template specialization."); 17084 17085 // If this might be a member specialization of a static data member, check 17086 // the specialization is visible. We already did the checks for variable 17087 // template specializations when we created them. 17088 if (NeedDefinition && TSK != TSK_Undeclared && 17089 !isa<VarTemplateSpecializationDecl>(Var)) 17090 SemaRef.checkSpecializationVisibility(Loc, Var); 17091 17092 // Perform implicit instantiation of static data members, static data member 17093 // templates of class templates, and variable template specializations. Delay 17094 // instantiations of variable templates, except for those that could be used 17095 // in a constant expression. 17096 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17097 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17098 // instantiation declaration if a variable is usable in a constant 17099 // expression (among other cases). 17100 bool TryInstantiating = 17101 TSK == TSK_ImplicitInstantiation || 17102 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17103 17104 if (TryInstantiating) { 17105 SourceLocation PointOfInstantiation = 17106 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17107 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17108 if (FirstInstantiation) { 17109 PointOfInstantiation = Loc; 17110 if (MSI) 17111 MSI->setPointOfInstantiation(PointOfInstantiation); 17112 else 17113 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17114 } 17115 17116 bool InstantiationDependent = false; 17117 bool IsNonDependent = 17118 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17119 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17120 : true; 17121 17122 // Do not instantiate specializations that are still type-dependent. 17123 if (IsNonDependent) { 17124 if (UsableInConstantExpr) { 17125 // Do not defer instantiations of variables that could be used in a 17126 // constant expression. 17127 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17128 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17129 }); 17130 } else if (FirstInstantiation || 17131 isa<VarTemplateSpecializationDecl>(Var)) { 17132 // FIXME: For a specialization of a variable template, we don't 17133 // distinguish between "declaration and type implicitly instantiated" 17134 // and "implicit instantiation of definition requested", so we have 17135 // no direct way to avoid enqueueing the pending instantiation 17136 // multiple times. 17137 SemaRef.PendingInstantiations 17138 .push_back(std::make_pair(Var, PointOfInstantiation)); 17139 } 17140 } 17141 } 17142 } 17143 17144 // C++2a [basic.def.odr]p4: 17145 // A variable x whose name appears as a potentially-evaluated expression e 17146 // is odr-used by e unless 17147 // -- x is a reference that is usable in constant expressions 17148 // -- x is a variable of non-reference type that is usable in constant 17149 // expressions and has no mutable subobjects [FIXME], and e is an 17150 // element of the set of potential results of an expression of 17151 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17152 // conversion is applied 17153 // -- x is a variable of non-reference type, and e is an element of the set 17154 // of potential results of a discarded-value expression to which the 17155 // lvalue-to-rvalue conversion is not applied [FIXME] 17156 // 17157 // We check the first part of the second bullet here, and 17158 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17159 // FIXME: To get the third bullet right, we need to delay this even for 17160 // variables that are not usable in constant expressions. 17161 17162 // If we already know this isn't an odr-use, there's nothing more to do. 17163 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17164 if (DRE->isNonOdrUse()) 17165 return; 17166 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17167 if (ME->isNonOdrUse()) 17168 return; 17169 17170 switch (OdrUse) { 17171 case OdrUseContext::None: 17172 assert((!E || isa<FunctionParmPackExpr>(E)) && 17173 "missing non-odr-use marking for unevaluated decl ref"); 17174 break; 17175 17176 case OdrUseContext::FormallyOdrUsed: 17177 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17178 // behavior. 17179 break; 17180 17181 case OdrUseContext::Used: 17182 // If we might later find that this expression isn't actually an odr-use, 17183 // delay the marking. 17184 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17185 SemaRef.MaybeODRUseExprs.insert(E); 17186 else 17187 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17188 break; 17189 17190 case OdrUseContext::Dependent: 17191 // If this is a dependent context, we don't need to mark variables as 17192 // odr-used, but we may still need to track them for lambda capture. 17193 // FIXME: Do we also need to do this inside dependent typeid expressions 17194 // (which are modeled as unevaluated at this point)? 17195 const bool RefersToEnclosingScope = 17196 (SemaRef.CurContext != Var->getDeclContext() && 17197 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17198 if (RefersToEnclosingScope) { 17199 LambdaScopeInfo *const LSI = 17200 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17201 if (LSI && (!LSI->CallOperator || 17202 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17203 // If a variable could potentially be odr-used, defer marking it so 17204 // until we finish analyzing the full expression for any 17205 // lvalue-to-rvalue 17206 // or discarded value conversions that would obviate odr-use. 17207 // Add it to the list of potential captures that will be analyzed 17208 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17209 // unless the variable is a reference that was initialized by a constant 17210 // expression (this will never need to be captured or odr-used). 17211 // 17212 // FIXME: We can simplify this a lot after implementing P0588R1. 17213 assert(E && "Capture variable should be used in an expression."); 17214 if (!Var->getType()->isReferenceType() || 17215 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17216 LSI->addPotentialCapture(E->IgnoreParens()); 17217 } 17218 } 17219 break; 17220 } 17221 } 17222 17223 /// Mark a variable referenced, and check whether it is odr-used 17224 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17225 /// used directly for normal expressions referring to VarDecl. 17226 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17227 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17228 } 17229 17230 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17231 Decl *D, Expr *E, bool MightBeOdrUse) { 17232 if (SemaRef.isInOpenMPDeclareTargetContext()) 17233 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17234 17235 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17236 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17237 return; 17238 } 17239 17240 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17241 17242 // If this is a call to a method via a cast, also mark the method in the 17243 // derived class used in case codegen can devirtualize the call. 17244 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17245 if (!ME) 17246 return; 17247 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17248 if (!MD) 17249 return; 17250 // Only attempt to devirtualize if this is truly a virtual call. 17251 bool IsVirtualCall = MD->isVirtual() && 17252 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17253 if (!IsVirtualCall) 17254 return; 17255 17256 // If it's possible to devirtualize the call, mark the called function 17257 // referenced. 17258 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17259 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17260 if (DM) 17261 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17262 } 17263 17264 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17265 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17266 // TODO: update this with DR# once a defect report is filed. 17267 // C++11 defect. The address of a pure member should not be an ODR use, even 17268 // if it's a qualified reference. 17269 bool OdrUse = true; 17270 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17271 if (Method->isVirtual() && 17272 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17273 OdrUse = false; 17274 17275 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17276 if (!isConstantEvaluated() && FD->isConsteval() && 17277 !RebuildingImmediateInvocation) 17278 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17279 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17280 } 17281 17282 /// Perform reference-marking and odr-use handling for a MemberExpr. 17283 void Sema::MarkMemberReferenced(MemberExpr *E) { 17284 // C++11 [basic.def.odr]p2: 17285 // A non-overloaded function whose name appears as a potentially-evaluated 17286 // expression or a member of a set of candidate functions, if selected by 17287 // overload resolution when referred to from a potentially-evaluated 17288 // expression, is odr-used, unless it is a pure virtual function and its 17289 // name is not explicitly qualified. 17290 bool MightBeOdrUse = true; 17291 if (E->performsVirtualDispatch(getLangOpts())) { 17292 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17293 if (Method->isPure()) 17294 MightBeOdrUse = false; 17295 } 17296 SourceLocation Loc = 17297 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17298 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17299 } 17300 17301 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17302 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17303 for (VarDecl *VD : *E) 17304 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17305 } 17306 17307 /// Perform marking for a reference to an arbitrary declaration. It 17308 /// marks the declaration referenced, and performs odr-use checking for 17309 /// functions and variables. This method should not be used when building a 17310 /// normal expression which refers to a variable. 17311 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17312 bool MightBeOdrUse) { 17313 if (MightBeOdrUse) { 17314 if (auto *VD = dyn_cast<VarDecl>(D)) { 17315 MarkVariableReferenced(Loc, VD); 17316 return; 17317 } 17318 } 17319 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17320 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17321 return; 17322 } 17323 D->setReferenced(); 17324 } 17325 17326 namespace { 17327 // Mark all of the declarations used by a type as referenced. 17328 // FIXME: Not fully implemented yet! We need to have a better understanding 17329 // of when we're entering a context we should not recurse into. 17330 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17331 // TreeTransforms rebuilding the type in a new context. Rather than 17332 // duplicating the TreeTransform logic, we should consider reusing it here. 17333 // Currently that causes problems when rebuilding LambdaExprs. 17334 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17335 Sema &S; 17336 SourceLocation Loc; 17337 17338 public: 17339 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17340 17341 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17342 17343 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17344 }; 17345 } 17346 17347 bool MarkReferencedDecls::TraverseTemplateArgument( 17348 const TemplateArgument &Arg) { 17349 { 17350 // A non-type template argument is a constant-evaluated context. 17351 EnterExpressionEvaluationContext Evaluated( 17352 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17353 if (Arg.getKind() == TemplateArgument::Declaration) { 17354 if (Decl *D = Arg.getAsDecl()) 17355 S.MarkAnyDeclReferenced(Loc, D, true); 17356 } else if (Arg.getKind() == TemplateArgument::Expression) { 17357 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17358 } 17359 } 17360 17361 return Inherited::TraverseTemplateArgument(Arg); 17362 } 17363 17364 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17365 MarkReferencedDecls Marker(*this, Loc); 17366 Marker.TraverseType(T); 17367 } 17368 17369 namespace { 17370 /// Helper class that marks all of the declarations referenced by 17371 /// potentially-evaluated subexpressions as "referenced". 17372 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17373 Sema &S; 17374 bool SkipLocalVariables; 17375 17376 public: 17377 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17378 17379 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17380 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17381 17382 void VisitDeclRefExpr(DeclRefExpr *E) { 17383 // If we were asked not to visit local variables, don't. 17384 if (SkipLocalVariables) { 17385 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17386 if (VD->hasLocalStorage()) 17387 return; 17388 } 17389 17390 S.MarkDeclRefReferenced(E); 17391 } 17392 17393 void VisitMemberExpr(MemberExpr *E) { 17394 S.MarkMemberReferenced(E); 17395 Inherited::VisitMemberExpr(E); 17396 } 17397 17398 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17399 S.MarkFunctionReferenced( 17400 E->getBeginLoc(), 17401 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17402 Visit(E->getSubExpr()); 17403 } 17404 17405 void VisitCXXNewExpr(CXXNewExpr *E) { 17406 if (E->getOperatorNew()) 17407 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17408 if (E->getOperatorDelete()) 17409 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17410 Inherited::VisitCXXNewExpr(E); 17411 } 17412 17413 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17414 if (E->getOperatorDelete()) 17415 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17416 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17417 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17418 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17419 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17420 } 17421 17422 Inherited::VisitCXXDeleteExpr(E); 17423 } 17424 17425 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17426 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17427 Inherited::VisitCXXConstructExpr(E); 17428 } 17429 17430 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17431 Visit(E->getExpr()); 17432 } 17433 }; 17434 } 17435 17436 /// Mark any declarations that appear within this expression or any 17437 /// potentially-evaluated subexpressions as "referenced". 17438 /// 17439 /// \param SkipLocalVariables If true, don't mark local variables as 17440 /// 'referenced'. 17441 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17442 bool SkipLocalVariables) { 17443 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17444 } 17445 17446 /// Emit a diagnostic that describes an effect on the run-time behavior 17447 /// of the program being compiled. 17448 /// 17449 /// This routine emits the given diagnostic when the code currently being 17450 /// type-checked is "potentially evaluated", meaning that there is a 17451 /// possibility that the code will actually be executable. Code in sizeof() 17452 /// expressions, code used only during overload resolution, etc., are not 17453 /// potentially evaluated. This routine will suppress such diagnostics or, 17454 /// in the absolutely nutty case of potentially potentially evaluated 17455 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17456 /// later. 17457 /// 17458 /// This routine should be used for all diagnostics that describe the run-time 17459 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17460 /// Failure to do so will likely result in spurious diagnostics or failures 17461 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17462 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17463 const PartialDiagnostic &PD) { 17464 switch (ExprEvalContexts.back().Context) { 17465 case ExpressionEvaluationContext::Unevaluated: 17466 case ExpressionEvaluationContext::UnevaluatedList: 17467 case ExpressionEvaluationContext::UnevaluatedAbstract: 17468 case ExpressionEvaluationContext::DiscardedStatement: 17469 // The argument will never be evaluated, so don't complain. 17470 break; 17471 17472 case ExpressionEvaluationContext::ConstantEvaluated: 17473 // Relevant diagnostics should be produced by constant evaluation. 17474 break; 17475 17476 case ExpressionEvaluationContext::PotentiallyEvaluated: 17477 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17478 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17479 FunctionScopes.back()->PossiblyUnreachableDiags. 17480 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17481 return true; 17482 } 17483 17484 // The initializer of a constexpr variable or of the first declaration of a 17485 // static data member is not syntactically a constant evaluated constant, 17486 // but nonetheless is always required to be a constant expression, so we 17487 // can skip diagnosing. 17488 // FIXME: Using the mangling context here is a hack. 17489 if (auto *VD = dyn_cast_or_null<VarDecl>( 17490 ExprEvalContexts.back().ManglingContextDecl)) { 17491 if (VD->isConstexpr() || 17492 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17493 break; 17494 // FIXME: For any other kind of variable, we should build a CFG for its 17495 // initializer and check whether the context in question is reachable. 17496 } 17497 17498 Diag(Loc, PD); 17499 return true; 17500 } 17501 17502 return false; 17503 } 17504 17505 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17506 const PartialDiagnostic &PD) { 17507 return DiagRuntimeBehavior( 17508 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17509 } 17510 17511 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17512 CallExpr *CE, FunctionDecl *FD) { 17513 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17514 return false; 17515 17516 // If we're inside a decltype's expression, don't check for a valid return 17517 // type or construct temporaries until we know whether this is the last call. 17518 if (ExprEvalContexts.back().ExprContext == 17519 ExpressionEvaluationContextRecord::EK_Decltype) { 17520 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17521 return false; 17522 } 17523 17524 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17525 FunctionDecl *FD; 17526 CallExpr *CE; 17527 17528 public: 17529 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17530 : FD(FD), CE(CE) { } 17531 17532 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17533 if (!FD) { 17534 S.Diag(Loc, diag::err_call_incomplete_return) 17535 << T << CE->getSourceRange(); 17536 return; 17537 } 17538 17539 S.Diag(Loc, diag::err_call_function_incomplete_return) 17540 << CE->getSourceRange() << FD->getDeclName() << T; 17541 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17542 << FD->getDeclName(); 17543 } 17544 } Diagnoser(FD, CE); 17545 17546 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17547 return true; 17548 17549 return false; 17550 } 17551 17552 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17553 // will prevent this condition from triggering, which is what we want. 17554 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17555 SourceLocation Loc; 17556 17557 unsigned diagnostic = diag::warn_condition_is_assignment; 17558 bool IsOrAssign = false; 17559 17560 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17561 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17562 return; 17563 17564 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17565 17566 // Greylist some idioms by putting them into a warning subcategory. 17567 if (ObjCMessageExpr *ME 17568 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17569 Selector Sel = ME->getSelector(); 17570 17571 // self = [<foo> init...] 17572 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17573 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17574 17575 // <foo> = [<bar> nextObject] 17576 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17577 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17578 } 17579 17580 Loc = Op->getOperatorLoc(); 17581 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17582 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17583 return; 17584 17585 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17586 Loc = Op->getOperatorLoc(); 17587 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17588 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17589 else { 17590 // Not an assignment. 17591 return; 17592 } 17593 17594 Diag(Loc, diagnostic) << E->getSourceRange(); 17595 17596 SourceLocation Open = E->getBeginLoc(); 17597 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17598 Diag(Loc, diag::note_condition_assign_silence) 17599 << FixItHint::CreateInsertion(Open, "(") 17600 << FixItHint::CreateInsertion(Close, ")"); 17601 17602 if (IsOrAssign) 17603 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17604 << FixItHint::CreateReplacement(Loc, "!="); 17605 else 17606 Diag(Loc, diag::note_condition_assign_to_comparison) 17607 << FixItHint::CreateReplacement(Loc, "=="); 17608 } 17609 17610 /// Redundant parentheses over an equality comparison can indicate 17611 /// that the user intended an assignment used as condition. 17612 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17613 // Don't warn if the parens came from a macro. 17614 SourceLocation parenLoc = ParenE->getBeginLoc(); 17615 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17616 return; 17617 // Don't warn for dependent expressions. 17618 if (ParenE->isTypeDependent()) 17619 return; 17620 17621 Expr *E = ParenE->IgnoreParens(); 17622 17623 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17624 if (opE->getOpcode() == BO_EQ && 17625 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17626 == Expr::MLV_Valid) { 17627 SourceLocation Loc = opE->getOperatorLoc(); 17628 17629 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17630 SourceRange ParenERange = ParenE->getSourceRange(); 17631 Diag(Loc, diag::note_equality_comparison_silence) 17632 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17633 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17634 Diag(Loc, diag::note_equality_comparison_to_assign) 17635 << FixItHint::CreateReplacement(Loc, "="); 17636 } 17637 } 17638 17639 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17640 bool IsConstexpr) { 17641 DiagnoseAssignmentAsCondition(E); 17642 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17643 DiagnoseEqualityWithExtraParens(parenE); 17644 17645 ExprResult result = CheckPlaceholderExpr(E); 17646 if (result.isInvalid()) return ExprError(); 17647 E = result.get(); 17648 17649 if (!E->isTypeDependent()) { 17650 if (getLangOpts().CPlusPlus) 17651 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17652 17653 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17654 if (ERes.isInvalid()) 17655 return ExprError(); 17656 E = ERes.get(); 17657 17658 QualType T = E->getType(); 17659 if (!T->isScalarType()) { // C99 6.8.4.1p1 17660 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17661 << T << E->getSourceRange(); 17662 return ExprError(); 17663 } 17664 CheckBoolLikeConversion(E, Loc); 17665 } 17666 17667 return E; 17668 } 17669 17670 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17671 Expr *SubExpr, ConditionKind CK) { 17672 // Empty conditions are valid in for-statements. 17673 if (!SubExpr) 17674 return ConditionResult(); 17675 17676 ExprResult Cond; 17677 switch (CK) { 17678 case ConditionKind::Boolean: 17679 Cond = CheckBooleanCondition(Loc, SubExpr); 17680 break; 17681 17682 case ConditionKind::ConstexprIf: 17683 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17684 break; 17685 17686 case ConditionKind::Switch: 17687 Cond = CheckSwitchCondition(Loc, SubExpr); 17688 break; 17689 } 17690 if (Cond.isInvalid()) 17691 return ConditionError(); 17692 17693 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17694 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17695 if (!FullExpr.get()) 17696 return ConditionError(); 17697 17698 return ConditionResult(*this, nullptr, FullExpr, 17699 CK == ConditionKind::ConstexprIf); 17700 } 17701 17702 namespace { 17703 /// A visitor for rebuilding a call to an __unknown_any expression 17704 /// to have an appropriate type. 17705 struct RebuildUnknownAnyFunction 17706 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17707 17708 Sema &S; 17709 17710 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17711 17712 ExprResult VisitStmt(Stmt *S) { 17713 llvm_unreachable("unexpected statement!"); 17714 } 17715 17716 ExprResult VisitExpr(Expr *E) { 17717 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17718 << E->getSourceRange(); 17719 return ExprError(); 17720 } 17721 17722 /// Rebuild an expression which simply semantically wraps another 17723 /// expression which it shares the type and value kind of. 17724 template <class T> ExprResult rebuildSugarExpr(T *E) { 17725 ExprResult SubResult = Visit(E->getSubExpr()); 17726 if (SubResult.isInvalid()) return ExprError(); 17727 17728 Expr *SubExpr = SubResult.get(); 17729 E->setSubExpr(SubExpr); 17730 E->setType(SubExpr->getType()); 17731 E->setValueKind(SubExpr->getValueKind()); 17732 assert(E->getObjectKind() == OK_Ordinary); 17733 return E; 17734 } 17735 17736 ExprResult VisitParenExpr(ParenExpr *E) { 17737 return rebuildSugarExpr(E); 17738 } 17739 17740 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17741 return rebuildSugarExpr(E); 17742 } 17743 17744 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17745 ExprResult SubResult = Visit(E->getSubExpr()); 17746 if (SubResult.isInvalid()) return ExprError(); 17747 17748 Expr *SubExpr = SubResult.get(); 17749 E->setSubExpr(SubExpr); 17750 E->setType(S.Context.getPointerType(SubExpr->getType())); 17751 assert(E->getValueKind() == VK_RValue); 17752 assert(E->getObjectKind() == OK_Ordinary); 17753 return E; 17754 } 17755 17756 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17757 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17758 17759 E->setType(VD->getType()); 17760 17761 assert(E->getValueKind() == VK_RValue); 17762 if (S.getLangOpts().CPlusPlus && 17763 !(isa<CXXMethodDecl>(VD) && 17764 cast<CXXMethodDecl>(VD)->isInstance())) 17765 E->setValueKind(VK_LValue); 17766 17767 return E; 17768 } 17769 17770 ExprResult VisitMemberExpr(MemberExpr *E) { 17771 return resolveDecl(E, E->getMemberDecl()); 17772 } 17773 17774 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17775 return resolveDecl(E, E->getDecl()); 17776 } 17777 }; 17778 } 17779 17780 /// Given a function expression of unknown-any type, try to rebuild it 17781 /// to have a function type. 17782 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17783 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17784 if (Result.isInvalid()) return ExprError(); 17785 return S.DefaultFunctionArrayConversion(Result.get()); 17786 } 17787 17788 namespace { 17789 /// A visitor for rebuilding an expression of type __unknown_anytype 17790 /// into one which resolves the type directly on the referring 17791 /// expression. Strict preservation of the original source 17792 /// structure is not a goal. 17793 struct RebuildUnknownAnyExpr 17794 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17795 17796 Sema &S; 17797 17798 /// The current destination type. 17799 QualType DestType; 17800 17801 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17802 : S(S), DestType(CastType) {} 17803 17804 ExprResult VisitStmt(Stmt *S) { 17805 llvm_unreachable("unexpected statement!"); 17806 } 17807 17808 ExprResult VisitExpr(Expr *E) { 17809 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17810 << E->getSourceRange(); 17811 return ExprError(); 17812 } 17813 17814 ExprResult VisitCallExpr(CallExpr *E); 17815 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17816 17817 /// Rebuild an expression which simply semantically wraps another 17818 /// expression which it shares the type and value kind of. 17819 template <class T> ExprResult rebuildSugarExpr(T *E) { 17820 ExprResult SubResult = Visit(E->getSubExpr()); 17821 if (SubResult.isInvalid()) return ExprError(); 17822 Expr *SubExpr = SubResult.get(); 17823 E->setSubExpr(SubExpr); 17824 E->setType(SubExpr->getType()); 17825 E->setValueKind(SubExpr->getValueKind()); 17826 assert(E->getObjectKind() == OK_Ordinary); 17827 return E; 17828 } 17829 17830 ExprResult VisitParenExpr(ParenExpr *E) { 17831 return rebuildSugarExpr(E); 17832 } 17833 17834 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17835 return rebuildSugarExpr(E); 17836 } 17837 17838 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17839 const PointerType *Ptr = DestType->getAs<PointerType>(); 17840 if (!Ptr) { 17841 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17842 << E->getSourceRange(); 17843 return ExprError(); 17844 } 17845 17846 if (isa<CallExpr>(E->getSubExpr())) { 17847 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17848 << E->getSourceRange(); 17849 return ExprError(); 17850 } 17851 17852 assert(E->getValueKind() == VK_RValue); 17853 assert(E->getObjectKind() == OK_Ordinary); 17854 E->setType(DestType); 17855 17856 // Build the sub-expression as if it were an object of the pointee type. 17857 DestType = Ptr->getPointeeType(); 17858 ExprResult SubResult = Visit(E->getSubExpr()); 17859 if (SubResult.isInvalid()) return ExprError(); 17860 E->setSubExpr(SubResult.get()); 17861 return E; 17862 } 17863 17864 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17865 17866 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17867 17868 ExprResult VisitMemberExpr(MemberExpr *E) { 17869 return resolveDecl(E, E->getMemberDecl()); 17870 } 17871 17872 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17873 return resolveDecl(E, E->getDecl()); 17874 } 17875 }; 17876 } 17877 17878 /// Rebuilds a call expression which yielded __unknown_anytype. 17879 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17880 Expr *CalleeExpr = E->getCallee(); 17881 17882 enum FnKind { 17883 FK_MemberFunction, 17884 FK_FunctionPointer, 17885 FK_BlockPointer 17886 }; 17887 17888 FnKind Kind; 17889 QualType CalleeType = CalleeExpr->getType(); 17890 if (CalleeType == S.Context.BoundMemberTy) { 17891 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17892 Kind = FK_MemberFunction; 17893 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17894 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17895 CalleeType = Ptr->getPointeeType(); 17896 Kind = FK_FunctionPointer; 17897 } else { 17898 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17899 Kind = FK_BlockPointer; 17900 } 17901 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17902 17903 // Verify that this is a legal result type of a function. 17904 if (DestType->isArrayType() || DestType->isFunctionType()) { 17905 unsigned diagID = diag::err_func_returning_array_function; 17906 if (Kind == FK_BlockPointer) 17907 diagID = diag::err_block_returning_array_function; 17908 17909 S.Diag(E->getExprLoc(), diagID) 17910 << DestType->isFunctionType() << DestType; 17911 return ExprError(); 17912 } 17913 17914 // Otherwise, go ahead and set DestType as the call's result. 17915 E->setType(DestType.getNonLValueExprType(S.Context)); 17916 E->setValueKind(Expr::getValueKindForType(DestType)); 17917 assert(E->getObjectKind() == OK_Ordinary); 17918 17919 // Rebuild the function type, replacing the result type with DestType. 17920 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17921 if (Proto) { 17922 // __unknown_anytype(...) is a special case used by the debugger when 17923 // it has no idea what a function's signature is. 17924 // 17925 // We want to build this call essentially under the K&R 17926 // unprototyped rules, but making a FunctionNoProtoType in C++ 17927 // would foul up all sorts of assumptions. However, we cannot 17928 // simply pass all arguments as variadic arguments, nor can we 17929 // portably just call the function under a non-variadic type; see 17930 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17931 // However, it turns out that in practice it is generally safe to 17932 // call a function declared as "A foo(B,C,D);" under the prototype 17933 // "A foo(B,C,D,...);". The only known exception is with the 17934 // Windows ABI, where any variadic function is implicitly cdecl 17935 // regardless of its normal CC. Therefore we change the parameter 17936 // types to match the types of the arguments. 17937 // 17938 // This is a hack, but it is far superior to moving the 17939 // corresponding target-specific code from IR-gen to Sema/AST. 17940 17941 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17942 SmallVector<QualType, 8> ArgTypes; 17943 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17944 ArgTypes.reserve(E->getNumArgs()); 17945 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17946 Expr *Arg = E->getArg(i); 17947 QualType ArgType = Arg->getType(); 17948 if (E->isLValue()) { 17949 ArgType = S.Context.getLValueReferenceType(ArgType); 17950 } else if (E->isXValue()) { 17951 ArgType = S.Context.getRValueReferenceType(ArgType); 17952 } 17953 ArgTypes.push_back(ArgType); 17954 } 17955 ParamTypes = ArgTypes; 17956 } 17957 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17958 Proto->getExtProtoInfo()); 17959 } else { 17960 DestType = S.Context.getFunctionNoProtoType(DestType, 17961 FnType->getExtInfo()); 17962 } 17963 17964 // Rebuild the appropriate pointer-to-function type. 17965 switch (Kind) { 17966 case FK_MemberFunction: 17967 // Nothing to do. 17968 break; 17969 17970 case FK_FunctionPointer: 17971 DestType = S.Context.getPointerType(DestType); 17972 break; 17973 17974 case FK_BlockPointer: 17975 DestType = S.Context.getBlockPointerType(DestType); 17976 break; 17977 } 17978 17979 // Finally, we can recurse. 17980 ExprResult CalleeResult = Visit(CalleeExpr); 17981 if (!CalleeResult.isUsable()) return ExprError(); 17982 E->setCallee(CalleeResult.get()); 17983 17984 // Bind a temporary if necessary. 17985 return S.MaybeBindToTemporary(E); 17986 } 17987 17988 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17989 // Verify that this is a legal result type of a call. 17990 if (DestType->isArrayType() || DestType->isFunctionType()) { 17991 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17992 << DestType->isFunctionType() << DestType; 17993 return ExprError(); 17994 } 17995 17996 // Rewrite the method result type if available. 17997 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17998 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17999 Method->setReturnType(DestType); 18000 } 18001 18002 // Change the type of the message. 18003 E->setType(DestType.getNonReferenceType()); 18004 E->setValueKind(Expr::getValueKindForType(DestType)); 18005 18006 return S.MaybeBindToTemporary(E); 18007 } 18008 18009 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18010 // The only case we should ever see here is a function-to-pointer decay. 18011 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18012 assert(E->getValueKind() == VK_RValue); 18013 assert(E->getObjectKind() == OK_Ordinary); 18014 18015 E->setType(DestType); 18016 18017 // Rebuild the sub-expression as the pointee (function) type. 18018 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18019 18020 ExprResult Result = Visit(E->getSubExpr()); 18021 if (!Result.isUsable()) return ExprError(); 18022 18023 E->setSubExpr(Result.get()); 18024 return E; 18025 } else if (E->getCastKind() == CK_LValueToRValue) { 18026 assert(E->getValueKind() == VK_RValue); 18027 assert(E->getObjectKind() == OK_Ordinary); 18028 18029 assert(isa<BlockPointerType>(E->getType())); 18030 18031 E->setType(DestType); 18032 18033 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18034 DestType = S.Context.getLValueReferenceType(DestType); 18035 18036 ExprResult Result = Visit(E->getSubExpr()); 18037 if (!Result.isUsable()) return ExprError(); 18038 18039 E->setSubExpr(Result.get()); 18040 return E; 18041 } else { 18042 llvm_unreachable("Unhandled cast type!"); 18043 } 18044 } 18045 18046 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18047 ExprValueKind ValueKind = VK_LValue; 18048 QualType Type = DestType; 18049 18050 // We know how to make this work for certain kinds of decls: 18051 18052 // - functions 18053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18054 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18055 DestType = Ptr->getPointeeType(); 18056 ExprResult Result = resolveDecl(E, VD); 18057 if (Result.isInvalid()) return ExprError(); 18058 return S.ImpCastExprToType(Result.get(), Type, 18059 CK_FunctionToPointerDecay, VK_RValue); 18060 } 18061 18062 if (!Type->isFunctionType()) { 18063 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18064 << VD << E->getSourceRange(); 18065 return ExprError(); 18066 } 18067 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18068 // We must match the FunctionDecl's type to the hack introduced in 18069 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18070 // type. See the lengthy commentary in that routine. 18071 QualType FDT = FD->getType(); 18072 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18073 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18074 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18075 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18076 SourceLocation Loc = FD->getLocation(); 18077 FunctionDecl *NewFD = FunctionDecl::Create( 18078 S.Context, FD->getDeclContext(), Loc, Loc, 18079 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18080 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18081 /*ConstexprKind*/ CSK_unspecified); 18082 18083 if (FD->getQualifier()) 18084 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18085 18086 SmallVector<ParmVarDecl*, 16> Params; 18087 for (const auto &AI : FT->param_types()) { 18088 ParmVarDecl *Param = 18089 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18090 Param->setScopeInfo(0, Params.size()); 18091 Params.push_back(Param); 18092 } 18093 NewFD->setParams(Params); 18094 DRE->setDecl(NewFD); 18095 VD = DRE->getDecl(); 18096 } 18097 } 18098 18099 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18100 if (MD->isInstance()) { 18101 ValueKind = VK_RValue; 18102 Type = S.Context.BoundMemberTy; 18103 } 18104 18105 // Function references aren't l-values in C. 18106 if (!S.getLangOpts().CPlusPlus) 18107 ValueKind = VK_RValue; 18108 18109 // - variables 18110 } else if (isa<VarDecl>(VD)) { 18111 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18112 Type = RefTy->getPointeeType(); 18113 } else if (Type->isFunctionType()) { 18114 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18115 << VD << E->getSourceRange(); 18116 return ExprError(); 18117 } 18118 18119 // - nothing else 18120 } else { 18121 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18122 << VD << E->getSourceRange(); 18123 return ExprError(); 18124 } 18125 18126 // Modifying the declaration like this is friendly to IR-gen but 18127 // also really dangerous. 18128 VD->setType(DestType); 18129 E->setType(Type); 18130 E->setValueKind(ValueKind); 18131 return E; 18132 } 18133 18134 /// Check a cast of an unknown-any type. We intentionally only 18135 /// trigger this for C-style casts. 18136 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18137 Expr *CastExpr, CastKind &CastKind, 18138 ExprValueKind &VK, CXXCastPath &Path) { 18139 // The type we're casting to must be either void or complete. 18140 if (!CastType->isVoidType() && 18141 RequireCompleteType(TypeRange.getBegin(), CastType, 18142 diag::err_typecheck_cast_to_incomplete)) 18143 return ExprError(); 18144 18145 // Rewrite the casted expression from scratch. 18146 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18147 if (!result.isUsable()) return ExprError(); 18148 18149 CastExpr = result.get(); 18150 VK = CastExpr->getValueKind(); 18151 CastKind = CK_NoOp; 18152 18153 return CastExpr; 18154 } 18155 18156 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18157 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18158 } 18159 18160 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18161 Expr *arg, QualType ¶mType) { 18162 // If the syntactic form of the argument is not an explicit cast of 18163 // any sort, just do default argument promotion. 18164 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18165 if (!castArg) { 18166 ExprResult result = DefaultArgumentPromotion(arg); 18167 if (result.isInvalid()) return ExprError(); 18168 paramType = result.get()->getType(); 18169 return result; 18170 } 18171 18172 // Otherwise, use the type that was written in the explicit cast. 18173 assert(!arg->hasPlaceholderType()); 18174 paramType = castArg->getTypeAsWritten(); 18175 18176 // Copy-initialize a parameter of that type. 18177 InitializedEntity entity = 18178 InitializedEntity::InitializeParameter(Context, paramType, 18179 /*consumed*/ false); 18180 return PerformCopyInitialization(entity, callLoc, arg); 18181 } 18182 18183 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18184 Expr *orig = E; 18185 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18186 while (true) { 18187 E = E->IgnoreParenImpCasts(); 18188 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18189 E = call->getCallee(); 18190 diagID = diag::err_uncasted_call_of_unknown_any; 18191 } else { 18192 break; 18193 } 18194 } 18195 18196 SourceLocation loc; 18197 NamedDecl *d; 18198 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18199 loc = ref->getLocation(); 18200 d = ref->getDecl(); 18201 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18202 loc = mem->getMemberLoc(); 18203 d = mem->getMemberDecl(); 18204 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18205 diagID = diag::err_uncasted_call_of_unknown_any; 18206 loc = msg->getSelectorStartLoc(); 18207 d = msg->getMethodDecl(); 18208 if (!d) { 18209 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18210 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18211 << orig->getSourceRange(); 18212 return ExprError(); 18213 } 18214 } else { 18215 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18216 << E->getSourceRange(); 18217 return ExprError(); 18218 } 18219 18220 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18221 18222 // Never recoverable. 18223 return ExprError(); 18224 } 18225 18226 /// Check for operands with placeholder types and complain if found. 18227 /// Returns ExprError() if there was an error and no recovery was possible. 18228 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18229 if (!getLangOpts().CPlusPlus) { 18230 // C cannot handle TypoExpr nodes on either side of a binop because it 18231 // doesn't handle dependent types properly, so make sure any TypoExprs have 18232 // been dealt with before checking the operands. 18233 ExprResult Result = CorrectDelayedTyposInExpr(E); 18234 if (!Result.isUsable()) return ExprError(); 18235 E = Result.get(); 18236 } 18237 18238 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18239 if (!placeholderType) return E; 18240 18241 switch (placeholderType->getKind()) { 18242 18243 // Overloaded expressions. 18244 case BuiltinType::Overload: { 18245 // Try to resolve a single function template specialization. 18246 // This is obligatory. 18247 ExprResult Result = E; 18248 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18249 return Result; 18250 18251 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18252 // leaves Result unchanged on failure. 18253 Result = E; 18254 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18255 return Result; 18256 18257 // If that failed, try to recover with a call. 18258 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18259 /*complain*/ true); 18260 return Result; 18261 } 18262 18263 // Bound member functions. 18264 case BuiltinType::BoundMember: { 18265 ExprResult result = E; 18266 const Expr *BME = E->IgnoreParens(); 18267 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18268 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18269 if (isa<CXXPseudoDestructorExpr>(BME)) { 18270 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18271 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18272 if (ME->getMemberNameInfo().getName().getNameKind() == 18273 DeclarationName::CXXDestructorName) 18274 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18275 } 18276 tryToRecoverWithCall(result, PD, 18277 /*complain*/ true); 18278 return result; 18279 } 18280 18281 // ARC unbridged casts. 18282 case BuiltinType::ARCUnbridgedCast: { 18283 Expr *realCast = stripARCUnbridgedCast(E); 18284 diagnoseARCUnbridgedCast(realCast); 18285 return realCast; 18286 } 18287 18288 // Expressions of unknown type. 18289 case BuiltinType::UnknownAny: 18290 return diagnoseUnknownAnyExpr(*this, E); 18291 18292 // Pseudo-objects. 18293 case BuiltinType::PseudoObject: 18294 return checkPseudoObjectRValue(E); 18295 18296 case BuiltinType::BuiltinFn: { 18297 // Accept __noop without parens by implicitly converting it to a call expr. 18298 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18299 if (DRE) { 18300 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18301 if (FD->getBuiltinID() == Builtin::BI__noop) { 18302 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18303 CK_BuiltinFnToFnPtr) 18304 .get(); 18305 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18306 VK_RValue, SourceLocation()); 18307 } 18308 } 18309 18310 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18311 return ExprError(); 18312 } 18313 18314 // Expressions of unknown type. 18315 case BuiltinType::OMPArraySection: 18316 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18317 return ExprError(); 18318 18319 // Everything else should be impossible. 18320 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18321 case BuiltinType::Id: 18322 #include "clang/Basic/OpenCLImageTypes.def" 18323 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18324 case BuiltinType::Id: 18325 #include "clang/Basic/OpenCLExtensionTypes.def" 18326 #define SVE_TYPE(Name, Id, SingletonId) \ 18327 case BuiltinType::Id: 18328 #include "clang/Basic/AArch64SVEACLETypes.def" 18329 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18330 #define PLACEHOLDER_TYPE(Id, SingletonId) 18331 #include "clang/AST/BuiltinTypes.def" 18332 break; 18333 } 18334 18335 llvm_unreachable("invalid placeholder type!"); 18336 } 18337 18338 bool Sema::CheckCaseExpression(Expr *E) { 18339 if (E->isTypeDependent()) 18340 return true; 18341 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18342 return E->getType()->isIntegralOrEnumerationType(); 18343 return false; 18344 } 18345 18346 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18347 ExprResult 18348 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18349 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18350 "Unknown Objective-C Boolean value!"); 18351 QualType BoolT = Context.ObjCBuiltinBoolTy; 18352 if (!Context.getBOOLDecl()) { 18353 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18354 Sema::LookupOrdinaryName); 18355 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18356 NamedDecl *ND = Result.getFoundDecl(); 18357 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18358 Context.setBOOLDecl(TD); 18359 } 18360 } 18361 if (Context.getBOOLDecl()) 18362 BoolT = Context.getBOOLType(); 18363 return new (Context) 18364 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18365 } 18366 18367 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18368 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18369 SourceLocation RParen) { 18370 18371 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18372 18373 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18374 return Spec.getPlatform() == Platform; 18375 }); 18376 18377 VersionTuple Version; 18378 if (Spec != AvailSpecs.end()) 18379 Version = Spec->getVersion(); 18380 18381 // The use of `@available` in the enclosing function should be analyzed to 18382 // warn when it's used inappropriately (i.e. not if(@available)). 18383 if (getCurFunctionOrMethodDecl()) 18384 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18385 else if (getCurBlock() || getCurLambda()) 18386 getCurFunction()->HasPotentialAvailabilityViolations = true; 18387 18388 return new (Context) 18389 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18390 } 18391 18392 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18393 assert(E->isTypeDependent()); 18394 return isa<UnresolvedLookupExpr>(E); 18395 } 18396