1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/FixedPoint.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 } 297 298 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 299 // Lambdas are only default-constructible or assignable in C++2a onwards. 300 if (MD->getParent()->isLambda() && 301 ((isa<CXXConstructorDecl>(MD) && 302 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 303 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 304 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 305 << !isa<CXXConstructorDecl>(MD); 306 } 307 } 308 309 auto getReferencedObjCProp = [](const NamedDecl *D) -> 310 const ObjCPropertyDecl * { 311 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 312 return MD->findPropertyDecl(); 313 return nullptr; 314 }; 315 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 316 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 317 return true; 318 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 319 return true; 320 } 321 322 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 323 // Only the variables omp_in and omp_out are allowed in the combiner. 324 // Only the variables omp_priv and omp_orig are allowed in the 325 // initializer-clause. 326 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 327 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 328 isa<VarDecl>(D)) { 329 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 330 << getCurFunction()->HasOMPDeclareReductionCombiner; 331 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 332 return true; 333 } 334 335 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 336 // List-items in map clauses on this construct may only refer to the declared 337 // variable var and entities that could be referenced by a procedure defined 338 // at the same location 339 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 340 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 341 isa<VarDecl>(D)) { 342 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 343 << DMD->getVarName().getAsString(); 344 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 345 return true; 346 } 347 348 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 349 AvoidPartialAvailabilityChecks, ClassReceiver); 350 351 DiagnoseUnusedOfDecl(*this, D, Loc); 352 353 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 354 355 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 356 !isUnevaluatedContext()) { 357 // C++ [expr.prim.req.nested] p3 358 // A local parameter shall only appear as an unevaluated operand 359 // (Clause 8) within the constraint-expression. 360 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 361 << D; 362 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 363 return true; 364 } 365 366 return false; 367 } 368 369 /// DiagnoseSentinelCalls - This routine checks whether a call or 370 /// message-send is to a declaration with the sentinel attribute, and 371 /// if so, it checks that the requirements of the sentinel are 372 /// satisfied. 373 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 374 ArrayRef<Expr *> Args) { 375 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 376 if (!attr) 377 return; 378 379 // The number of formal parameters of the declaration. 380 unsigned numFormalParams; 381 382 // The kind of declaration. This is also an index into a %select in 383 // the diagnostic. 384 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 385 386 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 387 numFormalParams = MD->param_size(); 388 calleeType = CT_Method; 389 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 390 numFormalParams = FD->param_size(); 391 calleeType = CT_Function; 392 } else if (isa<VarDecl>(D)) { 393 QualType type = cast<ValueDecl>(D)->getType(); 394 const FunctionType *fn = nullptr; 395 if (const PointerType *ptr = type->getAs<PointerType>()) { 396 fn = ptr->getPointeeType()->getAs<FunctionType>(); 397 if (!fn) return; 398 calleeType = CT_Function; 399 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 400 fn = ptr->getPointeeType()->castAs<FunctionType>(); 401 calleeType = CT_Block; 402 } else { 403 return; 404 } 405 406 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 407 numFormalParams = proto->getNumParams(); 408 } else { 409 numFormalParams = 0; 410 } 411 } else { 412 return; 413 } 414 415 // "nullPos" is the number of formal parameters at the end which 416 // effectively count as part of the variadic arguments. This is 417 // useful if you would prefer to not have *any* formal parameters, 418 // but the language forces you to have at least one. 419 unsigned nullPos = attr->getNullPos(); 420 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 421 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 422 423 // The number of arguments which should follow the sentinel. 424 unsigned numArgsAfterSentinel = attr->getSentinel(); 425 426 // If there aren't enough arguments for all the formal parameters, 427 // the sentinel, and the args after the sentinel, complain. 428 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 429 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 430 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 431 return; 432 } 433 434 // Otherwise, find the sentinel expression. 435 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 436 if (!sentinelExpr) return; 437 if (sentinelExpr->isValueDependent()) return; 438 if (Context.isSentinelNullExpr(sentinelExpr)) return; 439 440 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 441 // or 'NULL' if those are actually defined in the context. Only use 442 // 'nil' for ObjC methods, where it's much more likely that the 443 // variadic arguments form a list of object pointers. 444 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 445 std::string NullValue; 446 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 447 NullValue = "nil"; 448 else if (getLangOpts().CPlusPlus11) 449 NullValue = "nullptr"; 450 else if (PP.isMacroDefined("NULL")) 451 NullValue = "NULL"; 452 else 453 NullValue = "(void*) 0"; 454 455 if (MissingNilLoc.isInvalid()) 456 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 457 else 458 Diag(MissingNilLoc, diag::warn_missing_sentinel) 459 << int(calleeType) 460 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 461 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 462 } 463 464 SourceRange Sema::getExprRange(Expr *E) const { 465 return E ? E->getSourceRange() : SourceRange(); 466 } 467 468 //===----------------------------------------------------------------------===// 469 // Standard Promotions and Conversions 470 //===----------------------------------------------------------------------===// 471 472 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 473 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 474 // Handle any placeholder expressions which made it here. 475 if (E->getType()->isPlaceholderType()) { 476 ExprResult result = CheckPlaceholderExpr(E); 477 if (result.isInvalid()) return ExprError(); 478 E = result.get(); 479 } 480 481 QualType Ty = E->getType(); 482 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 483 484 if (Ty->isFunctionType()) { 485 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 486 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 487 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 488 return ExprError(); 489 490 E = ImpCastExprToType(E, Context.getPointerType(Ty), 491 CK_FunctionToPointerDecay).get(); 492 } else if (Ty->isArrayType()) { 493 // In C90 mode, arrays only promote to pointers if the array expression is 494 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 495 // type 'array of type' is converted to an expression that has type 'pointer 496 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 497 // that has type 'array of type' ...". The relevant change is "an lvalue" 498 // (C90) to "an expression" (C99). 499 // 500 // C++ 4.2p1: 501 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 502 // T" can be converted to an rvalue of type "pointer to T". 503 // 504 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 505 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 506 CK_ArrayToPointerDecay).get(); 507 } 508 return E; 509 } 510 511 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 512 // Check to see if we are dereferencing a null pointer. If so, 513 // and if not volatile-qualified, this is undefined behavior that the 514 // optimizer will delete, so warn about it. People sometimes try to use this 515 // to get a deterministic trap and are surprised by clang's behavior. This 516 // only handles the pattern "*null", which is a very syntactic check. 517 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 518 if (UO && UO->getOpcode() == UO_Deref && 519 UO->getSubExpr()->getType()->isPointerType()) { 520 const LangAS AS = 521 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 522 if ((!isTargetAddressSpace(AS) || 523 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 524 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 525 S.Context, Expr::NPC_ValueDependentIsNotNull) && 526 !UO->getType().isVolatileQualified()) { 527 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 528 S.PDiag(diag::warn_indirection_through_null) 529 << UO->getSubExpr()->getSourceRange()); 530 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 531 S.PDiag(diag::note_indirection_through_null)); 532 } 533 } 534 } 535 536 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 537 SourceLocation AssignLoc, 538 const Expr* RHS) { 539 const ObjCIvarDecl *IV = OIRE->getDecl(); 540 if (!IV) 541 return; 542 543 DeclarationName MemberName = IV->getDeclName(); 544 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 545 if (!Member || !Member->isStr("isa")) 546 return; 547 548 const Expr *Base = OIRE->getBase(); 549 QualType BaseType = Base->getType(); 550 if (OIRE->isArrow()) 551 BaseType = BaseType->getPointeeType(); 552 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 553 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 554 ObjCInterfaceDecl *ClassDeclared = nullptr; 555 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 556 if (!ClassDeclared->getSuperClass() 557 && (*ClassDeclared->ivar_begin()) == IV) { 558 if (RHS) { 559 NamedDecl *ObjectSetClass = 560 S.LookupSingleName(S.TUScope, 561 &S.Context.Idents.get("object_setClass"), 562 SourceLocation(), S.LookupOrdinaryName); 563 if (ObjectSetClass) { 564 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 565 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 566 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 567 "object_setClass(") 568 << FixItHint::CreateReplacement( 569 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 570 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 571 } 572 else 573 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 574 } else { 575 NamedDecl *ObjectGetClass = 576 S.LookupSingleName(S.TUScope, 577 &S.Context.Idents.get("object_getClass"), 578 SourceLocation(), S.LookupOrdinaryName); 579 if (ObjectGetClass) 580 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 581 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 582 "object_getClass(") 583 << FixItHint::CreateReplacement( 584 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 587 } 588 S.Diag(IV->getLocation(), diag::note_ivar_decl); 589 } 590 } 591 } 592 593 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 594 // Handle any placeholder expressions which made it here. 595 if (E->getType()->isPlaceholderType()) { 596 ExprResult result = CheckPlaceholderExpr(E); 597 if (result.isInvalid()) return ExprError(); 598 E = result.get(); 599 } 600 601 // C++ [conv.lval]p1: 602 // A glvalue of a non-function, non-array type T can be 603 // converted to a prvalue. 604 if (!E->isGLValue()) return E; 605 606 QualType T = E->getType(); 607 assert(!T.isNull() && "r-value conversion on typeless expression?"); 608 609 // We don't want to throw lvalue-to-rvalue casts on top of 610 // expressions of certain types in C++. 611 if (getLangOpts().CPlusPlus && 612 (E->getType() == Context.OverloadTy || 613 T->isDependentType() || 614 T->isRecordType())) 615 return E; 616 617 // The C standard is actually really unclear on this point, and 618 // DR106 tells us what the result should be but not why. It's 619 // generally best to say that void types just doesn't undergo 620 // lvalue-to-rvalue at all. Note that expressions of unqualified 621 // 'void' type are never l-values, but qualified void can be. 622 if (T->isVoidType()) 623 return E; 624 625 // OpenCL usually rejects direct accesses to values of 'half' type. 626 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 627 T->isHalfType()) { 628 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 629 << 0 << T; 630 return ExprError(); 631 } 632 633 CheckForNullPointerDereference(*this, E); 634 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 635 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 636 &Context.Idents.get("object_getClass"), 637 SourceLocation(), LookupOrdinaryName); 638 if (ObjectGetClass) 639 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 640 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 641 << FixItHint::CreateReplacement( 642 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 643 else 644 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 645 } 646 else if (const ObjCIvarRefExpr *OIRE = 647 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 648 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 649 650 // C++ [conv.lval]p1: 651 // [...] If T is a non-class type, the type of the prvalue is the 652 // cv-unqualified version of T. Otherwise, the type of the 653 // rvalue is T. 654 // 655 // C99 6.3.2.1p2: 656 // If the lvalue has qualified type, the value has the unqualified 657 // version of the type of the lvalue; otherwise, the value has the 658 // type of the lvalue. 659 if (T.hasQualifiers()) 660 T = T.getUnqualifiedType(); 661 662 // Under the MS ABI, lock down the inheritance model now. 663 if (T->isMemberPointerType() && 664 Context.getTargetInfo().getCXXABI().isMicrosoft()) 665 (void)isCompleteType(E->getExprLoc(), T); 666 667 ExprResult Res = CheckLValueToRValueConversionOperand(E); 668 if (Res.isInvalid()) 669 return Res; 670 E = Res.get(); 671 672 // Loading a __weak object implicitly retains the value, so we need a cleanup to 673 // balance that. 674 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 675 Cleanup.setExprNeedsCleanups(true); 676 677 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 678 Cleanup.setExprNeedsCleanups(true); 679 680 // C++ [conv.lval]p3: 681 // If T is cv std::nullptr_t, the result is a null pointer constant. 682 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 683 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 684 685 // C11 6.3.2.1p2: 686 // ... if the lvalue has atomic type, the value has the non-atomic version 687 // of the type of the lvalue ... 688 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 689 T = Atomic->getValueType().getUnqualifiedType(); 690 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 691 nullptr, VK_RValue); 692 } 693 694 return Res; 695 } 696 697 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 698 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 699 if (Res.isInvalid()) 700 return ExprError(); 701 Res = DefaultLvalueConversion(Res.get()); 702 if (Res.isInvalid()) 703 return ExprError(); 704 return Res; 705 } 706 707 /// CallExprUnaryConversions - a special case of an unary conversion 708 /// performed on a function designator of a call expression. 709 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 710 QualType Ty = E->getType(); 711 ExprResult Res = E; 712 // Only do implicit cast for a function type, but not for a pointer 713 // to function type. 714 if (Ty->isFunctionType()) { 715 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 716 CK_FunctionToPointerDecay).get(); 717 if (Res.isInvalid()) 718 return ExprError(); 719 } 720 Res = DefaultLvalueConversion(Res.get()); 721 if (Res.isInvalid()) 722 return ExprError(); 723 return Res.get(); 724 } 725 726 /// UsualUnaryConversions - Performs various conversions that are common to most 727 /// operators (C99 6.3). The conversions of array and function types are 728 /// sometimes suppressed. For example, the array->pointer conversion doesn't 729 /// apply if the array is an argument to the sizeof or address (&) operators. 730 /// In these instances, this routine should *not* be called. 731 ExprResult Sema::UsualUnaryConversions(Expr *E) { 732 // First, convert to an r-value. 733 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 734 if (Res.isInvalid()) 735 return ExprError(); 736 E = Res.get(); 737 738 QualType Ty = E->getType(); 739 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 740 741 // Half FP have to be promoted to float unless it is natively supported 742 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 743 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 744 745 // Try to perform integral promotions if the object has a theoretically 746 // promotable type. 747 if (Ty->isIntegralOrUnscopedEnumerationType()) { 748 // C99 6.3.1.1p2: 749 // 750 // The following may be used in an expression wherever an int or 751 // unsigned int may be used: 752 // - an object or expression with an integer type whose integer 753 // conversion rank is less than or equal to the rank of int 754 // and unsigned int. 755 // - A bit-field of type _Bool, int, signed int, or unsigned int. 756 // 757 // If an int can represent all values of the original type, the 758 // value is converted to an int; otherwise, it is converted to an 759 // unsigned int. These are called the integer promotions. All 760 // other types are unchanged by the integer promotions. 761 762 QualType PTy = Context.isPromotableBitField(E); 763 if (!PTy.isNull()) { 764 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 765 return E; 766 } 767 if (Ty->isPromotableIntegerType()) { 768 QualType PT = Context.getPromotedIntegerType(Ty); 769 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 770 return E; 771 } 772 } 773 return E; 774 } 775 776 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 777 /// do not have a prototype. Arguments that have type float or __fp16 778 /// are promoted to double. All other argument types are converted by 779 /// UsualUnaryConversions(). 780 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 781 QualType Ty = E->getType(); 782 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 783 784 ExprResult Res = UsualUnaryConversions(E); 785 if (Res.isInvalid()) 786 return ExprError(); 787 E = Res.get(); 788 789 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 790 // promote to double. 791 // Note that default argument promotion applies only to float (and 792 // half/fp16); it does not apply to _Float16. 793 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 794 if (BTy && (BTy->getKind() == BuiltinType::Half || 795 BTy->getKind() == BuiltinType::Float)) { 796 if (getLangOpts().OpenCL && 797 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 798 if (BTy->getKind() == BuiltinType::Half) { 799 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 800 } 801 } else { 802 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 803 } 804 } 805 806 // C++ performs lvalue-to-rvalue conversion as a default argument 807 // promotion, even on class types, but note: 808 // C++11 [conv.lval]p2: 809 // When an lvalue-to-rvalue conversion occurs in an unevaluated 810 // operand or a subexpression thereof the value contained in the 811 // referenced object is not accessed. Otherwise, if the glvalue 812 // has a class type, the conversion copy-initializes a temporary 813 // of type T from the glvalue and the result of the conversion 814 // is a prvalue for the temporary. 815 // FIXME: add some way to gate this entire thing for correctness in 816 // potentially potentially evaluated contexts. 817 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 818 ExprResult Temp = PerformCopyInitialization( 819 InitializedEntity::InitializeTemporary(E->getType()), 820 E->getExprLoc(), E); 821 if (Temp.isInvalid()) 822 return ExprError(); 823 E = Temp.get(); 824 } 825 826 return E; 827 } 828 829 /// Determine the degree of POD-ness for an expression. 830 /// Incomplete types are considered POD, since this check can be performed 831 /// when we're in an unevaluated context. 832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 833 if (Ty->isIncompleteType()) { 834 // C++11 [expr.call]p7: 835 // After these conversions, if the argument does not have arithmetic, 836 // enumeration, pointer, pointer to member, or class type, the program 837 // is ill-formed. 838 // 839 // Since we've already performed array-to-pointer and function-to-pointer 840 // decay, the only such type in C++ is cv void. This also handles 841 // initializer lists as variadic arguments. 842 if (Ty->isVoidType()) 843 return VAK_Invalid; 844 845 if (Ty->isObjCObjectType()) 846 return VAK_Invalid; 847 return VAK_Valid; 848 } 849 850 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 851 return VAK_Invalid; 852 853 if (Ty.isCXX98PODType(Context)) 854 return VAK_Valid; 855 856 // C++11 [expr.call]p7: 857 // Passing a potentially-evaluated argument of class type (Clause 9) 858 // having a non-trivial copy constructor, a non-trivial move constructor, 859 // or a non-trivial destructor, with no corresponding parameter, 860 // is conditionally-supported with implementation-defined semantics. 861 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 862 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 863 if (!Record->hasNonTrivialCopyConstructor() && 864 !Record->hasNonTrivialMoveConstructor() && 865 !Record->hasNonTrivialDestructor()) 866 return VAK_ValidInCXX11; 867 868 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 869 return VAK_Valid; 870 871 if (Ty->isObjCObjectType()) 872 return VAK_Invalid; 873 874 if (getLangOpts().MSVCCompat) 875 return VAK_MSVCUndefined; 876 877 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 878 // permitted to reject them. We should consider doing so. 879 return VAK_Undefined; 880 } 881 882 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 883 // Don't allow one to pass an Objective-C interface to a vararg. 884 const QualType &Ty = E->getType(); 885 VarArgKind VAK = isValidVarArgType(Ty); 886 887 // Complain about passing non-POD types through varargs. 888 switch (VAK) { 889 case VAK_ValidInCXX11: 890 DiagRuntimeBehavior( 891 E->getBeginLoc(), nullptr, 892 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 893 LLVM_FALLTHROUGH; 894 case VAK_Valid: 895 if (Ty->isRecordType()) { 896 // This is unlikely to be what the user intended. If the class has a 897 // 'c_str' member function, the user probably meant to call that. 898 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 899 PDiag(diag::warn_pass_class_arg_to_vararg) 900 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 901 } 902 break; 903 904 case VAK_Undefined: 905 case VAK_MSVCUndefined: 906 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 907 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 908 << getLangOpts().CPlusPlus11 << Ty << CT); 909 break; 910 911 case VAK_Invalid: 912 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 913 Diag(E->getBeginLoc(), 914 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 915 << Ty << CT; 916 else if (Ty->isObjCObjectType()) 917 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 918 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 919 << Ty << CT); 920 else 921 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 922 << isa<InitListExpr>(E) << Ty << CT; 923 break; 924 } 925 } 926 927 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 928 /// will create a trap if the resulting type is not a POD type. 929 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 930 FunctionDecl *FDecl) { 931 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 932 // Strip the unbridged-cast placeholder expression off, if applicable. 933 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 934 (CT == VariadicMethod || 935 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 936 E = stripARCUnbridgedCast(E); 937 938 // Otherwise, do normal placeholder checking. 939 } else { 940 ExprResult ExprRes = CheckPlaceholderExpr(E); 941 if (ExprRes.isInvalid()) 942 return ExprError(); 943 E = ExprRes.get(); 944 } 945 } 946 947 ExprResult ExprRes = DefaultArgumentPromotion(E); 948 if (ExprRes.isInvalid()) 949 return ExprError(); 950 E = ExprRes.get(); 951 952 // Diagnostics regarding non-POD argument types are 953 // emitted along with format string checking in Sema::CheckFunctionCall(). 954 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 955 // Turn this into a trap. 956 CXXScopeSpec SS; 957 SourceLocation TemplateKWLoc; 958 UnqualifiedId Name; 959 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 960 E->getBeginLoc()); 961 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 962 /*HasTrailingLParen=*/true, 963 /*IsAddressOfOperand=*/false); 964 if (TrapFn.isInvalid()) 965 return ExprError(); 966 967 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 968 None, E->getEndLoc()); 969 if (Call.isInvalid()) 970 return ExprError(); 971 972 ExprResult Comma = 973 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 974 if (Comma.isInvalid()) 975 return ExprError(); 976 return Comma.get(); 977 } 978 979 if (!getLangOpts().CPlusPlus && 980 RequireCompleteType(E->getExprLoc(), E->getType(), 981 diag::err_call_incomplete_argument)) 982 return ExprError(); 983 984 return E; 985 } 986 987 /// Converts an integer to complex float type. Helper function of 988 /// UsualArithmeticConversions() 989 /// 990 /// \return false if the integer expression is an integer type and is 991 /// successfully converted to the complex type. 992 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 993 ExprResult &ComplexExpr, 994 QualType IntTy, 995 QualType ComplexTy, 996 bool SkipCast) { 997 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 998 if (SkipCast) return false; 999 if (IntTy->isIntegerType()) { 1000 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1003 CK_FloatingRealToComplex); 1004 } else { 1005 assert(IntTy->isComplexIntegerType()); 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1007 CK_IntegralComplexToFloatingComplex); 1008 } 1009 return false; 1010 } 1011 1012 /// Handle arithmetic conversion with complex types. Helper function of 1013 /// UsualArithmeticConversions() 1014 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1015 ExprResult &RHS, QualType LHSType, 1016 QualType RHSType, 1017 bool IsCompAssign) { 1018 // if we have an integer operand, the result is the complex type. 1019 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1020 /*skipCast*/false)) 1021 return LHSType; 1022 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1023 /*skipCast*/IsCompAssign)) 1024 return RHSType; 1025 1026 // This handles complex/complex, complex/float, or float/complex. 1027 // When both operands are complex, the shorter operand is converted to the 1028 // type of the longer, and that is the type of the result. This corresponds 1029 // to what is done when combining two real floating-point operands. 1030 // The fun begins when size promotion occur across type domains. 1031 // From H&S 6.3.4: When one operand is complex and the other is a real 1032 // floating-point type, the less precise type is converted, within it's 1033 // real or complex domain, to the precision of the other type. For example, 1034 // when combining a "long double" with a "double _Complex", the 1035 // "double _Complex" is promoted to "long double _Complex". 1036 1037 // Compute the rank of the two types, regardless of whether they are complex. 1038 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1039 1040 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1041 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1042 QualType LHSElementType = 1043 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1044 QualType RHSElementType = 1045 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1046 1047 QualType ResultType = S.Context.getComplexType(LHSElementType); 1048 if (Order < 0) { 1049 // Promote the precision of the LHS if not an assignment. 1050 ResultType = S.Context.getComplexType(RHSElementType); 1051 if (!IsCompAssign) { 1052 if (LHSComplexType) 1053 LHS = 1054 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1055 else 1056 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1057 } 1058 } else if (Order > 0) { 1059 // Promote the precision of the RHS. 1060 if (RHSComplexType) 1061 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1062 else 1063 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1064 } 1065 return ResultType; 1066 } 1067 1068 /// Handle arithmetic conversion from integer to float. Helper function 1069 /// of UsualArithmeticConversions() 1070 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1071 ExprResult &IntExpr, 1072 QualType FloatTy, QualType IntTy, 1073 bool ConvertFloat, bool ConvertInt) { 1074 if (IntTy->isIntegerType()) { 1075 if (ConvertInt) 1076 // Convert intExpr to the lhs floating point type. 1077 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1078 CK_IntegralToFloating); 1079 return FloatTy; 1080 } 1081 1082 // Convert both sides to the appropriate complex float. 1083 assert(IntTy->isComplexIntegerType()); 1084 QualType result = S.Context.getComplexType(FloatTy); 1085 1086 // _Complex int -> _Complex float 1087 if (ConvertInt) 1088 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1089 CK_IntegralComplexToFloatingComplex); 1090 1091 // float -> _Complex float 1092 if (ConvertFloat) 1093 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1094 CK_FloatingRealToComplex); 1095 1096 return result; 1097 } 1098 1099 /// Handle arithmethic conversion with floating point types. Helper 1100 /// function of UsualArithmeticConversions() 1101 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1102 ExprResult &RHS, QualType LHSType, 1103 QualType RHSType, bool IsCompAssign) { 1104 bool LHSFloat = LHSType->isRealFloatingType(); 1105 bool RHSFloat = RHSType->isRealFloatingType(); 1106 1107 // If we have two real floating types, convert the smaller operand 1108 // to the bigger result. 1109 if (LHSFloat && RHSFloat) { 1110 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1111 if (order > 0) { 1112 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1113 return LHSType; 1114 } 1115 1116 assert(order < 0 && "illegal float comparison"); 1117 if (!IsCompAssign) 1118 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1119 return RHSType; 1120 } 1121 1122 if (LHSFloat) { 1123 // Half FP has to be promoted to float unless it is natively supported 1124 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1125 LHSType = S.Context.FloatTy; 1126 1127 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1128 /*ConvertFloat=*/!IsCompAssign, 1129 /*ConvertInt=*/ true); 1130 } 1131 assert(RHSFloat); 1132 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1133 /*convertInt=*/ true, 1134 /*convertFloat=*/!IsCompAssign); 1135 } 1136 1137 /// Diagnose attempts to convert between __float128 and long double if 1138 /// there is no support for such conversion. Helper function of 1139 /// UsualArithmeticConversions(). 1140 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1141 QualType RHSType) { 1142 /* No issue converting if at least one of the types is not a floating point 1143 type or the two types have the same rank. 1144 */ 1145 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1146 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1147 return false; 1148 1149 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1150 "The remaining types must be floating point types."); 1151 1152 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1153 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1154 1155 QualType LHSElemType = LHSComplex ? 1156 LHSComplex->getElementType() : LHSType; 1157 QualType RHSElemType = RHSComplex ? 1158 RHSComplex->getElementType() : RHSType; 1159 1160 // No issue if the two types have the same representation 1161 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1162 &S.Context.getFloatTypeSemantics(RHSElemType)) 1163 return false; 1164 1165 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1166 RHSElemType == S.Context.LongDoubleTy); 1167 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1168 RHSElemType == S.Context.Float128Ty); 1169 1170 // We've handled the situation where __float128 and long double have the same 1171 // representation. We allow all conversions for all possible long double types 1172 // except PPC's double double. 1173 return Float128AndLongDouble && 1174 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1175 &llvm::APFloat::PPCDoubleDouble()); 1176 } 1177 1178 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1179 1180 namespace { 1181 /// These helper callbacks are placed in an anonymous namespace to 1182 /// permit their use as function template parameters. 1183 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1184 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1185 } 1186 1187 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1188 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1189 CK_IntegralComplexCast); 1190 } 1191 } 1192 1193 /// Handle integer arithmetic conversions. Helper function of 1194 /// UsualArithmeticConversions() 1195 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1196 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1197 ExprResult &RHS, QualType LHSType, 1198 QualType RHSType, bool IsCompAssign) { 1199 // The rules for this case are in C99 6.3.1.8 1200 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1201 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1202 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1203 if (LHSSigned == RHSSigned) { 1204 // Same signedness; use the higher-ranked type 1205 if (order >= 0) { 1206 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1207 return LHSType; 1208 } else if (!IsCompAssign) 1209 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1210 return RHSType; 1211 } else if (order != (LHSSigned ? 1 : -1)) { 1212 // The unsigned type has greater than or equal rank to the 1213 // signed type, so use the unsigned type 1214 if (RHSSigned) { 1215 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1216 return LHSType; 1217 } else if (!IsCompAssign) 1218 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1219 return RHSType; 1220 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1221 // The two types are different widths; if we are here, that 1222 // means the signed type is larger than the unsigned type, so 1223 // use the signed type. 1224 if (LHSSigned) { 1225 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1226 return LHSType; 1227 } else if (!IsCompAssign) 1228 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1229 return RHSType; 1230 } else { 1231 // The signed type is higher-ranked than the unsigned type, 1232 // but isn't actually any bigger (like unsigned int and long 1233 // on most 32-bit systems). Use the unsigned type corresponding 1234 // to the signed type. 1235 QualType result = 1236 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1237 RHS = (*doRHSCast)(S, RHS.get(), result); 1238 if (!IsCompAssign) 1239 LHS = (*doLHSCast)(S, LHS.get(), result); 1240 return result; 1241 } 1242 } 1243 1244 /// Handle conversions with GCC complex int extension. Helper function 1245 /// of UsualArithmeticConversions() 1246 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1247 ExprResult &RHS, QualType LHSType, 1248 QualType RHSType, 1249 bool IsCompAssign) { 1250 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1251 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1252 1253 if (LHSComplexInt && RHSComplexInt) { 1254 QualType LHSEltType = LHSComplexInt->getElementType(); 1255 QualType RHSEltType = RHSComplexInt->getElementType(); 1256 QualType ScalarType = 1257 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1258 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1259 1260 return S.Context.getComplexType(ScalarType); 1261 } 1262 1263 if (LHSComplexInt) { 1264 QualType LHSEltType = LHSComplexInt->getElementType(); 1265 QualType ScalarType = 1266 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1267 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1268 QualType ComplexType = S.Context.getComplexType(ScalarType); 1269 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1270 CK_IntegralRealToComplex); 1271 1272 return ComplexType; 1273 } 1274 1275 assert(RHSComplexInt); 1276 1277 QualType RHSEltType = RHSComplexInt->getElementType(); 1278 QualType ScalarType = 1279 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1280 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1281 QualType ComplexType = S.Context.getComplexType(ScalarType); 1282 1283 if (!IsCompAssign) 1284 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1285 CK_IntegralRealToComplex); 1286 return ComplexType; 1287 } 1288 1289 /// Return the rank of a given fixed point or integer type. The value itself 1290 /// doesn't matter, but the values must be increasing with proper increasing 1291 /// rank as described in N1169 4.1.1. 1292 static unsigned GetFixedPointRank(QualType Ty) { 1293 const auto *BTy = Ty->getAs<BuiltinType>(); 1294 assert(BTy && "Expected a builtin type."); 1295 1296 switch (BTy->getKind()) { 1297 case BuiltinType::ShortFract: 1298 case BuiltinType::UShortFract: 1299 case BuiltinType::SatShortFract: 1300 case BuiltinType::SatUShortFract: 1301 return 1; 1302 case BuiltinType::Fract: 1303 case BuiltinType::UFract: 1304 case BuiltinType::SatFract: 1305 case BuiltinType::SatUFract: 1306 return 2; 1307 case BuiltinType::LongFract: 1308 case BuiltinType::ULongFract: 1309 case BuiltinType::SatLongFract: 1310 case BuiltinType::SatULongFract: 1311 return 3; 1312 case BuiltinType::ShortAccum: 1313 case BuiltinType::UShortAccum: 1314 case BuiltinType::SatShortAccum: 1315 case BuiltinType::SatUShortAccum: 1316 return 4; 1317 case BuiltinType::Accum: 1318 case BuiltinType::UAccum: 1319 case BuiltinType::SatAccum: 1320 case BuiltinType::SatUAccum: 1321 return 5; 1322 case BuiltinType::LongAccum: 1323 case BuiltinType::ULongAccum: 1324 case BuiltinType::SatLongAccum: 1325 case BuiltinType::SatULongAccum: 1326 return 6; 1327 default: 1328 if (BTy->isInteger()) 1329 return 0; 1330 llvm_unreachable("Unexpected fixed point or integer type"); 1331 } 1332 } 1333 1334 /// handleFixedPointConversion - Fixed point operations between fixed 1335 /// point types and integers or other fixed point types do not fall under 1336 /// usual arithmetic conversion since these conversions could result in loss 1337 /// of precsision (N1169 4.1.4). These operations should be calculated with 1338 /// the full precision of their result type (N1169 4.1.6.2.1). 1339 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1340 QualType RHSTy) { 1341 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1342 "Expected at least one of the operands to be a fixed point type"); 1343 assert((LHSTy->isFixedPointOrIntegerType() || 1344 RHSTy->isFixedPointOrIntegerType()) && 1345 "Special fixed point arithmetic operation conversions are only " 1346 "applied to ints or other fixed point types"); 1347 1348 // If one operand has signed fixed-point type and the other operand has 1349 // unsigned fixed-point type, then the unsigned fixed-point operand is 1350 // converted to its corresponding signed fixed-point type and the resulting 1351 // type is the type of the converted operand. 1352 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1353 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1354 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1355 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1356 1357 // The result type is the type with the highest rank, whereby a fixed-point 1358 // conversion rank is always greater than an integer conversion rank; if the 1359 // type of either of the operands is a saturating fixedpoint type, the result 1360 // type shall be the saturating fixed-point type corresponding to the type 1361 // with the highest rank; the resulting value is converted (taking into 1362 // account rounding and overflow) to the precision of the resulting type. 1363 // Same ranks between signed and unsigned types are resolved earlier, so both 1364 // types are either signed or both unsigned at this point. 1365 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1366 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1367 1368 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1369 1370 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1371 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1372 1373 return ResultTy; 1374 } 1375 1376 /// Check that the usual arithmetic conversions can be performed on this pair of 1377 /// expressions that might be of enumeration type. 1378 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1379 SourceLocation Loc, 1380 Sema::ArithConvKind ACK) { 1381 // C++2a [expr.arith.conv]p1: 1382 // If one operand is of enumeration type and the other operand is of a 1383 // different enumeration type or a floating-point type, this behavior is 1384 // deprecated ([depr.arith.conv.enum]). 1385 // 1386 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1387 // Eventually we will presumably reject these cases (in C++23 onwards?). 1388 QualType L = LHS->getType(), R = RHS->getType(); 1389 bool LEnum = L->isUnscopedEnumerationType(), 1390 REnum = R->isUnscopedEnumerationType(); 1391 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1392 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1393 (REnum && L->isFloatingType())) { 1394 S.Diag(Loc, S.getLangOpts().CPlusPlus2a 1395 ? diag::warn_arith_conv_enum_float_cxx2a 1396 : diag::warn_arith_conv_enum_float) 1397 << LHS->getSourceRange() << RHS->getSourceRange() 1398 << (int)ACK << LEnum << L << R; 1399 } else if (!IsCompAssign && LEnum && REnum && 1400 !S.Context.hasSameUnqualifiedType(L, R)) { 1401 unsigned DiagID; 1402 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1403 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1404 // If either enumeration type is unnamed, it's less likely that the 1405 // user cares about this, but this situation is still deprecated in 1406 // C++2a. Use a different warning group. 1407 DiagID = S.getLangOpts().CPlusPlus2a 1408 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a 1409 : diag::warn_arith_conv_mixed_anon_enum_types; 1410 } else if (ACK == Sema::ACK_Conditional) { 1411 // Conditional expressions are separated out because they have 1412 // historically had a different warning flag. 1413 DiagID = S.getLangOpts().CPlusPlus2a 1414 ? diag::warn_conditional_mixed_enum_types_cxx2a 1415 : diag::warn_conditional_mixed_enum_types; 1416 } else if (ACK == Sema::ACK_Comparison) { 1417 // Comparison expressions are separated out because they have 1418 // historically had a different warning flag. 1419 DiagID = S.getLangOpts().CPlusPlus2a 1420 ? diag::warn_comparison_mixed_enum_types_cxx2a 1421 : diag::warn_comparison_mixed_enum_types; 1422 } else { 1423 DiagID = S.getLangOpts().CPlusPlus2a 1424 ? diag::warn_arith_conv_mixed_enum_types_cxx2a 1425 : diag::warn_arith_conv_mixed_enum_types; 1426 } 1427 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1428 << (int)ACK << L << R; 1429 } 1430 } 1431 1432 /// UsualArithmeticConversions - Performs various conversions that are common to 1433 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1434 /// routine returns the first non-arithmetic type found. The client is 1435 /// responsible for emitting appropriate error diagnostics. 1436 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1437 SourceLocation Loc, 1438 ArithConvKind ACK) { 1439 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1440 1441 if (ACK != ACK_CompAssign) { 1442 LHS = UsualUnaryConversions(LHS.get()); 1443 if (LHS.isInvalid()) 1444 return QualType(); 1445 } 1446 1447 RHS = UsualUnaryConversions(RHS.get()); 1448 if (RHS.isInvalid()) 1449 return QualType(); 1450 1451 // For conversion purposes, we ignore any qualifiers. 1452 // For example, "const float" and "float" are equivalent. 1453 QualType LHSType = 1454 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1455 QualType RHSType = 1456 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1457 1458 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1459 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1460 LHSType = AtomicLHS->getValueType(); 1461 1462 // If both types are identical, no conversion is needed. 1463 if (LHSType == RHSType) 1464 return LHSType; 1465 1466 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1467 // The caller can deal with this (e.g. pointer + int). 1468 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1469 return QualType(); 1470 1471 // Apply unary and bitfield promotions to the LHS's type. 1472 QualType LHSUnpromotedType = LHSType; 1473 if (LHSType->isPromotableIntegerType()) 1474 LHSType = Context.getPromotedIntegerType(LHSType); 1475 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1476 if (!LHSBitfieldPromoteTy.isNull()) 1477 LHSType = LHSBitfieldPromoteTy; 1478 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1479 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1480 1481 // If both types are identical, no conversion is needed. 1482 if (LHSType == RHSType) 1483 return LHSType; 1484 1485 // ExtInt types aren't subject to conversions between them or normal integers, 1486 // so this fails. 1487 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1488 return QualType(); 1489 1490 // At this point, we have two different arithmetic types. 1491 1492 // Diagnose attempts to convert between __float128 and long double where 1493 // such conversions currently can't be handled. 1494 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1495 return QualType(); 1496 1497 // Handle complex types first (C99 6.3.1.8p1). 1498 if (LHSType->isComplexType() || RHSType->isComplexType()) 1499 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1500 ACK == ACK_CompAssign); 1501 1502 // Now handle "real" floating types (i.e. float, double, long double). 1503 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1504 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1505 ACK == ACK_CompAssign); 1506 1507 // Handle GCC complex int extension. 1508 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1509 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1510 ACK == ACK_CompAssign); 1511 1512 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1513 return handleFixedPointConversion(*this, LHSType, RHSType); 1514 1515 // Finally, we have two differing integer types. 1516 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1517 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1518 } 1519 1520 //===----------------------------------------------------------------------===// 1521 // Semantic Analysis for various Expression Types 1522 //===----------------------------------------------------------------------===// 1523 1524 1525 ExprResult 1526 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1527 SourceLocation DefaultLoc, 1528 SourceLocation RParenLoc, 1529 Expr *ControllingExpr, 1530 ArrayRef<ParsedType> ArgTypes, 1531 ArrayRef<Expr *> ArgExprs) { 1532 unsigned NumAssocs = ArgTypes.size(); 1533 assert(NumAssocs == ArgExprs.size()); 1534 1535 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1536 for (unsigned i = 0; i < NumAssocs; ++i) { 1537 if (ArgTypes[i]) 1538 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1539 else 1540 Types[i] = nullptr; 1541 } 1542 1543 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1544 ControllingExpr, 1545 llvm::makeArrayRef(Types, NumAssocs), 1546 ArgExprs); 1547 delete [] Types; 1548 return ER; 1549 } 1550 1551 ExprResult 1552 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1553 SourceLocation DefaultLoc, 1554 SourceLocation RParenLoc, 1555 Expr *ControllingExpr, 1556 ArrayRef<TypeSourceInfo *> Types, 1557 ArrayRef<Expr *> Exprs) { 1558 unsigned NumAssocs = Types.size(); 1559 assert(NumAssocs == Exprs.size()); 1560 1561 // Decay and strip qualifiers for the controlling expression type, and handle 1562 // placeholder type replacement. See committee discussion from WG14 DR423. 1563 { 1564 EnterExpressionEvaluationContext Unevaluated( 1565 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1566 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1567 if (R.isInvalid()) 1568 return ExprError(); 1569 ControllingExpr = R.get(); 1570 } 1571 1572 // The controlling expression is an unevaluated operand, so side effects are 1573 // likely unintended. 1574 if (!inTemplateInstantiation() && 1575 ControllingExpr->HasSideEffects(Context, false)) 1576 Diag(ControllingExpr->getExprLoc(), 1577 diag::warn_side_effects_unevaluated_context); 1578 1579 bool TypeErrorFound = false, 1580 IsResultDependent = ControllingExpr->isTypeDependent(), 1581 ContainsUnexpandedParameterPack 1582 = ControllingExpr->containsUnexpandedParameterPack(); 1583 1584 for (unsigned i = 0; i < NumAssocs; ++i) { 1585 if (Exprs[i]->containsUnexpandedParameterPack()) 1586 ContainsUnexpandedParameterPack = true; 1587 1588 if (Types[i]) { 1589 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1590 ContainsUnexpandedParameterPack = true; 1591 1592 if (Types[i]->getType()->isDependentType()) { 1593 IsResultDependent = true; 1594 } else { 1595 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1596 // complete object type other than a variably modified type." 1597 unsigned D = 0; 1598 if (Types[i]->getType()->isIncompleteType()) 1599 D = diag::err_assoc_type_incomplete; 1600 else if (!Types[i]->getType()->isObjectType()) 1601 D = diag::err_assoc_type_nonobject; 1602 else if (Types[i]->getType()->isVariablyModifiedType()) 1603 D = diag::err_assoc_type_variably_modified; 1604 1605 if (D != 0) { 1606 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1607 << Types[i]->getTypeLoc().getSourceRange() 1608 << Types[i]->getType(); 1609 TypeErrorFound = true; 1610 } 1611 1612 // C11 6.5.1.1p2 "No two generic associations in the same generic 1613 // selection shall specify compatible types." 1614 for (unsigned j = i+1; j < NumAssocs; ++j) 1615 if (Types[j] && !Types[j]->getType()->isDependentType() && 1616 Context.typesAreCompatible(Types[i]->getType(), 1617 Types[j]->getType())) { 1618 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1619 diag::err_assoc_compatible_types) 1620 << Types[j]->getTypeLoc().getSourceRange() 1621 << Types[j]->getType() 1622 << Types[i]->getType(); 1623 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1624 diag::note_compat_assoc) 1625 << Types[i]->getTypeLoc().getSourceRange() 1626 << Types[i]->getType(); 1627 TypeErrorFound = true; 1628 } 1629 } 1630 } 1631 } 1632 if (TypeErrorFound) 1633 return ExprError(); 1634 1635 // If we determined that the generic selection is result-dependent, don't 1636 // try to compute the result expression. 1637 if (IsResultDependent) 1638 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1639 Exprs, DefaultLoc, RParenLoc, 1640 ContainsUnexpandedParameterPack); 1641 1642 SmallVector<unsigned, 1> CompatIndices; 1643 unsigned DefaultIndex = -1U; 1644 for (unsigned i = 0; i < NumAssocs; ++i) { 1645 if (!Types[i]) 1646 DefaultIndex = i; 1647 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1648 Types[i]->getType())) 1649 CompatIndices.push_back(i); 1650 } 1651 1652 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1653 // type compatible with at most one of the types named in its generic 1654 // association list." 1655 if (CompatIndices.size() > 1) { 1656 // We strip parens here because the controlling expression is typically 1657 // parenthesized in macro definitions. 1658 ControllingExpr = ControllingExpr->IgnoreParens(); 1659 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1660 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1661 << (unsigned)CompatIndices.size(); 1662 for (unsigned I : CompatIndices) { 1663 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1664 diag::note_compat_assoc) 1665 << Types[I]->getTypeLoc().getSourceRange() 1666 << Types[I]->getType(); 1667 } 1668 return ExprError(); 1669 } 1670 1671 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1672 // its controlling expression shall have type compatible with exactly one of 1673 // the types named in its generic association list." 1674 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1675 // We strip parens here because the controlling expression is typically 1676 // parenthesized in macro definitions. 1677 ControllingExpr = ControllingExpr->IgnoreParens(); 1678 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1679 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1680 return ExprError(); 1681 } 1682 1683 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1684 // type name that is compatible with the type of the controlling expression, 1685 // then the result expression of the generic selection is the expression 1686 // in that generic association. Otherwise, the result expression of the 1687 // generic selection is the expression in the default generic association." 1688 unsigned ResultIndex = 1689 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1690 1691 return GenericSelectionExpr::Create( 1692 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1693 ContainsUnexpandedParameterPack, ResultIndex); 1694 } 1695 1696 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1697 /// location of the token and the offset of the ud-suffix within it. 1698 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1699 unsigned Offset) { 1700 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1701 S.getLangOpts()); 1702 } 1703 1704 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1705 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1706 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1707 IdentifierInfo *UDSuffix, 1708 SourceLocation UDSuffixLoc, 1709 ArrayRef<Expr*> Args, 1710 SourceLocation LitEndLoc) { 1711 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1712 1713 QualType ArgTy[2]; 1714 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1715 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1716 if (ArgTy[ArgIdx]->isArrayType()) 1717 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1718 } 1719 1720 DeclarationName OpName = 1721 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1722 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1723 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1724 1725 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1726 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1727 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1728 /*AllowStringTemplate*/ false, 1729 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1730 return ExprError(); 1731 1732 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1733 } 1734 1735 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1736 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1737 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1738 /// multiple tokens. However, the common case is that StringToks points to one 1739 /// string. 1740 /// 1741 ExprResult 1742 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1743 assert(!StringToks.empty() && "Must have at least one string!"); 1744 1745 StringLiteralParser Literal(StringToks, PP); 1746 if (Literal.hadError) 1747 return ExprError(); 1748 1749 SmallVector<SourceLocation, 4> StringTokLocs; 1750 for (const Token &Tok : StringToks) 1751 StringTokLocs.push_back(Tok.getLocation()); 1752 1753 QualType CharTy = Context.CharTy; 1754 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1755 if (Literal.isWide()) { 1756 CharTy = Context.getWideCharType(); 1757 Kind = StringLiteral::Wide; 1758 } else if (Literal.isUTF8()) { 1759 if (getLangOpts().Char8) 1760 CharTy = Context.Char8Ty; 1761 Kind = StringLiteral::UTF8; 1762 } else if (Literal.isUTF16()) { 1763 CharTy = Context.Char16Ty; 1764 Kind = StringLiteral::UTF16; 1765 } else if (Literal.isUTF32()) { 1766 CharTy = Context.Char32Ty; 1767 Kind = StringLiteral::UTF32; 1768 } else if (Literal.isPascal()) { 1769 CharTy = Context.UnsignedCharTy; 1770 } 1771 1772 // Warn on initializing an array of char from a u8 string literal; this 1773 // becomes ill-formed in C++2a. 1774 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1775 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1776 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1777 1778 // Create removals for all 'u8' prefixes in the string literal(s). This 1779 // ensures C++2a compatibility (but may change the program behavior when 1780 // built by non-Clang compilers for which the execution character set is 1781 // not always UTF-8). 1782 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1783 SourceLocation RemovalDiagLoc; 1784 for (const Token &Tok : StringToks) { 1785 if (Tok.getKind() == tok::utf8_string_literal) { 1786 if (RemovalDiagLoc.isInvalid()) 1787 RemovalDiagLoc = Tok.getLocation(); 1788 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1789 Tok.getLocation(), 1790 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1791 getSourceManager(), getLangOpts()))); 1792 } 1793 } 1794 Diag(RemovalDiagLoc, RemovalDiag); 1795 } 1796 1797 QualType StrTy = 1798 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1799 1800 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1801 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1802 Kind, Literal.Pascal, StrTy, 1803 &StringTokLocs[0], 1804 StringTokLocs.size()); 1805 if (Literal.getUDSuffix().empty()) 1806 return Lit; 1807 1808 // We're building a user-defined literal. 1809 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1810 SourceLocation UDSuffixLoc = 1811 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1812 Literal.getUDSuffixOffset()); 1813 1814 // Make sure we're allowed user-defined literals here. 1815 if (!UDLScope) 1816 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1817 1818 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1819 // operator "" X (str, len) 1820 QualType SizeType = Context.getSizeType(); 1821 1822 DeclarationName OpName = 1823 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1824 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1825 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1826 1827 QualType ArgTy[] = { 1828 Context.getArrayDecayedType(StrTy), SizeType 1829 }; 1830 1831 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1832 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1833 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1834 /*AllowStringTemplate*/ true, 1835 /*DiagnoseMissing*/ true)) { 1836 1837 case LOLR_Cooked: { 1838 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1839 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1840 StringTokLocs[0]); 1841 Expr *Args[] = { Lit, LenArg }; 1842 1843 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1844 } 1845 1846 case LOLR_StringTemplate: { 1847 TemplateArgumentListInfo ExplicitArgs; 1848 1849 unsigned CharBits = Context.getIntWidth(CharTy); 1850 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1851 llvm::APSInt Value(CharBits, CharIsUnsigned); 1852 1853 TemplateArgument TypeArg(CharTy); 1854 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1855 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1856 1857 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1858 Value = Lit->getCodeUnit(I); 1859 TemplateArgument Arg(Context, Value, CharTy); 1860 TemplateArgumentLocInfo ArgInfo; 1861 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1862 } 1863 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1864 &ExplicitArgs); 1865 } 1866 case LOLR_Raw: 1867 case LOLR_Template: 1868 case LOLR_ErrorNoDiagnostic: 1869 llvm_unreachable("unexpected literal operator lookup result"); 1870 case LOLR_Error: 1871 return ExprError(); 1872 } 1873 llvm_unreachable("unexpected literal operator lookup result"); 1874 } 1875 1876 DeclRefExpr * 1877 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1878 SourceLocation Loc, 1879 const CXXScopeSpec *SS) { 1880 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1881 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1882 } 1883 1884 DeclRefExpr * 1885 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1886 const DeclarationNameInfo &NameInfo, 1887 const CXXScopeSpec *SS, NamedDecl *FoundD, 1888 SourceLocation TemplateKWLoc, 1889 const TemplateArgumentListInfo *TemplateArgs) { 1890 NestedNameSpecifierLoc NNS = 1891 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1892 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1893 TemplateArgs); 1894 } 1895 1896 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1897 // A declaration named in an unevaluated operand never constitutes an odr-use. 1898 if (isUnevaluatedContext()) 1899 return NOUR_Unevaluated; 1900 1901 // C++2a [basic.def.odr]p4: 1902 // A variable x whose name appears as a potentially-evaluated expression e 1903 // is odr-used by e unless [...] x is a reference that is usable in 1904 // constant expressions. 1905 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1906 if (VD->getType()->isReferenceType() && 1907 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1908 VD->isUsableInConstantExpressions(Context)) 1909 return NOUR_Constant; 1910 } 1911 1912 // All remaining non-variable cases constitute an odr-use. For variables, we 1913 // need to wait and see how the expression is used. 1914 return NOUR_None; 1915 } 1916 1917 /// BuildDeclRefExpr - Build an expression that references a 1918 /// declaration that does not require a closure capture. 1919 DeclRefExpr * 1920 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1921 const DeclarationNameInfo &NameInfo, 1922 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1923 SourceLocation TemplateKWLoc, 1924 const TemplateArgumentListInfo *TemplateArgs) { 1925 bool RefersToCapturedVariable = 1926 isa<VarDecl>(D) && 1927 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1928 1929 DeclRefExpr *E = DeclRefExpr::Create( 1930 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1931 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1932 MarkDeclRefReferenced(E); 1933 1934 // C++ [except.spec]p17: 1935 // An exception-specification is considered to be needed when: 1936 // - in an expression, the function is the unique lookup result or 1937 // the selected member of a set of overloaded functions. 1938 // 1939 // We delay doing this until after we've built the function reference and 1940 // marked it as used so that: 1941 // a) if the function is defaulted, we get errors from defining it before / 1942 // instead of errors from computing its exception specification, and 1943 // b) if the function is a defaulted comparison, we can use the body we 1944 // build when defining it as input to the exception specification 1945 // computation rather than computing a new body. 1946 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1947 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1948 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1949 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1950 } 1951 } 1952 1953 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1954 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1955 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1956 getCurFunction()->recordUseOfWeak(E); 1957 1958 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1959 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1960 FD = IFD->getAnonField(); 1961 if (FD) { 1962 UnusedPrivateFields.remove(FD); 1963 // Just in case we're building an illegal pointer-to-member. 1964 if (FD->isBitField()) 1965 E->setObjectKind(OK_BitField); 1966 } 1967 1968 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1969 // designates a bit-field. 1970 if (auto *BD = dyn_cast<BindingDecl>(D)) 1971 if (auto *BE = BD->getBinding()) 1972 E->setObjectKind(BE->getObjectKind()); 1973 1974 return E; 1975 } 1976 1977 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1978 /// possibly a list of template arguments. 1979 /// 1980 /// If this produces template arguments, it is permitted to call 1981 /// DecomposeTemplateName. 1982 /// 1983 /// This actually loses a lot of source location information for 1984 /// non-standard name kinds; we should consider preserving that in 1985 /// some way. 1986 void 1987 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1988 TemplateArgumentListInfo &Buffer, 1989 DeclarationNameInfo &NameInfo, 1990 const TemplateArgumentListInfo *&TemplateArgs) { 1991 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1992 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1993 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1994 1995 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1996 Id.TemplateId->NumArgs); 1997 translateTemplateArguments(TemplateArgsPtr, Buffer); 1998 1999 TemplateName TName = Id.TemplateId->Template.get(); 2000 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2001 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2002 TemplateArgs = &Buffer; 2003 } else { 2004 NameInfo = GetNameFromUnqualifiedId(Id); 2005 TemplateArgs = nullptr; 2006 } 2007 } 2008 2009 static void emitEmptyLookupTypoDiagnostic( 2010 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2011 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2012 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2013 DeclContext *Ctx = 2014 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2015 if (!TC) { 2016 // Emit a special diagnostic for failed member lookups. 2017 // FIXME: computing the declaration context might fail here (?) 2018 if (Ctx) 2019 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2020 << SS.getRange(); 2021 else 2022 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2023 return; 2024 } 2025 2026 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2027 bool DroppedSpecifier = 2028 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2029 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2030 ? diag::note_implicit_param_decl 2031 : diag::note_previous_decl; 2032 if (!Ctx) 2033 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2034 SemaRef.PDiag(NoteID)); 2035 else 2036 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2037 << Typo << Ctx << DroppedSpecifier 2038 << SS.getRange(), 2039 SemaRef.PDiag(NoteID)); 2040 } 2041 2042 /// Diagnose an empty lookup. 2043 /// 2044 /// \return false if new lookup candidates were found 2045 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2046 CorrectionCandidateCallback &CCC, 2047 TemplateArgumentListInfo *ExplicitTemplateArgs, 2048 ArrayRef<Expr *> Args, TypoExpr **Out) { 2049 DeclarationName Name = R.getLookupName(); 2050 2051 unsigned diagnostic = diag::err_undeclared_var_use; 2052 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2053 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2054 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2055 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2056 diagnostic = diag::err_undeclared_use; 2057 diagnostic_suggest = diag::err_undeclared_use_suggest; 2058 } 2059 2060 // If the original lookup was an unqualified lookup, fake an 2061 // unqualified lookup. This is useful when (for example) the 2062 // original lookup would not have found something because it was a 2063 // dependent name. 2064 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2065 while (DC) { 2066 if (isa<CXXRecordDecl>(DC)) { 2067 LookupQualifiedName(R, DC); 2068 2069 if (!R.empty()) { 2070 // Don't give errors about ambiguities in this lookup. 2071 R.suppressDiagnostics(); 2072 2073 // During a default argument instantiation the CurContext points 2074 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2075 // function parameter list, hence add an explicit check. 2076 bool isDefaultArgument = 2077 !CodeSynthesisContexts.empty() && 2078 CodeSynthesisContexts.back().Kind == 2079 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2080 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2081 bool isInstance = CurMethod && 2082 CurMethod->isInstance() && 2083 DC == CurMethod->getParent() && !isDefaultArgument; 2084 2085 // Give a code modification hint to insert 'this->'. 2086 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2087 // Actually quite difficult! 2088 if (getLangOpts().MSVCCompat) 2089 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2090 if (isInstance) { 2091 Diag(R.getNameLoc(), diagnostic) << Name 2092 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2093 CheckCXXThisCapture(R.getNameLoc()); 2094 } else { 2095 Diag(R.getNameLoc(), diagnostic) << Name; 2096 } 2097 2098 // Do we really want to note all of these? 2099 for (NamedDecl *D : R) 2100 Diag(D->getLocation(), diag::note_dependent_var_use); 2101 2102 // Return true if we are inside a default argument instantiation 2103 // and the found name refers to an instance member function, otherwise 2104 // the function calling DiagnoseEmptyLookup will try to create an 2105 // implicit member call and this is wrong for default argument. 2106 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2107 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2108 return true; 2109 } 2110 2111 // Tell the callee to try to recover. 2112 return false; 2113 } 2114 2115 R.clear(); 2116 } 2117 2118 DC = DC->getLookupParent(); 2119 } 2120 2121 // We didn't find anything, so try to correct for a typo. 2122 TypoCorrection Corrected; 2123 if (S && Out) { 2124 SourceLocation TypoLoc = R.getNameLoc(); 2125 assert(!ExplicitTemplateArgs && 2126 "Diagnosing an empty lookup with explicit template args!"); 2127 *Out = CorrectTypoDelayed( 2128 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2129 [=](const TypoCorrection &TC) { 2130 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2131 diagnostic, diagnostic_suggest); 2132 }, 2133 nullptr, CTK_ErrorRecovery); 2134 if (*Out) 2135 return true; 2136 } else if (S && 2137 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2138 S, &SS, CCC, CTK_ErrorRecovery))) { 2139 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2140 bool DroppedSpecifier = 2141 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2142 R.setLookupName(Corrected.getCorrection()); 2143 2144 bool AcceptableWithRecovery = false; 2145 bool AcceptableWithoutRecovery = false; 2146 NamedDecl *ND = Corrected.getFoundDecl(); 2147 if (ND) { 2148 if (Corrected.isOverloaded()) { 2149 OverloadCandidateSet OCS(R.getNameLoc(), 2150 OverloadCandidateSet::CSK_Normal); 2151 OverloadCandidateSet::iterator Best; 2152 for (NamedDecl *CD : Corrected) { 2153 if (FunctionTemplateDecl *FTD = 2154 dyn_cast<FunctionTemplateDecl>(CD)) 2155 AddTemplateOverloadCandidate( 2156 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2157 Args, OCS); 2158 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2159 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2160 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2161 Args, OCS); 2162 } 2163 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2164 case OR_Success: 2165 ND = Best->FoundDecl; 2166 Corrected.setCorrectionDecl(ND); 2167 break; 2168 default: 2169 // FIXME: Arbitrarily pick the first declaration for the note. 2170 Corrected.setCorrectionDecl(ND); 2171 break; 2172 } 2173 } 2174 R.addDecl(ND); 2175 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2176 CXXRecordDecl *Record = nullptr; 2177 if (Corrected.getCorrectionSpecifier()) { 2178 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2179 Record = Ty->getAsCXXRecordDecl(); 2180 } 2181 if (!Record) 2182 Record = cast<CXXRecordDecl>( 2183 ND->getDeclContext()->getRedeclContext()); 2184 R.setNamingClass(Record); 2185 } 2186 2187 auto *UnderlyingND = ND->getUnderlyingDecl(); 2188 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2189 isa<FunctionTemplateDecl>(UnderlyingND); 2190 // FIXME: If we ended up with a typo for a type name or 2191 // Objective-C class name, we're in trouble because the parser 2192 // is in the wrong place to recover. Suggest the typo 2193 // correction, but don't make it a fix-it since we're not going 2194 // to recover well anyway. 2195 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2196 getAsTypeTemplateDecl(UnderlyingND) || 2197 isa<ObjCInterfaceDecl>(UnderlyingND); 2198 } else { 2199 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2200 // because we aren't able to recover. 2201 AcceptableWithoutRecovery = true; 2202 } 2203 2204 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2205 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2206 ? diag::note_implicit_param_decl 2207 : diag::note_previous_decl; 2208 if (SS.isEmpty()) 2209 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2210 PDiag(NoteID), AcceptableWithRecovery); 2211 else 2212 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2213 << Name << computeDeclContext(SS, false) 2214 << DroppedSpecifier << SS.getRange(), 2215 PDiag(NoteID), AcceptableWithRecovery); 2216 2217 // Tell the callee whether to try to recover. 2218 return !AcceptableWithRecovery; 2219 } 2220 } 2221 R.clear(); 2222 2223 // Emit a special diagnostic for failed member lookups. 2224 // FIXME: computing the declaration context might fail here (?) 2225 if (!SS.isEmpty()) { 2226 Diag(R.getNameLoc(), diag::err_no_member) 2227 << Name << computeDeclContext(SS, false) 2228 << SS.getRange(); 2229 return true; 2230 } 2231 2232 // Give up, we can't recover. 2233 Diag(R.getNameLoc(), diagnostic) << Name; 2234 return true; 2235 } 2236 2237 /// In Microsoft mode, if we are inside a template class whose parent class has 2238 /// dependent base classes, and we can't resolve an unqualified identifier, then 2239 /// assume the identifier is a member of a dependent base class. We can only 2240 /// recover successfully in static methods, instance methods, and other contexts 2241 /// where 'this' is available. This doesn't precisely match MSVC's 2242 /// instantiation model, but it's close enough. 2243 static Expr * 2244 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2245 DeclarationNameInfo &NameInfo, 2246 SourceLocation TemplateKWLoc, 2247 const TemplateArgumentListInfo *TemplateArgs) { 2248 // Only try to recover from lookup into dependent bases in static methods or 2249 // contexts where 'this' is available. 2250 QualType ThisType = S.getCurrentThisType(); 2251 const CXXRecordDecl *RD = nullptr; 2252 if (!ThisType.isNull()) 2253 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2254 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2255 RD = MD->getParent(); 2256 if (!RD || !RD->hasAnyDependentBases()) 2257 return nullptr; 2258 2259 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2260 // is available, suggest inserting 'this->' as a fixit. 2261 SourceLocation Loc = NameInfo.getLoc(); 2262 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2263 DB << NameInfo.getName() << RD; 2264 2265 if (!ThisType.isNull()) { 2266 DB << FixItHint::CreateInsertion(Loc, "this->"); 2267 return CXXDependentScopeMemberExpr::Create( 2268 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2269 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2270 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2271 } 2272 2273 // Synthesize a fake NNS that points to the derived class. This will 2274 // perform name lookup during template instantiation. 2275 CXXScopeSpec SS; 2276 auto *NNS = 2277 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2278 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2279 return DependentScopeDeclRefExpr::Create( 2280 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2281 TemplateArgs); 2282 } 2283 2284 ExprResult 2285 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2286 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2287 bool HasTrailingLParen, bool IsAddressOfOperand, 2288 CorrectionCandidateCallback *CCC, 2289 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2290 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2291 "cannot be direct & operand and have a trailing lparen"); 2292 if (SS.isInvalid()) 2293 return ExprError(); 2294 2295 TemplateArgumentListInfo TemplateArgsBuffer; 2296 2297 // Decompose the UnqualifiedId into the following data. 2298 DeclarationNameInfo NameInfo; 2299 const TemplateArgumentListInfo *TemplateArgs; 2300 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2301 2302 DeclarationName Name = NameInfo.getName(); 2303 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2304 SourceLocation NameLoc = NameInfo.getLoc(); 2305 2306 if (II && II->isEditorPlaceholder()) { 2307 // FIXME: When typed placeholders are supported we can create a typed 2308 // placeholder expression node. 2309 return ExprError(); 2310 } 2311 2312 // C++ [temp.dep.expr]p3: 2313 // An id-expression is type-dependent if it contains: 2314 // -- an identifier that was declared with a dependent type, 2315 // (note: handled after lookup) 2316 // -- a template-id that is dependent, 2317 // (note: handled in BuildTemplateIdExpr) 2318 // -- a conversion-function-id that specifies a dependent type, 2319 // -- a nested-name-specifier that contains a class-name that 2320 // names a dependent type. 2321 // Determine whether this is a member of an unknown specialization; 2322 // we need to handle these differently. 2323 bool DependentID = false; 2324 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2325 Name.getCXXNameType()->isDependentType()) { 2326 DependentID = true; 2327 } else if (SS.isSet()) { 2328 if (DeclContext *DC = computeDeclContext(SS, false)) { 2329 if (RequireCompleteDeclContext(SS, DC)) 2330 return ExprError(); 2331 } else { 2332 DependentID = true; 2333 } 2334 } 2335 2336 if (DependentID) 2337 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2338 IsAddressOfOperand, TemplateArgs); 2339 2340 // Perform the required lookup. 2341 LookupResult R(*this, NameInfo, 2342 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2343 ? LookupObjCImplicitSelfParam 2344 : LookupOrdinaryName); 2345 if (TemplateKWLoc.isValid() || TemplateArgs) { 2346 // Lookup the template name again to correctly establish the context in 2347 // which it was found. This is really unfortunate as we already did the 2348 // lookup to determine that it was a template name in the first place. If 2349 // this becomes a performance hit, we can work harder to preserve those 2350 // results until we get here but it's likely not worth it. 2351 bool MemberOfUnknownSpecialization; 2352 AssumedTemplateKind AssumedTemplate; 2353 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2354 MemberOfUnknownSpecialization, TemplateKWLoc, 2355 &AssumedTemplate)) 2356 return ExprError(); 2357 2358 if (MemberOfUnknownSpecialization || 2359 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2360 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2361 IsAddressOfOperand, TemplateArgs); 2362 } else { 2363 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2364 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2365 2366 // If the result might be in a dependent base class, this is a dependent 2367 // id-expression. 2368 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2369 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2370 IsAddressOfOperand, TemplateArgs); 2371 2372 // If this reference is in an Objective-C method, then we need to do 2373 // some special Objective-C lookup, too. 2374 if (IvarLookupFollowUp) { 2375 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2376 if (E.isInvalid()) 2377 return ExprError(); 2378 2379 if (Expr *Ex = E.getAs<Expr>()) 2380 return Ex; 2381 } 2382 } 2383 2384 if (R.isAmbiguous()) 2385 return ExprError(); 2386 2387 // This could be an implicitly declared function reference (legal in C90, 2388 // extension in C99, forbidden in C++). 2389 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2390 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2391 if (D) R.addDecl(D); 2392 } 2393 2394 // Determine whether this name might be a candidate for 2395 // argument-dependent lookup. 2396 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2397 2398 if (R.empty() && !ADL) { 2399 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2400 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2401 TemplateKWLoc, TemplateArgs)) 2402 return E; 2403 } 2404 2405 // Don't diagnose an empty lookup for inline assembly. 2406 if (IsInlineAsmIdentifier) 2407 return ExprError(); 2408 2409 // If this name wasn't predeclared and if this is not a function 2410 // call, diagnose the problem. 2411 TypoExpr *TE = nullptr; 2412 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2413 : nullptr); 2414 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2415 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2416 "Typo correction callback misconfigured"); 2417 if (CCC) { 2418 // Make sure the callback knows what the typo being diagnosed is. 2419 CCC->setTypoName(II); 2420 if (SS.isValid()) 2421 CCC->setTypoNNS(SS.getScopeRep()); 2422 } 2423 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2424 // a template name, but we happen to have always already looked up the name 2425 // before we get here if it must be a template name. 2426 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2427 None, &TE)) { 2428 if (TE && KeywordReplacement) { 2429 auto &State = getTypoExprState(TE); 2430 auto BestTC = State.Consumer->getNextCorrection(); 2431 if (BestTC.isKeyword()) { 2432 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2433 if (State.DiagHandler) 2434 State.DiagHandler(BestTC); 2435 KeywordReplacement->startToken(); 2436 KeywordReplacement->setKind(II->getTokenID()); 2437 KeywordReplacement->setIdentifierInfo(II); 2438 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2439 // Clean up the state associated with the TypoExpr, since it has 2440 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2441 clearDelayedTypo(TE); 2442 // Signal that a correction to a keyword was performed by returning a 2443 // valid-but-null ExprResult. 2444 return (Expr*)nullptr; 2445 } 2446 State.Consumer->resetCorrectionStream(); 2447 } 2448 return TE ? TE : ExprError(); 2449 } 2450 2451 assert(!R.empty() && 2452 "DiagnoseEmptyLookup returned false but added no results"); 2453 2454 // If we found an Objective-C instance variable, let 2455 // LookupInObjCMethod build the appropriate expression to 2456 // reference the ivar. 2457 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2458 R.clear(); 2459 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2460 // In a hopelessly buggy code, Objective-C instance variable 2461 // lookup fails and no expression will be built to reference it. 2462 if (!E.isInvalid() && !E.get()) 2463 return ExprError(); 2464 return E; 2465 } 2466 } 2467 2468 // This is guaranteed from this point on. 2469 assert(!R.empty() || ADL); 2470 2471 // Check whether this might be a C++ implicit instance member access. 2472 // C++ [class.mfct.non-static]p3: 2473 // When an id-expression that is not part of a class member access 2474 // syntax and not used to form a pointer to member is used in the 2475 // body of a non-static member function of class X, if name lookup 2476 // resolves the name in the id-expression to a non-static non-type 2477 // member of some class C, the id-expression is transformed into a 2478 // class member access expression using (*this) as the 2479 // postfix-expression to the left of the . operator. 2480 // 2481 // But we don't actually need to do this for '&' operands if R 2482 // resolved to a function or overloaded function set, because the 2483 // expression is ill-formed if it actually works out to be a 2484 // non-static member function: 2485 // 2486 // C++ [expr.ref]p4: 2487 // Otherwise, if E1.E2 refers to a non-static member function. . . 2488 // [t]he expression can be used only as the left-hand operand of a 2489 // member function call. 2490 // 2491 // There are other safeguards against such uses, but it's important 2492 // to get this right here so that we don't end up making a 2493 // spuriously dependent expression if we're inside a dependent 2494 // instance method. 2495 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2496 bool MightBeImplicitMember; 2497 if (!IsAddressOfOperand) 2498 MightBeImplicitMember = true; 2499 else if (!SS.isEmpty()) 2500 MightBeImplicitMember = false; 2501 else if (R.isOverloadedResult()) 2502 MightBeImplicitMember = false; 2503 else if (R.isUnresolvableResult()) 2504 MightBeImplicitMember = true; 2505 else 2506 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2507 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2508 isa<MSPropertyDecl>(R.getFoundDecl()); 2509 2510 if (MightBeImplicitMember) 2511 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2512 R, TemplateArgs, S); 2513 } 2514 2515 if (TemplateArgs || TemplateKWLoc.isValid()) { 2516 2517 // In C++1y, if this is a variable template id, then check it 2518 // in BuildTemplateIdExpr(). 2519 // The single lookup result must be a variable template declaration. 2520 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2521 Id.TemplateId->Kind == TNK_Var_template) { 2522 assert(R.getAsSingle<VarTemplateDecl>() && 2523 "There should only be one declaration found."); 2524 } 2525 2526 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2527 } 2528 2529 return BuildDeclarationNameExpr(SS, R, ADL); 2530 } 2531 2532 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2533 /// declaration name, generally during template instantiation. 2534 /// There's a large number of things which don't need to be done along 2535 /// this path. 2536 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2537 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2538 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2539 DeclContext *DC = computeDeclContext(SS, false); 2540 if (!DC) 2541 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2542 NameInfo, /*TemplateArgs=*/nullptr); 2543 2544 if (RequireCompleteDeclContext(SS, DC)) 2545 return ExprError(); 2546 2547 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2548 LookupQualifiedName(R, DC); 2549 2550 if (R.isAmbiguous()) 2551 return ExprError(); 2552 2553 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2554 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2555 NameInfo, /*TemplateArgs=*/nullptr); 2556 2557 if (R.empty()) { 2558 Diag(NameInfo.getLoc(), diag::err_no_member) 2559 << NameInfo.getName() << DC << SS.getRange(); 2560 return ExprError(); 2561 } 2562 2563 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2564 // Diagnose a missing typename if this resolved unambiguously to a type in 2565 // a dependent context. If we can recover with a type, downgrade this to 2566 // a warning in Microsoft compatibility mode. 2567 unsigned DiagID = diag::err_typename_missing; 2568 if (RecoveryTSI && getLangOpts().MSVCCompat) 2569 DiagID = diag::ext_typename_missing; 2570 SourceLocation Loc = SS.getBeginLoc(); 2571 auto D = Diag(Loc, DiagID); 2572 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2573 << SourceRange(Loc, NameInfo.getEndLoc()); 2574 2575 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2576 // context. 2577 if (!RecoveryTSI) 2578 return ExprError(); 2579 2580 // Only issue the fixit if we're prepared to recover. 2581 D << FixItHint::CreateInsertion(Loc, "typename "); 2582 2583 // Recover by pretending this was an elaborated type. 2584 QualType Ty = Context.getTypeDeclType(TD); 2585 TypeLocBuilder TLB; 2586 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2587 2588 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2589 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2590 QTL.setElaboratedKeywordLoc(SourceLocation()); 2591 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2592 2593 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2594 2595 return ExprEmpty(); 2596 } 2597 2598 // Defend against this resolving to an implicit member access. We usually 2599 // won't get here if this might be a legitimate a class member (we end up in 2600 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2601 // a pointer-to-member or in an unevaluated context in C++11. 2602 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2603 return BuildPossibleImplicitMemberExpr(SS, 2604 /*TemplateKWLoc=*/SourceLocation(), 2605 R, /*TemplateArgs=*/nullptr, S); 2606 2607 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2608 } 2609 2610 /// The parser has read a name in, and Sema has detected that we're currently 2611 /// inside an ObjC method. Perform some additional checks and determine if we 2612 /// should form a reference to an ivar. 2613 /// 2614 /// Ideally, most of this would be done by lookup, but there's 2615 /// actually quite a lot of extra work involved. 2616 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2617 IdentifierInfo *II) { 2618 SourceLocation Loc = Lookup.getNameLoc(); 2619 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2620 2621 // Check for error condition which is already reported. 2622 if (!CurMethod) 2623 return DeclResult(true); 2624 2625 // There are two cases to handle here. 1) scoped lookup could have failed, 2626 // in which case we should look for an ivar. 2) scoped lookup could have 2627 // found a decl, but that decl is outside the current instance method (i.e. 2628 // a global variable). In these two cases, we do a lookup for an ivar with 2629 // this name, if the lookup sucedes, we replace it our current decl. 2630 2631 // If we're in a class method, we don't normally want to look for 2632 // ivars. But if we don't find anything else, and there's an 2633 // ivar, that's an error. 2634 bool IsClassMethod = CurMethod->isClassMethod(); 2635 2636 bool LookForIvars; 2637 if (Lookup.empty()) 2638 LookForIvars = true; 2639 else if (IsClassMethod) 2640 LookForIvars = false; 2641 else 2642 LookForIvars = (Lookup.isSingleResult() && 2643 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2644 ObjCInterfaceDecl *IFace = nullptr; 2645 if (LookForIvars) { 2646 IFace = CurMethod->getClassInterface(); 2647 ObjCInterfaceDecl *ClassDeclared; 2648 ObjCIvarDecl *IV = nullptr; 2649 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2650 // Diagnose using an ivar in a class method. 2651 if (IsClassMethod) { 2652 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2653 return DeclResult(true); 2654 } 2655 2656 // Diagnose the use of an ivar outside of the declaring class. 2657 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2658 !declaresSameEntity(ClassDeclared, IFace) && 2659 !getLangOpts().DebuggerSupport) 2660 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2661 2662 // Success. 2663 return IV; 2664 } 2665 } else if (CurMethod->isInstanceMethod()) { 2666 // We should warn if a local variable hides an ivar. 2667 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2668 ObjCInterfaceDecl *ClassDeclared; 2669 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2670 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2671 declaresSameEntity(IFace, ClassDeclared)) 2672 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2673 } 2674 } 2675 } else if (Lookup.isSingleResult() && 2676 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2677 // If accessing a stand-alone ivar in a class method, this is an error. 2678 if (const ObjCIvarDecl *IV = 2679 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2680 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2681 return DeclResult(true); 2682 } 2683 } 2684 2685 // Didn't encounter an error, didn't find an ivar. 2686 return DeclResult(false); 2687 } 2688 2689 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2690 ObjCIvarDecl *IV) { 2691 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2692 assert(CurMethod && CurMethod->isInstanceMethod() && 2693 "should not reference ivar from this context"); 2694 2695 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2696 assert(IFace && "should not reference ivar from this context"); 2697 2698 // If we're referencing an invalid decl, just return this as a silent 2699 // error node. The error diagnostic was already emitted on the decl. 2700 if (IV->isInvalidDecl()) 2701 return ExprError(); 2702 2703 // Check if referencing a field with __attribute__((deprecated)). 2704 if (DiagnoseUseOfDecl(IV, Loc)) 2705 return ExprError(); 2706 2707 // FIXME: This should use a new expr for a direct reference, don't 2708 // turn this into Self->ivar, just return a BareIVarExpr or something. 2709 IdentifierInfo &II = Context.Idents.get("self"); 2710 UnqualifiedId SelfName; 2711 SelfName.setIdentifier(&II, SourceLocation()); 2712 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2713 CXXScopeSpec SelfScopeSpec; 2714 SourceLocation TemplateKWLoc; 2715 ExprResult SelfExpr = 2716 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2717 /*HasTrailingLParen=*/false, 2718 /*IsAddressOfOperand=*/false); 2719 if (SelfExpr.isInvalid()) 2720 return ExprError(); 2721 2722 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2723 if (SelfExpr.isInvalid()) 2724 return ExprError(); 2725 2726 MarkAnyDeclReferenced(Loc, IV, true); 2727 2728 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2729 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2730 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2731 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2732 2733 ObjCIvarRefExpr *Result = new (Context) 2734 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2735 IV->getLocation(), SelfExpr.get(), true, true); 2736 2737 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2738 if (!isUnevaluatedContext() && 2739 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2740 getCurFunction()->recordUseOfWeak(Result); 2741 } 2742 if (getLangOpts().ObjCAutoRefCount) 2743 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2744 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2745 2746 return Result; 2747 } 2748 2749 /// The parser has read a name in, and Sema has detected that we're currently 2750 /// inside an ObjC method. Perform some additional checks and determine if we 2751 /// should form a reference to an ivar. If so, build an expression referencing 2752 /// that ivar. 2753 ExprResult 2754 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2755 IdentifierInfo *II, bool AllowBuiltinCreation) { 2756 // FIXME: Integrate this lookup step into LookupParsedName. 2757 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2758 if (Ivar.isInvalid()) 2759 return ExprError(); 2760 if (Ivar.isUsable()) 2761 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2762 cast<ObjCIvarDecl>(Ivar.get())); 2763 2764 if (Lookup.empty() && II && AllowBuiltinCreation) 2765 LookupBuiltin(Lookup); 2766 2767 // Sentinel value saying that we didn't do anything special. 2768 return ExprResult(false); 2769 } 2770 2771 /// Cast a base object to a member's actual type. 2772 /// 2773 /// Logically this happens in three phases: 2774 /// 2775 /// * First we cast from the base type to the naming class. 2776 /// The naming class is the class into which we were looking 2777 /// when we found the member; it's the qualifier type if a 2778 /// qualifier was provided, and otherwise it's the base type. 2779 /// 2780 /// * Next we cast from the naming class to the declaring class. 2781 /// If the member we found was brought into a class's scope by 2782 /// a using declaration, this is that class; otherwise it's 2783 /// the class declaring the member. 2784 /// 2785 /// * Finally we cast from the declaring class to the "true" 2786 /// declaring class of the member. This conversion does not 2787 /// obey access control. 2788 ExprResult 2789 Sema::PerformObjectMemberConversion(Expr *From, 2790 NestedNameSpecifier *Qualifier, 2791 NamedDecl *FoundDecl, 2792 NamedDecl *Member) { 2793 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2794 if (!RD) 2795 return From; 2796 2797 QualType DestRecordType; 2798 QualType DestType; 2799 QualType FromRecordType; 2800 QualType FromType = From->getType(); 2801 bool PointerConversions = false; 2802 if (isa<FieldDecl>(Member)) { 2803 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2804 auto FromPtrType = FromType->getAs<PointerType>(); 2805 DestRecordType = Context.getAddrSpaceQualType( 2806 DestRecordType, FromPtrType 2807 ? FromType->getPointeeType().getAddressSpace() 2808 : FromType.getAddressSpace()); 2809 2810 if (FromPtrType) { 2811 DestType = Context.getPointerType(DestRecordType); 2812 FromRecordType = FromPtrType->getPointeeType(); 2813 PointerConversions = true; 2814 } else { 2815 DestType = DestRecordType; 2816 FromRecordType = FromType; 2817 } 2818 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2819 if (Method->isStatic()) 2820 return From; 2821 2822 DestType = Method->getThisType(); 2823 DestRecordType = DestType->getPointeeType(); 2824 2825 if (FromType->getAs<PointerType>()) { 2826 FromRecordType = FromType->getPointeeType(); 2827 PointerConversions = true; 2828 } else { 2829 FromRecordType = FromType; 2830 DestType = DestRecordType; 2831 } 2832 2833 LangAS FromAS = FromRecordType.getAddressSpace(); 2834 LangAS DestAS = DestRecordType.getAddressSpace(); 2835 if (FromAS != DestAS) { 2836 QualType FromRecordTypeWithoutAS = 2837 Context.removeAddrSpaceQualType(FromRecordType); 2838 QualType FromTypeWithDestAS = 2839 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2840 if (PointerConversions) 2841 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2842 From = ImpCastExprToType(From, FromTypeWithDestAS, 2843 CK_AddressSpaceConversion, From->getValueKind()) 2844 .get(); 2845 } 2846 } else { 2847 // No conversion necessary. 2848 return From; 2849 } 2850 2851 if (DestType->isDependentType() || FromType->isDependentType()) 2852 return From; 2853 2854 // If the unqualified types are the same, no conversion is necessary. 2855 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2856 return From; 2857 2858 SourceRange FromRange = From->getSourceRange(); 2859 SourceLocation FromLoc = FromRange.getBegin(); 2860 2861 ExprValueKind VK = From->getValueKind(); 2862 2863 // C++ [class.member.lookup]p8: 2864 // [...] Ambiguities can often be resolved by qualifying a name with its 2865 // class name. 2866 // 2867 // If the member was a qualified name and the qualified referred to a 2868 // specific base subobject type, we'll cast to that intermediate type 2869 // first and then to the object in which the member is declared. That allows 2870 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2871 // 2872 // class Base { public: int x; }; 2873 // class Derived1 : public Base { }; 2874 // class Derived2 : public Base { }; 2875 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2876 // 2877 // void VeryDerived::f() { 2878 // x = 17; // error: ambiguous base subobjects 2879 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2880 // } 2881 if (Qualifier && Qualifier->getAsType()) { 2882 QualType QType = QualType(Qualifier->getAsType(), 0); 2883 assert(QType->isRecordType() && "lookup done with non-record type"); 2884 2885 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2886 2887 // In C++98, the qualifier type doesn't actually have to be a base 2888 // type of the object type, in which case we just ignore it. 2889 // Otherwise build the appropriate casts. 2890 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2891 CXXCastPath BasePath; 2892 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2893 FromLoc, FromRange, &BasePath)) 2894 return ExprError(); 2895 2896 if (PointerConversions) 2897 QType = Context.getPointerType(QType); 2898 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2899 VK, &BasePath).get(); 2900 2901 FromType = QType; 2902 FromRecordType = QRecordType; 2903 2904 // If the qualifier type was the same as the destination type, 2905 // we're done. 2906 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2907 return From; 2908 } 2909 } 2910 2911 bool IgnoreAccess = false; 2912 2913 // If we actually found the member through a using declaration, cast 2914 // down to the using declaration's type. 2915 // 2916 // Pointer equality is fine here because only one declaration of a 2917 // class ever has member declarations. 2918 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2919 assert(isa<UsingShadowDecl>(FoundDecl)); 2920 QualType URecordType = Context.getTypeDeclType( 2921 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2922 2923 // We only need to do this if the naming-class to declaring-class 2924 // conversion is non-trivial. 2925 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2926 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2927 CXXCastPath BasePath; 2928 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2929 FromLoc, FromRange, &BasePath)) 2930 return ExprError(); 2931 2932 QualType UType = URecordType; 2933 if (PointerConversions) 2934 UType = Context.getPointerType(UType); 2935 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2936 VK, &BasePath).get(); 2937 FromType = UType; 2938 FromRecordType = URecordType; 2939 } 2940 2941 // We don't do access control for the conversion from the 2942 // declaring class to the true declaring class. 2943 IgnoreAccess = true; 2944 } 2945 2946 CXXCastPath BasePath; 2947 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2948 FromLoc, FromRange, &BasePath, 2949 IgnoreAccess)) 2950 return ExprError(); 2951 2952 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2953 VK, &BasePath); 2954 } 2955 2956 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2957 const LookupResult &R, 2958 bool HasTrailingLParen) { 2959 // Only when used directly as the postfix-expression of a call. 2960 if (!HasTrailingLParen) 2961 return false; 2962 2963 // Never if a scope specifier was provided. 2964 if (SS.isSet()) 2965 return false; 2966 2967 // Only in C++ or ObjC++. 2968 if (!getLangOpts().CPlusPlus) 2969 return false; 2970 2971 // Turn off ADL when we find certain kinds of declarations during 2972 // normal lookup: 2973 for (NamedDecl *D : R) { 2974 // C++0x [basic.lookup.argdep]p3: 2975 // -- a declaration of a class member 2976 // Since using decls preserve this property, we check this on the 2977 // original decl. 2978 if (D->isCXXClassMember()) 2979 return false; 2980 2981 // C++0x [basic.lookup.argdep]p3: 2982 // -- a block-scope function declaration that is not a 2983 // using-declaration 2984 // NOTE: we also trigger this for function templates (in fact, we 2985 // don't check the decl type at all, since all other decl types 2986 // turn off ADL anyway). 2987 if (isa<UsingShadowDecl>(D)) 2988 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2989 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2990 return false; 2991 2992 // C++0x [basic.lookup.argdep]p3: 2993 // -- a declaration that is neither a function or a function 2994 // template 2995 // And also for builtin functions. 2996 if (isa<FunctionDecl>(D)) { 2997 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2998 2999 // But also builtin functions. 3000 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3001 return false; 3002 } else if (!isa<FunctionTemplateDecl>(D)) 3003 return false; 3004 } 3005 3006 return true; 3007 } 3008 3009 3010 /// Diagnoses obvious problems with the use of the given declaration 3011 /// as an expression. This is only actually called for lookups that 3012 /// were not overloaded, and it doesn't promise that the declaration 3013 /// will in fact be used. 3014 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3015 if (D->isInvalidDecl()) 3016 return true; 3017 3018 if (isa<TypedefNameDecl>(D)) { 3019 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3020 return true; 3021 } 3022 3023 if (isa<ObjCInterfaceDecl>(D)) { 3024 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3025 return true; 3026 } 3027 3028 if (isa<NamespaceDecl>(D)) { 3029 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3030 return true; 3031 } 3032 3033 return false; 3034 } 3035 3036 // Certain multiversion types should be treated as overloaded even when there is 3037 // only one result. 3038 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3039 assert(R.isSingleResult() && "Expected only a single result"); 3040 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3041 return FD && 3042 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3043 } 3044 3045 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3046 LookupResult &R, bool NeedsADL, 3047 bool AcceptInvalidDecl) { 3048 // If this is a single, fully-resolved result and we don't need ADL, 3049 // just build an ordinary singleton decl ref. 3050 if (!NeedsADL && R.isSingleResult() && 3051 !R.getAsSingle<FunctionTemplateDecl>() && 3052 !ShouldLookupResultBeMultiVersionOverload(R)) 3053 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3054 R.getRepresentativeDecl(), nullptr, 3055 AcceptInvalidDecl); 3056 3057 // We only need to check the declaration if there's exactly one 3058 // result, because in the overloaded case the results can only be 3059 // functions and function templates. 3060 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3061 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3062 return ExprError(); 3063 3064 // Otherwise, just build an unresolved lookup expression. Suppress 3065 // any lookup-related diagnostics; we'll hash these out later, when 3066 // we've picked a target. 3067 R.suppressDiagnostics(); 3068 3069 UnresolvedLookupExpr *ULE 3070 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3071 SS.getWithLocInContext(Context), 3072 R.getLookupNameInfo(), 3073 NeedsADL, R.isOverloadedResult(), 3074 R.begin(), R.end()); 3075 3076 return ULE; 3077 } 3078 3079 static void 3080 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3081 ValueDecl *var, DeclContext *DC); 3082 3083 /// Complete semantic analysis for a reference to the given declaration. 3084 ExprResult Sema::BuildDeclarationNameExpr( 3085 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3086 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3087 bool AcceptInvalidDecl) { 3088 assert(D && "Cannot refer to a NULL declaration"); 3089 assert(!isa<FunctionTemplateDecl>(D) && 3090 "Cannot refer unambiguously to a function template"); 3091 3092 SourceLocation Loc = NameInfo.getLoc(); 3093 if (CheckDeclInExpr(*this, Loc, D)) 3094 return ExprError(); 3095 3096 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3097 // Specifically diagnose references to class templates that are missing 3098 // a template argument list. 3099 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3100 return ExprError(); 3101 } 3102 3103 // Make sure that we're referring to a value. 3104 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3105 if (!VD) { 3106 Diag(Loc, diag::err_ref_non_value) 3107 << D << SS.getRange(); 3108 Diag(D->getLocation(), diag::note_declared_at); 3109 return ExprError(); 3110 } 3111 3112 // Check whether this declaration can be used. Note that we suppress 3113 // this check when we're going to perform argument-dependent lookup 3114 // on this function name, because this might not be the function 3115 // that overload resolution actually selects. 3116 if (DiagnoseUseOfDecl(VD, Loc)) 3117 return ExprError(); 3118 3119 // Only create DeclRefExpr's for valid Decl's. 3120 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3121 return ExprError(); 3122 3123 // Handle members of anonymous structs and unions. If we got here, 3124 // and the reference is to a class member indirect field, then this 3125 // must be the subject of a pointer-to-member expression. 3126 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3127 if (!indirectField->isCXXClassMember()) 3128 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3129 indirectField); 3130 3131 { 3132 QualType type = VD->getType(); 3133 if (type.isNull()) 3134 return ExprError(); 3135 ExprValueKind valueKind = VK_RValue; 3136 3137 switch (D->getKind()) { 3138 // Ignore all the non-ValueDecl kinds. 3139 #define ABSTRACT_DECL(kind) 3140 #define VALUE(type, base) 3141 #define DECL(type, base) \ 3142 case Decl::type: 3143 #include "clang/AST/DeclNodes.inc" 3144 llvm_unreachable("invalid value decl kind"); 3145 3146 // These shouldn't make it here. 3147 case Decl::ObjCAtDefsField: 3148 llvm_unreachable("forming non-member reference to ivar?"); 3149 3150 // Enum constants are always r-values and never references. 3151 // Unresolved using declarations are dependent. 3152 case Decl::EnumConstant: 3153 case Decl::UnresolvedUsingValue: 3154 case Decl::OMPDeclareReduction: 3155 case Decl::OMPDeclareMapper: 3156 valueKind = VK_RValue; 3157 break; 3158 3159 // Fields and indirect fields that got here must be for 3160 // pointer-to-member expressions; we just call them l-values for 3161 // internal consistency, because this subexpression doesn't really 3162 // exist in the high-level semantics. 3163 case Decl::Field: 3164 case Decl::IndirectField: 3165 case Decl::ObjCIvar: 3166 assert(getLangOpts().CPlusPlus && 3167 "building reference to field in C?"); 3168 3169 // These can't have reference type in well-formed programs, but 3170 // for internal consistency we do this anyway. 3171 type = type.getNonReferenceType(); 3172 valueKind = VK_LValue; 3173 break; 3174 3175 // Non-type template parameters are either l-values or r-values 3176 // depending on the type. 3177 case Decl::NonTypeTemplateParm: { 3178 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3179 type = reftype->getPointeeType(); 3180 valueKind = VK_LValue; // even if the parameter is an r-value reference 3181 break; 3182 } 3183 3184 // For non-references, we need to strip qualifiers just in case 3185 // the template parameter was declared as 'const int' or whatever. 3186 valueKind = VK_RValue; 3187 type = type.getUnqualifiedType(); 3188 break; 3189 } 3190 3191 case Decl::Var: 3192 case Decl::VarTemplateSpecialization: 3193 case Decl::VarTemplatePartialSpecialization: 3194 case Decl::Decomposition: 3195 case Decl::OMPCapturedExpr: 3196 // In C, "extern void blah;" is valid and is an r-value. 3197 if (!getLangOpts().CPlusPlus && 3198 !type.hasQualifiers() && 3199 type->isVoidType()) { 3200 valueKind = VK_RValue; 3201 break; 3202 } 3203 LLVM_FALLTHROUGH; 3204 3205 case Decl::ImplicitParam: 3206 case Decl::ParmVar: { 3207 // These are always l-values. 3208 valueKind = VK_LValue; 3209 type = type.getNonReferenceType(); 3210 3211 // FIXME: Does the addition of const really only apply in 3212 // potentially-evaluated contexts? Since the variable isn't actually 3213 // captured in an unevaluated context, it seems that the answer is no. 3214 if (!isUnevaluatedContext()) { 3215 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3216 if (!CapturedType.isNull()) 3217 type = CapturedType; 3218 } 3219 3220 break; 3221 } 3222 3223 case Decl::Binding: { 3224 // These are always lvalues. 3225 valueKind = VK_LValue; 3226 type = type.getNonReferenceType(); 3227 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3228 // decides how that's supposed to work. 3229 auto *BD = cast<BindingDecl>(VD); 3230 if (BD->getDeclContext() != CurContext) { 3231 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3232 if (DD && DD->hasLocalStorage()) 3233 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3234 } 3235 break; 3236 } 3237 3238 case Decl::Function: { 3239 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3240 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3241 type = Context.BuiltinFnTy; 3242 valueKind = VK_RValue; 3243 break; 3244 } 3245 } 3246 3247 const FunctionType *fty = type->castAs<FunctionType>(); 3248 3249 // If we're referring to a function with an __unknown_anytype 3250 // result type, make the entire expression __unknown_anytype. 3251 if (fty->getReturnType() == Context.UnknownAnyTy) { 3252 type = Context.UnknownAnyTy; 3253 valueKind = VK_RValue; 3254 break; 3255 } 3256 3257 // Functions are l-values in C++. 3258 if (getLangOpts().CPlusPlus) { 3259 valueKind = VK_LValue; 3260 break; 3261 } 3262 3263 // C99 DR 316 says that, if a function type comes from a 3264 // function definition (without a prototype), that type is only 3265 // used for checking compatibility. Therefore, when referencing 3266 // the function, we pretend that we don't have the full function 3267 // type. 3268 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3269 isa<FunctionProtoType>(fty)) 3270 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3271 fty->getExtInfo()); 3272 3273 // Functions are r-values in C. 3274 valueKind = VK_RValue; 3275 break; 3276 } 3277 3278 case Decl::CXXDeductionGuide: 3279 llvm_unreachable("building reference to deduction guide"); 3280 3281 case Decl::MSProperty: 3282 case Decl::MSGuid: 3283 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3284 // or duplicated between host and device? 3285 valueKind = VK_LValue; 3286 break; 3287 3288 case Decl::CXXMethod: 3289 // If we're referring to a method with an __unknown_anytype 3290 // result type, make the entire expression __unknown_anytype. 3291 // This should only be possible with a type written directly. 3292 if (const FunctionProtoType *proto 3293 = dyn_cast<FunctionProtoType>(VD->getType())) 3294 if (proto->getReturnType() == Context.UnknownAnyTy) { 3295 type = Context.UnknownAnyTy; 3296 valueKind = VK_RValue; 3297 break; 3298 } 3299 3300 // C++ methods are l-values if static, r-values if non-static. 3301 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3302 valueKind = VK_LValue; 3303 break; 3304 } 3305 LLVM_FALLTHROUGH; 3306 3307 case Decl::CXXConversion: 3308 case Decl::CXXDestructor: 3309 case Decl::CXXConstructor: 3310 valueKind = VK_RValue; 3311 break; 3312 } 3313 3314 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3315 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3316 TemplateArgs); 3317 } 3318 } 3319 3320 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3321 SmallString<32> &Target) { 3322 Target.resize(CharByteWidth * (Source.size() + 1)); 3323 char *ResultPtr = &Target[0]; 3324 const llvm::UTF8 *ErrorPtr; 3325 bool success = 3326 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3327 (void)success; 3328 assert(success); 3329 Target.resize(ResultPtr - &Target[0]); 3330 } 3331 3332 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3333 PredefinedExpr::IdentKind IK) { 3334 // Pick the current block, lambda, captured statement or function. 3335 Decl *currentDecl = nullptr; 3336 if (const BlockScopeInfo *BSI = getCurBlock()) 3337 currentDecl = BSI->TheDecl; 3338 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3339 currentDecl = LSI->CallOperator; 3340 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3341 currentDecl = CSI->TheCapturedDecl; 3342 else 3343 currentDecl = getCurFunctionOrMethodDecl(); 3344 3345 if (!currentDecl) { 3346 Diag(Loc, diag::ext_predef_outside_function); 3347 currentDecl = Context.getTranslationUnitDecl(); 3348 } 3349 3350 QualType ResTy; 3351 StringLiteral *SL = nullptr; 3352 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3353 ResTy = Context.DependentTy; 3354 else { 3355 // Pre-defined identifiers are of type char[x], where x is the length of 3356 // the string. 3357 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3358 unsigned Length = Str.length(); 3359 3360 llvm::APInt LengthI(32, Length + 1); 3361 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3362 ResTy = 3363 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3364 SmallString<32> RawChars; 3365 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3366 Str, RawChars); 3367 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3368 ArrayType::Normal, 3369 /*IndexTypeQuals*/ 0); 3370 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3371 /*Pascal*/ false, ResTy, Loc); 3372 } else { 3373 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3374 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3375 ArrayType::Normal, 3376 /*IndexTypeQuals*/ 0); 3377 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3378 /*Pascal*/ false, ResTy, Loc); 3379 } 3380 } 3381 3382 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3383 } 3384 3385 static std::pair<QualType, StringLiteral *> 3386 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3387 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3388 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3389 3390 if (OpType->isDependentType()) { 3391 Result.first = Context.DependentTy; 3392 return Result; 3393 } 3394 3395 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3396 llvm::APInt Length(32, Str.length() + 1); 3397 Result.first = 3398 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3399 Result.first = Context.getConstantArrayType( 3400 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3401 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3402 /*Pascal*/ false, Result.first, OpLoc); 3403 return Result; 3404 } 3405 3406 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3407 TypeSourceInfo *Operand) { 3408 QualType ResultTy; 3409 StringLiteral *SL; 3410 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3411 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3412 3413 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3414 PredefinedExpr::UniqueStableNameType, SL, 3415 Operand); 3416 } 3417 3418 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3419 Expr *E) { 3420 QualType ResultTy; 3421 StringLiteral *SL; 3422 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3423 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3424 3425 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3426 PredefinedExpr::UniqueStableNameExpr, SL, E); 3427 } 3428 3429 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3430 SourceLocation L, SourceLocation R, 3431 ParsedType Ty) { 3432 TypeSourceInfo *TInfo = nullptr; 3433 QualType T = GetTypeFromParser(Ty, &TInfo); 3434 3435 if (T.isNull()) 3436 return ExprError(); 3437 if (!TInfo) 3438 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3439 3440 return BuildUniqueStableName(OpLoc, TInfo); 3441 } 3442 3443 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3444 SourceLocation L, SourceLocation R, 3445 Expr *E) { 3446 return BuildUniqueStableName(OpLoc, E); 3447 } 3448 3449 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3450 PredefinedExpr::IdentKind IK; 3451 3452 switch (Kind) { 3453 default: llvm_unreachable("Unknown simple primary expr!"); 3454 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3455 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3456 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3457 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3458 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3459 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3460 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3461 } 3462 3463 return BuildPredefinedExpr(Loc, IK); 3464 } 3465 3466 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3467 SmallString<16> CharBuffer; 3468 bool Invalid = false; 3469 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3470 if (Invalid) 3471 return ExprError(); 3472 3473 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3474 PP, Tok.getKind()); 3475 if (Literal.hadError()) 3476 return ExprError(); 3477 3478 QualType Ty; 3479 if (Literal.isWide()) 3480 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3481 else if (Literal.isUTF8() && getLangOpts().Char8) 3482 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3483 else if (Literal.isUTF16()) 3484 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3485 else if (Literal.isUTF32()) 3486 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3487 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3488 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3489 else 3490 Ty = Context.CharTy; // 'x' -> char in C++ 3491 3492 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3493 if (Literal.isWide()) 3494 Kind = CharacterLiteral::Wide; 3495 else if (Literal.isUTF16()) 3496 Kind = CharacterLiteral::UTF16; 3497 else if (Literal.isUTF32()) 3498 Kind = CharacterLiteral::UTF32; 3499 else if (Literal.isUTF8()) 3500 Kind = CharacterLiteral::UTF8; 3501 3502 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3503 Tok.getLocation()); 3504 3505 if (Literal.getUDSuffix().empty()) 3506 return Lit; 3507 3508 // We're building a user-defined literal. 3509 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3510 SourceLocation UDSuffixLoc = 3511 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3512 3513 // Make sure we're allowed user-defined literals here. 3514 if (!UDLScope) 3515 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3516 3517 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3518 // operator "" X (ch) 3519 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3520 Lit, Tok.getLocation()); 3521 } 3522 3523 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3524 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3525 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3526 Context.IntTy, Loc); 3527 } 3528 3529 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3530 QualType Ty, SourceLocation Loc) { 3531 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3532 3533 using llvm::APFloat; 3534 APFloat Val(Format); 3535 3536 APFloat::opStatus result = Literal.GetFloatValue(Val); 3537 3538 // Overflow is always an error, but underflow is only an error if 3539 // we underflowed to zero (APFloat reports denormals as underflow). 3540 if ((result & APFloat::opOverflow) || 3541 ((result & APFloat::opUnderflow) && Val.isZero())) { 3542 unsigned diagnostic; 3543 SmallString<20> buffer; 3544 if (result & APFloat::opOverflow) { 3545 diagnostic = diag::warn_float_overflow; 3546 APFloat::getLargest(Format).toString(buffer); 3547 } else { 3548 diagnostic = diag::warn_float_underflow; 3549 APFloat::getSmallest(Format).toString(buffer); 3550 } 3551 3552 S.Diag(Loc, diagnostic) 3553 << Ty 3554 << StringRef(buffer.data(), buffer.size()); 3555 } 3556 3557 bool isExact = (result == APFloat::opOK); 3558 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3559 } 3560 3561 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3562 assert(E && "Invalid expression"); 3563 3564 if (E->isValueDependent()) 3565 return false; 3566 3567 QualType QT = E->getType(); 3568 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3569 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3570 return true; 3571 } 3572 3573 llvm::APSInt ValueAPS; 3574 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3575 3576 if (R.isInvalid()) 3577 return true; 3578 3579 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3580 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3581 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3582 << ValueAPS.toString(10) << ValueIsPositive; 3583 return true; 3584 } 3585 3586 return false; 3587 } 3588 3589 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3590 // Fast path for a single digit (which is quite common). A single digit 3591 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3592 if (Tok.getLength() == 1) { 3593 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3594 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3595 } 3596 3597 SmallString<128> SpellingBuffer; 3598 // NumericLiteralParser wants to overread by one character. Add padding to 3599 // the buffer in case the token is copied to the buffer. If getSpelling() 3600 // returns a StringRef to the memory buffer, it should have a null char at 3601 // the EOF, so it is also safe. 3602 SpellingBuffer.resize(Tok.getLength() + 1); 3603 3604 // Get the spelling of the token, which eliminates trigraphs, etc. 3605 bool Invalid = false; 3606 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3607 if (Invalid) 3608 return ExprError(); 3609 3610 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3611 if (Literal.hadError) 3612 return ExprError(); 3613 3614 if (Literal.hasUDSuffix()) { 3615 // We're building a user-defined literal. 3616 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3617 SourceLocation UDSuffixLoc = 3618 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3619 3620 // Make sure we're allowed user-defined literals here. 3621 if (!UDLScope) 3622 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3623 3624 QualType CookedTy; 3625 if (Literal.isFloatingLiteral()) { 3626 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3627 // long double, the literal is treated as a call of the form 3628 // operator "" X (f L) 3629 CookedTy = Context.LongDoubleTy; 3630 } else { 3631 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3632 // unsigned long long, the literal is treated as a call of the form 3633 // operator "" X (n ULL) 3634 CookedTy = Context.UnsignedLongLongTy; 3635 } 3636 3637 DeclarationName OpName = 3638 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3639 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3640 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3641 3642 SourceLocation TokLoc = Tok.getLocation(); 3643 3644 // Perform literal operator lookup to determine if we're building a raw 3645 // literal or a cooked one. 3646 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3647 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3648 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3649 /*AllowStringTemplate*/ false, 3650 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3651 case LOLR_ErrorNoDiagnostic: 3652 // Lookup failure for imaginary constants isn't fatal, there's still the 3653 // GNU extension producing _Complex types. 3654 break; 3655 case LOLR_Error: 3656 return ExprError(); 3657 case LOLR_Cooked: { 3658 Expr *Lit; 3659 if (Literal.isFloatingLiteral()) { 3660 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3661 } else { 3662 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3663 if (Literal.GetIntegerValue(ResultVal)) 3664 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3665 << /* Unsigned */ 1; 3666 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3667 Tok.getLocation()); 3668 } 3669 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3670 } 3671 3672 case LOLR_Raw: { 3673 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3674 // literal is treated as a call of the form 3675 // operator "" X ("n") 3676 unsigned Length = Literal.getUDSuffixOffset(); 3677 QualType StrTy = Context.getConstantArrayType( 3678 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3679 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3680 Expr *Lit = StringLiteral::Create( 3681 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3682 /*Pascal*/false, StrTy, &TokLoc, 1); 3683 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3684 } 3685 3686 case LOLR_Template: { 3687 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3688 // template), L is treated as a call fo the form 3689 // operator "" X <'c1', 'c2', ... 'ck'>() 3690 // where n is the source character sequence c1 c2 ... ck. 3691 TemplateArgumentListInfo ExplicitArgs; 3692 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3693 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3694 llvm::APSInt Value(CharBits, CharIsUnsigned); 3695 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3696 Value = TokSpelling[I]; 3697 TemplateArgument Arg(Context, Value, Context.CharTy); 3698 TemplateArgumentLocInfo ArgInfo; 3699 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3700 } 3701 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3702 &ExplicitArgs); 3703 } 3704 case LOLR_StringTemplate: 3705 llvm_unreachable("unexpected literal operator lookup result"); 3706 } 3707 } 3708 3709 Expr *Res; 3710 3711 if (Literal.isFixedPointLiteral()) { 3712 QualType Ty; 3713 3714 if (Literal.isAccum) { 3715 if (Literal.isHalf) { 3716 Ty = Context.ShortAccumTy; 3717 } else if (Literal.isLong) { 3718 Ty = Context.LongAccumTy; 3719 } else { 3720 Ty = Context.AccumTy; 3721 } 3722 } else if (Literal.isFract) { 3723 if (Literal.isHalf) { 3724 Ty = Context.ShortFractTy; 3725 } else if (Literal.isLong) { 3726 Ty = Context.LongFractTy; 3727 } else { 3728 Ty = Context.FractTy; 3729 } 3730 } 3731 3732 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3733 3734 bool isSigned = !Literal.isUnsigned; 3735 unsigned scale = Context.getFixedPointScale(Ty); 3736 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3737 3738 llvm::APInt Val(bit_width, 0, isSigned); 3739 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3740 bool ValIsZero = Val.isNullValue() && !Overflowed; 3741 3742 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3743 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3744 // Clause 6.4.4 - The value of a constant shall be in the range of 3745 // representable values for its type, with exception for constants of a 3746 // fract type with a value of exactly 1; such a constant shall denote 3747 // the maximal value for the type. 3748 --Val; 3749 else if (Val.ugt(MaxVal) || Overflowed) 3750 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3751 3752 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3753 Tok.getLocation(), scale); 3754 } else if (Literal.isFloatingLiteral()) { 3755 QualType Ty; 3756 if (Literal.isHalf){ 3757 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3758 Ty = Context.HalfTy; 3759 else { 3760 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3761 return ExprError(); 3762 } 3763 } else if (Literal.isFloat) 3764 Ty = Context.FloatTy; 3765 else if (Literal.isLong) 3766 Ty = Context.LongDoubleTy; 3767 else if (Literal.isFloat16) 3768 Ty = Context.Float16Ty; 3769 else if (Literal.isFloat128) 3770 Ty = Context.Float128Ty; 3771 else 3772 Ty = Context.DoubleTy; 3773 3774 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3775 3776 if (Ty == Context.DoubleTy) { 3777 if (getLangOpts().SinglePrecisionConstants) { 3778 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3779 if (BTy->getKind() != BuiltinType::Float) { 3780 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3781 } 3782 } else if (getLangOpts().OpenCL && 3783 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3784 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3785 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3786 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3787 } 3788 } 3789 } else if (!Literal.isIntegerLiteral()) { 3790 return ExprError(); 3791 } else { 3792 QualType Ty; 3793 3794 // 'long long' is a C99 or C++11 feature. 3795 if (!getLangOpts().C99 && Literal.isLongLong) { 3796 if (getLangOpts().CPlusPlus) 3797 Diag(Tok.getLocation(), 3798 getLangOpts().CPlusPlus11 ? 3799 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3800 else 3801 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3802 } 3803 3804 // Get the value in the widest-possible width. 3805 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3806 llvm::APInt ResultVal(MaxWidth, 0); 3807 3808 if (Literal.GetIntegerValue(ResultVal)) { 3809 // If this value didn't fit into uintmax_t, error and force to ull. 3810 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3811 << /* Unsigned */ 1; 3812 Ty = Context.UnsignedLongLongTy; 3813 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3814 "long long is not intmax_t?"); 3815 } else { 3816 // If this value fits into a ULL, try to figure out what else it fits into 3817 // according to the rules of C99 6.4.4.1p5. 3818 3819 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3820 // be an unsigned int. 3821 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3822 3823 // Check from smallest to largest, picking the smallest type we can. 3824 unsigned Width = 0; 3825 3826 // Microsoft specific integer suffixes are explicitly sized. 3827 if (Literal.MicrosoftInteger) { 3828 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3829 Width = 8; 3830 Ty = Context.CharTy; 3831 } else { 3832 Width = Literal.MicrosoftInteger; 3833 Ty = Context.getIntTypeForBitwidth(Width, 3834 /*Signed=*/!Literal.isUnsigned); 3835 } 3836 } 3837 3838 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3839 // Are int/unsigned possibilities? 3840 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3841 3842 // Does it fit in a unsigned int? 3843 if (ResultVal.isIntN(IntSize)) { 3844 // Does it fit in a signed int? 3845 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3846 Ty = Context.IntTy; 3847 else if (AllowUnsigned) 3848 Ty = Context.UnsignedIntTy; 3849 Width = IntSize; 3850 } 3851 } 3852 3853 // Are long/unsigned long possibilities? 3854 if (Ty.isNull() && !Literal.isLongLong) { 3855 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3856 3857 // Does it fit in a unsigned long? 3858 if (ResultVal.isIntN(LongSize)) { 3859 // Does it fit in a signed long? 3860 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3861 Ty = Context.LongTy; 3862 else if (AllowUnsigned) 3863 Ty = Context.UnsignedLongTy; 3864 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3865 // is compatible. 3866 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3867 const unsigned LongLongSize = 3868 Context.getTargetInfo().getLongLongWidth(); 3869 Diag(Tok.getLocation(), 3870 getLangOpts().CPlusPlus 3871 ? Literal.isLong 3872 ? diag::warn_old_implicitly_unsigned_long_cxx 3873 : /*C++98 UB*/ diag:: 3874 ext_old_implicitly_unsigned_long_cxx 3875 : diag::warn_old_implicitly_unsigned_long) 3876 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3877 : /*will be ill-formed*/ 1); 3878 Ty = Context.UnsignedLongTy; 3879 } 3880 Width = LongSize; 3881 } 3882 } 3883 3884 // Check long long if needed. 3885 if (Ty.isNull()) { 3886 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3887 3888 // Does it fit in a unsigned long long? 3889 if (ResultVal.isIntN(LongLongSize)) { 3890 // Does it fit in a signed long long? 3891 // To be compatible with MSVC, hex integer literals ending with the 3892 // LL or i64 suffix are always signed in Microsoft mode. 3893 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3894 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3895 Ty = Context.LongLongTy; 3896 else if (AllowUnsigned) 3897 Ty = Context.UnsignedLongLongTy; 3898 Width = LongLongSize; 3899 } 3900 } 3901 3902 // If we still couldn't decide a type, we probably have something that 3903 // does not fit in a signed long long, but has no U suffix. 3904 if (Ty.isNull()) { 3905 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3906 Ty = Context.UnsignedLongLongTy; 3907 Width = Context.getTargetInfo().getLongLongWidth(); 3908 } 3909 3910 if (ResultVal.getBitWidth() != Width) 3911 ResultVal = ResultVal.trunc(Width); 3912 } 3913 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3914 } 3915 3916 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3917 if (Literal.isImaginary) { 3918 Res = new (Context) ImaginaryLiteral(Res, 3919 Context.getComplexType(Res->getType())); 3920 3921 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3922 } 3923 return Res; 3924 } 3925 3926 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3927 assert(E && "ActOnParenExpr() missing expr"); 3928 return new (Context) ParenExpr(L, R, E); 3929 } 3930 3931 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3932 SourceLocation Loc, 3933 SourceRange ArgRange) { 3934 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3935 // scalar or vector data type argument..." 3936 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3937 // type (C99 6.2.5p18) or void. 3938 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3939 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3940 << T << ArgRange; 3941 return true; 3942 } 3943 3944 assert((T->isVoidType() || !T->isIncompleteType()) && 3945 "Scalar types should always be complete"); 3946 return false; 3947 } 3948 3949 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3950 SourceLocation Loc, 3951 SourceRange ArgRange, 3952 UnaryExprOrTypeTrait TraitKind) { 3953 // Invalid types must be hard errors for SFINAE in C++. 3954 if (S.LangOpts.CPlusPlus) 3955 return true; 3956 3957 // C99 6.5.3.4p1: 3958 if (T->isFunctionType() && 3959 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3960 TraitKind == UETT_PreferredAlignOf)) { 3961 // sizeof(function)/alignof(function) is allowed as an extension. 3962 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3963 << TraitKind << ArgRange; 3964 return false; 3965 } 3966 3967 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3968 // this is an error (OpenCL v1.1 s6.3.k) 3969 if (T->isVoidType()) { 3970 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3971 : diag::ext_sizeof_alignof_void_type; 3972 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3973 return false; 3974 } 3975 3976 return true; 3977 } 3978 3979 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3980 SourceLocation Loc, 3981 SourceRange ArgRange, 3982 UnaryExprOrTypeTrait TraitKind) { 3983 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3984 // runtime doesn't allow it. 3985 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3986 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3987 << T << (TraitKind == UETT_SizeOf) 3988 << ArgRange; 3989 return true; 3990 } 3991 3992 return false; 3993 } 3994 3995 /// Check whether E is a pointer from a decayed array type (the decayed 3996 /// pointer type is equal to T) and emit a warning if it is. 3997 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3998 Expr *E) { 3999 // Don't warn if the operation changed the type. 4000 if (T != E->getType()) 4001 return; 4002 4003 // Now look for array decays. 4004 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4005 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4006 return; 4007 4008 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4009 << ICE->getType() 4010 << ICE->getSubExpr()->getType(); 4011 } 4012 4013 /// Check the constraints on expression operands to unary type expression 4014 /// and type traits. 4015 /// 4016 /// Completes any types necessary and validates the constraints on the operand 4017 /// expression. The logic mostly mirrors the type-based overload, but may modify 4018 /// the expression as it completes the type for that expression through template 4019 /// instantiation, etc. 4020 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4021 UnaryExprOrTypeTrait ExprKind) { 4022 QualType ExprTy = E->getType(); 4023 assert(!ExprTy->isReferenceType()); 4024 4025 bool IsUnevaluatedOperand = 4026 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4027 ExprKind == UETT_PreferredAlignOf); 4028 if (IsUnevaluatedOperand) { 4029 ExprResult Result = CheckUnevaluatedOperand(E); 4030 if (Result.isInvalid()) 4031 return true; 4032 E = Result.get(); 4033 } 4034 4035 if (ExprKind == UETT_VecStep) 4036 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4037 E->getSourceRange()); 4038 4039 // Whitelist some types as extensions 4040 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4041 E->getSourceRange(), ExprKind)) 4042 return false; 4043 4044 // 'alignof' applied to an expression only requires the base element type of 4045 // the expression to be complete. 'sizeof' requires the expression's type to 4046 // be complete (and will attempt to complete it if it's an array of unknown 4047 // bound). 4048 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4049 if (RequireCompleteSizedType( 4050 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4051 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4052 E->getSourceRange())) 4053 return true; 4054 } else { 4055 if (RequireCompleteSizedExprType( 4056 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4057 E->getSourceRange())) 4058 return true; 4059 } 4060 4061 // Completing the expression's type may have changed it. 4062 ExprTy = E->getType(); 4063 assert(!ExprTy->isReferenceType()); 4064 4065 if (ExprTy->isFunctionType()) { 4066 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4067 << ExprKind << E->getSourceRange(); 4068 return true; 4069 } 4070 4071 // The operand for sizeof and alignof is in an unevaluated expression context, 4072 // so side effects could result in unintended consequences. 4073 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4074 E->HasSideEffects(Context, false)) 4075 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4076 4077 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4078 E->getSourceRange(), ExprKind)) 4079 return true; 4080 4081 if (ExprKind == UETT_SizeOf) { 4082 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4083 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4084 QualType OType = PVD->getOriginalType(); 4085 QualType Type = PVD->getType(); 4086 if (Type->isPointerType() && OType->isArrayType()) { 4087 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4088 << Type << OType; 4089 Diag(PVD->getLocation(), diag::note_declared_at); 4090 } 4091 } 4092 } 4093 4094 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4095 // decays into a pointer and returns an unintended result. This is most 4096 // likely a typo for "sizeof(array) op x". 4097 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4098 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4099 BO->getLHS()); 4100 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4101 BO->getRHS()); 4102 } 4103 } 4104 4105 return false; 4106 } 4107 4108 /// Check the constraints on operands to unary expression and type 4109 /// traits. 4110 /// 4111 /// This will complete any types necessary, and validate the various constraints 4112 /// on those operands. 4113 /// 4114 /// The UsualUnaryConversions() function is *not* called by this routine. 4115 /// C99 6.3.2.1p[2-4] all state: 4116 /// Except when it is the operand of the sizeof operator ... 4117 /// 4118 /// C++ [expr.sizeof]p4 4119 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4120 /// standard conversions are not applied to the operand of sizeof. 4121 /// 4122 /// This policy is followed for all of the unary trait expressions. 4123 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4124 SourceLocation OpLoc, 4125 SourceRange ExprRange, 4126 UnaryExprOrTypeTrait ExprKind) { 4127 if (ExprType->isDependentType()) 4128 return false; 4129 4130 // C++ [expr.sizeof]p2: 4131 // When applied to a reference or a reference type, the result 4132 // is the size of the referenced type. 4133 // C++11 [expr.alignof]p3: 4134 // When alignof is applied to a reference type, the result 4135 // shall be the alignment of the referenced type. 4136 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4137 ExprType = Ref->getPointeeType(); 4138 4139 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4140 // When alignof or _Alignof is applied to an array type, the result 4141 // is the alignment of the element type. 4142 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4143 ExprKind == UETT_OpenMPRequiredSimdAlign) 4144 ExprType = Context.getBaseElementType(ExprType); 4145 4146 if (ExprKind == UETT_VecStep) 4147 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4148 4149 // Whitelist some types as extensions 4150 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4151 ExprKind)) 4152 return false; 4153 4154 if (RequireCompleteSizedType( 4155 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4156 ExprKind, ExprRange)) 4157 return true; 4158 4159 if (ExprType->isFunctionType()) { 4160 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4161 << ExprKind << ExprRange; 4162 return true; 4163 } 4164 4165 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4166 ExprKind)) 4167 return true; 4168 4169 return false; 4170 } 4171 4172 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4173 // Cannot know anything else if the expression is dependent. 4174 if (E->isTypeDependent()) 4175 return false; 4176 4177 if (E->getObjectKind() == OK_BitField) { 4178 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4179 << 1 << E->getSourceRange(); 4180 return true; 4181 } 4182 4183 ValueDecl *D = nullptr; 4184 Expr *Inner = E->IgnoreParens(); 4185 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4186 D = DRE->getDecl(); 4187 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4188 D = ME->getMemberDecl(); 4189 } 4190 4191 // If it's a field, require the containing struct to have a 4192 // complete definition so that we can compute the layout. 4193 // 4194 // This can happen in C++11 onwards, either by naming the member 4195 // in a way that is not transformed into a member access expression 4196 // (in an unevaluated operand, for instance), or by naming the member 4197 // in a trailing-return-type. 4198 // 4199 // For the record, since __alignof__ on expressions is a GCC 4200 // extension, GCC seems to permit this but always gives the 4201 // nonsensical answer 0. 4202 // 4203 // We don't really need the layout here --- we could instead just 4204 // directly check for all the appropriate alignment-lowing 4205 // attributes --- but that would require duplicating a lot of 4206 // logic that just isn't worth duplicating for such a marginal 4207 // use-case. 4208 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4209 // Fast path this check, since we at least know the record has a 4210 // definition if we can find a member of it. 4211 if (!FD->getParent()->isCompleteDefinition()) { 4212 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4213 << E->getSourceRange(); 4214 return true; 4215 } 4216 4217 // Otherwise, if it's a field, and the field doesn't have 4218 // reference type, then it must have a complete type (or be a 4219 // flexible array member, which we explicitly want to 4220 // white-list anyway), which makes the following checks trivial. 4221 if (!FD->getType()->isReferenceType()) 4222 return false; 4223 } 4224 4225 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4226 } 4227 4228 bool Sema::CheckVecStepExpr(Expr *E) { 4229 E = E->IgnoreParens(); 4230 4231 // Cannot know anything else if the expression is dependent. 4232 if (E->isTypeDependent()) 4233 return false; 4234 4235 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4236 } 4237 4238 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4239 CapturingScopeInfo *CSI) { 4240 assert(T->isVariablyModifiedType()); 4241 assert(CSI != nullptr); 4242 4243 // We're going to walk down into the type and look for VLA expressions. 4244 do { 4245 const Type *Ty = T.getTypePtr(); 4246 switch (Ty->getTypeClass()) { 4247 #define TYPE(Class, Base) 4248 #define ABSTRACT_TYPE(Class, Base) 4249 #define NON_CANONICAL_TYPE(Class, Base) 4250 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4251 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4252 #include "clang/AST/TypeNodes.inc" 4253 T = QualType(); 4254 break; 4255 // These types are never variably-modified. 4256 case Type::Builtin: 4257 case Type::Complex: 4258 case Type::Vector: 4259 case Type::ExtVector: 4260 case Type::Record: 4261 case Type::Enum: 4262 case Type::Elaborated: 4263 case Type::TemplateSpecialization: 4264 case Type::ObjCObject: 4265 case Type::ObjCInterface: 4266 case Type::ObjCObjectPointer: 4267 case Type::ObjCTypeParam: 4268 case Type::Pipe: 4269 case Type::ExtInt: 4270 llvm_unreachable("type class is never variably-modified!"); 4271 case Type::Adjusted: 4272 T = cast<AdjustedType>(Ty)->getOriginalType(); 4273 break; 4274 case Type::Decayed: 4275 T = cast<DecayedType>(Ty)->getPointeeType(); 4276 break; 4277 case Type::Pointer: 4278 T = cast<PointerType>(Ty)->getPointeeType(); 4279 break; 4280 case Type::BlockPointer: 4281 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4282 break; 4283 case Type::LValueReference: 4284 case Type::RValueReference: 4285 T = cast<ReferenceType>(Ty)->getPointeeType(); 4286 break; 4287 case Type::MemberPointer: 4288 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4289 break; 4290 case Type::ConstantArray: 4291 case Type::IncompleteArray: 4292 // Losing element qualification here is fine. 4293 T = cast<ArrayType>(Ty)->getElementType(); 4294 break; 4295 case Type::VariableArray: { 4296 // Losing element qualification here is fine. 4297 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4298 4299 // Unknown size indication requires no size computation. 4300 // Otherwise, evaluate and record it. 4301 auto Size = VAT->getSizeExpr(); 4302 if (Size && !CSI->isVLATypeCaptured(VAT) && 4303 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4304 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4305 4306 T = VAT->getElementType(); 4307 break; 4308 } 4309 case Type::FunctionProto: 4310 case Type::FunctionNoProto: 4311 T = cast<FunctionType>(Ty)->getReturnType(); 4312 break; 4313 case Type::Paren: 4314 case Type::TypeOf: 4315 case Type::UnaryTransform: 4316 case Type::Attributed: 4317 case Type::SubstTemplateTypeParm: 4318 case Type::PackExpansion: 4319 case Type::MacroQualified: 4320 // Keep walking after single level desugaring. 4321 T = T.getSingleStepDesugaredType(Context); 4322 break; 4323 case Type::Typedef: 4324 T = cast<TypedefType>(Ty)->desugar(); 4325 break; 4326 case Type::Decltype: 4327 T = cast<DecltypeType>(Ty)->desugar(); 4328 break; 4329 case Type::Auto: 4330 case Type::DeducedTemplateSpecialization: 4331 T = cast<DeducedType>(Ty)->getDeducedType(); 4332 break; 4333 case Type::TypeOfExpr: 4334 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4335 break; 4336 case Type::Atomic: 4337 T = cast<AtomicType>(Ty)->getValueType(); 4338 break; 4339 } 4340 } while (!T.isNull() && T->isVariablyModifiedType()); 4341 } 4342 4343 /// Build a sizeof or alignof expression given a type operand. 4344 ExprResult 4345 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4346 SourceLocation OpLoc, 4347 UnaryExprOrTypeTrait ExprKind, 4348 SourceRange R) { 4349 if (!TInfo) 4350 return ExprError(); 4351 4352 QualType T = TInfo->getType(); 4353 4354 if (!T->isDependentType() && 4355 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4356 return ExprError(); 4357 4358 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4359 if (auto *TT = T->getAs<TypedefType>()) { 4360 for (auto I = FunctionScopes.rbegin(), 4361 E = std::prev(FunctionScopes.rend()); 4362 I != E; ++I) { 4363 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4364 if (CSI == nullptr) 4365 break; 4366 DeclContext *DC = nullptr; 4367 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4368 DC = LSI->CallOperator; 4369 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4370 DC = CRSI->TheCapturedDecl; 4371 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4372 DC = BSI->TheDecl; 4373 if (DC) { 4374 if (DC->containsDecl(TT->getDecl())) 4375 break; 4376 captureVariablyModifiedType(Context, T, CSI); 4377 } 4378 } 4379 } 4380 } 4381 4382 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4383 return new (Context) UnaryExprOrTypeTraitExpr( 4384 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4385 } 4386 4387 /// Build a sizeof or alignof expression given an expression 4388 /// operand. 4389 ExprResult 4390 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4391 UnaryExprOrTypeTrait ExprKind) { 4392 ExprResult PE = CheckPlaceholderExpr(E); 4393 if (PE.isInvalid()) 4394 return ExprError(); 4395 4396 E = PE.get(); 4397 4398 // Verify that the operand is valid. 4399 bool isInvalid = false; 4400 if (E->isTypeDependent()) { 4401 // Delay type-checking for type-dependent expressions. 4402 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4403 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4404 } else if (ExprKind == UETT_VecStep) { 4405 isInvalid = CheckVecStepExpr(E); 4406 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4407 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4408 isInvalid = true; 4409 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4410 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4411 isInvalid = true; 4412 } else { 4413 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4414 } 4415 4416 if (isInvalid) 4417 return ExprError(); 4418 4419 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4420 PE = TransformToPotentiallyEvaluated(E); 4421 if (PE.isInvalid()) return ExprError(); 4422 E = PE.get(); 4423 } 4424 4425 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4426 return new (Context) UnaryExprOrTypeTraitExpr( 4427 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4428 } 4429 4430 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4431 /// expr and the same for @c alignof and @c __alignof 4432 /// Note that the ArgRange is invalid if isType is false. 4433 ExprResult 4434 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4435 UnaryExprOrTypeTrait ExprKind, bool IsType, 4436 void *TyOrEx, SourceRange ArgRange) { 4437 // If error parsing type, ignore. 4438 if (!TyOrEx) return ExprError(); 4439 4440 if (IsType) { 4441 TypeSourceInfo *TInfo; 4442 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4443 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4444 } 4445 4446 Expr *ArgEx = (Expr *)TyOrEx; 4447 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4448 return Result; 4449 } 4450 4451 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4452 bool IsReal) { 4453 if (V.get()->isTypeDependent()) 4454 return S.Context.DependentTy; 4455 4456 // _Real and _Imag are only l-values for normal l-values. 4457 if (V.get()->getObjectKind() != OK_Ordinary) { 4458 V = S.DefaultLvalueConversion(V.get()); 4459 if (V.isInvalid()) 4460 return QualType(); 4461 } 4462 4463 // These operators return the element type of a complex type. 4464 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4465 return CT->getElementType(); 4466 4467 // Otherwise they pass through real integer and floating point types here. 4468 if (V.get()->getType()->isArithmeticType()) 4469 return V.get()->getType(); 4470 4471 // Test for placeholders. 4472 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4473 if (PR.isInvalid()) return QualType(); 4474 if (PR.get() != V.get()) { 4475 V = PR; 4476 return CheckRealImagOperand(S, V, Loc, IsReal); 4477 } 4478 4479 // Reject anything else. 4480 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4481 << (IsReal ? "__real" : "__imag"); 4482 return QualType(); 4483 } 4484 4485 4486 4487 ExprResult 4488 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4489 tok::TokenKind Kind, Expr *Input) { 4490 UnaryOperatorKind Opc; 4491 switch (Kind) { 4492 default: llvm_unreachable("Unknown unary op!"); 4493 case tok::plusplus: Opc = UO_PostInc; break; 4494 case tok::minusminus: Opc = UO_PostDec; break; 4495 } 4496 4497 // Since this might is a postfix expression, get rid of ParenListExprs. 4498 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4499 if (Result.isInvalid()) return ExprError(); 4500 Input = Result.get(); 4501 4502 return BuildUnaryOp(S, OpLoc, Opc, Input); 4503 } 4504 4505 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4506 /// 4507 /// \return true on error 4508 static bool checkArithmeticOnObjCPointer(Sema &S, 4509 SourceLocation opLoc, 4510 Expr *op) { 4511 assert(op->getType()->isObjCObjectPointerType()); 4512 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4513 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4514 return false; 4515 4516 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4517 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4518 << op->getSourceRange(); 4519 return true; 4520 } 4521 4522 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4523 auto *BaseNoParens = Base->IgnoreParens(); 4524 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4525 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4526 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4527 } 4528 4529 ExprResult 4530 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4531 Expr *idx, SourceLocation rbLoc) { 4532 if (base && !base->getType().isNull() && 4533 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4534 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4535 /*Length=*/nullptr, rbLoc); 4536 4537 // Since this might be a postfix expression, get rid of ParenListExprs. 4538 if (isa<ParenListExpr>(base)) { 4539 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4540 if (result.isInvalid()) return ExprError(); 4541 base = result.get(); 4542 } 4543 4544 // A comma-expression as the index is deprecated in C++2a onwards. 4545 if (getLangOpts().CPlusPlus2a && 4546 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4547 (isa<CXXOperatorCallExpr>(idx) && 4548 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4549 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4550 << SourceRange(base->getBeginLoc(), rbLoc); 4551 } 4552 4553 // Handle any non-overload placeholder types in the base and index 4554 // expressions. We can't handle overloads here because the other 4555 // operand might be an overloadable type, in which case the overload 4556 // resolution for the operator overload should get the first crack 4557 // at the overload. 4558 bool IsMSPropertySubscript = false; 4559 if (base->getType()->isNonOverloadPlaceholderType()) { 4560 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4561 if (!IsMSPropertySubscript) { 4562 ExprResult result = CheckPlaceholderExpr(base); 4563 if (result.isInvalid()) 4564 return ExprError(); 4565 base = result.get(); 4566 } 4567 } 4568 if (idx->getType()->isNonOverloadPlaceholderType()) { 4569 ExprResult result = CheckPlaceholderExpr(idx); 4570 if (result.isInvalid()) return ExprError(); 4571 idx = result.get(); 4572 } 4573 4574 // Build an unanalyzed expression if either operand is type-dependent. 4575 if (getLangOpts().CPlusPlus && 4576 (base->isTypeDependent() || idx->isTypeDependent())) { 4577 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4578 VK_LValue, OK_Ordinary, rbLoc); 4579 } 4580 4581 // MSDN, property (C++) 4582 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4583 // This attribute can also be used in the declaration of an empty array in a 4584 // class or structure definition. For example: 4585 // __declspec(property(get=GetX, put=PutX)) int x[]; 4586 // The above statement indicates that x[] can be used with one or more array 4587 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4588 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4589 if (IsMSPropertySubscript) { 4590 // Build MS property subscript expression if base is MS property reference 4591 // or MS property subscript. 4592 return new (Context) MSPropertySubscriptExpr( 4593 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4594 } 4595 4596 // Use C++ overloaded-operator rules if either operand has record 4597 // type. The spec says to do this if either type is *overloadable*, 4598 // but enum types can't declare subscript operators or conversion 4599 // operators, so there's nothing interesting for overload resolution 4600 // to do if there aren't any record types involved. 4601 // 4602 // ObjC pointers have their own subscripting logic that is not tied 4603 // to overload resolution and so should not take this path. 4604 if (getLangOpts().CPlusPlus && 4605 (base->getType()->isRecordType() || 4606 (!base->getType()->isObjCObjectPointerType() && 4607 idx->getType()->isRecordType()))) { 4608 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4609 } 4610 4611 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4612 4613 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4614 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4615 4616 return Res; 4617 } 4618 4619 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4620 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4621 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4622 4623 // For expressions like `&(*s).b`, the base is recorded and what should be 4624 // checked. 4625 const MemberExpr *Member = nullptr; 4626 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4627 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4628 4629 LastRecord.PossibleDerefs.erase(StrippedExpr); 4630 } 4631 4632 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4633 QualType ResultTy = E->getType(); 4634 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4635 4636 // Bail if the element is an array since it is not memory access. 4637 if (isa<ArrayType>(ResultTy)) 4638 return; 4639 4640 if (ResultTy->hasAttr(attr::NoDeref)) { 4641 LastRecord.PossibleDerefs.insert(E); 4642 return; 4643 } 4644 4645 // Check if the base type is a pointer to a member access of a struct 4646 // marked with noderef. 4647 const Expr *Base = E->getBase(); 4648 QualType BaseTy = Base->getType(); 4649 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4650 // Not a pointer access 4651 return; 4652 4653 const MemberExpr *Member = nullptr; 4654 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4655 Member->isArrow()) 4656 Base = Member->getBase(); 4657 4658 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4659 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4660 LastRecord.PossibleDerefs.insert(E); 4661 } 4662 } 4663 4664 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4665 Expr *LowerBound, 4666 SourceLocation ColonLoc, Expr *Length, 4667 SourceLocation RBLoc) { 4668 if (Base->getType()->isPlaceholderType() && 4669 !Base->getType()->isSpecificPlaceholderType( 4670 BuiltinType::OMPArraySection)) { 4671 ExprResult Result = CheckPlaceholderExpr(Base); 4672 if (Result.isInvalid()) 4673 return ExprError(); 4674 Base = Result.get(); 4675 } 4676 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4677 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4678 if (Result.isInvalid()) 4679 return ExprError(); 4680 Result = DefaultLvalueConversion(Result.get()); 4681 if (Result.isInvalid()) 4682 return ExprError(); 4683 LowerBound = Result.get(); 4684 } 4685 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4686 ExprResult Result = CheckPlaceholderExpr(Length); 4687 if (Result.isInvalid()) 4688 return ExprError(); 4689 Result = DefaultLvalueConversion(Result.get()); 4690 if (Result.isInvalid()) 4691 return ExprError(); 4692 Length = Result.get(); 4693 } 4694 4695 // Build an unanalyzed expression if either operand is type-dependent. 4696 if (Base->isTypeDependent() || 4697 (LowerBound && 4698 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4699 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4700 return new (Context) 4701 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4702 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4703 } 4704 4705 // Perform default conversions. 4706 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4707 QualType ResultTy; 4708 if (OriginalTy->isAnyPointerType()) { 4709 ResultTy = OriginalTy->getPointeeType(); 4710 } else if (OriginalTy->isArrayType()) { 4711 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4712 } else { 4713 return ExprError( 4714 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4715 << Base->getSourceRange()); 4716 } 4717 // C99 6.5.2.1p1 4718 if (LowerBound) { 4719 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4720 LowerBound); 4721 if (Res.isInvalid()) 4722 return ExprError(Diag(LowerBound->getExprLoc(), 4723 diag::err_omp_typecheck_section_not_integer) 4724 << 0 << LowerBound->getSourceRange()); 4725 LowerBound = Res.get(); 4726 4727 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4728 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4729 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4730 << 0 << LowerBound->getSourceRange(); 4731 } 4732 if (Length) { 4733 auto Res = 4734 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4735 if (Res.isInvalid()) 4736 return ExprError(Diag(Length->getExprLoc(), 4737 diag::err_omp_typecheck_section_not_integer) 4738 << 1 << Length->getSourceRange()); 4739 Length = Res.get(); 4740 4741 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4742 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4743 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4744 << 1 << Length->getSourceRange(); 4745 } 4746 4747 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4748 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4749 // type. Note that functions are not objects, and that (in C99 parlance) 4750 // incomplete types are not object types. 4751 if (ResultTy->isFunctionType()) { 4752 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4753 << ResultTy << Base->getSourceRange(); 4754 return ExprError(); 4755 } 4756 4757 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4758 diag::err_omp_section_incomplete_type, Base)) 4759 return ExprError(); 4760 4761 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4762 Expr::EvalResult Result; 4763 if (LowerBound->EvaluateAsInt(Result, Context)) { 4764 // OpenMP 4.5, [2.4 Array Sections] 4765 // The array section must be a subset of the original array. 4766 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4767 if (LowerBoundValue.isNegative()) { 4768 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4769 << LowerBound->getSourceRange(); 4770 return ExprError(); 4771 } 4772 } 4773 } 4774 4775 if (Length) { 4776 Expr::EvalResult Result; 4777 if (Length->EvaluateAsInt(Result, Context)) { 4778 // OpenMP 4.5, [2.4 Array Sections] 4779 // The length must evaluate to non-negative integers. 4780 llvm::APSInt LengthValue = Result.Val.getInt(); 4781 if (LengthValue.isNegative()) { 4782 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4783 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4784 << Length->getSourceRange(); 4785 return ExprError(); 4786 } 4787 } 4788 } else if (ColonLoc.isValid() && 4789 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4790 !OriginalTy->isVariableArrayType()))) { 4791 // OpenMP 4.5, [2.4 Array Sections] 4792 // When the size of the array dimension is not known, the length must be 4793 // specified explicitly. 4794 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4795 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4796 return ExprError(); 4797 } 4798 4799 if (!Base->getType()->isSpecificPlaceholderType( 4800 BuiltinType::OMPArraySection)) { 4801 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4802 if (Result.isInvalid()) 4803 return ExprError(); 4804 Base = Result.get(); 4805 } 4806 return new (Context) 4807 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4808 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4809 } 4810 4811 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4812 SourceLocation RParenLoc, 4813 ArrayRef<Expr *> Dims, 4814 ArrayRef<SourceRange> Brackets) { 4815 if (Base->getType()->isPlaceholderType()) { 4816 ExprResult Result = CheckPlaceholderExpr(Base); 4817 if (Result.isInvalid()) 4818 return ExprError(); 4819 Result = DefaultLvalueConversion(Result.get()); 4820 if (Result.isInvalid()) 4821 return ExprError(); 4822 Base = Result.get(); 4823 } 4824 QualType BaseTy = Base->getType(); 4825 // Delay analysis of the types/expressions if instantiation/specialization is 4826 // required. 4827 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4828 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4829 LParenLoc, RParenLoc, Dims, Brackets); 4830 if (!BaseTy->isPointerType() || 4831 (!Base->isTypeDependent() && 4832 BaseTy->getPointeeType()->isIncompleteType())) 4833 return ExprError(Diag(Base->getExprLoc(), 4834 diag::err_omp_non_pointer_type_array_shaping_base) 4835 << Base->getSourceRange()); 4836 4837 SmallVector<Expr *, 4> NewDims; 4838 bool ErrorFound = false; 4839 for (Expr *Dim : Dims) { 4840 if (Dim->getType()->isPlaceholderType()) { 4841 ExprResult Result = CheckPlaceholderExpr(Dim); 4842 if (Result.isInvalid()) { 4843 ErrorFound = true; 4844 continue; 4845 } 4846 Result = DefaultLvalueConversion(Result.get()); 4847 if (Result.isInvalid()) { 4848 ErrorFound = true; 4849 continue; 4850 } 4851 Dim = Result.get(); 4852 } 4853 if (!Dim->isTypeDependent()) { 4854 ExprResult Result = 4855 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4856 if (Result.isInvalid()) { 4857 ErrorFound = true; 4858 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 4859 << Dim->getSourceRange(); 4860 continue; 4861 } 4862 Dim = Result.get(); 4863 Expr::EvalResult EvResult; 4864 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 4865 // OpenMP 5.0, [2.1.4 Array Shaping] 4866 // Each si is an integral type expression that must evaluate to a 4867 // positive integer. 4868 llvm::APSInt Value = EvResult.Val.getInt(); 4869 if (!Value.isStrictlyPositive()) { 4870 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 4871 << Value.toString(/*Radix=*/10, /*Signed=*/true) 4872 << Dim->getSourceRange(); 4873 ErrorFound = true; 4874 continue; 4875 } 4876 } 4877 } 4878 NewDims.push_back(Dim); 4879 } 4880 if (ErrorFound) 4881 return ExprError(); 4882 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 4883 LParenLoc, RParenLoc, NewDims, Brackets); 4884 } 4885 4886 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 4887 SourceLocation LLoc, SourceLocation RLoc, 4888 ArrayRef<OMPIteratorData> Data) { 4889 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 4890 bool IsCorrect = true; 4891 for (const OMPIteratorData &D : Data) { 4892 TypeSourceInfo *TInfo = nullptr; 4893 SourceLocation StartLoc; 4894 QualType DeclTy; 4895 if (!D.Type.getAsOpaquePtr()) { 4896 // OpenMP 5.0, 2.1.6 Iterators 4897 // In an iterator-specifier, if the iterator-type is not specified then 4898 // the type of that iterator is of int type. 4899 DeclTy = Context.IntTy; 4900 StartLoc = D.DeclIdentLoc; 4901 } else { 4902 DeclTy = GetTypeFromParser(D.Type, &TInfo); 4903 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 4904 } 4905 4906 bool IsDeclTyDependent = DeclTy->isDependentType() || 4907 DeclTy->containsUnexpandedParameterPack() || 4908 DeclTy->isInstantiationDependentType(); 4909 if (!IsDeclTyDependent) { 4910 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 4911 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4912 // The iterator-type must be an integral or pointer type. 4913 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4914 << DeclTy; 4915 IsCorrect = false; 4916 continue; 4917 } 4918 if (DeclTy.isConstant(Context)) { 4919 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4920 // The iterator-type must not be const qualified. 4921 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4922 << DeclTy; 4923 IsCorrect = false; 4924 continue; 4925 } 4926 } 4927 4928 // Iterator declaration. 4929 assert(D.DeclIdent && "Identifier expected."); 4930 // Always try to create iterator declarator to avoid extra error messages 4931 // about unknown declarations use. 4932 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 4933 D.DeclIdent, DeclTy, TInfo, SC_None); 4934 VD->setImplicit(); 4935 if (S) { 4936 // Check for conflicting previous declaration. 4937 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 4938 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4939 ForVisibleRedeclaration); 4940 Previous.suppressDiagnostics(); 4941 LookupName(Previous, S); 4942 4943 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 4944 /*AllowInlineNamespace=*/false); 4945 if (!Previous.empty()) { 4946 NamedDecl *Old = Previous.getRepresentativeDecl(); 4947 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 4948 Diag(Old->getLocation(), diag::note_previous_definition); 4949 } else { 4950 PushOnScopeChains(VD, S); 4951 } 4952 } else { 4953 CurContext->addDecl(VD); 4954 } 4955 Expr *Begin = D.Range.Begin; 4956 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 4957 ExprResult BeginRes = 4958 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 4959 Begin = BeginRes.get(); 4960 } 4961 Expr *End = D.Range.End; 4962 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 4963 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 4964 End = EndRes.get(); 4965 } 4966 Expr *Step = D.Range.Step; 4967 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 4968 if (!Step->getType()->isIntegralType(Context)) { 4969 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 4970 << Step << Step->getSourceRange(); 4971 IsCorrect = false; 4972 continue; 4973 } 4974 llvm::APSInt Result; 4975 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 4976 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 4977 // If the step expression of a range-specification equals zero, the 4978 // behavior is unspecified. 4979 if (IsConstant && Result.isNullValue()) { 4980 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 4981 << Step << Step->getSourceRange(); 4982 IsCorrect = false; 4983 continue; 4984 } 4985 } 4986 if (!Begin || !End || !IsCorrect) { 4987 IsCorrect = false; 4988 continue; 4989 } 4990 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 4991 IDElem.IteratorDecl = VD; 4992 IDElem.AssignmentLoc = D.AssignLoc; 4993 IDElem.Range.Begin = Begin; 4994 IDElem.Range.End = End; 4995 IDElem.Range.Step = Step; 4996 IDElem.ColonLoc = D.ColonLoc; 4997 IDElem.SecondColonLoc = D.SecColonLoc; 4998 } 4999 if (!IsCorrect) { 5000 // Invalidate all created iterator declarations if error is found. 5001 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5002 if (Decl *ID = D.IteratorDecl) 5003 ID->setInvalidDecl(); 5004 } 5005 return ExprError(); 5006 } 5007 SmallVector<OMPIteratorHelperData, 4> Helpers; 5008 if (!CurContext->isDependentContext()) { 5009 // Build number of ityeration for each iteration range. 5010 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5011 // ((Begini-Stepi-1-Endi) / -Stepi); 5012 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5013 // (Endi - Begini) 5014 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5015 D.Range.Begin); 5016 if(!Res.isUsable()) { 5017 IsCorrect = false; 5018 continue; 5019 } 5020 ExprResult St, St1; 5021 if (D.Range.Step) { 5022 St = D.Range.Step; 5023 // (Endi - Begini) + Stepi 5024 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5025 if (!Res.isUsable()) { 5026 IsCorrect = false; 5027 continue; 5028 } 5029 // (Endi - Begini) + Stepi - 1 5030 Res = 5031 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5032 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5033 if (!Res.isUsable()) { 5034 IsCorrect = false; 5035 continue; 5036 } 5037 // ((Endi - Begini) + Stepi - 1) / Stepi 5038 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5039 if (!Res.isUsable()) { 5040 IsCorrect = false; 5041 continue; 5042 } 5043 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5044 // (Begini - Endi) 5045 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5046 D.Range.Begin, D.Range.End); 5047 if (!Res1.isUsable()) { 5048 IsCorrect = false; 5049 continue; 5050 } 5051 // (Begini - Endi) - Stepi 5052 Res1 = 5053 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5054 if (!Res1.isUsable()) { 5055 IsCorrect = false; 5056 continue; 5057 } 5058 // (Begini - Endi) - Stepi - 1 5059 Res1 = 5060 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5061 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5062 if (!Res1.isUsable()) { 5063 IsCorrect = false; 5064 continue; 5065 } 5066 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5067 Res1 = 5068 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5069 if (!Res1.isUsable()) { 5070 IsCorrect = false; 5071 continue; 5072 } 5073 // Stepi > 0. 5074 ExprResult CmpRes = 5075 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5076 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5077 if (!CmpRes.isUsable()) { 5078 IsCorrect = false; 5079 continue; 5080 } 5081 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5082 Res.get(), Res1.get()); 5083 if (!Res.isUsable()) { 5084 IsCorrect = false; 5085 continue; 5086 } 5087 } 5088 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5089 if (!Res.isUsable()) { 5090 IsCorrect = false; 5091 continue; 5092 } 5093 5094 // Build counter update. 5095 // Build counter. 5096 auto *CounterVD = 5097 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5098 D.IteratorDecl->getBeginLoc(), nullptr, 5099 Res.get()->getType(), nullptr, SC_None); 5100 CounterVD->setImplicit(); 5101 ExprResult RefRes = 5102 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5103 D.IteratorDecl->getBeginLoc()); 5104 // Build counter update. 5105 // I = Begini + counter * Stepi; 5106 ExprResult UpdateRes; 5107 if (D.Range.Step) { 5108 UpdateRes = CreateBuiltinBinOp( 5109 D.AssignmentLoc, BO_Mul, 5110 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5111 } else { 5112 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5113 } 5114 if (!UpdateRes.isUsable()) { 5115 IsCorrect = false; 5116 continue; 5117 } 5118 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5119 UpdateRes.get()); 5120 if (!UpdateRes.isUsable()) { 5121 IsCorrect = false; 5122 continue; 5123 } 5124 ExprResult VDRes = 5125 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5126 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5127 D.IteratorDecl->getBeginLoc()); 5128 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5129 UpdateRes.get()); 5130 if (!UpdateRes.isUsable()) { 5131 IsCorrect = false; 5132 continue; 5133 } 5134 UpdateRes = 5135 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5136 if (!UpdateRes.isUsable()) { 5137 IsCorrect = false; 5138 continue; 5139 } 5140 ExprResult CounterUpdateRes = 5141 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5142 if (!CounterUpdateRes.isUsable()) { 5143 IsCorrect = false; 5144 continue; 5145 } 5146 CounterUpdateRes = 5147 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5148 if (!CounterUpdateRes.isUsable()) { 5149 IsCorrect = false; 5150 continue; 5151 } 5152 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5153 HD.CounterVD = CounterVD; 5154 HD.Upper = Res.get(); 5155 HD.Update = UpdateRes.get(); 5156 HD.CounterUpdate = CounterUpdateRes.get(); 5157 } 5158 } else { 5159 Helpers.assign(ID.size(), {}); 5160 } 5161 if (!IsCorrect) { 5162 // Invalidate all created iterator declarations if error is found. 5163 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5164 if (Decl *ID = D.IteratorDecl) 5165 ID->setInvalidDecl(); 5166 } 5167 return ExprError(); 5168 } 5169 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5170 LLoc, RLoc, ID, Helpers); 5171 } 5172 5173 ExprResult 5174 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5175 Expr *Idx, SourceLocation RLoc) { 5176 Expr *LHSExp = Base; 5177 Expr *RHSExp = Idx; 5178 5179 ExprValueKind VK = VK_LValue; 5180 ExprObjectKind OK = OK_Ordinary; 5181 5182 // Per C++ core issue 1213, the result is an xvalue if either operand is 5183 // a non-lvalue array, and an lvalue otherwise. 5184 if (getLangOpts().CPlusPlus11) { 5185 for (auto *Op : {LHSExp, RHSExp}) { 5186 Op = Op->IgnoreImplicit(); 5187 if (Op->getType()->isArrayType() && !Op->isLValue()) 5188 VK = VK_XValue; 5189 } 5190 } 5191 5192 // Perform default conversions. 5193 if (!LHSExp->getType()->getAs<VectorType>()) { 5194 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5195 if (Result.isInvalid()) 5196 return ExprError(); 5197 LHSExp = Result.get(); 5198 } 5199 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5200 if (Result.isInvalid()) 5201 return ExprError(); 5202 RHSExp = Result.get(); 5203 5204 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5205 5206 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5207 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5208 // in the subscript position. As a result, we need to derive the array base 5209 // and index from the expression types. 5210 Expr *BaseExpr, *IndexExpr; 5211 QualType ResultType; 5212 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5213 BaseExpr = LHSExp; 5214 IndexExpr = RHSExp; 5215 ResultType = Context.DependentTy; 5216 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5217 BaseExpr = LHSExp; 5218 IndexExpr = RHSExp; 5219 ResultType = PTy->getPointeeType(); 5220 } else if (const ObjCObjectPointerType *PTy = 5221 LHSTy->getAs<ObjCObjectPointerType>()) { 5222 BaseExpr = LHSExp; 5223 IndexExpr = RHSExp; 5224 5225 // Use custom logic if this should be the pseudo-object subscript 5226 // expression. 5227 if (!LangOpts.isSubscriptPointerArithmetic()) 5228 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5229 nullptr); 5230 5231 ResultType = PTy->getPointeeType(); 5232 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5233 // Handle the uncommon case of "123[Ptr]". 5234 BaseExpr = RHSExp; 5235 IndexExpr = LHSExp; 5236 ResultType = PTy->getPointeeType(); 5237 } else if (const ObjCObjectPointerType *PTy = 5238 RHSTy->getAs<ObjCObjectPointerType>()) { 5239 // Handle the uncommon case of "123[Ptr]". 5240 BaseExpr = RHSExp; 5241 IndexExpr = LHSExp; 5242 ResultType = PTy->getPointeeType(); 5243 if (!LangOpts.isSubscriptPointerArithmetic()) { 5244 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5245 << ResultType << BaseExpr->getSourceRange(); 5246 return ExprError(); 5247 } 5248 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5249 BaseExpr = LHSExp; // vectors: V[123] 5250 IndexExpr = RHSExp; 5251 // We apply C++ DR1213 to vector subscripting too. 5252 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5253 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5254 if (Materialized.isInvalid()) 5255 return ExprError(); 5256 LHSExp = Materialized.get(); 5257 } 5258 VK = LHSExp->getValueKind(); 5259 if (VK != VK_RValue) 5260 OK = OK_VectorComponent; 5261 5262 ResultType = VTy->getElementType(); 5263 QualType BaseType = BaseExpr->getType(); 5264 Qualifiers BaseQuals = BaseType.getQualifiers(); 5265 Qualifiers MemberQuals = ResultType.getQualifiers(); 5266 Qualifiers Combined = BaseQuals + MemberQuals; 5267 if (Combined != MemberQuals) 5268 ResultType = Context.getQualifiedType(ResultType, Combined); 5269 } else if (LHSTy->isArrayType()) { 5270 // If we see an array that wasn't promoted by 5271 // DefaultFunctionArrayLvalueConversion, it must be an array that 5272 // wasn't promoted because of the C90 rule that doesn't 5273 // allow promoting non-lvalue arrays. Warn, then 5274 // force the promotion here. 5275 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5276 << LHSExp->getSourceRange(); 5277 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5278 CK_ArrayToPointerDecay).get(); 5279 LHSTy = LHSExp->getType(); 5280 5281 BaseExpr = LHSExp; 5282 IndexExpr = RHSExp; 5283 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5284 } else if (RHSTy->isArrayType()) { 5285 // Same as previous, except for 123[f().a] case 5286 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5287 << RHSExp->getSourceRange(); 5288 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5289 CK_ArrayToPointerDecay).get(); 5290 RHSTy = RHSExp->getType(); 5291 5292 BaseExpr = RHSExp; 5293 IndexExpr = LHSExp; 5294 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5295 } else { 5296 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5297 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5298 } 5299 // C99 6.5.2.1p1 5300 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5301 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5302 << IndexExpr->getSourceRange()); 5303 5304 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5305 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5306 && !IndexExpr->isTypeDependent()) 5307 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5308 5309 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5310 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5311 // type. Note that Functions are not objects, and that (in C99 parlance) 5312 // incomplete types are not object types. 5313 if (ResultType->isFunctionType()) { 5314 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5315 << ResultType << BaseExpr->getSourceRange(); 5316 return ExprError(); 5317 } 5318 5319 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5320 // GNU extension: subscripting on pointer to void 5321 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5322 << BaseExpr->getSourceRange(); 5323 5324 // C forbids expressions of unqualified void type from being l-values. 5325 // See IsCForbiddenLValueType. 5326 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5327 } else if (!ResultType->isDependentType() && 5328 RequireCompleteSizedType( 5329 LLoc, ResultType, 5330 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5331 return ExprError(); 5332 5333 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5334 !ResultType.isCForbiddenLValueType()); 5335 5336 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5337 FunctionScopes.size() > 1) { 5338 if (auto *TT = 5339 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5340 for (auto I = FunctionScopes.rbegin(), 5341 E = std::prev(FunctionScopes.rend()); 5342 I != E; ++I) { 5343 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5344 if (CSI == nullptr) 5345 break; 5346 DeclContext *DC = nullptr; 5347 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5348 DC = LSI->CallOperator; 5349 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5350 DC = CRSI->TheCapturedDecl; 5351 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5352 DC = BSI->TheDecl; 5353 if (DC) { 5354 if (DC->containsDecl(TT->getDecl())) 5355 break; 5356 captureVariablyModifiedType( 5357 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5358 } 5359 } 5360 } 5361 } 5362 5363 return new (Context) 5364 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5365 } 5366 5367 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5368 ParmVarDecl *Param) { 5369 if (Param->hasUnparsedDefaultArg()) { 5370 Diag(CallLoc, 5371 diag::err_use_of_default_argument_to_function_declared_later) << 5372 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5373 Diag(UnparsedDefaultArgLocs[Param], 5374 diag::note_default_argument_declared_here); 5375 return true; 5376 } 5377 5378 if (Param->hasUninstantiatedDefaultArg()) { 5379 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5380 5381 EnterExpressionEvaluationContext EvalContext( 5382 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5383 5384 // Instantiate the expression. 5385 // 5386 // FIXME: Pass in a correct Pattern argument, otherwise 5387 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5388 // 5389 // template<typename T> 5390 // struct A { 5391 // static int FooImpl(); 5392 // 5393 // template<typename Tp> 5394 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5395 // // template argument list [[T], [Tp]], should be [[Tp]]. 5396 // friend A<Tp> Foo(int a); 5397 // }; 5398 // 5399 // template<typename T> 5400 // A<T> Foo(int a = A<T>::FooImpl()); 5401 MultiLevelTemplateArgumentList MutiLevelArgList 5402 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5403 5404 InstantiatingTemplate Inst(*this, CallLoc, Param, 5405 MutiLevelArgList.getInnermost()); 5406 if (Inst.isInvalid()) 5407 return true; 5408 if (Inst.isAlreadyInstantiating()) { 5409 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5410 Param->setInvalidDecl(); 5411 return true; 5412 } 5413 5414 ExprResult Result; 5415 { 5416 // C++ [dcl.fct.default]p5: 5417 // The names in the [default argument] expression are bound, and 5418 // the semantic constraints are checked, at the point where the 5419 // default argument expression appears. 5420 ContextRAII SavedContext(*this, FD); 5421 LocalInstantiationScope Local(*this); 5422 runWithSufficientStackSpace(CallLoc, [&] { 5423 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5424 /*DirectInit*/false); 5425 }); 5426 } 5427 if (Result.isInvalid()) 5428 return true; 5429 5430 // Check the expression as an initializer for the parameter. 5431 InitializedEntity Entity 5432 = InitializedEntity::InitializeParameter(Context, Param); 5433 InitializationKind Kind = InitializationKind::CreateCopy( 5434 Param->getLocation(), 5435 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5436 Expr *ResultE = Result.getAs<Expr>(); 5437 5438 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5439 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5440 if (Result.isInvalid()) 5441 return true; 5442 5443 Result = 5444 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5445 /*DiscardedValue*/ false); 5446 if (Result.isInvalid()) 5447 return true; 5448 5449 // Remember the instantiated default argument. 5450 Param->setDefaultArg(Result.getAs<Expr>()); 5451 if (ASTMutationListener *L = getASTMutationListener()) { 5452 L->DefaultArgumentInstantiated(Param); 5453 } 5454 } 5455 5456 // If the default argument expression is not set yet, we are building it now. 5457 if (!Param->hasInit()) { 5458 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5459 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5460 Param->setInvalidDecl(); 5461 return true; 5462 } 5463 5464 // If the default expression creates temporaries, we need to 5465 // push them to the current stack of expression temporaries so they'll 5466 // be properly destroyed. 5467 // FIXME: We should really be rebuilding the default argument with new 5468 // bound temporaries; see the comment in PR5810. 5469 // We don't need to do that with block decls, though, because 5470 // blocks in default argument expression can never capture anything. 5471 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5472 // Set the "needs cleanups" bit regardless of whether there are 5473 // any explicit objects. 5474 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5475 5476 // Append all the objects to the cleanup list. Right now, this 5477 // should always be a no-op, because blocks in default argument 5478 // expressions should never be able to capture anything. 5479 assert(!Init->getNumObjects() && 5480 "default argument expression has capturing blocks?"); 5481 } 5482 5483 // We already type-checked the argument, so we know it works. 5484 // Just mark all of the declarations in this potentially-evaluated expression 5485 // as being "referenced". 5486 EnterExpressionEvaluationContext EvalContext( 5487 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5488 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5489 /*SkipLocalVariables=*/true); 5490 return false; 5491 } 5492 5493 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5494 FunctionDecl *FD, ParmVarDecl *Param) { 5495 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5496 return ExprError(); 5497 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5498 } 5499 5500 Sema::VariadicCallType 5501 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5502 Expr *Fn) { 5503 if (Proto && Proto->isVariadic()) { 5504 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5505 return VariadicConstructor; 5506 else if (Fn && Fn->getType()->isBlockPointerType()) 5507 return VariadicBlock; 5508 else if (FDecl) { 5509 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5510 if (Method->isInstance()) 5511 return VariadicMethod; 5512 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5513 return VariadicMethod; 5514 return VariadicFunction; 5515 } 5516 return VariadicDoesNotApply; 5517 } 5518 5519 namespace { 5520 class FunctionCallCCC final : public FunctionCallFilterCCC { 5521 public: 5522 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5523 unsigned NumArgs, MemberExpr *ME) 5524 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5525 FunctionName(FuncName) {} 5526 5527 bool ValidateCandidate(const TypoCorrection &candidate) override { 5528 if (!candidate.getCorrectionSpecifier() || 5529 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5530 return false; 5531 } 5532 5533 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5534 } 5535 5536 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5537 return std::make_unique<FunctionCallCCC>(*this); 5538 } 5539 5540 private: 5541 const IdentifierInfo *const FunctionName; 5542 }; 5543 } 5544 5545 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5546 FunctionDecl *FDecl, 5547 ArrayRef<Expr *> Args) { 5548 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5549 DeclarationName FuncName = FDecl->getDeclName(); 5550 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5551 5552 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5553 if (TypoCorrection Corrected = S.CorrectTypo( 5554 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5555 S.getScopeForContext(S.CurContext), nullptr, CCC, 5556 Sema::CTK_ErrorRecovery)) { 5557 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5558 if (Corrected.isOverloaded()) { 5559 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5560 OverloadCandidateSet::iterator Best; 5561 for (NamedDecl *CD : Corrected) { 5562 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5563 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5564 OCS); 5565 } 5566 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5567 case OR_Success: 5568 ND = Best->FoundDecl; 5569 Corrected.setCorrectionDecl(ND); 5570 break; 5571 default: 5572 break; 5573 } 5574 } 5575 ND = ND->getUnderlyingDecl(); 5576 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5577 return Corrected; 5578 } 5579 } 5580 return TypoCorrection(); 5581 } 5582 5583 /// ConvertArgumentsForCall - Converts the arguments specified in 5584 /// Args/NumArgs to the parameter types of the function FDecl with 5585 /// function prototype Proto. Call is the call expression itself, and 5586 /// Fn is the function expression. For a C++ member function, this 5587 /// routine does not attempt to convert the object argument. Returns 5588 /// true if the call is ill-formed. 5589 bool 5590 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5591 FunctionDecl *FDecl, 5592 const FunctionProtoType *Proto, 5593 ArrayRef<Expr *> Args, 5594 SourceLocation RParenLoc, 5595 bool IsExecConfig) { 5596 // Bail out early if calling a builtin with custom typechecking. 5597 if (FDecl) 5598 if (unsigned ID = FDecl->getBuiltinID()) 5599 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5600 return false; 5601 5602 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5603 // assignment, to the types of the corresponding parameter, ... 5604 unsigned NumParams = Proto->getNumParams(); 5605 bool Invalid = false; 5606 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5607 unsigned FnKind = Fn->getType()->isBlockPointerType() 5608 ? 1 /* block */ 5609 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5610 : 0 /* function */); 5611 5612 // If too few arguments are available (and we don't have default 5613 // arguments for the remaining parameters), don't make the call. 5614 if (Args.size() < NumParams) { 5615 if (Args.size() < MinArgs) { 5616 TypoCorrection TC; 5617 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5618 unsigned diag_id = 5619 MinArgs == NumParams && !Proto->isVariadic() 5620 ? diag::err_typecheck_call_too_few_args_suggest 5621 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5622 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5623 << static_cast<unsigned>(Args.size()) 5624 << TC.getCorrectionRange()); 5625 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5626 Diag(RParenLoc, 5627 MinArgs == NumParams && !Proto->isVariadic() 5628 ? diag::err_typecheck_call_too_few_args_one 5629 : diag::err_typecheck_call_too_few_args_at_least_one) 5630 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5631 else 5632 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5633 ? diag::err_typecheck_call_too_few_args 5634 : diag::err_typecheck_call_too_few_args_at_least) 5635 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5636 << Fn->getSourceRange(); 5637 5638 // Emit the location of the prototype. 5639 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5640 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5641 5642 return true; 5643 } 5644 // We reserve space for the default arguments when we create 5645 // the call expression, before calling ConvertArgumentsForCall. 5646 assert((Call->getNumArgs() == NumParams) && 5647 "We should have reserved space for the default arguments before!"); 5648 } 5649 5650 // If too many are passed and not variadic, error on the extras and drop 5651 // them. 5652 if (Args.size() > NumParams) { 5653 if (!Proto->isVariadic()) { 5654 TypoCorrection TC; 5655 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5656 unsigned diag_id = 5657 MinArgs == NumParams && !Proto->isVariadic() 5658 ? diag::err_typecheck_call_too_many_args_suggest 5659 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5660 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5661 << static_cast<unsigned>(Args.size()) 5662 << TC.getCorrectionRange()); 5663 } else if (NumParams == 1 && FDecl && 5664 FDecl->getParamDecl(0)->getDeclName()) 5665 Diag(Args[NumParams]->getBeginLoc(), 5666 MinArgs == NumParams 5667 ? diag::err_typecheck_call_too_many_args_one 5668 : diag::err_typecheck_call_too_many_args_at_most_one) 5669 << FnKind << FDecl->getParamDecl(0) 5670 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5671 << SourceRange(Args[NumParams]->getBeginLoc(), 5672 Args.back()->getEndLoc()); 5673 else 5674 Diag(Args[NumParams]->getBeginLoc(), 5675 MinArgs == NumParams 5676 ? diag::err_typecheck_call_too_many_args 5677 : diag::err_typecheck_call_too_many_args_at_most) 5678 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5679 << Fn->getSourceRange() 5680 << SourceRange(Args[NumParams]->getBeginLoc(), 5681 Args.back()->getEndLoc()); 5682 5683 // Emit the location of the prototype. 5684 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5685 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5686 5687 // This deletes the extra arguments. 5688 Call->shrinkNumArgs(NumParams); 5689 return true; 5690 } 5691 } 5692 SmallVector<Expr *, 8> AllArgs; 5693 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5694 5695 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5696 AllArgs, CallType); 5697 if (Invalid) 5698 return true; 5699 unsigned TotalNumArgs = AllArgs.size(); 5700 for (unsigned i = 0; i < TotalNumArgs; ++i) 5701 Call->setArg(i, AllArgs[i]); 5702 5703 return false; 5704 } 5705 5706 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5707 const FunctionProtoType *Proto, 5708 unsigned FirstParam, ArrayRef<Expr *> Args, 5709 SmallVectorImpl<Expr *> &AllArgs, 5710 VariadicCallType CallType, bool AllowExplicit, 5711 bool IsListInitialization) { 5712 unsigned NumParams = Proto->getNumParams(); 5713 bool Invalid = false; 5714 size_t ArgIx = 0; 5715 // Continue to check argument types (even if we have too few/many args). 5716 for (unsigned i = FirstParam; i < NumParams; i++) { 5717 QualType ProtoArgType = Proto->getParamType(i); 5718 5719 Expr *Arg; 5720 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5721 if (ArgIx < Args.size()) { 5722 Arg = Args[ArgIx++]; 5723 5724 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5725 diag::err_call_incomplete_argument, Arg)) 5726 return true; 5727 5728 // Strip the unbridged-cast placeholder expression off, if applicable. 5729 bool CFAudited = false; 5730 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5731 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5732 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5733 Arg = stripARCUnbridgedCast(Arg); 5734 else if (getLangOpts().ObjCAutoRefCount && 5735 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5736 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5737 CFAudited = true; 5738 5739 if (Proto->getExtParameterInfo(i).isNoEscape()) 5740 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5741 BE->getBlockDecl()->setDoesNotEscape(); 5742 5743 InitializedEntity Entity = 5744 Param ? InitializedEntity::InitializeParameter(Context, Param, 5745 ProtoArgType) 5746 : InitializedEntity::InitializeParameter( 5747 Context, ProtoArgType, Proto->isParamConsumed(i)); 5748 5749 // Remember that parameter belongs to a CF audited API. 5750 if (CFAudited) 5751 Entity.setParameterCFAudited(); 5752 5753 ExprResult ArgE = PerformCopyInitialization( 5754 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5755 if (ArgE.isInvalid()) 5756 return true; 5757 5758 Arg = ArgE.getAs<Expr>(); 5759 } else { 5760 assert(Param && "can't use default arguments without a known callee"); 5761 5762 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5763 if (ArgExpr.isInvalid()) 5764 return true; 5765 5766 Arg = ArgExpr.getAs<Expr>(); 5767 } 5768 5769 // Check for array bounds violations for each argument to the call. This 5770 // check only triggers warnings when the argument isn't a more complex Expr 5771 // with its own checking, such as a BinaryOperator. 5772 CheckArrayAccess(Arg); 5773 5774 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5775 CheckStaticArrayArgument(CallLoc, Param, Arg); 5776 5777 AllArgs.push_back(Arg); 5778 } 5779 5780 // If this is a variadic call, handle args passed through "...". 5781 if (CallType != VariadicDoesNotApply) { 5782 // Assume that extern "C" functions with variadic arguments that 5783 // return __unknown_anytype aren't *really* variadic. 5784 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5785 FDecl->isExternC()) { 5786 for (Expr *A : Args.slice(ArgIx)) { 5787 QualType paramType; // ignored 5788 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5789 Invalid |= arg.isInvalid(); 5790 AllArgs.push_back(arg.get()); 5791 } 5792 5793 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5794 } else { 5795 for (Expr *A : Args.slice(ArgIx)) { 5796 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5797 Invalid |= Arg.isInvalid(); 5798 // Copy blocks to the heap. 5799 if (A->getType()->isBlockPointerType()) 5800 maybeExtendBlockObject(Arg); 5801 AllArgs.push_back(Arg.get()); 5802 } 5803 } 5804 5805 // Check for array bounds violations. 5806 for (Expr *A : Args.slice(ArgIx)) 5807 CheckArrayAccess(A); 5808 } 5809 return Invalid; 5810 } 5811 5812 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5813 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5814 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5815 TL = DTL.getOriginalLoc(); 5816 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5817 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5818 << ATL.getLocalSourceRange(); 5819 } 5820 5821 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5822 /// array parameter, check that it is non-null, and that if it is formed by 5823 /// array-to-pointer decay, the underlying array is sufficiently large. 5824 /// 5825 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5826 /// array type derivation, then for each call to the function, the value of the 5827 /// corresponding actual argument shall provide access to the first element of 5828 /// an array with at least as many elements as specified by the size expression. 5829 void 5830 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5831 ParmVarDecl *Param, 5832 const Expr *ArgExpr) { 5833 // Static array parameters are not supported in C++. 5834 if (!Param || getLangOpts().CPlusPlus) 5835 return; 5836 5837 QualType OrigTy = Param->getOriginalType(); 5838 5839 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5840 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5841 return; 5842 5843 if (ArgExpr->isNullPointerConstant(Context, 5844 Expr::NPC_NeverValueDependent)) { 5845 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5846 DiagnoseCalleeStaticArrayParam(*this, Param); 5847 return; 5848 } 5849 5850 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5851 if (!CAT) 5852 return; 5853 5854 const ConstantArrayType *ArgCAT = 5855 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5856 if (!ArgCAT) 5857 return; 5858 5859 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5860 ArgCAT->getElementType())) { 5861 if (ArgCAT->getSize().ult(CAT->getSize())) { 5862 Diag(CallLoc, diag::warn_static_array_too_small) 5863 << ArgExpr->getSourceRange() 5864 << (unsigned)ArgCAT->getSize().getZExtValue() 5865 << (unsigned)CAT->getSize().getZExtValue() << 0; 5866 DiagnoseCalleeStaticArrayParam(*this, Param); 5867 } 5868 return; 5869 } 5870 5871 Optional<CharUnits> ArgSize = 5872 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5873 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5874 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5875 Diag(CallLoc, diag::warn_static_array_too_small) 5876 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5877 << (unsigned)ParmSize->getQuantity() << 1; 5878 DiagnoseCalleeStaticArrayParam(*this, Param); 5879 } 5880 } 5881 5882 /// Given a function expression of unknown-any type, try to rebuild it 5883 /// to have a function type. 5884 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5885 5886 /// Is the given type a placeholder that we need to lower out 5887 /// immediately during argument processing? 5888 static bool isPlaceholderToRemoveAsArg(QualType type) { 5889 // Placeholders are never sugared. 5890 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5891 if (!placeholder) return false; 5892 5893 switch (placeholder->getKind()) { 5894 // Ignore all the non-placeholder types. 5895 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5896 case BuiltinType::Id: 5897 #include "clang/Basic/OpenCLImageTypes.def" 5898 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5899 case BuiltinType::Id: 5900 #include "clang/Basic/OpenCLExtensionTypes.def" 5901 // In practice we'll never use this, since all SVE types are sugared 5902 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5903 #define SVE_TYPE(Name, Id, SingletonId) \ 5904 case BuiltinType::Id: 5905 #include "clang/Basic/AArch64SVEACLETypes.def" 5906 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5907 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5908 #include "clang/AST/BuiltinTypes.def" 5909 return false; 5910 5911 // We cannot lower out overload sets; they might validly be resolved 5912 // by the call machinery. 5913 case BuiltinType::Overload: 5914 return false; 5915 5916 // Unbridged casts in ARC can be handled in some call positions and 5917 // should be left in place. 5918 case BuiltinType::ARCUnbridgedCast: 5919 return false; 5920 5921 // Pseudo-objects should be converted as soon as possible. 5922 case BuiltinType::PseudoObject: 5923 return true; 5924 5925 // The debugger mode could theoretically but currently does not try 5926 // to resolve unknown-typed arguments based on known parameter types. 5927 case BuiltinType::UnknownAny: 5928 return true; 5929 5930 // These are always invalid as call arguments and should be reported. 5931 case BuiltinType::BoundMember: 5932 case BuiltinType::BuiltinFn: 5933 case BuiltinType::OMPArraySection: 5934 case BuiltinType::OMPArrayShaping: 5935 case BuiltinType::OMPIterator: 5936 return true; 5937 5938 } 5939 llvm_unreachable("bad builtin type kind"); 5940 } 5941 5942 /// Check an argument list for placeholders that we won't try to 5943 /// handle later. 5944 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5945 // Apply this processing to all the arguments at once instead of 5946 // dying at the first failure. 5947 bool hasInvalid = false; 5948 for (size_t i = 0, e = args.size(); i != e; i++) { 5949 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5950 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5951 if (result.isInvalid()) hasInvalid = true; 5952 else args[i] = result.get(); 5953 } else if (hasInvalid) { 5954 (void)S.CorrectDelayedTyposInExpr(args[i]); 5955 } 5956 } 5957 return hasInvalid; 5958 } 5959 5960 /// If a builtin function has a pointer argument with no explicit address 5961 /// space, then it should be able to accept a pointer to any address 5962 /// space as input. In order to do this, we need to replace the 5963 /// standard builtin declaration with one that uses the same address space 5964 /// as the call. 5965 /// 5966 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5967 /// it does not contain any pointer arguments without 5968 /// an address space qualifer. Otherwise the rewritten 5969 /// FunctionDecl is returned. 5970 /// TODO: Handle pointer return types. 5971 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5972 FunctionDecl *FDecl, 5973 MultiExprArg ArgExprs) { 5974 5975 QualType DeclType = FDecl->getType(); 5976 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5977 5978 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5979 ArgExprs.size() < FT->getNumParams()) 5980 return nullptr; 5981 5982 bool NeedsNewDecl = false; 5983 unsigned i = 0; 5984 SmallVector<QualType, 8> OverloadParams; 5985 5986 for (QualType ParamType : FT->param_types()) { 5987 5988 // Convert array arguments to pointer to simplify type lookup. 5989 ExprResult ArgRes = 5990 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5991 if (ArgRes.isInvalid()) 5992 return nullptr; 5993 Expr *Arg = ArgRes.get(); 5994 QualType ArgType = Arg->getType(); 5995 if (!ParamType->isPointerType() || 5996 ParamType.hasAddressSpace() || 5997 !ArgType->isPointerType() || 5998 !ArgType->getPointeeType().hasAddressSpace()) { 5999 OverloadParams.push_back(ParamType); 6000 continue; 6001 } 6002 6003 QualType PointeeType = ParamType->getPointeeType(); 6004 if (PointeeType.hasAddressSpace()) 6005 continue; 6006 6007 NeedsNewDecl = true; 6008 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6009 6010 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6011 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6012 } 6013 6014 if (!NeedsNewDecl) 6015 return nullptr; 6016 6017 FunctionProtoType::ExtProtoInfo EPI; 6018 EPI.Variadic = FT->isVariadic(); 6019 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6020 OverloadParams, EPI); 6021 DeclContext *Parent = FDecl->getParent(); 6022 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6023 FDecl->getLocation(), 6024 FDecl->getLocation(), 6025 FDecl->getIdentifier(), 6026 OverloadTy, 6027 /*TInfo=*/nullptr, 6028 SC_Extern, false, 6029 /*hasPrototype=*/true); 6030 SmallVector<ParmVarDecl*, 16> Params; 6031 FT = cast<FunctionProtoType>(OverloadTy); 6032 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6033 QualType ParamType = FT->getParamType(i); 6034 ParmVarDecl *Parm = 6035 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6036 SourceLocation(), nullptr, ParamType, 6037 /*TInfo=*/nullptr, SC_None, nullptr); 6038 Parm->setScopeInfo(0, i); 6039 Params.push_back(Parm); 6040 } 6041 OverloadDecl->setParams(Params); 6042 return OverloadDecl; 6043 } 6044 6045 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6046 FunctionDecl *Callee, 6047 MultiExprArg ArgExprs) { 6048 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6049 // similar attributes) really don't like it when functions are called with an 6050 // invalid number of args. 6051 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6052 /*PartialOverloading=*/false) && 6053 !Callee->isVariadic()) 6054 return; 6055 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6056 return; 6057 6058 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 6059 S.Diag(Fn->getBeginLoc(), 6060 isa<CXXMethodDecl>(Callee) 6061 ? diag::err_ovl_no_viable_member_function_in_call 6062 : diag::err_ovl_no_viable_function_in_call) 6063 << Callee << Callee->getSourceRange(); 6064 S.Diag(Callee->getLocation(), 6065 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6066 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6067 return; 6068 } 6069 } 6070 6071 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6072 const UnresolvedMemberExpr *const UME, Sema &S) { 6073 6074 const auto GetFunctionLevelDCIfCXXClass = 6075 [](Sema &S) -> const CXXRecordDecl * { 6076 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6077 if (!DC || !DC->getParent()) 6078 return nullptr; 6079 6080 // If the call to some member function was made from within a member 6081 // function body 'M' return return 'M's parent. 6082 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6083 return MD->getParent()->getCanonicalDecl(); 6084 // else the call was made from within a default member initializer of a 6085 // class, so return the class. 6086 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6087 return RD->getCanonicalDecl(); 6088 return nullptr; 6089 }; 6090 // If our DeclContext is neither a member function nor a class (in the 6091 // case of a lambda in a default member initializer), we can't have an 6092 // enclosing 'this'. 6093 6094 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6095 if (!CurParentClass) 6096 return false; 6097 6098 // The naming class for implicit member functions call is the class in which 6099 // name lookup starts. 6100 const CXXRecordDecl *const NamingClass = 6101 UME->getNamingClass()->getCanonicalDecl(); 6102 assert(NamingClass && "Must have naming class even for implicit access"); 6103 6104 // If the unresolved member functions were found in a 'naming class' that is 6105 // related (either the same or derived from) to the class that contains the 6106 // member function that itself contained the implicit member access. 6107 6108 return CurParentClass == NamingClass || 6109 CurParentClass->isDerivedFrom(NamingClass); 6110 } 6111 6112 static void 6113 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6114 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6115 6116 if (!UME) 6117 return; 6118 6119 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6120 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6121 // already been captured, or if this is an implicit member function call (if 6122 // it isn't, an attempt to capture 'this' should already have been made). 6123 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6124 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6125 return; 6126 6127 // Check if the naming class in which the unresolved members were found is 6128 // related (same as or is a base of) to the enclosing class. 6129 6130 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6131 return; 6132 6133 6134 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6135 // If the enclosing function is not dependent, then this lambda is 6136 // capture ready, so if we can capture this, do so. 6137 if (!EnclosingFunctionCtx->isDependentContext()) { 6138 // If the current lambda and all enclosing lambdas can capture 'this' - 6139 // then go ahead and capture 'this' (since our unresolved overload set 6140 // contains at least one non-static member function). 6141 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6142 S.CheckCXXThisCapture(CallLoc); 6143 } else if (S.CurContext->isDependentContext()) { 6144 // ... since this is an implicit member reference, that might potentially 6145 // involve a 'this' capture, mark 'this' for potential capture in 6146 // enclosing lambdas. 6147 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6148 CurLSI->addPotentialThisCapture(CallLoc); 6149 } 6150 } 6151 6152 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6153 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6154 Expr *ExecConfig) { 6155 ExprResult Call = 6156 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6157 if (Call.isInvalid()) 6158 return Call; 6159 6160 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6161 // language modes. 6162 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6163 if (ULE->hasExplicitTemplateArgs() && 6164 ULE->decls_begin() == ULE->decls_end()) { 6165 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 6166 ? diag::warn_cxx17_compat_adl_only_template_id 6167 : diag::ext_adl_only_template_id) 6168 << ULE->getName(); 6169 } 6170 } 6171 6172 if (LangOpts.OpenMP) 6173 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6174 ExecConfig); 6175 6176 return Call; 6177 } 6178 6179 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6180 /// This provides the location of the left/right parens and a list of comma 6181 /// locations. 6182 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6183 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6184 Expr *ExecConfig, bool IsExecConfig) { 6185 // Since this might be a postfix expression, get rid of ParenListExprs. 6186 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6187 if (Result.isInvalid()) return ExprError(); 6188 Fn = Result.get(); 6189 6190 if (checkArgsForPlaceholders(*this, ArgExprs)) 6191 return ExprError(); 6192 6193 if (getLangOpts().CPlusPlus) { 6194 // If this is a pseudo-destructor expression, build the call immediately. 6195 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6196 if (!ArgExprs.empty()) { 6197 // Pseudo-destructor calls should not have any arguments. 6198 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6199 << FixItHint::CreateRemoval( 6200 SourceRange(ArgExprs.front()->getBeginLoc(), 6201 ArgExprs.back()->getEndLoc())); 6202 } 6203 6204 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6205 VK_RValue, RParenLoc); 6206 } 6207 if (Fn->getType() == Context.PseudoObjectTy) { 6208 ExprResult result = CheckPlaceholderExpr(Fn); 6209 if (result.isInvalid()) return ExprError(); 6210 Fn = result.get(); 6211 } 6212 6213 // Determine whether this is a dependent call inside a C++ template, 6214 // in which case we won't do any semantic analysis now. 6215 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6216 if (ExecConfig) { 6217 return CUDAKernelCallExpr::Create( 6218 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6219 Context.DependentTy, VK_RValue, RParenLoc); 6220 } else { 6221 6222 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6223 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6224 Fn->getBeginLoc()); 6225 6226 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6227 VK_RValue, RParenLoc); 6228 } 6229 } 6230 6231 // Determine whether this is a call to an object (C++ [over.call.object]). 6232 if (Fn->getType()->isRecordType()) 6233 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6234 RParenLoc); 6235 6236 if (Fn->getType() == Context.UnknownAnyTy) { 6237 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6238 if (result.isInvalid()) return ExprError(); 6239 Fn = result.get(); 6240 } 6241 6242 if (Fn->getType() == Context.BoundMemberTy) { 6243 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6244 RParenLoc); 6245 } 6246 } 6247 6248 // Check for overloaded calls. This can happen even in C due to extensions. 6249 if (Fn->getType() == Context.OverloadTy) { 6250 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6251 6252 // We aren't supposed to apply this logic if there's an '&' involved. 6253 if (!find.HasFormOfMemberPointer) { 6254 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6255 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6256 VK_RValue, RParenLoc); 6257 OverloadExpr *ovl = find.Expression; 6258 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6259 return BuildOverloadedCallExpr( 6260 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6261 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6262 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6263 RParenLoc); 6264 } 6265 } 6266 6267 // If we're directly calling a function, get the appropriate declaration. 6268 if (Fn->getType() == Context.UnknownAnyTy) { 6269 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6270 if (result.isInvalid()) return ExprError(); 6271 Fn = result.get(); 6272 } 6273 6274 Expr *NakedFn = Fn->IgnoreParens(); 6275 6276 bool CallingNDeclIndirectly = false; 6277 NamedDecl *NDecl = nullptr; 6278 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6279 if (UnOp->getOpcode() == UO_AddrOf) { 6280 CallingNDeclIndirectly = true; 6281 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6282 } 6283 } 6284 6285 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6286 NDecl = DRE->getDecl(); 6287 6288 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6289 if (FDecl && FDecl->getBuiltinID()) { 6290 // Rewrite the function decl for this builtin by replacing parameters 6291 // with no explicit address space with the address space of the arguments 6292 // in ArgExprs. 6293 if ((FDecl = 6294 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6295 NDecl = FDecl; 6296 Fn = DeclRefExpr::Create( 6297 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6298 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6299 nullptr, DRE->isNonOdrUse()); 6300 } 6301 } 6302 } else if (isa<MemberExpr>(NakedFn)) 6303 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6304 6305 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6306 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6307 FD, /*Complain=*/true, Fn->getBeginLoc())) 6308 return ExprError(); 6309 6310 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6311 return ExprError(); 6312 6313 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6314 } 6315 6316 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6317 ExecConfig, IsExecConfig); 6318 } 6319 6320 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6321 /// 6322 /// __builtin_astype( value, dst type ) 6323 /// 6324 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6325 SourceLocation BuiltinLoc, 6326 SourceLocation RParenLoc) { 6327 ExprValueKind VK = VK_RValue; 6328 ExprObjectKind OK = OK_Ordinary; 6329 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6330 QualType SrcTy = E->getType(); 6331 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6332 return ExprError(Diag(BuiltinLoc, 6333 diag::err_invalid_astype_of_different_size) 6334 << DstTy 6335 << SrcTy 6336 << E->getSourceRange()); 6337 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6338 } 6339 6340 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6341 /// provided arguments. 6342 /// 6343 /// __builtin_convertvector( value, dst type ) 6344 /// 6345 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6346 SourceLocation BuiltinLoc, 6347 SourceLocation RParenLoc) { 6348 TypeSourceInfo *TInfo; 6349 GetTypeFromParser(ParsedDestTy, &TInfo); 6350 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6351 } 6352 6353 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6354 /// i.e. an expression not of \p OverloadTy. The expression should 6355 /// unary-convert to an expression of function-pointer or 6356 /// block-pointer type. 6357 /// 6358 /// \param NDecl the declaration being called, if available 6359 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6360 SourceLocation LParenLoc, 6361 ArrayRef<Expr *> Args, 6362 SourceLocation RParenLoc, Expr *Config, 6363 bool IsExecConfig, ADLCallKind UsesADL) { 6364 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6365 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6366 6367 // Functions with 'interrupt' attribute cannot be called directly. 6368 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6369 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6370 return ExprError(); 6371 } 6372 6373 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6374 // so there's some risk when calling out to non-interrupt handler functions 6375 // that the callee might not preserve them. This is easy to diagnose here, 6376 // but can be very challenging to debug. 6377 if (auto *Caller = getCurFunctionDecl()) 6378 if (Caller->hasAttr<ARMInterruptAttr>()) { 6379 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6380 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6381 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6382 } 6383 6384 // Promote the function operand. 6385 // We special-case function promotion here because we only allow promoting 6386 // builtin functions to function pointers in the callee of a call. 6387 ExprResult Result; 6388 QualType ResultTy; 6389 if (BuiltinID && 6390 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6391 // Extract the return type from the (builtin) function pointer type. 6392 // FIXME Several builtins still have setType in 6393 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6394 // Builtins.def to ensure they are correct before removing setType calls. 6395 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6396 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6397 ResultTy = FDecl->getCallResultType(); 6398 } else { 6399 Result = CallExprUnaryConversions(Fn); 6400 ResultTy = Context.BoolTy; 6401 } 6402 if (Result.isInvalid()) 6403 return ExprError(); 6404 Fn = Result.get(); 6405 6406 // Check for a valid function type, but only if it is not a builtin which 6407 // requires custom type checking. These will be handled by 6408 // CheckBuiltinFunctionCall below just after creation of the call expression. 6409 const FunctionType *FuncT = nullptr; 6410 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6411 retry: 6412 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6413 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6414 // have type pointer to function". 6415 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6416 if (!FuncT) 6417 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6418 << Fn->getType() << Fn->getSourceRange()); 6419 } else if (const BlockPointerType *BPT = 6420 Fn->getType()->getAs<BlockPointerType>()) { 6421 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6422 } else { 6423 // Handle calls to expressions of unknown-any type. 6424 if (Fn->getType() == Context.UnknownAnyTy) { 6425 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6426 if (rewrite.isInvalid()) 6427 return ExprError(); 6428 Fn = rewrite.get(); 6429 goto retry; 6430 } 6431 6432 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6433 << Fn->getType() << Fn->getSourceRange()); 6434 } 6435 } 6436 6437 // Get the number of parameters in the function prototype, if any. 6438 // We will allocate space for max(Args.size(), NumParams) arguments 6439 // in the call expression. 6440 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6441 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6442 6443 CallExpr *TheCall; 6444 if (Config) { 6445 assert(UsesADL == ADLCallKind::NotADL && 6446 "CUDAKernelCallExpr should not use ADL"); 6447 TheCall = 6448 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6449 ResultTy, VK_RValue, RParenLoc, NumParams); 6450 } else { 6451 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6452 RParenLoc, NumParams, UsesADL); 6453 } 6454 6455 if (!getLangOpts().CPlusPlus) { 6456 // Forget about the nulled arguments since typo correction 6457 // do not handle them well. 6458 TheCall->shrinkNumArgs(Args.size()); 6459 // C cannot always handle TypoExpr nodes in builtin calls and direct 6460 // function calls as their argument checking don't necessarily handle 6461 // dependent types properly, so make sure any TypoExprs have been 6462 // dealt with. 6463 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6464 if (!Result.isUsable()) return ExprError(); 6465 CallExpr *TheOldCall = TheCall; 6466 TheCall = dyn_cast<CallExpr>(Result.get()); 6467 bool CorrectedTypos = TheCall != TheOldCall; 6468 if (!TheCall) return Result; 6469 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6470 6471 // A new call expression node was created if some typos were corrected. 6472 // However it may not have been constructed with enough storage. In this 6473 // case, rebuild the node with enough storage. The waste of space is 6474 // immaterial since this only happens when some typos were corrected. 6475 if (CorrectedTypos && Args.size() < NumParams) { 6476 if (Config) 6477 TheCall = CUDAKernelCallExpr::Create( 6478 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6479 RParenLoc, NumParams); 6480 else 6481 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6482 RParenLoc, NumParams, UsesADL); 6483 } 6484 // We can now handle the nulled arguments for the default arguments. 6485 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6486 } 6487 6488 // Bail out early if calling a builtin with custom type checking. 6489 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6490 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6491 6492 if (getLangOpts().CUDA) { 6493 if (Config) { 6494 // CUDA: Kernel calls must be to global functions 6495 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6496 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6497 << FDecl << Fn->getSourceRange()); 6498 6499 // CUDA: Kernel function must have 'void' return type 6500 if (!FuncT->getReturnType()->isVoidType() && 6501 !FuncT->getReturnType()->getAs<AutoType>() && 6502 !FuncT->getReturnType()->isInstantiationDependentType()) 6503 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6504 << Fn->getType() << Fn->getSourceRange()); 6505 } else { 6506 // CUDA: Calls to global functions must be configured 6507 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6508 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6509 << FDecl << Fn->getSourceRange()); 6510 } 6511 } 6512 6513 // Check for a valid return type 6514 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6515 FDecl)) 6516 return ExprError(); 6517 6518 // We know the result type of the call, set it. 6519 TheCall->setType(FuncT->getCallResultType(Context)); 6520 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6521 6522 if (Proto) { 6523 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6524 IsExecConfig)) 6525 return ExprError(); 6526 } else { 6527 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6528 6529 if (FDecl) { 6530 // Check if we have too few/too many template arguments, based 6531 // on our knowledge of the function definition. 6532 const FunctionDecl *Def = nullptr; 6533 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6534 Proto = Def->getType()->getAs<FunctionProtoType>(); 6535 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6536 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6537 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6538 } 6539 6540 // If the function we're calling isn't a function prototype, but we have 6541 // a function prototype from a prior declaratiom, use that prototype. 6542 if (!FDecl->hasPrototype()) 6543 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6544 } 6545 6546 // Promote the arguments (C99 6.5.2.2p6). 6547 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6548 Expr *Arg = Args[i]; 6549 6550 if (Proto && i < Proto->getNumParams()) { 6551 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6552 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6553 ExprResult ArgE = 6554 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6555 if (ArgE.isInvalid()) 6556 return true; 6557 6558 Arg = ArgE.getAs<Expr>(); 6559 6560 } else { 6561 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6562 6563 if (ArgE.isInvalid()) 6564 return true; 6565 6566 Arg = ArgE.getAs<Expr>(); 6567 } 6568 6569 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6570 diag::err_call_incomplete_argument, Arg)) 6571 return ExprError(); 6572 6573 TheCall->setArg(i, Arg); 6574 } 6575 } 6576 6577 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6578 if (!Method->isStatic()) 6579 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6580 << Fn->getSourceRange()); 6581 6582 // Check for sentinels 6583 if (NDecl) 6584 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6585 6586 // Do special checking on direct calls to functions. 6587 if (FDecl) { 6588 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6589 return ExprError(); 6590 6591 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6592 6593 if (BuiltinID) 6594 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6595 } else if (NDecl) { 6596 if (CheckPointerCall(NDecl, TheCall, Proto)) 6597 return ExprError(); 6598 } else { 6599 if (CheckOtherCall(TheCall, Proto)) 6600 return ExprError(); 6601 } 6602 6603 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6604 } 6605 6606 ExprResult 6607 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6608 SourceLocation RParenLoc, Expr *InitExpr) { 6609 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6610 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6611 6612 TypeSourceInfo *TInfo; 6613 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6614 if (!TInfo) 6615 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6616 6617 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6618 } 6619 6620 ExprResult 6621 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6622 SourceLocation RParenLoc, Expr *LiteralExpr) { 6623 QualType literalType = TInfo->getType(); 6624 6625 if (literalType->isArrayType()) { 6626 if (RequireCompleteSizedType( 6627 LParenLoc, Context.getBaseElementType(literalType), 6628 diag::err_array_incomplete_or_sizeless_type, 6629 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6630 return ExprError(); 6631 if (literalType->isVariableArrayType()) 6632 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6633 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6634 } else if (!literalType->isDependentType() && 6635 RequireCompleteType(LParenLoc, literalType, 6636 diag::err_typecheck_decl_incomplete_type, 6637 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6638 return ExprError(); 6639 6640 InitializedEntity Entity 6641 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6642 InitializationKind Kind 6643 = InitializationKind::CreateCStyleCast(LParenLoc, 6644 SourceRange(LParenLoc, RParenLoc), 6645 /*InitList=*/true); 6646 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6647 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6648 &literalType); 6649 if (Result.isInvalid()) 6650 return ExprError(); 6651 LiteralExpr = Result.get(); 6652 6653 bool isFileScope = !CurContext->isFunctionOrMethod(); 6654 6655 // In C, compound literals are l-values for some reason. 6656 // For GCC compatibility, in C++, file-scope array compound literals with 6657 // constant initializers are also l-values, and compound literals are 6658 // otherwise prvalues. 6659 // 6660 // (GCC also treats C++ list-initialized file-scope array prvalues with 6661 // constant initializers as l-values, but that's non-conforming, so we don't 6662 // follow it there.) 6663 // 6664 // FIXME: It would be better to handle the lvalue cases as materializing and 6665 // lifetime-extending a temporary object, but our materialized temporaries 6666 // representation only supports lifetime extension from a variable, not "out 6667 // of thin air". 6668 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6669 // is bound to the result of applying array-to-pointer decay to the compound 6670 // literal. 6671 // FIXME: GCC supports compound literals of reference type, which should 6672 // obviously have a value kind derived from the kind of reference involved. 6673 ExprValueKind VK = 6674 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6675 ? VK_RValue 6676 : VK_LValue; 6677 6678 if (isFileScope) 6679 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6680 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6681 Expr *Init = ILE->getInit(i); 6682 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6683 } 6684 6685 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6686 VK, LiteralExpr, isFileScope); 6687 if (isFileScope) { 6688 if (!LiteralExpr->isTypeDependent() && 6689 !LiteralExpr->isValueDependent() && 6690 !literalType->isDependentType()) // C99 6.5.2.5p3 6691 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6692 return ExprError(); 6693 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6694 literalType.getAddressSpace() != LangAS::Default) { 6695 // Embedded-C extensions to C99 6.5.2.5: 6696 // "If the compound literal occurs inside the body of a function, the 6697 // type name shall not be qualified by an address-space qualifier." 6698 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6699 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6700 return ExprError(); 6701 } 6702 6703 if (!isFileScope && !getLangOpts().CPlusPlus) { 6704 // Compound literals that have automatic storage duration are destroyed at 6705 // the end of the scope in C; in C++, they're just temporaries. 6706 6707 // Emit diagnostics if it is or contains a C union type that is non-trivial 6708 // to destruct. 6709 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6710 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6711 NTCUC_CompoundLiteral, NTCUK_Destruct); 6712 6713 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6714 if (literalType.isDestructedType()) { 6715 Cleanup.setExprNeedsCleanups(true); 6716 ExprCleanupObjects.push_back(E); 6717 getCurFunction()->setHasBranchProtectedScope(); 6718 } 6719 } 6720 6721 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6722 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6723 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6724 E->getInitializer()->getExprLoc()); 6725 6726 return MaybeBindToTemporary(E); 6727 } 6728 6729 ExprResult 6730 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6731 SourceLocation RBraceLoc) { 6732 // Only produce each kind of designated initialization diagnostic once. 6733 SourceLocation FirstDesignator; 6734 bool DiagnosedArrayDesignator = false; 6735 bool DiagnosedNestedDesignator = false; 6736 bool DiagnosedMixedDesignator = false; 6737 6738 // Check that any designated initializers are syntactically valid in the 6739 // current language mode. 6740 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6741 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6742 if (FirstDesignator.isInvalid()) 6743 FirstDesignator = DIE->getBeginLoc(); 6744 6745 if (!getLangOpts().CPlusPlus) 6746 break; 6747 6748 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6749 DiagnosedNestedDesignator = true; 6750 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6751 << DIE->getDesignatorsSourceRange(); 6752 } 6753 6754 for (auto &Desig : DIE->designators()) { 6755 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6756 DiagnosedArrayDesignator = true; 6757 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6758 << Desig.getSourceRange(); 6759 } 6760 } 6761 6762 if (!DiagnosedMixedDesignator && 6763 !isa<DesignatedInitExpr>(InitArgList[0])) { 6764 DiagnosedMixedDesignator = true; 6765 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6766 << DIE->getSourceRange(); 6767 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6768 << InitArgList[0]->getSourceRange(); 6769 } 6770 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6771 isa<DesignatedInitExpr>(InitArgList[0])) { 6772 DiagnosedMixedDesignator = true; 6773 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6774 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6775 << DIE->getSourceRange(); 6776 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6777 << InitArgList[I]->getSourceRange(); 6778 } 6779 } 6780 6781 if (FirstDesignator.isValid()) { 6782 // Only diagnose designated initiaization as a C++20 extension if we didn't 6783 // already diagnose use of (non-C++20) C99 designator syntax. 6784 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6785 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6786 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6787 ? diag::warn_cxx17_compat_designated_init 6788 : diag::ext_cxx_designated_init); 6789 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6790 Diag(FirstDesignator, diag::ext_designated_init); 6791 } 6792 } 6793 6794 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6795 } 6796 6797 ExprResult 6798 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6799 SourceLocation RBraceLoc) { 6800 // Semantic analysis for initializers is done by ActOnDeclarator() and 6801 // CheckInitializer() - it requires knowledge of the object being initialized. 6802 6803 // Immediately handle non-overload placeholders. Overloads can be 6804 // resolved contextually, but everything else here can't. 6805 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6806 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6807 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6808 6809 // Ignore failures; dropping the entire initializer list because 6810 // of one failure would be terrible for indexing/etc. 6811 if (result.isInvalid()) continue; 6812 6813 InitArgList[I] = result.get(); 6814 } 6815 } 6816 6817 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6818 RBraceLoc); 6819 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6820 return E; 6821 } 6822 6823 /// Do an explicit extend of the given block pointer if we're in ARC. 6824 void Sema::maybeExtendBlockObject(ExprResult &E) { 6825 assert(E.get()->getType()->isBlockPointerType()); 6826 assert(E.get()->isRValue()); 6827 6828 // Only do this in an r-value context. 6829 if (!getLangOpts().ObjCAutoRefCount) return; 6830 6831 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6832 CK_ARCExtendBlockObject, E.get(), 6833 /*base path*/ nullptr, VK_RValue); 6834 Cleanup.setExprNeedsCleanups(true); 6835 } 6836 6837 /// Prepare a conversion of the given expression to an ObjC object 6838 /// pointer type. 6839 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6840 QualType type = E.get()->getType(); 6841 if (type->isObjCObjectPointerType()) { 6842 return CK_BitCast; 6843 } else if (type->isBlockPointerType()) { 6844 maybeExtendBlockObject(E); 6845 return CK_BlockPointerToObjCPointerCast; 6846 } else { 6847 assert(type->isPointerType()); 6848 return CK_CPointerToObjCPointerCast; 6849 } 6850 } 6851 6852 /// Prepares for a scalar cast, performing all the necessary stages 6853 /// except the final cast and returning the kind required. 6854 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6855 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6856 // Also, callers should have filtered out the invalid cases with 6857 // pointers. Everything else should be possible. 6858 6859 QualType SrcTy = Src.get()->getType(); 6860 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6861 return CK_NoOp; 6862 6863 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6864 case Type::STK_MemberPointer: 6865 llvm_unreachable("member pointer type in C"); 6866 6867 case Type::STK_CPointer: 6868 case Type::STK_BlockPointer: 6869 case Type::STK_ObjCObjectPointer: 6870 switch (DestTy->getScalarTypeKind()) { 6871 case Type::STK_CPointer: { 6872 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6873 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6874 if (SrcAS != DestAS) 6875 return CK_AddressSpaceConversion; 6876 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6877 return CK_NoOp; 6878 return CK_BitCast; 6879 } 6880 case Type::STK_BlockPointer: 6881 return (SrcKind == Type::STK_BlockPointer 6882 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6883 case Type::STK_ObjCObjectPointer: 6884 if (SrcKind == Type::STK_ObjCObjectPointer) 6885 return CK_BitCast; 6886 if (SrcKind == Type::STK_CPointer) 6887 return CK_CPointerToObjCPointerCast; 6888 maybeExtendBlockObject(Src); 6889 return CK_BlockPointerToObjCPointerCast; 6890 case Type::STK_Bool: 6891 return CK_PointerToBoolean; 6892 case Type::STK_Integral: 6893 return CK_PointerToIntegral; 6894 case Type::STK_Floating: 6895 case Type::STK_FloatingComplex: 6896 case Type::STK_IntegralComplex: 6897 case Type::STK_MemberPointer: 6898 case Type::STK_FixedPoint: 6899 llvm_unreachable("illegal cast from pointer"); 6900 } 6901 llvm_unreachable("Should have returned before this"); 6902 6903 case Type::STK_FixedPoint: 6904 switch (DestTy->getScalarTypeKind()) { 6905 case Type::STK_FixedPoint: 6906 return CK_FixedPointCast; 6907 case Type::STK_Bool: 6908 return CK_FixedPointToBoolean; 6909 case Type::STK_Integral: 6910 return CK_FixedPointToIntegral; 6911 case Type::STK_Floating: 6912 case Type::STK_IntegralComplex: 6913 case Type::STK_FloatingComplex: 6914 Diag(Src.get()->getExprLoc(), 6915 diag::err_unimplemented_conversion_with_fixed_point_type) 6916 << DestTy; 6917 return CK_IntegralCast; 6918 case Type::STK_CPointer: 6919 case Type::STK_ObjCObjectPointer: 6920 case Type::STK_BlockPointer: 6921 case Type::STK_MemberPointer: 6922 llvm_unreachable("illegal cast to pointer type"); 6923 } 6924 llvm_unreachable("Should have returned before this"); 6925 6926 case Type::STK_Bool: // casting from bool is like casting from an integer 6927 case Type::STK_Integral: 6928 switch (DestTy->getScalarTypeKind()) { 6929 case Type::STK_CPointer: 6930 case Type::STK_ObjCObjectPointer: 6931 case Type::STK_BlockPointer: 6932 if (Src.get()->isNullPointerConstant(Context, 6933 Expr::NPC_ValueDependentIsNull)) 6934 return CK_NullToPointer; 6935 return CK_IntegralToPointer; 6936 case Type::STK_Bool: 6937 return CK_IntegralToBoolean; 6938 case Type::STK_Integral: 6939 return CK_IntegralCast; 6940 case Type::STK_Floating: 6941 return CK_IntegralToFloating; 6942 case Type::STK_IntegralComplex: 6943 Src = ImpCastExprToType(Src.get(), 6944 DestTy->castAs<ComplexType>()->getElementType(), 6945 CK_IntegralCast); 6946 return CK_IntegralRealToComplex; 6947 case Type::STK_FloatingComplex: 6948 Src = ImpCastExprToType(Src.get(), 6949 DestTy->castAs<ComplexType>()->getElementType(), 6950 CK_IntegralToFloating); 6951 return CK_FloatingRealToComplex; 6952 case Type::STK_MemberPointer: 6953 llvm_unreachable("member pointer type in C"); 6954 case Type::STK_FixedPoint: 6955 return CK_IntegralToFixedPoint; 6956 } 6957 llvm_unreachable("Should have returned before this"); 6958 6959 case Type::STK_Floating: 6960 switch (DestTy->getScalarTypeKind()) { 6961 case Type::STK_Floating: 6962 return CK_FloatingCast; 6963 case Type::STK_Bool: 6964 return CK_FloatingToBoolean; 6965 case Type::STK_Integral: 6966 return CK_FloatingToIntegral; 6967 case Type::STK_FloatingComplex: 6968 Src = ImpCastExprToType(Src.get(), 6969 DestTy->castAs<ComplexType>()->getElementType(), 6970 CK_FloatingCast); 6971 return CK_FloatingRealToComplex; 6972 case Type::STK_IntegralComplex: 6973 Src = ImpCastExprToType(Src.get(), 6974 DestTy->castAs<ComplexType>()->getElementType(), 6975 CK_FloatingToIntegral); 6976 return CK_IntegralRealToComplex; 6977 case Type::STK_CPointer: 6978 case Type::STK_ObjCObjectPointer: 6979 case Type::STK_BlockPointer: 6980 llvm_unreachable("valid float->pointer cast?"); 6981 case Type::STK_MemberPointer: 6982 llvm_unreachable("member pointer type in C"); 6983 case Type::STK_FixedPoint: 6984 Diag(Src.get()->getExprLoc(), 6985 diag::err_unimplemented_conversion_with_fixed_point_type) 6986 << SrcTy; 6987 return CK_IntegralCast; 6988 } 6989 llvm_unreachable("Should have returned before this"); 6990 6991 case Type::STK_FloatingComplex: 6992 switch (DestTy->getScalarTypeKind()) { 6993 case Type::STK_FloatingComplex: 6994 return CK_FloatingComplexCast; 6995 case Type::STK_IntegralComplex: 6996 return CK_FloatingComplexToIntegralComplex; 6997 case Type::STK_Floating: { 6998 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6999 if (Context.hasSameType(ET, DestTy)) 7000 return CK_FloatingComplexToReal; 7001 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7002 return CK_FloatingCast; 7003 } 7004 case Type::STK_Bool: 7005 return CK_FloatingComplexToBoolean; 7006 case Type::STK_Integral: 7007 Src = ImpCastExprToType(Src.get(), 7008 SrcTy->castAs<ComplexType>()->getElementType(), 7009 CK_FloatingComplexToReal); 7010 return CK_FloatingToIntegral; 7011 case Type::STK_CPointer: 7012 case Type::STK_ObjCObjectPointer: 7013 case Type::STK_BlockPointer: 7014 llvm_unreachable("valid complex float->pointer cast?"); 7015 case Type::STK_MemberPointer: 7016 llvm_unreachable("member pointer type in C"); 7017 case Type::STK_FixedPoint: 7018 Diag(Src.get()->getExprLoc(), 7019 diag::err_unimplemented_conversion_with_fixed_point_type) 7020 << SrcTy; 7021 return CK_IntegralCast; 7022 } 7023 llvm_unreachable("Should have returned before this"); 7024 7025 case Type::STK_IntegralComplex: 7026 switch (DestTy->getScalarTypeKind()) { 7027 case Type::STK_FloatingComplex: 7028 return CK_IntegralComplexToFloatingComplex; 7029 case Type::STK_IntegralComplex: 7030 return CK_IntegralComplexCast; 7031 case Type::STK_Integral: { 7032 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7033 if (Context.hasSameType(ET, DestTy)) 7034 return CK_IntegralComplexToReal; 7035 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7036 return CK_IntegralCast; 7037 } 7038 case Type::STK_Bool: 7039 return CK_IntegralComplexToBoolean; 7040 case Type::STK_Floating: 7041 Src = ImpCastExprToType(Src.get(), 7042 SrcTy->castAs<ComplexType>()->getElementType(), 7043 CK_IntegralComplexToReal); 7044 return CK_IntegralToFloating; 7045 case Type::STK_CPointer: 7046 case Type::STK_ObjCObjectPointer: 7047 case Type::STK_BlockPointer: 7048 llvm_unreachable("valid complex int->pointer cast?"); 7049 case Type::STK_MemberPointer: 7050 llvm_unreachable("member pointer type in C"); 7051 case Type::STK_FixedPoint: 7052 Diag(Src.get()->getExprLoc(), 7053 diag::err_unimplemented_conversion_with_fixed_point_type) 7054 << SrcTy; 7055 return CK_IntegralCast; 7056 } 7057 llvm_unreachable("Should have returned before this"); 7058 } 7059 7060 llvm_unreachable("Unhandled scalar cast"); 7061 } 7062 7063 static bool breakDownVectorType(QualType type, uint64_t &len, 7064 QualType &eltType) { 7065 // Vectors are simple. 7066 if (const VectorType *vecType = type->getAs<VectorType>()) { 7067 len = vecType->getNumElements(); 7068 eltType = vecType->getElementType(); 7069 assert(eltType->isScalarType()); 7070 return true; 7071 } 7072 7073 // We allow lax conversion to and from non-vector types, but only if 7074 // they're real types (i.e. non-complex, non-pointer scalar types). 7075 if (!type->isRealType()) return false; 7076 7077 len = 1; 7078 eltType = type; 7079 return true; 7080 } 7081 7082 /// Are the two types lax-compatible vector types? That is, given 7083 /// that one of them is a vector, do they have equal storage sizes, 7084 /// where the storage size is the number of elements times the element 7085 /// size? 7086 /// 7087 /// This will also return false if either of the types is neither a 7088 /// vector nor a real type. 7089 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7090 assert(destTy->isVectorType() || srcTy->isVectorType()); 7091 7092 // Disallow lax conversions between scalars and ExtVectors (these 7093 // conversions are allowed for other vector types because common headers 7094 // depend on them). Most scalar OP ExtVector cases are handled by the 7095 // splat path anyway, which does what we want (convert, not bitcast). 7096 // What this rules out for ExtVectors is crazy things like char4*float. 7097 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7098 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7099 7100 uint64_t srcLen, destLen; 7101 QualType srcEltTy, destEltTy; 7102 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7103 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7104 7105 // ASTContext::getTypeSize will return the size rounded up to a 7106 // power of 2, so instead of using that, we need to use the raw 7107 // element size multiplied by the element count. 7108 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7109 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7110 7111 return (srcLen * srcEltSize == destLen * destEltSize); 7112 } 7113 7114 /// Is this a legal conversion between two types, one of which is 7115 /// known to be a vector type? 7116 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7117 assert(destTy->isVectorType() || srcTy->isVectorType()); 7118 7119 switch (Context.getLangOpts().getLaxVectorConversions()) { 7120 case LangOptions::LaxVectorConversionKind::None: 7121 return false; 7122 7123 case LangOptions::LaxVectorConversionKind::Integer: 7124 if (!srcTy->isIntegralOrEnumerationType()) { 7125 auto *Vec = srcTy->getAs<VectorType>(); 7126 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7127 return false; 7128 } 7129 if (!destTy->isIntegralOrEnumerationType()) { 7130 auto *Vec = destTy->getAs<VectorType>(); 7131 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7132 return false; 7133 } 7134 // OK, integer (vector) -> integer (vector) bitcast. 7135 break; 7136 7137 case LangOptions::LaxVectorConversionKind::All: 7138 break; 7139 } 7140 7141 return areLaxCompatibleVectorTypes(srcTy, destTy); 7142 } 7143 7144 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7145 CastKind &Kind) { 7146 assert(VectorTy->isVectorType() && "Not a vector type!"); 7147 7148 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7149 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7150 return Diag(R.getBegin(), 7151 Ty->isVectorType() ? 7152 diag::err_invalid_conversion_between_vectors : 7153 diag::err_invalid_conversion_between_vector_and_integer) 7154 << VectorTy << Ty << R; 7155 } else 7156 return Diag(R.getBegin(), 7157 diag::err_invalid_conversion_between_vector_and_scalar) 7158 << VectorTy << Ty << R; 7159 7160 Kind = CK_BitCast; 7161 return false; 7162 } 7163 7164 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7165 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7166 7167 if (DestElemTy == SplattedExpr->getType()) 7168 return SplattedExpr; 7169 7170 assert(DestElemTy->isFloatingType() || 7171 DestElemTy->isIntegralOrEnumerationType()); 7172 7173 CastKind CK; 7174 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7175 // OpenCL requires that we convert `true` boolean expressions to -1, but 7176 // only when splatting vectors. 7177 if (DestElemTy->isFloatingType()) { 7178 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7179 // in two steps: boolean to signed integral, then to floating. 7180 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7181 CK_BooleanToSignedIntegral); 7182 SplattedExpr = CastExprRes.get(); 7183 CK = CK_IntegralToFloating; 7184 } else { 7185 CK = CK_BooleanToSignedIntegral; 7186 } 7187 } else { 7188 ExprResult CastExprRes = SplattedExpr; 7189 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7190 if (CastExprRes.isInvalid()) 7191 return ExprError(); 7192 SplattedExpr = CastExprRes.get(); 7193 } 7194 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7195 } 7196 7197 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7198 Expr *CastExpr, CastKind &Kind) { 7199 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7200 7201 QualType SrcTy = CastExpr->getType(); 7202 7203 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7204 // an ExtVectorType. 7205 // In OpenCL, casts between vectors of different types are not allowed. 7206 // (See OpenCL 6.2). 7207 if (SrcTy->isVectorType()) { 7208 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7209 (getLangOpts().OpenCL && 7210 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7211 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7212 << DestTy << SrcTy << R; 7213 return ExprError(); 7214 } 7215 Kind = CK_BitCast; 7216 return CastExpr; 7217 } 7218 7219 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7220 // conversion will take place first from scalar to elt type, and then 7221 // splat from elt type to vector. 7222 if (SrcTy->isPointerType()) 7223 return Diag(R.getBegin(), 7224 diag::err_invalid_conversion_between_vector_and_scalar) 7225 << DestTy << SrcTy << R; 7226 7227 Kind = CK_VectorSplat; 7228 return prepareVectorSplat(DestTy, CastExpr); 7229 } 7230 7231 ExprResult 7232 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7233 Declarator &D, ParsedType &Ty, 7234 SourceLocation RParenLoc, Expr *CastExpr) { 7235 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7236 "ActOnCastExpr(): missing type or expr"); 7237 7238 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7239 if (D.isInvalidType()) 7240 return ExprError(); 7241 7242 if (getLangOpts().CPlusPlus) { 7243 // Check that there are no default arguments (C++ only). 7244 CheckExtraCXXDefaultArguments(D); 7245 } else { 7246 // Make sure any TypoExprs have been dealt with. 7247 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7248 if (!Res.isUsable()) 7249 return ExprError(); 7250 CastExpr = Res.get(); 7251 } 7252 7253 checkUnusedDeclAttributes(D); 7254 7255 QualType castType = castTInfo->getType(); 7256 Ty = CreateParsedType(castType, castTInfo); 7257 7258 bool isVectorLiteral = false; 7259 7260 // Check for an altivec or OpenCL literal, 7261 // i.e. all the elements are integer constants. 7262 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7263 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7264 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7265 && castType->isVectorType() && (PE || PLE)) { 7266 if (PLE && PLE->getNumExprs() == 0) { 7267 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7268 return ExprError(); 7269 } 7270 if (PE || PLE->getNumExprs() == 1) { 7271 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7272 if (!E->getType()->isVectorType()) 7273 isVectorLiteral = true; 7274 } 7275 else 7276 isVectorLiteral = true; 7277 } 7278 7279 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7280 // then handle it as such. 7281 if (isVectorLiteral) 7282 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7283 7284 // If the Expr being casted is a ParenListExpr, handle it specially. 7285 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7286 // sequence of BinOp comma operators. 7287 if (isa<ParenListExpr>(CastExpr)) { 7288 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7289 if (Result.isInvalid()) return ExprError(); 7290 CastExpr = Result.get(); 7291 } 7292 7293 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7294 !getSourceManager().isInSystemMacro(LParenLoc)) 7295 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7296 7297 CheckTollFreeBridgeCast(castType, CastExpr); 7298 7299 CheckObjCBridgeRelatedCast(castType, CastExpr); 7300 7301 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7302 7303 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7304 } 7305 7306 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7307 SourceLocation RParenLoc, Expr *E, 7308 TypeSourceInfo *TInfo) { 7309 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7310 "Expected paren or paren list expression"); 7311 7312 Expr **exprs; 7313 unsigned numExprs; 7314 Expr *subExpr; 7315 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7316 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7317 LiteralLParenLoc = PE->getLParenLoc(); 7318 LiteralRParenLoc = PE->getRParenLoc(); 7319 exprs = PE->getExprs(); 7320 numExprs = PE->getNumExprs(); 7321 } else { // isa<ParenExpr> by assertion at function entrance 7322 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7323 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7324 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7325 exprs = &subExpr; 7326 numExprs = 1; 7327 } 7328 7329 QualType Ty = TInfo->getType(); 7330 assert(Ty->isVectorType() && "Expected vector type"); 7331 7332 SmallVector<Expr *, 8> initExprs; 7333 const VectorType *VTy = Ty->castAs<VectorType>(); 7334 unsigned numElems = VTy->getNumElements(); 7335 7336 // '(...)' form of vector initialization in AltiVec: the number of 7337 // initializers must be one or must match the size of the vector. 7338 // If a single value is specified in the initializer then it will be 7339 // replicated to all the components of the vector 7340 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7341 // The number of initializers must be one or must match the size of the 7342 // vector. If a single value is specified in the initializer then it will 7343 // be replicated to all the components of the vector 7344 if (numExprs == 1) { 7345 QualType ElemTy = VTy->getElementType(); 7346 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7347 if (Literal.isInvalid()) 7348 return ExprError(); 7349 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7350 PrepareScalarCast(Literal, ElemTy)); 7351 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7352 } 7353 else if (numExprs < numElems) { 7354 Diag(E->getExprLoc(), 7355 diag::err_incorrect_number_of_vector_initializers); 7356 return ExprError(); 7357 } 7358 else 7359 initExprs.append(exprs, exprs + numExprs); 7360 } 7361 else { 7362 // For OpenCL, when the number of initializers is a single value, 7363 // it will be replicated to all components of the vector. 7364 if (getLangOpts().OpenCL && 7365 VTy->getVectorKind() == VectorType::GenericVector && 7366 numExprs == 1) { 7367 QualType ElemTy = VTy->getElementType(); 7368 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7369 if (Literal.isInvalid()) 7370 return ExprError(); 7371 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7372 PrepareScalarCast(Literal, ElemTy)); 7373 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7374 } 7375 7376 initExprs.append(exprs, exprs + numExprs); 7377 } 7378 // FIXME: This means that pretty-printing the final AST will produce curly 7379 // braces instead of the original commas. 7380 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7381 initExprs, LiteralRParenLoc); 7382 initE->setType(Ty); 7383 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7384 } 7385 7386 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7387 /// the ParenListExpr into a sequence of comma binary operators. 7388 ExprResult 7389 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7390 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7391 if (!E) 7392 return OrigExpr; 7393 7394 ExprResult Result(E->getExpr(0)); 7395 7396 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7397 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7398 E->getExpr(i)); 7399 7400 if (Result.isInvalid()) return ExprError(); 7401 7402 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7403 } 7404 7405 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7406 SourceLocation R, 7407 MultiExprArg Val) { 7408 return ParenListExpr::Create(Context, L, Val, R); 7409 } 7410 7411 /// Emit a specialized diagnostic when one expression is a null pointer 7412 /// constant and the other is not a pointer. Returns true if a diagnostic is 7413 /// emitted. 7414 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7415 SourceLocation QuestionLoc) { 7416 Expr *NullExpr = LHSExpr; 7417 Expr *NonPointerExpr = RHSExpr; 7418 Expr::NullPointerConstantKind NullKind = 7419 NullExpr->isNullPointerConstant(Context, 7420 Expr::NPC_ValueDependentIsNotNull); 7421 7422 if (NullKind == Expr::NPCK_NotNull) { 7423 NullExpr = RHSExpr; 7424 NonPointerExpr = LHSExpr; 7425 NullKind = 7426 NullExpr->isNullPointerConstant(Context, 7427 Expr::NPC_ValueDependentIsNotNull); 7428 } 7429 7430 if (NullKind == Expr::NPCK_NotNull) 7431 return false; 7432 7433 if (NullKind == Expr::NPCK_ZeroExpression) 7434 return false; 7435 7436 if (NullKind == Expr::NPCK_ZeroLiteral) { 7437 // In this case, check to make sure that we got here from a "NULL" 7438 // string in the source code. 7439 NullExpr = NullExpr->IgnoreParenImpCasts(); 7440 SourceLocation loc = NullExpr->getExprLoc(); 7441 if (!findMacroSpelling(loc, "NULL")) 7442 return false; 7443 } 7444 7445 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7446 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7447 << NonPointerExpr->getType() << DiagType 7448 << NonPointerExpr->getSourceRange(); 7449 return true; 7450 } 7451 7452 /// Return false if the condition expression is valid, true otherwise. 7453 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7454 QualType CondTy = Cond->getType(); 7455 7456 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7457 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7458 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7459 << CondTy << Cond->getSourceRange(); 7460 return true; 7461 } 7462 7463 // C99 6.5.15p2 7464 if (CondTy->isScalarType()) return false; 7465 7466 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7467 << CondTy << Cond->getSourceRange(); 7468 return true; 7469 } 7470 7471 /// Handle when one or both operands are void type. 7472 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7473 ExprResult &RHS) { 7474 Expr *LHSExpr = LHS.get(); 7475 Expr *RHSExpr = RHS.get(); 7476 7477 if (!LHSExpr->getType()->isVoidType()) 7478 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7479 << RHSExpr->getSourceRange(); 7480 if (!RHSExpr->getType()->isVoidType()) 7481 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7482 << LHSExpr->getSourceRange(); 7483 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7484 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7485 return S.Context.VoidTy; 7486 } 7487 7488 /// Return false if the NullExpr can be promoted to PointerTy, 7489 /// true otherwise. 7490 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7491 QualType PointerTy) { 7492 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7493 !NullExpr.get()->isNullPointerConstant(S.Context, 7494 Expr::NPC_ValueDependentIsNull)) 7495 return true; 7496 7497 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7498 return false; 7499 } 7500 7501 /// Checks compatibility between two pointers and return the resulting 7502 /// type. 7503 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7504 ExprResult &RHS, 7505 SourceLocation Loc) { 7506 QualType LHSTy = LHS.get()->getType(); 7507 QualType RHSTy = RHS.get()->getType(); 7508 7509 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7510 // Two identical pointers types are always compatible. 7511 return LHSTy; 7512 } 7513 7514 QualType lhptee, rhptee; 7515 7516 // Get the pointee types. 7517 bool IsBlockPointer = false; 7518 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7519 lhptee = LHSBTy->getPointeeType(); 7520 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7521 IsBlockPointer = true; 7522 } else { 7523 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7524 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7525 } 7526 7527 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7528 // differently qualified versions of compatible types, the result type is 7529 // a pointer to an appropriately qualified version of the composite 7530 // type. 7531 7532 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7533 // clause doesn't make sense for our extensions. E.g. address space 2 should 7534 // be incompatible with address space 3: they may live on different devices or 7535 // anything. 7536 Qualifiers lhQual = lhptee.getQualifiers(); 7537 Qualifiers rhQual = rhptee.getQualifiers(); 7538 7539 LangAS ResultAddrSpace = LangAS::Default; 7540 LangAS LAddrSpace = lhQual.getAddressSpace(); 7541 LangAS RAddrSpace = rhQual.getAddressSpace(); 7542 7543 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7544 // spaces is disallowed. 7545 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7546 ResultAddrSpace = LAddrSpace; 7547 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7548 ResultAddrSpace = RAddrSpace; 7549 else { 7550 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7551 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7552 << RHS.get()->getSourceRange(); 7553 return QualType(); 7554 } 7555 7556 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7557 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7558 lhQual.removeCVRQualifiers(); 7559 rhQual.removeCVRQualifiers(); 7560 7561 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7562 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7563 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7564 // qual types are compatible iff 7565 // * corresponded types are compatible 7566 // * CVR qualifiers are equal 7567 // * address spaces are equal 7568 // Thus for conditional operator we merge CVR and address space unqualified 7569 // pointees and if there is a composite type we return a pointer to it with 7570 // merged qualifiers. 7571 LHSCastKind = 7572 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7573 RHSCastKind = 7574 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7575 lhQual.removeAddressSpace(); 7576 rhQual.removeAddressSpace(); 7577 7578 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7579 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7580 7581 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7582 7583 if (CompositeTy.isNull()) { 7584 // In this situation, we assume void* type. No especially good 7585 // reason, but this is what gcc does, and we do have to pick 7586 // to get a consistent AST. 7587 QualType incompatTy; 7588 incompatTy = S.Context.getPointerType( 7589 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7590 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7591 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7592 7593 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7594 // for casts between types with incompatible address space qualifiers. 7595 // For the following code the compiler produces casts between global and 7596 // local address spaces of the corresponded innermost pointees: 7597 // local int *global *a; 7598 // global int *global *b; 7599 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7600 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7601 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7602 << RHS.get()->getSourceRange(); 7603 7604 return incompatTy; 7605 } 7606 7607 // The pointer types are compatible. 7608 // In case of OpenCL ResultTy should have the address space qualifier 7609 // which is a superset of address spaces of both the 2nd and the 3rd 7610 // operands of the conditional operator. 7611 QualType ResultTy = [&, ResultAddrSpace]() { 7612 if (S.getLangOpts().OpenCL) { 7613 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7614 CompositeQuals.setAddressSpace(ResultAddrSpace); 7615 return S.Context 7616 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7617 .withCVRQualifiers(MergedCVRQual); 7618 } 7619 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7620 }(); 7621 if (IsBlockPointer) 7622 ResultTy = S.Context.getBlockPointerType(ResultTy); 7623 else 7624 ResultTy = S.Context.getPointerType(ResultTy); 7625 7626 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7627 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7628 return ResultTy; 7629 } 7630 7631 /// Return the resulting type when the operands are both block pointers. 7632 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7633 ExprResult &LHS, 7634 ExprResult &RHS, 7635 SourceLocation Loc) { 7636 QualType LHSTy = LHS.get()->getType(); 7637 QualType RHSTy = RHS.get()->getType(); 7638 7639 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7640 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7641 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7642 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7643 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7644 return destType; 7645 } 7646 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7647 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7648 << RHS.get()->getSourceRange(); 7649 return QualType(); 7650 } 7651 7652 // We have 2 block pointer types. 7653 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7654 } 7655 7656 /// Return the resulting type when the operands are both pointers. 7657 static QualType 7658 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7659 ExprResult &RHS, 7660 SourceLocation Loc) { 7661 // get the pointer types 7662 QualType LHSTy = LHS.get()->getType(); 7663 QualType RHSTy = RHS.get()->getType(); 7664 7665 // get the "pointed to" types 7666 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7667 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7668 7669 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7670 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7671 // Figure out necessary qualifiers (C99 6.5.15p6) 7672 QualType destPointee 7673 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7674 QualType destType = S.Context.getPointerType(destPointee); 7675 // Add qualifiers if necessary. 7676 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7677 // Promote to void*. 7678 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7679 return destType; 7680 } 7681 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7682 QualType destPointee 7683 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7684 QualType destType = S.Context.getPointerType(destPointee); 7685 // Add qualifiers if necessary. 7686 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7687 // Promote to void*. 7688 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7689 return destType; 7690 } 7691 7692 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7693 } 7694 7695 /// Return false if the first expression is not an integer and the second 7696 /// expression is not a pointer, true otherwise. 7697 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7698 Expr* PointerExpr, SourceLocation Loc, 7699 bool IsIntFirstExpr) { 7700 if (!PointerExpr->getType()->isPointerType() || 7701 !Int.get()->getType()->isIntegerType()) 7702 return false; 7703 7704 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7705 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7706 7707 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7708 << Expr1->getType() << Expr2->getType() 7709 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7710 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7711 CK_IntegralToPointer); 7712 return true; 7713 } 7714 7715 /// Simple conversion between integer and floating point types. 7716 /// 7717 /// Used when handling the OpenCL conditional operator where the 7718 /// condition is a vector while the other operands are scalar. 7719 /// 7720 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7721 /// types are either integer or floating type. Between the two 7722 /// operands, the type with the higher rank is defined as the "result 7723 /// type". The other operand needs to be promoted to the same type. No 7724 /// other type promotion is allowed. We cannot use 7725 /// UsualArithmeticConversions() for this purpose, since it always 7726 /// promotes promotable types. 7727 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7728 ExprResult &RHS, 7729 SourceLocation QuestionLoc) { 7730 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7731 if (LHS.isInvalid()) 7732 return QualType(); 7733 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7734 if (RHS.isInvalid()) 7735 return QualType(); 7736 7737 // For conversion purposes, we ignore any qualifiers. 7738 // For example, "const float" and "float" are equivalent. 7739 QualType LHSType = 7740 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7741 QualType RHSType = 7742 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7743 7744 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7745 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7746 << LHSType << LHS.get()->getSourceRange(); 7747 return QualType(); 7748 } 7749 7750 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7751 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7752 << RHSType << RHS.get()->getSourceRange(); 7753 return QualType(); 7754 } 7755 7756 // If both types are identical, no conversion is needed. 7757 if (LHSType == RHSType) 7758 return LHSType; 7759 7760 // Now handle "real" floating types (i.e. float, double, long double). 7761 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7762 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7763 /*IsCompAssign = */ false); 7764 7765 // Finally, we have two differing integer types. 7766 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7767 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7768 } 7769 7770 /// Convert scalar operands to a vector that matches the 7771 /// condition in length. 7772 /// 7773 /// Used when handling the OpenCL conditional operator where the 7774 /// condition is a vector while the other operands are scalar. 7775 /// 7776 /// We first compute the "result type" for the scalar operands 7777 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7778 /// into a vector of that type where the length matches the condition 7779 /// vector type. s6.11.6 requires that the element types of the result 7780 /// and the condition must have the same number of bits. 7781 static QualType 7782 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7783 QualType CondTy, SourceLocation QuestionLoc) { 7784 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7785 if (ResTy.isNull()) return QualType(); 7786 7787 const VectorType *CV = CondTy->getAs<VectorType>(); 7788 assert(CV); 7789 7790 // Determine the vector result type 7791 unsigned NumElements = CV->getNumElements(); 7792 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7793 7794 // Ensure that all types have the same number of bits 7795 if (S.Context.getTypeSize(CV->getElementType()) 7796 != S.Context.getTypeSize(ResTy)) { 7797 // Since VectorTy is created internally, it does not pretty print 7798 // with an OpenCL name. Instead, we just print a description. 7799 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7800 SmallString<64> Str; 7801 llvm::raw_svector_ostream OS(Str); 7802 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7803 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7804 << CondTy << OS.str(); 7805 return QualType(); 7806 } 7807 7808 // Convert operands to the vector result type 7809 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7810 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7811 7812 return VectorTy; 7813 } 7814 7815 /// Return false if this is a valid OpenCL condition vector 7816 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7817 SourceLocation QuestionLoc) { 7818 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7819 // integral type. 7820 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7821 assert(CondTy); 7822 QualType EleTy = CondTy->getElementType(); 7823 if (EleTy->isIntegerType()) return false; 7824 7825 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7826 << Cond->getType() << Cond->getSourceRange(); 7827 return true; 7828 } 7829 7830 /// Return false if the vector condition type and the vector 7831 /// result type are compatible. 7832 /// 7833 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7834 /// number of elements, and their element types have the same number 7835 /// of bits. 7836 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7837 SourceLocation QuestionLoc) { 7838 const VectorType *CV = CondTy->getAs<VectorType>(); 7839 const VectorType *RV = VecResTy->getAs<VectorType>(); 7840 assert(CV && RV); 7841 7842 if (CV->getNumElements() != RV->getNumElements()) { 7843 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7844 << CondTy << VecResTy; 7845 return true; 7846 } 7847 7848 QualType CVE = CV->getElementType(); 7849 QualType RVE = RV->getElementType(); 7850 7851 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7852 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7853 << CondTy << VecResTy; 7854 return true; 7855 } 7856 7857 return false; 7858 } 7859 7860 /// Return the resulting type for the conditional operator in 7861 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7862 /// s6.3.i) when the condition is a vector type. 7863 static QualType 7864 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7865 ExprResult &LHS, ExprResult &RHS, 7866 SourceLocation QuestionLoc) { 7867 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7868 if (Cond.isInvalid()) 7869 return QualType(); 7870 QualType CondTy = Cond.get()->getType(); 7871 7872 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7873 return QualType(); 7874 7875 // If either operand is a vector then find the vector type of the 7876 // result as specified in OpenCL v1.1 s6.3.i. 7877 if (LHS.get()->getType()->isVectorType() || 7878 RHS.get()->getType()->isVectorType()) { 7879 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7880 /*isCompAssign*/false, 7881 /*AllowBothBool*/true, 7882 /*AllowBoolConversions*/false); 7883 if (VecResTy.isNull()) return QualType(); 7884 // The result type must match the condition type as specified in 7885 // OpenCL v1.1 s6.11.6. 7886 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7887 return QualType(); 7888 return VecResTy; 7889 } 7890 7891 // Both operands are scalar. 7892 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7893 } 7894 7895 /// Return true if the Expr is block type 7896 static bool checkBlockType(Sema &S, const Expr *E) { 7897 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7898 QualType Ty = CE->getCallee()->getType(); 7899 if (Ty->isBlockPointerType()) { 7900 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7901 return true; 7902 } 7903 } 7904 return false; 7905 } 7906 7907 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7908 /// In that case, LHS = cond. 7909 /// C99 6.5.15 7910 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7911 ExprResult &RHS, ExprValueKind &VK, 7912 ExprObjectKind &OK, 7913 SourceLocation QuestionLoc) { 7914 7915 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7916 if (!LHSResult.isUsable()) return QualType(); 7917 LHS = LHSResult; 7918 7919 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7920 if (!RHSResult.isUsable()) return QualType(); 7921 RHS = RHSResult; 7922 7923 // C++ is sufficiently different to merit its own checker. 7924 if (getLangOpts().CPlusPlus) 7925 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7926 7927 VK = VK_RValue; 7928 OK = OK_Ordinary; 7929 7930 // The OpenCL operator with a vector condition is sufficiently 7931 // different to merit its own checker. 7932 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7933 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7934 7935 // First, check the condition. 7936 Cond = UsualUnaryConversions(Cond.get()); 7937 if (Cond.isInvalid()) 7938 return QualType(); 7939 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7940 return QualType(); 7941 7942 // Now check the two expressions. 7943 if (LHS.get()->getType()->isVectorType() || 7944 RHS.get()->getType()->isVectorType()) 7945 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7946 /*AllowBothBool*/true, 7947 /*AllowBoolConversions*/false); 7948 7949 QualType ResTy = 7950 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7951 if (LHS.isInvalid() || RHS.isInvalid()) 7952 return QualType(); 7953 7954 QualType LHSTy = LHS.get()->getType(); 7955 QualType RHSTy = RHS.get()->getType(); 7956 7957 // Diagnose attempts to convert between __float128 and long double where 7958 // such conversions currently can't be handled. 7959 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7960 Diag(QuestionLoc, 7961 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7963 return QualType(); 7964 } 7965 7966 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7967 // selection operator (?:). 7968 if (getLangOpts().OpenCL && 7969 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7970 return QualType(); 7971 } 7972 7973 // If both operands have arithmetic type, do the usual arithmetic conversions 7974 // to find a common type: C99 6.5.15p3,5. 7975 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7976 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7977 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7978 7979 return ResTy; 7980 } 7981 7982 // If both operands are the same structure or union type, the result is that 7983 // type. 7984 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7985 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7986 if (LHSRT->getDecl() == RHSRT->getDecl()) 7987 // "If both the operands have structure or union type, the result has 7988 // that type." This implies that CV qualifiers are dropped. 7989 return LHSTy.getUnqualifiedType(); 7990 // FIXME: Type of conditional expression must be complete in C mode. 7991 } 7992 7993 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7994 // The following || allows only one side to be void (a GCC-ism). 7995 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7996 return checkConditionalVoidType(*this, LHS, RHS); 7997 } 7998 7999 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8000 // the type of the other operand." 8001 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8002 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8003 8004 // All objective-c pointer type analysis is done here. 8005 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8006 QuestionLoc); 8007 if (LHS.isInvalid() || RHS.isInvalid()) 8008 return QualType(); 8009 if (!compositeType.isNull()) 8010 return compositeType; 8011 8012 8013 // Handle block pointer types. 8014 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8015 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8016 QuestionLoc); 8017 8018 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8019 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8020 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8021 QuestionLoc); 8022 8023 // GCC compatibility: soften pointer/integer mismatch. Note that 8024 // null pointers have been filtered out by this point. 8025 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8026 /*IsIntFirstExpr=*/true)) 8027 return RHSTy; 8028 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8029 /*IsIntFirstExpr=*/false)) 8030 return LHSTy; 8031 8032 // Allow ?: operations in which both operands have the same 8033 // built-in sizeless type. 8034 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8035 return LHSTy; 8036 8037 // Emit a better diagnostic if one of the expressions is a null pointer 8038 // constant and the other is not a pointer type. In this case, the user most 8039 // likely forgot to take the address of the other expression. 8040 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8041 return QualType(); 8042 8043 // Otherwise, the operands are not compatible. 8044 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8045 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8046 << RHS.get()->getSourceRange(); 8047 return QualType(); 8048 } 8049 8050 /// FindCompositeObjCPointerType - Helper method to find composite type of 8051 /// two objective-c pointer types of the two input expressions. 8052 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8053 SourceLocation QuestionLoc) { 8054 QualType LHSTy = LHS.get()->getType(); 8055 QualType RHSTy = RHS.get()->getType(); 8056 8057 // Handle things like Class and struct objc_class*. Here we case the result 8058 // to the pseudo-builtin, because that will be implicitly cast back to the 8059 // redefinition type if an attempt is made to access its fields. 8060 if (LHSTy->isObjCClassType() && 8061 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8062 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8063 return LHSTy; 8064 } 8065 if (RHSTy->isObjCClassType() && 8066 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8067 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8068 return RHSTy; 8069 } 8070 // And the same for struct objc_object* / id 8071 if (LHSTy->isObjCIdType() && 8072 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8073 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8074 return LHSTy; 8075 } 8076 if (RHSTy->isObjCIdType() && 8077 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8078 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8079 return RHSTy; 8080 } 8081 // And the same for struct objc_selector* / SEL 8082 if (Context.isObjCSelType(LHSTy) && 8083 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8084 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8085 return LHSTy; 8086 } 8087 if (Context.isObjCSelType(RHSTy) && 8088 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8089 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8090 return RHSTy; 8091 } 8092 // Check constraints for Objective-C object pointers types. 8093 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8094 8095 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8096 // Two identical object pointer types are always compatible. 8097 return LHSTy; 8098 } 8099 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8100 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8101 QualType compositeType = LHSTy; 8102 8103 // If both operands are interfaces and either operand can be 8104 // assigned to the other, use that type as the composite 8105 // type. This allows 8106 // xxx ? (A*) a : (B*) b 8107 // where B is a subclass of A. 8108 // 8109 // Additionally, as for assignment, if either type is 'id' 8110 // allow silent coercion. Finally, if the types are 8111 // incompatible then make sure to use 'id' as the composite 8112 // type so the result is acceptable for sending messages to. 8113 8114 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8115 // It could return the composite type. 8116 if (!(compositeType = 8117 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8118 // Nothing more to do. 8119 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8120 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8121 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8122 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8123 } else if ((LHSOPT->isObjCQualifiedIdType() || 8124 RHSOPT->isObjCQualifiedIdType()) && 8125 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8126 true)) { 8127 // Need to handle "id<xx>" explicitly. 8128 // GCC allows qualified id and any Objective-C type to devolve to 8129 // id. Currently localizing to here until clear this should be 8130 // part of ObjCQualifiedIdTypesAreCompatible. 8131 compositeType = Context.getObjCIdType(); 8132 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8133 compositeType = Context.getObjCIdType(); 8134 } else { 8135 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8136 << LHSTy << RHSTy 8137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8138 QualType incompatTy = Context.getObjCIdType(); 8139 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8140 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8141 return incompatTy; 8142 } 8143 // The object pointer types are compatible. 8144 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8145 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8146 return compositeType; 8147 } 8148 // Check Objective-C object pointer types and 'void *' 8149 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8150 if (getLangOpts().ObjCAutoRefCount) { 8151 // ARC forbids the implicit conversion of object pointers to 'void *', 8152 // so these types are not compatible. 8153 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8154 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8155 LHS = RHS = true; 8156 return QualType(); 8157 } 8158 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8159 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8160 QualType destPointee 8161 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8162 QualType destType = Context.getPointerType(destPointee); 8163 // Add qualifiers if necessary. 8164 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8165 // Promote to void*. 8166 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8167 return destType; 8168 } 8169 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8170 if (getLangOpts().ObjCAutoRefCount) { 8171 // ARC forbids the implicit conversion of object pointers to 'void *', 8172 // so these types are not compatible. 8173 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8174 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8175 LHS = RHS = true; 8176 return QualType(); 8177 } 8178 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8179 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8180 QualType destPointee 8181 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8182 QualType destType = Context.getPointerType(destPointee); 8183 // Add qualifiers if necessary. 8184 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8185 // Promote to void*. 8186 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8187 return destType; 8188 } 8189 return QualType(); 8190 } 8191 8192 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8193 /// ParenRange in parentheses. 8194 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8195 const PartialDiagnostic &Note, 8196 SourceRange ParenRange) { 8197 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8198 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8199 EndLoc.isValid()) { 8200 Self.Diag(Loc, Note) 8201 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8202 << FixItHint::CreateInsertion(EndLoc, ")"); 8203 } else { 8204 // We can't display the parentheses, so just show the bare note. 8205 Self.Diag(Loc, Note) << ParenRange; 8206 } 8207 } 8208 8209 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8210 return BinaryOperator::isAdditiveOp(Opc) || 8211 BinaryOperator::isMultiplicativeOp(Opc) || 8212 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8213 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8214 // not any of the logical operators. Bitwise-xor is commonly used as a 8215 // logical-xor because there is no logical-xor operator. The logical 8216 // operators, including uses of xor, have a high false positive rate for 8217 // precedence warnings. 8218 } 8219 8220 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8221 /// expression, either using a built-in or overloaded operator, 8222 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8223 /// expression. 8224 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8225 Expr **RHSExprs) { 8226 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8227 E = E->IgnoreImpCasts(); 8228 E = E->IgnoreConversionOperator(); 8229 E = E->IgnoreImpCasts(); 8230 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8231 E = MTE->getSubExpr(); 8232 E = E->IgnoreImpCasts(); 8233 } 8234 8235 // Built-in binary operator. 8236 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8237 if (IsArithmeticOp(OP->getOpcode())) { 8238 *Opcode = OP->getOpcode(); 8239 *RHSExprs = OP->getRHS(); 8240 return true; 8241 } 8242 } 8243 8244 // Overloaded operator. 8245 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8246 if (Call->getNumArgs() != 2) 8247 return false; 8248 8249 // Make sure this is really a binary operator that is safe to pass into 8250 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8251 OverloadedOperatorKind OO = Call->getOperator(); 8252 if (OO < OO_Plus || OO > OO_Arrow || 8253 OO == OO_PlusPlus || OO == OO_MinusMinus) 8254 return false; 8255 8256 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8257 if (IsArithmeticOp(OpKind)) { 8258 *Opcode = OpKind; 8259 *RHSExprs = Call->getArg(1); 8260 return true; 8261 } 8262 } 8263 8264 return false; 8265 } 8266 8267 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8268 /// or is a logical expression such as (x==y) which has int type, but is 8269 /// commonly interpreted as boolean. 8270 static bool ExprLooksBoolean(Expr *E) { 8271 E = E->IgnoreParenImpCasts(); 8272 8273 if (E->getType()->isBooleanType()) 8274 return true; 8275 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8276 return OP->isComparisonOp() || OP->isLogicalOp(); 8277 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8278 return OP->getOpcode() == UO_LNot; 8279 if (E->getType()->isPointerType()) 8280 return true; 8281 // FIXME: What about overloaded operator calls returning "unspecified boolean 8282 // type"s (commonly pointer-to-members)? 8283 8284 return false; 8285 } 8286 8287 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8288 /// and binary operator are mixed in a way that suggests the programmer assumed 8289 /// the conditional operator has higher precedence, for example: 8290 /// "int x = a + someBinaryCondition ? 1 : 2". 8291 static void DiagnoseConditionalPrecedence(Sema &Self, 8292 SourceLocation OpLoc, 8293 Expr *Condition, 8294 Expr *LHSExpr, 8295 Expr *RHSExpr) { 8296 BinaryOperatorKind CondOpcode; 8297 Expr *CondRHS; 8298 8299 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8300 return; 8301 if (!ExprLooksBoolean(CondRHS)) 8302 return; 8303 8304 // The condition is an arithmetic binary expression, with a right- 8305 // hand side that looks boolean, so warn. 8306 8307 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8308 ? diag::warn_precedence_bitwise_conditional 8309 : diag::warn_precedence_conditional; 8310 8311 Self.Diag(OpLoc, DiagID) 8312 << Condition->getSourceRange() 8313 << BinaryOperator::getOpcodeStr(CondOpcode); 8314 8315 SuggestParentheses( 8316 Self, OpLoc, 8317 Self.PDiag(diag::note_precedence_silence) 8318 << BinaryOperator::getOpcodeStr(CondOpcode), 8319 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8320 8321 SuggestParentheses(Self, OpLoc, 8322 Self.PDiag(diag::note_precedence_conditional_first), 8323 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8324 } 8325 8326 /// Compute the nullability of a conditional expression. 8327 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8328 QualType LHSTy, QualType RHSTy, 8329 ASTContext &Ctx) { 8330 if (!ResTy->isAnyPointerType()) 8331 return ResTy; 8332 8333 auto GetNullability = [&Ctx](QualType Ty) { 8334 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8335 if (Kind) 8336 return *Kind; 8337 return NullabilityKind::Unspecified; 8338 }; 8339 8340 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8341 NullabilityKind MergedKind; 8342 8343 // Compute nullability of a binary conditional expression. 8344 if (IsBin) { 8345 if (LHSKind == NullabilityKind::NonNull) 8346 MergedKind = NullabilityKind::NonNull; 8347 else 8348 MergedKind = RHSKind; 8349 // Compute nullability of a normal conditional expression. 8350 } else { 8351 if (LHSKind == NullabilityKind::Nullable || 8352 RHSKind == NullabilityKind::Nullable) 8353 MergedKind = NullabilityKind::Nullable; 8354 else if (LHSKind == NullabilityKind::NonNull) 8355 MergedKind = RHSKind; 8356 else if (RHSKind == NullabilityKind::NonNull) 8357 MergedKind = LHSKind; 8358 else 8359 MergedKind = NullabilityKind::Unspecified; 8360 } 8361 8362 // Return if ResTy already has the correct nullability. 8363 if (GetNullability(ResTy) == MergedKind) 8364 return ResTy; 8365 8366 // Strip all nullability from ResTy. 8367 while (ResTy->getNullability(Ctx)) 8368 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8369 8370 // Create a new AttributedType with the new nullability kind. 8371 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8372 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8373 } 8374 8375 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8376 /// in the case of a the GNU conditional expr extension. 8377 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8378 SourceLocation ColonLoc, 8379 Expr *CondExpr, Expr *LHSExpr, 8380 Expr *RHSExpr) { 8381 if (!getLangOpts().CPlusPlus) { 8382 // C cannot handle TypoExpr nodes in the condition because it 8383 // doesn't handle dependent types properly, so make sure any TypoExprs have 8384 // been dealt with before checking the operands. 8385 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8386 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8387 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8388 8389 if (!CondResult.isUsable()) 8390 return ExprError(); 8391 8392 if (LHSExpr) { 8393 if (!LHSResult.isUsable()) 8394 return ExprError(); 8395 } 8396 8397 if (!RHSResult.isUsable()) 8398 return ExprError(); 8399 8400 CondExpr = CondResult.get(); 8401 LHSExpr = LHSResult.get(); 8402 RHSExpr = RHSResult.get(); 8403 } 8404 8405 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8406 // was the condition. 8407 OpaqueValueExpr *opaqueValue = nullptr; 8408 Expr *commonExpr = nullptr; 8409 if (!LHSExpr) { 8410 commonExpr = CondExpr; 8411 // Lower out placeholder types first. This is important so that we don't 8412 // try to capture a placeholder. This happens in few cases in C++; such 8413 // as Objective-C++'s dictionary subscripting syntax. 8414 if (commonExpr->hasPlaceholderType()) { 8415 ExprResult result = CheckPlaceholderExpr(commonExpr); 8416 if (!result.isUsable()) return ExprError(); 8417 commonExpr = result.get(); 8418 } 8419 // We usually want to apply unary conversions *before* saving, except 8420 // in the special case of a C++ l-value conditional. 8421 if (!(getLangOpts().CPlusPlus 8422 && !commonExpr->isTypeDependent() 8423 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8424 && commonExpr->isGLValue() 8425 && commonExpr->isOrdinaryOrBitFieldObject() 8426 && RHSExpr->isOrdinaryOrBitFieldObject() 8427 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8428 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8429 if (commonRes.isInvalid()) 8430 return ExprError(); 8431 commonExpr = commonRes.get(); 8432 } 8433 8434 // If the common expression is a class or array prvalue, materialize it 8435 // so that we can safely refer to it multiple times. 8436 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8437 commonExpr->getType()->isArrayType())) { 8438 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8439 if (MatExpr.isInvalid()) 8440 return ExprError(); 8441 commonExpr = MatExpr.get(); 8442 } 8443 8444 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8445 commonExpr->getType(), 8446 commonExpr->getValueKind(), 8447 commonExpr->getObjectKind(), 8448 commonExpr); 8449 LHSExpr = CondExpr = opaqueValue; 8450 } 8451 8452 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8453 ExprValueKind VK = VK_RValue; 8454 ExprObjectKind OK = OK_Ordinary; 8455 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8456 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8457 VK, OK, QuestionLoc); 8458 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8459 RHS.isInvalid()) 8460 return ExprError(); 8461 8462 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8463 RHS.get()); 8464 8465 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8466 8467 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8468 Context); 8469 8470 if (!commonExpr) 8471 return new (Context) 8472 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8473 RHS.get(), result, VK, OK); 8474 8475 return new (Context) BinaryConditionalOperator( 8476 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8477 ColonLoc, result, VK, OK); 8478 } 8479 8480 // Check if we have a conversion between incompatible cmse function pointer 8481 // types, that is, a conversion between a function pointer with the 8482 // cmse_nonsecure_call attribute and one without. 8483 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8484 QualType ToType) { 8485 if (const auto *ToFn = 8486 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8487 if (const auto *FromFn = 8488 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8489 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8490 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8491 8492 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8493 } 8494 } 8495 return false; 8496 } 8497 8498 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8499 // being closely modeled after the C99 spec:-). The odd characteristic of this 8500 // routine is it effectively iqnores the qualifiers on the top level pointee. 8501 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8502 // FIXME: add a couple examples in this comment. 8503 static Sema::AssignConvertType 8504 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8505 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8506 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8507 8508 // get the "pointed to" type (ignoring qualifiers at the top level) 8509 const Type *lhptee, *rhptee; 8510 Qualifiers lhq, rhq; 8511 std::tie(lhptee, lhq) = 8512 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8513 std::tie(rhptee, rhq) = 8514 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8515 8516 Sema::AssignConvertType ConvTy = Sema::Compatible; 8517 8518 // C99 6.5.16.1p1: This following citation is common to constraints 8519 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8520 // qualifiers of the type *pointed to* by the right; 8521 8522 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8523 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8524 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8525 // Ignore lifetime for further calculation. 8526 lhq.removeObjCLifetime(); 8527 rhq.removeObjCLifetime(); 8528 } 8529 8530 if (!lhq.compatiblyIncludes(rhq)) { 8531 // Treat address-space mismatches as fatal. 8532 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8533 return Sema::IncompatiblePointerDiscardsQualifiers; 8534 8535 // It's okay to add or remove GC or lifetime qualifiers when converting to 8536 // and from void*. 8537 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8538 .compatiblyIncludes( 8539 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8540 && (lhptee->isVoidType() || rhptee->isVoidType())) 8541 ; // keep old 8542 8543 // Treat lifetime mismatches as fatal. 8544 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8545 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8546 8547 // For GCC/MS compatibility, other qualifier mismatches are treated 8548 // as still compatible in C. 8549 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8550 } 8551 8552 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8553 // incomplete type and the other is a pointer to a qualified or unqualified 8554 // version of void... 8555 if (lhptee->isVoidType()) { 8556 if (rhptee->isIncompleteOrObjectType()) 8557 return ConvTy; 8558 8559 // As an extension, we allow cast to/from void* to function pointer. 8560 assert(rhptee->isFunctionType()); 8561 return Sema::FunctionVoidPointer; 8562 } 8563 8564 if (rhptee->isVoidType()) { 8565 if (lhptee->isIncompleteOrObjectType()) 8566 return ConvTy; 8567 8568 // As an extension, we allow cast to/from void* to function pointer. 8569 assert(lhptee->isFunctionType()); 8570 return Sema::FunctionVoidPointer; 8571 } 8572 8573 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8574 // unqualified versions of compatible types, ... 8575 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8576 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8577 // Check if the pointee types are compatible ignoring the sign. 8578 // We explicitly check for char so that we catch "char" vs 8579 // "unsigned char" on systems where "char" is unsigned. 8580 if (lhptee->isCharType()) 8581 ltrans = S.Context.UnsignedCharTy; 8582 else if (lhptee->hasSignedIntegerRepresentation()) 8583 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8584 8585 if (rhptee->isCharType()) 8586 rtrans = S.Context.UnsignedCharTy; 8587 else if (rhptee->hasSignedIntegerRepresentation()) 8588 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8589 8590 if (ltrans == rtrans) { 8591 // Types are compatible ignoring the sign. Qualifier incompatibility 8592 // takes priority over sign incompatibility because the sign 8593 // warning can be disabled. 8594 if (ConvTy != Sema::Compatible) 8595 return ConvTy; 8596 8597 return Sema::IncompatiblePointerSign; 8598 } 8599 8600 // If we are a multi-level pointer, it's possible that our issue is simply 8601 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8602 // the eventual target type is the same and the pointers have the same 8603 // level of indirection, this must be the issue. 8604 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8605 do { 8606 std::tie(lhptee, lhq) = 8607 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8608 std::tie(rhptee, rhq) = 8609 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8610 8611 // Inconsistent address spaces at this point is invalid, even if the 8612 // address spaces would be compatible. 8613 // FIXME: This doesn't catch address space mismatches for pointers of 8614 // different nesting levels, like: 8615 // __local int *** a; 8616 // int ** b = a; 8617 // It's not clear how to actually determine when such pointers are 8618 // invalidly incompatible. 8619 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8620 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8621 8622 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8623 8624 if (lhptee == rhptee) 8625 return Sema::IncompatibleNestedPointerQualifiers; 8626 } 8627 8628 // General pointer incompatibility takes priority over qualifiers. 8629 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8630 return Sema::IncompatibleFunctionPointer; 8631 return Sema::IncompatiblePointer; 8632 } 8633 if (!S.getLangOpts().CPlusPlus && 8634 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8635 return Sema::IncompatibleFunctionPointer; 8636 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8637 return Sema::IncompatibleFunctionPointer; 8638 return ConvTy; 8639 } 8640 8641 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8642 /// block pointer types are compatible or whether a block and normal pointer 8643 /// are compatible. It is more restrict than comparing two function pointer 8644 // types. 8645 static Sema::AssignConvertType 8646 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8647 QualType RHSType) { 8648 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8649 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8650 8651 QualType lhptee, rhptee; 8652 8653 // get the "pointed to" type (ignoring qualifiers at the top level) 8654 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8655 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8656 8657 // In C++, the types have to match exactly. 8658 if (S.getLangOpts().CPlusPlus) 8659 return Sema::IncompatibleBlockPointer; 8660 8661 Sema::AssignConvertType ConvTy = Sema::Compatible; 8662 8663 // For blocks we enforce that qualifiers are identical. 8664 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8665 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8666 if (S.getLangOpts().OpenCL) { 8667 LQuals.removeAddressSpace(); 8668 RQuals.removeAddressSpace(); 8669 } 8670 if (LQuals != RQuals) 8671 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8672 8673 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8674 // assignment. 8675 // The current behavior is similar to C++ lambdas. A block might be 8676 // assigned to a variable iff its return type and parameters are compatible 8677 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8678 // an assignment. Presumably it should behave in way that a function pointer 8679 // assignment does in C, so for each parameter and return type: 8680 // * CVR and address space of LHS should be a superset of CVR and address 8681 // space of RHS. 8682 // * unqualified types should be compatible. 8683 if (S.getLangOpts().OpenCL) { 8684 if (!S.Context.typesAreBlockPointerCompatible( 8685 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8686 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8687 return Sema::IncompatibleBlockPointer; 8688 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8689 return Sema::IncompatibleBlockPointer; 8690 8691 return ConvTy; 8692 } 8693 8694 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8695 /// for assignment compatibility. 8696 static Sema::AssignConvertType 8697 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8698 QualType RHSType) { 8699 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8700 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8701 8702 if (LHSType->isObjCBuiltinType()) { 8703 // Class is not compatible with ObjC object pointers. 8704 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8705 !RHSType->isObjCQualifiedClassType()) 8706 return Sema::IncompatiblePointer; 8707 return Sema::Compatible; 8708 } 8709 if (RHSType->isObjCBuiltinType()) { 8710 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8711 !LHSType->isObjCQualifiedClassType()) 8712 return Sema::IncompatiblePointer; 8713 return Sema::Compatible; 8714 } 8715 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8716 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8717 8718 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8719 // make an exception for id<P> 8720 !LHSType->isObjCQualifiedIdType()) 8721 return Sema::CompatiblePointerDiscardsQualifiers; 8722 8723 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8724 return Sema::Compatible; 8725 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8726 return Sema::IncompatibleObjCQualifiedId; 8727 return Sema::IncompatiblePointer; 8728 } 8729 8730 Sema::AssignConvertType 8731 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8732 QualType LHSType, QualType RHSType) { 8733 // Fake up an opaque expression. We don't actually care about what 8734 // cast operations are required, so if CheckAssignmentConstraints 8735 // adds casts to this they'll be wasted, but fortunately that doesn't 8736 // usually happen on valid code. 8737 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8738 ExprResult RHSPtr = &RHSExpr; 8739 CastKind K; 8740 8741 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8742 } 8743 8744 /// This helper function returns true if QT is a vector type that has element 8745 /// type ElementType. 8746 static bool isVector(QualType QT, QualType ElementType) { 8747 if (const VectorType *VT = QT->getAs<VectorType>()) 8748 return VT->getElementType().getCanonicalType() == ElementType; 8749 return false; 8750 } 8751 8752 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8753 /// has code to accommodate several GCC extensions when type checking 8754 /// pointers. Here are some objectionable examples that GCC considers warnings: 8755 /// 8756 /// int a, *pint; 8757 /// short *pshort; 8758 /// struct foo *pfoo; 8759 /// 8760 /// pint = pshort; // warning: assignment from incompatible pointer type 8761 /// a = pint; // warning: assignment makes integer from pointer without a cast 8762 /// pint = a; // warning: assignment makes pointer from integer without a cast 8763 /// pint = pfoo; // warning: assignment from incompatible pointer type 8764 /// 8765 /// As a result, the code for dealing with pointers is more complex than the 8766 /// C99 spec dictates. 8767 /// 8768 /// Sets 'Kind' for any result kind except Incompatible. 8769 Sema::AssignConvertType 8770 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8771 CastKind &Kind, bool ConvertRHS) { 8772 QualType RHSType = RHS.get()->getType(); 8773 QualType OrigLHSType = LHSType; 8774 8775 // Get canonical types. We're not formatting these types, just comparing 8776 // them. 8777 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8778 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8779 8780 // Common case: no conversion required. 8781 if (LHSType == RHSType) { 8782 Kind = CK_NoOp; 8783 return Compatible; 8784 } 8785 8786 // If we have an atomic type, try a non-atomic assignment, then just add an 8787 // atomic qualification step. 8788 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8789 Sema::AssignConvertType result = 8790 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8791 if (result != Compatible) 8792 return result; 8793 if (Kind != CK_NoOp && ConvertRHS) 8794 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8795 Kind = CK_NonAtomicToAtomic; 8796 return Compatible; 8797 } 8798 8799 // If the left-hand side is a reference type, then we are in a 8800 // (rare!) case where we've allowed the use of references in C, 8801 // e.g., as a parameter type in a built-in function. In this case, 8802 // just make sure that the type referenced is compatible with the 8803 // right-hand side type. The caller is responsible for adjusting 8804 // LHSType so that the resulting expression does not have reference 8805 // type. 8806 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8807 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8808 Kind = CK_LValueBitCast; 8809 return Compatible; 8810 } 8811 return Incompatible; 8812 } 8813 8814 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8815 // to the same ExtVector type. 8816 if (LHSType->isExtVectorType()) { 8817 if (RHSType->isExtVectorType()) 8818 return Incompatible; 8819 if (RHSType->isArithmeticType()) { 8820 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8821 if (ConvertRHS) 8822 RHS = prepareVectorSplat(LHSType, RHS.get()); 8823 Kind = CK_VectorSplat; 8824 return Compatible; 8825 } 8826 } 8827 8828 // Conversions to or from vector type. 8829 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8830 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8831 // Allow assignments of an AltiVec vector type to an equivalent GCC 8832 // vector type and vice versa 8833 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8834 Kind = CK_BitCast; 8835 return Compatible; 8836 } 8837 8838 // If we are allowing lax vector conversions, and LHS and RHS are both 8839 // vectors, the total size only needs to be the same. This is a bitcast; 8840 // no bits are changed but the result type is different. 8841 if (isLaxVectorConversion(RHSType, LHSType)) { 8842 Kind = CK_BitCast; 8843 return IncompatibleVectors; 8844 } 8845 } 8846 8847 // When the RHS comes from another lax conversion (e.g. binops between 8848 // scalars and vectors) the result is canonicalized as a vector. When the 8849 // LHS is also a vector, the lax is allowed by the condition above. Handle 8850 // the case where LHS is a scalar. 8851 if (LHSType->isScalarType()) { 8852 const VectorType *VecType = RHSType->getAs<VectorType>(); 8853 if (VecType && VecType->getNumElements() == 1 && 8854 isLaxVectorConversion(RHSType, LHSType)) { 8855 ExprResult *VecExpr = &RHS; 8856 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8857 Kind = CK_BitCast; 8858 return Compatible; 8859 } 8860 } 8861 8862 return Incompatible; 8863 } 8864 8865 // Diagnose attempts to convert between __float128 and long double where 8866 // such conversions currently can't be handled. 8867 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8868 return Incompatible; 8869 8870 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8871 // discards the imaginary part. 8872 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8873 !LHSType->getAs<ComplexType>()) 8874 return Incompatible; 8875 8876 // Arithmetic conversions. 8877 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8878 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8879 if (ConvertRHS) 8880 Kind = PrepareScalarCast(RHS, LHSType); 8881 return Compatible; 8882 } 8883 8884 // Conversions to normal pointers. 8885 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8886 // U* -> T* 8887 if (isa<PointerType>(RHSType)) { 8888 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8889 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8890 if (AddrSpaceL != AddrSpaceR) 8891 Kind = CK_AddressSpaceConversion; 8892 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8893 Kind = CK_NoOp; 8894 else 8895 Kind = CK_BitCast; 8896 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8897 } 8898 8899 // int -> T* 8900 if (RHSType->isIntegerType()) { 8901 Kind = CK_IntegralToPointer; // FIXME: null? 8902 return IntToPointer; 8903 } 8904 8905 // C pointers are not compatible with ObjC object pointers, 8906 // with two exceptions: 8907 if (isa<ObjCObjectPointerType>(RHSType)) { 8908 // - conversions to void* 8909 if (LHSPointer->getPointeeType()->isVoidType()) { 8910 Kind = CK_BitCast; 8911 return Compatible; 8912 } 8913 8914 // - conversions from 'Class' to the redefinition type 8915 if (RHSType->isObjCClassType() && 8916 Context.hasSameType(LHSType, 8917 Context.getObjCClassRedefinitionType())) { 8918 Kind = CK_BitCast; 8919 return Compatible; 8920 } 8921 8922 Kind = CK_BitCast; 8923 return IncompatiblePointer; 8924 } 8925 8926 // U^ -> void* 8927 if (RHSType->getAs<BlockPointerType>()) { 8928 if (LHSPointer->getPointeeType()->isVoidType()) { 8929 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8930 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8931 ->getPointeeType() 8932 .getAddressSpace(); 8933 Kind = 8934 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8935 return Compatible; 8936 } 8937 } 8938 8939 return Incompatible; 8940 } 8941 8942 // Conversions to block pointers. 8943 if (isa<BlockPointerType>(LHSType)) { 8944 // U^ -> T^ 8945 if (RHSType->isBlockPointerType()) { 8946 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8947 ->getPointeeType() 8948 .getAddressSpace(); 8949 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8950 ->getPointeeType() 8951 .getAddressSpace(); 8952 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8953 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8954 } 8955 8956 // int or null -> T^ 8957 if (RHSType->isIntegerType()) { 8958 Kind = CK_IntegralToPointer; // FIXME: null 8959 return IntToBlockPointer; 8960 } 8961 8962 // id -> T^ 8963 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8964 Kind = CK_AnyPointerToBlockPointerCast; 8965 return Compatible; 8966 } 8967 8968 // void* -> T^ 8969 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8970 if (RHSPT->getPointeeType()->isVoidType()) { 8971 Kind = CK_AnyPointerToBlockPointerCast; 8972 return Compatible; 8973 } 8974 8975 return Incompatible; 8976 } 8977 8978 // Conversions to Objective-C pointers. 8979 if (isa<ObjCObjectPointerType>(LHSType)) { 8980 // A* -> B* 8981 if (RHSType->isObjCObjectPointerType()) { 8982 Kind = CK_BitCast; 8983 Sema::AssignConvertType result = 8984 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8985 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8986 result == Compatible && 8987 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8988 result = IncompatibleObjCWeakRef; 8989 return result; 8990 } 8991 8992 // int or null -> A* 8993 if (RHSType->isIntegerType()) { 8994 Kind = CK_IntegralToPointer; // FIXME: null 8995 return IntToPointer; 8996 } 8997 8998 // In general, C pointers are not compatible with ObjC object pointers, 8999 // with two exceptions: 9000 if (isa<PointerType>(RHSType)) { 9001 Kind = CK_CPointerToObjCPointerCast; 9002 9003 // - conversions from 'void*' 9004 if (RHSType->isVoidPointerType()) { 9005 return Compatible; 9006 } 9007 9008 // - conversions to 'Class' from its redefinition type 9009 if (LHSType->isObjCClassType() && 9010 Context.hasSameType(RHSType, 9011 Context.getObjCClassRedefinitionType())) { 9012 return Compatible; 9013 } 9014 9015 return IncompatiblePointer; 9016 } 9017 9018 // Only under strict condition T^ is compatible with an Objective-C pointer. 9019 if (RHSType->isBlockPointerType() && 9020 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9021 if (ConvertRHS) 9022 maybeExtendBlockObject(RHS); 9023 Kind = CK_BlockPointerToObjCPointerCast; 9024 return Compatible; 9025 } 9026 9027 return Incompatible; 9028 } 9029 9030 // Conversions from pointers that are not covered by the above. 9031 if (isa<PointerType>(RHSType)) { 9032 // T* -> _Bool 9033 if (LHSType == Context.BoolTy) { 9034 Kind = CK_PointerToBoolean; 9035 return Compatible; 9036 } 9037 9038 // T* -> int 9039 if (LHSType->isIntegerType()) { 9040 Kind = CK_PointerToIntegral; 9041 return PointerToInt; 9042 } 9043 9044 return Incompatible; 9045 } 9046 9047 // Conversions from Objective-C pointers that are not covered by the above. 9048 if (isa<ObjCObjectPointerType>(RHSType)) { 9049 // T* -> _Bool 9050 if (LHSType == Context.BoolTy) { 9051 Kind = CK_PointerToBoolean; 9052 return Compatible; 9053 } 9054 9055 // T* -> int 9056 if (LHSType->isIntegerType()) { 9057 Kind = CK_PointerToIntegral; 9058 return PointerToInt; 9059 } 9060 9061 return Incompatible; 9062 } 9063 9064 // struct A -> struct B 9065 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9066 if (Context.typesAreCompatible(LHSType, RHSType)) { 9067 Kind = CK_NoOp; 9068 return Compatible; 9069 } 9070 } 9071 9072 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9073 Kind = CK_IntToOCLSampler; 9074 return Compatible; 9075 } 9076 9077 return Incompatible; 9078 } 9079 9080 /// Constructs a transparent union from an expression that is 9081 /// used to initialize the transparent union. 9082 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9083 ExprResult &EResult, QualType UnionType, 9084 FieldDecl *Field) { 9085 // Build an initializer list that designates the appropriate member 9086 // of the transparent union. 9087 Expr *E = EResult.get(); 9088 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9089 E, SourceLocation()); 9090 Initializer->setType(UnionType); 9091 Initializer->setInitializedFieldInUnion(Field); 9092 9093 // Build a compound literal constructing a value of the transparent 9094 // union type from this initializer list. 9095 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9096 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9097 VK_RValue, Initializer, false); 9098 } 9099 9100 Sema::AssignConvertType 9101 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9102 ExprResult &RHS) { 9103 QualType RHSType = RHS.get()->getType(); 9104 9105 // If the ArgType is a Union type, we want to handle a potential 9106 // transparent_union GCC extension. 9107 const RecordType *UT = ArgType->getAsUnionType(); 9108 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9109 return Incompatible; 9110 9111 // The field to initialize within the transparent union. 9112 RecordDecl *UD = UT->getDecl(); 9113 FieldDecl *InitField = nullptr; 9114 // It's compatible if the expression matches any of the fields. 9115 for (auto *it : UD->fields()) { 9116 if (it->getType()->isPointerType()) { 9117 // If the transparent union contains a pointer type, we allow: 9118 // 1) void pointer 9119 // 2) null pointer constant 9120 if (RHSType->isPointerType()) 9121 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9122 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9123 InitField = it; 9124 break; 9125 } 9126 9127 if (RHS.get()->isNullPointerConstant(Context, 9128 Expr::NPC_ValueDependentIsNull)) { 9129 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9130 CK_NullToPointer); 9131 InitField = it; 9132 break; 9133 } 9134 } 9135 9136 CastKind Kind; 9137 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9138 == Compatible) { 9139 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9140 InitField = it; 9141 break; 9142 } 9143 } 9144 9145 if (!InitField) 9146 return Incompatible; 9147 9148 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9149 return Compatible; 9150 } 9151 9152 Sema::AssignConvertType 9153 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9154 bool Diagnose, 9155 bool DiagnoseCFAudited, 9156 bool ConvertRHS) { 9157 // We need to be able to tell the caller whether we diagnosed a problem, if 9158 // they ask us to issue diagnostics. 9159 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9160 9161 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9162 // we can't avoid *all* modifications at the moment, so we need some somewhere 9163 // to put the updated value. 9164 ExprResult LocalRHS = CallerRHS; 9165 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9166 9167 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9168 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9169 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9170 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9171 Diag(RHS.get()->getExprLoc(), 9172 diag::warn_noderef_to_dereferenceable_pointer) 9173 << RHS.get()->getSourceRange(); 9174 } 9175 } 9176 } 9177 9178 if (getLangOpts().CPlusPlus) { 9179 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9180 // C++ 5.17p3: If the left operand is not of class type, the 9181 // expression is implicitly converted (C++ 4) to the 9182 // cv-unqualified type of the left operand. 9183 QualType RHSType = RHS.get()->getType(); 9184 if (Diagnose) { 9185 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9186 AA_Assigning); 9187 } else { 9188 ImplicitConversionSequence ICS = 9189 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9190 /*SuppressUserConversions=*/false, 9191 AllowedExplicit::None, 9192 /*InOverloadResolution=*/false, 9193 /*CStyle=*/false, 9194 /*AllowObjCWritebackConversion=*/false); 9195 if (ICS.isFailure()) 9196 return Incompatible; 9197 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9198 ICS, AA_Assigning); 9199 } 9200 if (RHS.isInvalid()) 9201 return Incompatible; 9202 Sema::AssignConvertType result = Compatible; 9203 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9204 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9205 result = IncompatibleObjCWeakRef; 9206 return result; 9207 } 9208 9209 // FIXME: Currently, we fall through and treat C++ classes like C 9210 // structures. 9211 // FIXME: We also fall through for atomics; not sure what should 9212 // happen there, though. 9213 } else if (RHS.get()->getType() == Context.OverloadTy) { 9214 // As a set of extensions to C, we support overloading on functions. These 9215 // functions need to be resolved here. 9216 DeclAccessPair DAP; 9217 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9218 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9219 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9220 else 9221 return Incompatible; 9222 } 9223 9224 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9225 // a null pointer constant. 9226 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9227 LHSType->isBlockPointerType()) && 9228 RHS.get()->isNullPointerConstant(Context, 9229 Expr::NPC_ValueDependentIsNull)) { 9230 if (Diagnose || ConvertRHS) { 9231 CastKind Kind; 9232 CXXCastPath Path; 9233 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9234 /*IgnoreBaseAccess=*/false, Diagnose); 9235 if (ConvertRHS) 9236 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9237 } 9238 return Compatible; 9239 } 9240 9241 // OpenCL queue_t type assignment. 9242 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9243 Context, Expr::NPC_ValueDependentIsNull)) { 9244 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9245 return Compatible; 9246 } 9247 9248 // This check seems unnatural, however it is necessary to ensure the proper 9249 // conversion of functions/arrays. If the conversion were done for all 9250 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9251 // expressions that suppress this implicit conversion (&, sizeof). 9252 // 9253 // Suppress this for references: C++ 8.5.3p5. 9254 if (!LHSType->isReferenceType()) { 9255 // FIXME: We potentially allocate here even if ConvertRHS is false. 9256 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9257 if (RHS.isInvalid()) 9258 return Incompatible; 9259 } 9260 CastKind Kind; 9261 Sema::AssignConvertType result = 9262 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9263 9264 // C99 6.5.16.1p2: The value of the right operand is converted to the 9265 // type of the assignment expression. 9266 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9267 // so that we can use references in built-in functions even in C. 9268 // The getNonReferenceType() call makes sure that the resulting expression 9269 // does not have reference type. 9270 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9271 QualType Ty = LHSType.getNonLValueExprType(Context); 9272 Expr *E = RHS.get(); 9273 9274 // Check for various Objective-C errors. If we are not reporting 9275 // diagnostics and just checking for errors, e.g., during overload 9276 // resolution, return Incompatible to indicate the failure. 9277 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9278 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9279 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9280 if (!Diagnose) 9281 return Incompatible; 9282 } 9283 if (getLangOpts().ObjC && 9284 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9285 E->getType(), E, Diagnose) || 9286 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 9287 if (!Diagnose) 9288 return Incompatible; 9289 // Replace the expression with a corrected version and continue so we 9290 // can find further errors. 9291 RHS = E; 9292 return Compatible; 9293 } 9294 9295 if (ConvertRHS) 9296 RHS = ImpCastExprToType(E, Ty, Kind); 9297 } 9298 9299 return result; 9300 } 9301 9302 namespace { 9303 /// The original operand to an operator, prior to the application of the usual 9304 /// arithmetic conversions and converting the arguments of a builtin operator 9305 /// candidate. 9306 struct OriginalOperand { 9307 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9308 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9309 Op = MTE->getSubExpr(); 9310 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9311 Op = BTE->getSubExpr(); 9312 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9313 Orig = ICE->getSubExprAsWritten(); 9314 Conversion = ICE->getConversionFunction(); 9315 } 9316 } 9317 9318 QualType getType() const { return Orig->getType(); } 9319 9320 Expr *Orig; 9321 NamedDecl *Conversion; 9322 }; 9323 } 9324 9325 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9326 ExprResult &RHS) { 9327 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9328 9329 Diag(Loc, diag::err_typecheck_invalid_operands) 9330 << OrigLHS.getType() << OrigRHS.getType() 9331 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9332 9333 // If a user-defined conversion was applied to either of the operands prior 9334 // to applying the built-in operator rules, tell the user about it. 9335 if (OrigLHS.Conversion) { 9336 Diag(OrigLHS.Conversion->getLocation(), 9337 diag::note_typecheck_invalid_operands_converted) 9338 << 0 << LHS.get()->getType(); 9339 } 9340 if (OrigRHS.Conversion) { 9341 Diag(OrigRHS.Conversion->getLocation(), 9342 diag::note_typecheck_invalid_operands_converted) 9343 << 1 << RHS.get()->getType(); 9344 } 9345 9346 return QualType(); 9347 } 9348 9349 // Diagnose cases where a scalar was implicitly converted to a vector and 9350 // diagnose the underlying types. Otherwise, diagnose the error 9351 // as invalid vector logical operands for non-C++ cases. 9352 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9353 ExprResult &RHS) { 9354 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9355 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9356 9357 bool LHSNatVec = LHSType->isVectorType(); 9358 bool RHSNatVec = RHSType->isVectorType(); 9359 9360 if (!(LHSNatVec && RHSNatVec)) { 9361 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9362 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9363 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9364 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9365 << Vector->getSourceRange(); 9366 return QualType(); 9367 } 9368 9369 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9370 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9371 << RHS.get()->getSourceRange(); 9372 9373 return QualType(); 9374 } 9375 9376 /// Try to convert a value of non-vector type to a vector type by converting 9377 /// the type to the element type of the vector and then performing a splat. 9378 /// If the language is OpenCL, we only use conversions that promote scalar 9379 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9380 /// for float->int. 9381 /// 9382 /// OpenCL V2.0 6.2.6.p2: 9383 /// An error shall occur if any scalar operand type has greater rank 9384 /// than the type of the vector element. 9385 /// 9386 /// \param scalar - if non-null, actually perform the conversions 9387 /// \return true if the operation fails (but without diagnosing the failure) 9388 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9389 QualType scalarTy, 9390 QualType vectorEltTy, 9391 QualType vectorTy, 9392 unsigned &DiagID) { 9393 // The conversion to apply to the scalar before splatting it, 9394 // if necessary. 9395 CastKind scalarCast = CK_NoOp; 9396 9397 if (vectorEltTy->isIntegralType(S.Context)) { 9398 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9399 (scalarTy->isIntegerType() && 9400 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9401 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9402 return true; 9403 } 9404 if (!scalarTy->isIntegralType(S.Context)) 9405 return true; 9406 scalarCast = CK_IntegralCast; 9407 } else if (vectorEltTy->isRealFloatingType()) { 9408 if (scalarTy->isRealFloatingType()) { 9409 if (S.getLangOpts().OpenCL && 9410 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9411 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9412 return true; 9413 } 9414 scalarCast = CK_FloatingCast; 9415 } 9416 else if (scalarTy->isIntegralType(S.Context)) 9417 scalarCast = CK_IntegralToFloating; 9418 else 9419 return true; 9420 } else { 9421 return true; 9422 } 9423 9424 // Adjust scalar if desired. 9425 if (scalar) { 9426 if (scalarCast != CK_NoOp) 9427 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9428 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9429 } 9430 return false; 9431 } 9432 9433 /// Convert vector E to a vector with the same number of elements but different 9434 /// element type. 9435 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9436 const auto *VecTy = E->getType()->getAs<VectorType>(); 9437 assert(VecTy && "Expression E must be a vector"); 9438 QualType NewVecTy = S.Context.getVectorType(ElementType, 9439 VecTy->getNumElements(), 9440 VecTy->getVectorKind()); 9441 9442 // Look through the implicit cast. Return the subexpression if its type is 9443 // NewVecTy. 9444 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9445 if (ICE->getSubExpr()->getType() == NewVecTy) 9446 return ICE->getSubExpr(); 9447 9448 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9449 return S.ImpCastExprToType(E, NewVecTy, Cast); 9450 } 9451 9452 /// Test if a (constant) integer Int can be casted to another integer type 9453 /// IntTy without losing precision. 9454 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9455 QualType OtherIntTy) { 9456 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9457 9458 // Reject cases where the value of the Int is unknown as that would 9459 // possibly cause truncation, but accept cases where the scalar can be 9460 // demoted without loss of precision. 9461 Expr::EvalResult EVResult; 9462 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9463 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9464 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9465 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9466 9467 if (CstInt) { 9468 // If the scalar is constant and is of a higher order and has more active 9469 // bits that the vector element type, reject it. 9470 llvm::APSInt Result = EVResult.Val.getInt(); 9471 unsigned NumBits = IntSigned 9472 ? (Result.isNegative() ? Result.getMinSignedBits() 9473 : Result.getActiveBits()) 9474 : Result.getActiveBits(); 9475 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9476 return true; 9477 9478 // If the signedness of the scalar type and the vector element type 9479 // differs and the number of bits is greater than that of the vector 9480 // element reject it. 9481 return (IntSigned != OtherIntSigned && 9482 NumBits > S.Context.getIntWidth(OtherIntTy)); 9483 } 9484 9485 // Reject cases where the value of the scalar is not constant and it's 9486 // order is greater than that of the vector element type. 9487 return (Order < 0); 9488 } 9489 9490 /// Test if a (constant) integer Int can be casted to floating point type 9491 /// FloatTy without losing precision. 9492 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9493 QualType FloatTy) { 9494 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9495 9496 // Determine if the integer constant can be expressed as a floating point 9497 // number of the appropriate type. 9498 Expr::EvalResult EVResult; 9499 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9500 9501 uint64_t Bits = 0; 9502 if (CstInt) { 9503 // Reject constants that would be truncated if they were converted to 9504 // the floating point type. Test by simple to/from conversion. 9505 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9506 // could be avoided if there was a convertFromAPInt method 9507 // which could signal back if implicit truncation occurred. 9508 llvm::APSInt Result = EVResult.Val.getInt(); 9509 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9510 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9511 llvm::APFloat::rmTowardZero); 9512 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9513 !IntTy->hasSignedIntegerRepresentation()); 9514 bool Ignored = false; 9515 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9516 &Ignored); 9517 if (Result != ConvertBack) 9518 return true; 9519 } else { 9520 // Reject types that cannot be fully encoded into the mantissa of 9521 // the float. 9522 Bits = S.Context.getTypeSize(IntTy); 9523 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9524 S.Context.getFloatTypeSemantics(FloatTy)); 9525 if (Bits > FloatPrec) 9526 return true; 9527 } 9528 9529 return false; 9530 } 9531 9532 /// Attempt to convert and splat Scalar into a vector whose types matches 9533 /// Vector following GCC conversion rules. The rule is that implicit 9534 /// conversion can occur when Scalar can be casted to match Vector's element 9535 /// type without causing truncation of Scalar. 9536 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9537 ExprResult *Vector) { 9538 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9539 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9540 const VectorType *VT = VectorTy->getAs<VectorType>(); 9541 9542 assert(!isa<ExtVectorType>(VT) && 9543 "ExtVectorTypes should not be handled here!"); 9544 9545 QualType VectorEltTy = VT->getElementType(); 9546 9547 // Reject cases where the vector element type or the scalar element type are 9548 // not integral or floating point types. 9549 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9550 return true; 9551 9552 // The conversion to apply to the scalar before splatting it, 9553 // if necessary. 9554 CastKind ScalarCast = CK_NoOp; 9555 9556 // Accept cases where the vector elements are integers and the scalar is 9557 // an integer. 9558 // FIXME: Notionally if the scalar was a floating point value with a precise 9559 // integral representation, we could cast it to an appropriate integer 9560 // type and then perform the rest of the checks here. GCC will perform 9561 // this conversion in some cases as determined by the input language. 9562 // We should accept it on a language independent basis. 9563 if (VectorEltTy->isIntegralType(S.Context) && 9564 ScalarTy->isIntegralType(S.Context) && 9565 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9566 9567 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9568 return true; 9569 9570 ScalarCast = CK_IntegralCast; 9571 } else if (VectorEltTy->isIntegralType(S.Context) && 9572 ScalarTy->isRealFloatingType()) { 9573 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9574 ScalarCast = CK_FloatingToIntegral; 9575 else 9576 return true; 9577 } else if (VectorEltTy->isRealFloatingType()) { 9578 if (ScalarTy->isRealFloatingType()) { 9579 9580 // Reject cases where the scalar type is not a constant and has a higher 9581 // Order than the vector element type. 9582 llvm::APFloat Result(0.0); 9583 9584 // Determine whether this is a constant scalar. In the event that the 9585 // value is dependent (and thus cannot be evaluated by the constant 9586 // evaluator), skip the evaluation. This will then diagnose once the 9587 // expression is instantiated. 9588 bool CstScalar = Scalar->get()->isValueDependent() || 9589 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9590 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9591 if (!CstScalar && Order < 0) 9592 return true; 9593 9594 // If the scalar cannot be safely casted to the vector element type, 9595 // reject it. 9596 if (CstScalar) { 9597 bool Truncated = false; 9598 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9599 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9600 if (Truncated) 9601 return true; 9602 } 9603 9604 ScalarCast = CK_FloatingCast; 9605 } else if (ScalarTy->isIntegralType(S.Context)) { 9606 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9607 return true; 9608 9609 ScalarCast = CK_IntegralToFloating; 9610 } else 9611 return true; 9612 } 9613 9614 // Adjust scalar if desired. 9615 if (Scalar) { 9616 if (ScalarCast != CK_NoOp) 9617 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9618 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9619 } 9620 return false; 9621 } 9622 9623 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9624 SourceLocation Loc, bool IsCompAssign, 9625 bool AllowBothBool, 9626 bool AllowBoolConversions) { 9627 if (!IsCompAssign) { 9628 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9629 if (LHS.isInvalid()) 9630 return QualType(); 9631 } 9632 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9633 if (RHS.isInvalid()) 9634 return QualType(); 9635 9636 // For conversion purposes, we ignore any qualifiers. 9637 // For example, "const float" and "float" are equivalent. 9638 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9639 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9640 9641 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9642 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9643 assert(LHSVecType || RHSVecType); 9644 9645 // AltiVec-style "vector bool op vector bool" combinations are allowed 9646 // for some operators but not others. 9647 if (!AllowBothBool && 9648 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9649 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9650 return InvalidOperands(Loc, LHS, RHS); 9651 9652 // If the vector types are identical, return. 9653 if (Context.hasSameType(LHSType, RHSType)) 9654 return LHSType; 9655 9656 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9657 if (LHSVecType && RHSVecType && 9658 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9659 if (isa<ExtVectorType>(LHSVecType)) { 9660 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9661 return LHSType; 9662 } 9663 9664 if (!IsCompAssign) 9665 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9666 return RHSType; 9667 } 9668 9669 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9670 // can be mixed, with the result being the non-bool type. The non-bool 9671 // operand must have integer element type. 9672 if (AllowBoolConversions && LHSVecType && RHSVecType && 9673 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9674 (Context.getTypeSize(LHSVecType->getElementType()) == 9675 Context.getTypeSize(RHSVecType->getElementType()))) { 9676 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9677 LHSVecType->getElementType()->isIntegerType() && 9678 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9680 return LHSType; 9681 } 9682 if (!IsCompAssign && 9683 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9684 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9685 RHSVecType->getElementType()->isIntegerType()) { 9686 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9687 return RHSType; 9688 } 9689 } 9690 9691 // If there's a vector type and a scalar, try to convert the scalar to 9692 // the vector element type and splat. 9693 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9694 if (!RHSVecType) { 9695 if (isa<ExtVectorType>(LHSVecType)) { 9696 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9697 LHSVecType->getElementType(), LHSType, 9698 DiagID)) 9699 return LHSType; 9700 } else { 9701 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9702 return LHSType; 9703 } 9704 } 9705 if (!LHSVecType) { 9706 if (isa<ExtVectorType>(RHSVecType)) { 9707 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9708 LHSType, RHSVecType->getElementType(), 9709 RHSType, DiagID)) 9710 return RHSType; 9711 } else { 9712 if (LHS.get()->getValueKind() == VK_LValue || 9713 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9714 return RHSType; 9715 } 9716 } 9717 9718 // FIXME: The code below also handles conversion between vectors and 9719 // non-scalars, we should break this down into fine grained specific checks 9720 // and emit proper diagnostics. 9721 QualType VecType = LHSVecType ? LHSType : RHSType; 9722 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9723 QualType OtherType = LHSVecType ? RHSType : LHSType; 9724 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9725 if (isLaxVectorConversion(OtherType, VecType)) { 9726 // If we're allowing lax vector conversions, only the total (data) size 9727 // needs to be the same. For non compound assignment, if one of the types is 9728 // scalar, the result is always the vector type. 9729 if (!IsCompAssign) { 9730 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9731 return VecType; 9732 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9733 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9734 // type. Note that this is already done by non-compound assignments in 9735 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9736 // <1 x T> -> T. The result is also a vector type. 9737 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9738 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9739 ExprResult *RHSExpr = &RHS; 9740 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9741 return VecType; 9742 } 9743 } 9744 9745 // Okay, the expression is invalid. 9746 9747 // If there's a non-vector, non-real operand, diagnose that. 9748 if ((!RHSVecType && !RHSType->isRealType()) || 9749 (!LHSVecType && !LHSType->isRealType())) { 9750 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9751 << LHSType << RHSType 9752 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9753 return QualType(); 9754 } 9755 9756 // OpenCL V1.1 6.2.6.p1: 9757 // If the operands are of more than one vector type, then an error shall 9758 // occur. Implicit conversions between vector types are not permitted, per 9759 // section 6.2.1. 9760 if (getLangOpts().OpenCL && 9761 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9762 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9763 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9764 << RHSType; 9765 return QualType(); 9766 } 9767 9768 9769 // If there is a vector type that is not a ExtVector and a scalar, we reach 9770 // this point if scalar could not be converted to the vector's element type 9771 // without truncation. 9772 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9773 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9774 QualType Scalar = LHSVecType ? RHSType : LHSType; 9775 QualType Vector = LHSVecType ? LHSType : RHSType; 9776 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9777 Diag(Loc, 9778 diag::err_typecheck_vector_not_convertable_implict_truncation) 9779 << ScalarOrVector << Scalar << Vector; 9780 9781 return QualType(); 9782 } 9783 9784 // Otherwise, use the generic diagnostic. 9785 Diag(Loc, DiagID) 9786 << LHSType << RHSType 9787 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9788 return QualType(); 9789 } 9790 9791 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9792 // expression. These are mainly cases where the null pointer is used as an 9793 // integer instead of a pointer. 9794 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9795 SourceLocation Loc, bool IsCompare) { 9796 // The canonical way to check for a GNU null is with isNullPointerConstant, 9797 // but we use a bit of a hack here for speed; this is a relatively 9798 // hot path, and isNullPointerConstant is slow. 9799 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9800 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9801 9802 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9803 9804 // Avoid analyzing cases where the result will either be invalid (and 9805 // diagnosed as such) or entirely valid and not something to warn about. 9806 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9807 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9808 return; 9809 9810 // Comparison operations would not make sense with a null pointer no matter 9811 // what the other expression is. 9812 if (!IsCompare) { 9813 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9814 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9815 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9816 return; 9817 } 9818 9819 // The rest of the operations only make sense with a null pointer 9820 // if the other expression is a pointer. 9821 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9822 NonNullType->canDecayToPointerType()) 9823 return; 9824 9825 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9826 << LHSNull /* LHS is NULL */ << NonNullType 9827 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9828 } 9829 9830 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9831 SourceLocation Loc) { 9832 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9833 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9834 if (!LUE || !RUE) 9835 return; 9836 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9837 RUE->getKind() != UETT_SizeOf) 9838 return; 9839 9840 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9841 QualType LHSTy = LHSArg->getType(); 9842 QualType RHSTy; 9843 9844 if (RUE->isArgumentType()) 9845 RHSTy = RUE->getArgumentType(); 9846 else 9847 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9848 9849 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9850 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9851 return; 9852 9853 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9854 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9855 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9856 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9857 << LHSArgDecl; 9858 } 9859 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9860 QualType ArrayElemTy = ArrayTy->getElementType(); 9861 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9862 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9863 ArrayElemTy->isCharType() || 9864 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9865 return; 9866 S.Diag(Loc, diag::warn_division_sizeof_array) 9867 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9868 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9869 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9870 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9871 << LHSArgDecl; 9872 } 9873 9874 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9875 } 9876 } 9877 9878 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9879 ExprResult &RHS, 9880 SourceLocation Loc, bool IsDiv) { 9881 // Check for division/remainder by zero. 9882 Expr::EvalResult RHSValue; 9883 if (!RHS.get()->isValueDependent() && 9884 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9885 RHSValue.Val.getInt() == 0) 9886 S.DiagRuntimeBehavior(Loc, RHS.get(), 9887 S.PDiag(diag::warn_remainder_division_by_zero) 9888 << IsDiv << RHS.get()->getSourceRange()); 9889 } 9890 9891 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9892 SourceLocation Loc, 9893 bool IsCompAssign, bool IsDiv) { 9894 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9895 9896 if (LHS.get()->getType()->isVectorType() || 9897 RHS.get()->getType()->isVectorType()) 9898 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9899 /*AllowBothBool*/getLangOpts().AltiVec, 9900 /*AllowBoolConversions*/false); 9901 9902 QualType compType = UsualArithmeticConversions( 9903 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9904 if (LHS.isInvalid() || RHS.isInvalid()) 9905 return QualType(); 9906 9907 9908 if (compType.isNull() || !compType->isArithmeticType()) 9909 return InvalidOperands(Loc, LHS, RHS); 9910 if (IsDiv) { 9911 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9912 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9913 } 9914 return compType; 9915 } 9916 9917 QualType Sema::CheckRemainderOperands( 9918 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9919 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9920 9921 if (LHS.get()->getType()->isVectorType() || 9922 RHS.get()->getType()->isVectorType()) { 9923 if (LHS.get()->getType()->hasIntegerRepresentation() && 9924 RHS.get()->getType()->hasIntegerRepresentation()) 9925 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9926 /*AllowBothBool*/getLangOpts().AltiVec, 9927 /*AllowBoolConversions*/false); 9928 return InvalidOperands(Loc, LHS, RHS); 9929 } 9930 9931 QualType compType = UsualArithmeticConversions( 9932 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9933 if (LHS.isInvalid() || RHS.isInvalid()) 9934 return QualType(); 9935 9936 if (compType.isNull() || !compType->isIntegerType()) 9937 return InvalidOperands(Loc, LHS, RHS); 9938 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9939 return compType; 9940 } 9941 9942 /// Diagnose invalid arithmetic on two void pointers. 9943 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9944 Expr *LHSExpr, Expr *RHSExpr) { 9945 S.Diag(Loc, S.getLangOpts().CPlusPlus 9946 ? diag::err_typecheck_pointer_arith_void_type 9947 : diag::ext_gnu_void_ptr) 9948 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9949 << RHSExpr->getSourceRange(); 9950 } 9951 9952 /// Diagnose invalid arithmetic on a void pointer. 9953 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9954 Expr *Pointer) { 9955 S.Diag(Loc, S.getLangOpts().CPlusPlus 9956 ? diag::err_typecheck_pointer_arith_void_type 9957 : diag::ext_gnu_void_ptr) 9958 << 0 /* one pointer */ << Pointer->getSourceRange(); 9959 } 9960 9961 /// Diagnose invalid arithmetic on a null pointer. 9962 /// 9963 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9964 /// idiom, which we recognize as a GNU extension. 9965 /// 9966 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9967 Expr *Pointer, bool IsGNUIdiom) { 9968 if (IsGNUIdiom) 9969 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9970 << Pointer->getSourceRange(); 9971 else 9972 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9973 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9974 } 9975 9976 /// Diagnose invalid arithmetic on two function pointers. 9977 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9978 Expr *LHS, Expr *RHS) { 9979 assert(LHS->getType()->isAnyPointerType()); 9980 assert(RHS->getType()->isAnyPointerType()); 9981 S.Diag(Loc, S.getLangOpts().CPlusPlus 9982 ? diag::err_typecheck_pointer_arith_function_type 9983 : diag::ext_gnu_ptr_func_arith) 9984 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9985 // We only show the second type if it differs from the first. 9986 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9987 RHS->getType()) 9988 << RHS->getType()->getPointeeType() 9989 << LHS->getSourceRange() << RHS->getSourceRange(); 9990 } 9991 9992 /// Diagnose invalid arithmetic on a function pointer. 9993 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9994 Expr *Pointer) { 9995 assert(Pointer->getType()->isAnyPointerType()); 9996 S.Diag(Loc, S.getLangOpts().CPlusPlus 9997 ? diag::err_typecheck_pointer_arith_function_type 9998 : diag::ext_gnu_ptr_func_arith) 9999 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10000 << 0 /* one pointer, so only one type */ 10001 << Pointer->getSourceRange(); 10002 } 10003 10004 /// Emit error if Operand is incomplete pointer type 10005 /// 10006 /// \returns True if pointer has incomplete type 10007 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10008 Expr *Operand) { 10009 QualType ResType = Operand->getType(); 10010 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10011 ResType = ResAtomicType->getValueType(); 10012 10013 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10014 QualType PointeeTy = ResType->getPointeeType(); 10015 return S.RequireCompleteSizedType( 10016 Loc, PointeeTy, 10017 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10018 Operand->getSourceRange()); 10019 } 10020 10021 /// Check the validity of an arithmetic pointer operand. 10022 /// 10023 /// If the operand has pointer type, this code will check for pointer types 10024 /// which are invalid in arithmetic operations. These will be diagnosed 10025 /// appropriately, including whether or not the use is supported as an 10026 /// extension. 10027 /// 10028 /// \returns True when the operand is valid to use (even if as an extension). 10029 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10030 Expr *Operand) { 10031 QualType ResType = Operand->getType(); 10032 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10033 ResType = ResAtomicType->getValueType(); 10034 10035 if (!ResType->isAnyPointerType()) return true; 10036 10037 QualType PointeeTy = ResType->getPointeeType(); 10038 if (PointeeTy->isVoidType()) { 10039 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10040 return !S.getLangOpts().CPlusPlus; 10041 } 10042 if (PointeeTy->isFunctionType()) { 10043 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10044 return !S.getLangOpts().CPlusPlus; 10045 } 10046 10047 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10048 10049 return true; 10050 } 10051 10052 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10053 /// operands. 10054 /// 10055 /// This routine will diagnose any invalid arithmetic on pointer operands much 10056 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10057 /// for emitting a single diagnostic even for operations where both LHS and RHS 10058 /// are (potentially problematic) pointers. 10059 /// 10060 /// \returns True when the operand is valid to use (even if as an extension). 10061 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10062 Expr *LHSExpr, Expr *RHSExpr) { 10063 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10064 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10065 if (!isLHSPointer && !isRHSPointer) return true; 10066 10067 QualType LHSPointeeTy, RHSPointeeTy; 10068 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10069 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10070 10071 // if both are pointers check if operation is valid wrt address spaces 10072 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 10073 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 10074 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 10075 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 10076 S.Diag(Loc, 10077 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10078 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10079 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10080 return false; 10081 } 10082 } 10083 10084 // Check for arithmetic on pointers to incomplete types. 10085 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10086 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10087 if (isLHSVoidPtr || isRHSVoidPtr) { 10088 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10089 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10090 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10091 10092 return !S.getLangOpts().CPlusPlus; 10093 } 10094 10095 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10096 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10097 if (isLHSFuncPtr || isRHSFuncPtr) { 10098 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10099 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10100 RHSExpr); 10101 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10102 10103 return !S.getLangOpts().CPlusPlus; 10104 } 10105 10106 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10107 return false; 10108 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10109 return false; 10110 10111 return true; 10112 } 10113 10114 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10115 /// literal. 10116 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10117 Expr *LHSExpr, Expr *RHSExpr) { 10118 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10119 Expr* IndexExpr = RHSExpr; 10120 if (!StrExpr) { 10121 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10122 IndexExpr = LHSExpr; 10123 } 10124 10125 bool IsStringPlusInt = StrExpr && 10126 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10127 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10128 return; 10129 10130 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10131 Self.Diag(OpLoc, diag::warn_string_plus_int) 10132 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10133 10134 // Only print a fixit for "str" + int, not for int + "str". 10135 if (IndexExpr == RHSExpr) { 10136 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10137 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10138 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10139 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10140 << FixItHint::CreateInsertion(EndLoc, "]"); 10141 } else 10142 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10143 } 10144 10145 /// Emit a warning when adding a char literal to a string. 10146 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10147 Expr *LHSExpr, Expr *RHSExpr) { 10148 const Expr *StringRefExpr = LHSExpr; 10149 const CharacterLiteral *CharExpr = 10150 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10151 10152 if (!CharExpr) { 10153 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10154 StringRefExpr = RHSExpr; 10155 } 10156 10157 if (!CharExpr || !StringRefExpr) 10158 return; 10159 10160 const QualType StringType = StringRefExpr->getType(); 10161 10162 // Return if not a PointerType. 10163 if (!StringType->isAnyPointerType()) 10164 return; 10165 10166 // Return if not a CharacterType. 10167 if (!StringType->getPointeeType()->isAnyCharacterType()) 10168 return; 10169 10170 ASTContext &Ctx = Self.getASTContext(); 10171 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10172 10173 const QualType CharType = CharExpr->getType(); 10174 if (!CharType->isAnyCharacterType() && 10175 CharType->isIntegerType() && 10176 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10177 Self.Diag(OpLoc, diag::warn_string_plus_char) 10178 << DiagRange << Ctx.CharTy; 10179 } else { 10180 Self.Diag(OpLoc, diag::warn_string_plus_char) 10181 << DiagRange << CharExpr->getType(); 10182 } 10183 10184 // Only print a fixit for str + char, not for char + str. 10185 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10186 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10187 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10188 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10189 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10190 << FixItHint::CreateInsertion(EndLoc, "]"); 10191 } else { 10192 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10193 } 10194 } 10195 10196 /// Emit error when two pointers are incompatible. 10197 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10198 Expr *LHSExpr, Expr *RHSExpr) { 10199 assert(LHSExpr->getType()->isAnyPointerType()); 10200 assert(RHSExpr->getType()->isAnyPointerType()); 10201 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10202 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10203 << RHSExpr->getSourceRange(); 10204 } 10205 10206 // C99 6.5.6 10207 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10208 SourceLocation Loc, BinaryOperatorKind Opc, 10209 QualType* CompLHSTy) { 10210 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10211 10212 if (LHS.get()->getType()->isVectorType() || 10213 RHS.get()->getType()->isVectorType()) { 10214 QualType compType = CheckVectorOperands( 10215 LHS, RHS, Loc, CompLHSTy, 10216 /*AllowBothBool*/getLangOpts().AltiVec, 10217 /*AllowBoolConversions*/getLangOpts().ZVector); 10218 if (CompLHSTy) *CompLHSTy = compType; 10219 return compType; 10220 } 10221 10222 QualType compType = UsualArithmeticConversions( 10223 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10224 if (LHS.isInvalid() || RHS.isInvalid()) 10225 return QualType(); 10226 10227 // Diagnose "string literal" '+' int and string '+' "char literal". 10228 if (Opc == BO_Add) { 10229 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10230 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10231 } 10232 10233 // handle the common case first (both operands are arithmetic). 10234 if (!compType.isNull() && compType->isArithmeticType()) { 10235 if (CompLHSTy) *CompLHSTy = compType; 10236 return compType; 10237 } 10238 10239 // Type-checking. Ultimately the pointer's going to be in PExp; 10240 // note that we bias towards the LHS being the pointer. 10241 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10242 10243 bool isObjCPointer; 10244 if (PExp->getType()->isPointerType()) { 10245 isObjCPointer = false; 10246 } else if (PExp->getType()->isObjCObjectPointerType()) { 10247 isObjCPointer = true; 10248 } else { 10249 std::swap(PExp, IExp); 10250 if (PExp->getType()->isPointerType()) { 10251 isObjCPointer = false; 10252 } else if (PExp->getType()->isObjCObjectPointerType()) { 10253 isObjCPointer = true; 10254 } else { 10255 return InvalidOperands(Loc, LHS, RHS); 10256 } 10257 } 10258 assert(PExp->getType()->isAnyPointerType()); 10259 10260 if (!IExp->getType()->isIntegerType()) 10261 return InvalidOperands(Loc, LHS, RHS); 10262 10263 // Adding to a null pointer results in undefined behavior. 10264 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10265 Context, Expr::NPC_ValueDependentIsNotNull)) { 10266 // In C++ adding zero to a null pointer is defined. 10267 Expr::EvalResult KnownVal; 10268 if (!getLangOpts().CPlusPlus || 10269 (!IExp->isValueDependent() && 10270 (!IExp->EvaluateAsInt(KnownVal, Context) || 10271 KnownVal.Val.getInt() != 0))) { 10272 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10273 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10274 Context, BO_Add, PExp, IExp); 10275 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10276 } 10277 } 10278 10279 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10280 return QualType(); 10281 10282 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10283 return QualType(); 10284 10285 // Check array bounds for pointer arithemtic 10286 CheckArrayAccess(PExp, IExp); 10287 10288 if (CompLHSTy) { 10289 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10290 if (LHSTy.isNull()) { 10291 LHSTy = LHS.get()->getType(); 10292 if (LHSTy->isPromotableIntegerType()) 10293 LHSTy = Context.getPromotedIntegerType(LHSTy); 10294 } 10295 *CompLHSTy = LHSTy; 10296 } 10297 10298 return PExp->getType(); 10299 } 10300 10301 // C99 6.5.6 10302 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10303 SourceLocation Loc, 10304 QualType* CompLHSTy) { 10305 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10306 10307 if (LHS.get()->getType()->isVectorType() || 10308 RHS.get()->getType()->isVectorType()) { 10309 QualType compType = CheckVectorOperands( 10310 LHS, RHS, Loc, CompLHSTy, 10311 /*AllowBothBool*/getLangOpts().AltiVec, 10312 /*AllowBoolConversions*/getLangOpts().ZVector); 10313 if (CompLHSTy) *CompLHSTy = compType; 10314 return compType; 10315 } 10316 10317 QualType compType = UsualArithmeticConversions( 10318 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10319 if (LHS.isInvalid() || RHS.isInvalid()) 10320 return QualType(); 10321 10322 // Enforce type constraints: C99 6.5.6p3. 10323 10324 // Handle the common case first (both operands are arithmetic). 10325 if (!compType.isNull() && compType->isArithmeticType()) { 10326 if (CompLHSTy) *CompLHSTy = compType; 10327 return compType; 10328 } 10329 10330 // Either ptr - int or ptr - ptr. 10331 if (LHS.get()->getType()->isAnyPointerType()) { 10332 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10333 10334 // Diagnose bad cases where we step over interface counts. 10335 if (LHS.get()->getType()->isObjCObjectPointerType() && 10336 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10337 return QualType(); 10338 10339 // The result type of a pointer-int computation is the pointer type. 10340 if (RHS.get()->getType()->isIntegerType()) { 10341 // Subtracting from a null pointer should produce a warning. 10342 // The last argument to the diagnose call says this doesn't match the 10343 // GNU int-to-pointer idiom. 10344 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10345 Expr::NPC_ValueDependentIsNotNull)) { 10346 // In C++ adding zero to a null pointer is defined. 10347 Expr::EvalResult KnownVal; 10348 if (!getLangOpts().CPlusPlus || 10349 (!RHS.get()->isValueDependent() && 10350 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10351 KnownVal.Val.getInt() != 0))) { 10352 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10353 } 10354 } 10355 10356 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10357 return QualType(); 10358 10359 // Check array bounds for pointer arithemtic 10360 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10361 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10362 10363 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10364 return LHS.get()->getType(); 10365 } 10366 10367 // Handle pointer-pointer subtractions. 10368 if (const PointerType *RHSPTy 10369 = RHS.get()->getType()->getAs<PointerType>()) { 10370 QualType rpointee = RHSPTy->getPointeeType(); 10371 10372 if (getLangOpts().CPlusPlus) { 10373 // Pointee types must be the same: C++ [expr.add] 10374 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10375 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10376 } 10377 } else { 10378 // Pointee types must be compatible C99 6.5.6p3 10379 if (!Context.typesAreCompatible( 10380 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10381 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10382 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10383 return QualType(); 10384 } 10385 } 10386 10387 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10388 LHS.get(), RHS.get())) 10389 return QualType(); 10390 10391 // FIXME: Add warnings for nullptr - ptr. 10392 10393 // The pointee type may have zero size. As an extension, a structure or 10394 // union may have zero size or an array may have zero length. In this 10395 // case subtraction does not make sense. 10396 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10397 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10398 if (ElementSize.isZero()) { 10399 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10400 << rpointee.getUnqualifiedType() 10401 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10402 } 10403 } 10404 10405 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10406 return Context.getPointerDiffType(); 10407 } 10408 } 10409 10410 return InvalidOperands(Loc, LHS, RHS); 10411 } 10412 10413 static bool isScopedEnumerationType(QualType T) { 10414 if (const EnumType *ET = T->getAs<EnumType>()) 10415 return ET->getDecl()->isScoped(); 10416 return false; 10417 } 10418 10419 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10420 SourceLocation Loc, BinaryOperatorKind Opc, 10421 QualType LHSType) { 10422 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10423 // so skip remaining warnings as we don't want to modify values within Sema. 10424 if (S.getLangOpts().OpenCL) 10425 return; 10426 10427 // Check right/shifter operand 10428 Expr::EvalResult RHSResult; 10429 if (RHS.get()->isValueDependent() || 10430 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10431 return; 10432 llvm::APSInt Right = RHSResult.Val.getInt(); 10433 10434 if (Right.isNegative()) { 10435 S.DiagRuntimeBehavior(Loc, RHS.get(), 10436 S.PDiag(diag::warn_shift_negative) 10437 << RHS.get()->getSourceRange()); 10438 return; 10439 } 10440 10441 QualType LHSExprType = LHS.get()->getType(); 10442 uint64_t LeftSize = LHSExprType->isExtIntType() 10443 ? S.Context.getIntWidth(LHSExprType) 10444 : S.Context.getTypeSize(LHSExprType); 10445 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10446 if (Right.uge(LeftBits)) { 10447 S.DiagRuntimeBehavior(Loc, RHS.get(), 10448 S.PDiag(diag::warn_shift_gt_typewidth) 10449 << RHS.get()->getSourceRange()); 10450 return; 10451 } 10452 10453 if (Opc != BO_Shl) 10454 return; 10455 10456 // When left shifting an ICE which is signed, we can check for overflow which 10457 // according to C++ standards prior to C++2a has undefined behavior 10458 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10459 // more than the maximum value representable in the result type, so never 10460 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10461 // expression is still probably a bug.) 10462 Expr::EvalResult LHSResult; 10463 if (LHS.get()->isValueDependent() || 10464 LHSType->hasUnsignedIntegerRepresentation() || 10465 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10466 return; 10467 llvm::APSInt Left = LHSResult.Val.getInt(); 10468 10469 // If LHS does not have a signed type and non-negative value 10470 // then, the behavior is undefined before C++2a. Warn about it. 10471 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10472 !S.getLangOpts().CPlusPlus2a) { 10473 S.DiagRuntimeBehavior(Loc, LHS.get(), 10474 S.PDiag(diag::warn_shift_lhs_negative) 10475 << LHS.get()->getSourceRange()); 10476 return; 10477 } 10478 10479 llvm::APInt ResultBits = 10480 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10481 if (LeftBits.uge(ResultBits)) 10482 return; 10483 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10484 Result = Result.shl(Right); 10485 10486 // Print the bit representation of the signed integer as an unsigned 10487 // hexadecimal number. 10488 SmallString<40> HexResult; 10489 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10490 10491 // If we are only missing a sign bit, this is less likely to result in actual 10492 // bugs -- if the result is cast back to an unsigned type, it will have the 10493 // expected value. Thus we place this behind a different warning that can be 10494 // turned off separately if needed. 10495 if (LeftBits == ResultBits - 1) { 10496 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10497 << HexResult << LHSType 10498 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10499 return; 10500 } 10501 10502 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10503 << HexResult.str() << Result.getMinSignedBits() << LHSType 10504 << Left.getBitWidth() << LHS.get()->getSourceRange() 10505 << RHS.get()->getSourceRange(); 10506 } 10507 10508 /// Return the resulting type when a vector is shifted 10509 /// by a scalar or vector shift amount. 10510 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10511 SourceLocation Loc, bool IsCompAssign) { 10512 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10513 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10514 !LHS.get()->getType()->isVectorType()) { 10515 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10516 << RHS.get()->getType() << LHS.get()->getType() 10517 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10518 return QualType(); 10519 } 10520 10521 if (!IsCompAssign) { 10522 LHS = S.UsualUnaryConversions(LHS.get()); 10523 if (LHS.isInvalid()) return QualType(); 10524 } 10525 10526 RHS = S.UsualUnaryConversions(RHS.get()); 10527 if (RHS.isInvalid()) return QualType(); 10528 10529 QualType LHSType = LHS.get()->getType(); 10530 // Note that LHS might be a scalar because the routine calls not only in 10531 // OpenCL case. 10532 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10533 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10534 10535 // Note that RHS might not be a vector. 10536 QualType RHSType = RHS.get()->getType(); 10537 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10538 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10539 10540 // The operands need to be integers. 10541 if (!LHSEleType->isIntegerType()) { 10542 S.Diag(Loc, diag::err_typecheck_expect_int) 10543 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10544 return QualType(); 10545 } 10546 10547 if (!RHSEleType->isIntegerType()) { 10548 S.Diag(Loc, diag::err_typecheck_expect_int) 10549 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10550 return QualType(); 10551 } 10552 10553 if (!LHSVecTy) { 10554 assert(RHSVecTy); 10555 if (IsCompAssign) 10556 return RHSType; 10557 if (LHSEleType != RHSEleType) { 10558 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10559 LHSEleType = RHSEleType; 10560 } 10561 QualType VecTy = 10562 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10563 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10564 LHSType = VecTy; 10565 } else if (RHSVecTy) { 10566 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10567 // are applied component-wise. So if RHS is a vector, then ensure 10568 // that the number of elements is the same as LHS... 10569 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10570 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10571 << LHS.get()->getType() << RHS.get()->getType() 10572 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10573 return QualType(); 10574 } 10575 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10576 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10577 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10578 if (LHSBT != RHSBT && 10579 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10580 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10581 << LHS.get()->getType() << RHS.get()->getType() 10582 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10583 } 10584 } 10585 } else { 10586 // ...else expand RHS to match the number of elements in LHS. 10587 QualType VecTy = 10588 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10589 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10590 } 10591 10592 return LHSType; 10593 } 10594 10595 // C99 6.5.7 10596 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10597 SourceLocation Loc, BinaryOperatorKind Opc, 10598 bool IsCompAssign) { 10599 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10600 10601 // Vector shifts promote their scalar inputs to vector type. 10602 if (LHS.get()->getType()->isVectorType() || 10603 RHS.get()->getType()->isVectorType()) { 10604 if (LangOpts.ZVector) { 10605 // The shift operators for the z vector extensions work basically 10606 // like general shifts, except that neither the LHS nor the RHS is 10607 // allowed to be a "vector bool". 10608 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10609 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10610 return InvalidOperands(Loc, LHS, RHS); 10611 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10612 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10613 return InvalidOperands(Loc, LHS, RHS); 10614 } 10615 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10616 } 10617 10618 // Shifts don't perform usual arithmetic conversions, they just do integer 10619 // promotions on each operand. C99 6.5.7p3 10620 10621 // For the LHS, do usual unary conversions, but then reset them away 10622 // if this is a compound assignment. 10623 ExprResult OldLHS = LHS; 10624 LHS = UsualUnaryConversions(LHS.get()); 10625 if (LHS.isInvalid()) 10626 return QualType(); 10627 QualType LHSType = LHS.get()->getType(); 10628 if (IsCompAssign) LHS = OldLHS; 10629 10630 // The RHS is simpler. 10631 RHS = UsualUnaryConversions(RHS.get()); 10632 if (RHS.isInvalid()) 10633 return QualType(); 10634 QualType RHSType = RHS.get()->getType(); 10635 10636 // C99 6.5.7p2: Each of the operands shall have integer type. 10637 if (!LHSType->hasIntegerRepresentation() || 10638 !RHSType->hasIntegerRepresentation()) 10639 return InvalidOperands(Loc, LHS, RHS); 10640 10641 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10642 // hasIntegerRepresentation() above instead of this. 10643 if (isScopedEnumerationType(LHSType) || 10644 isScopedEnumerationType(RHSType)) { 10645 return InvalidOperands(Loc, LHS, RHS); 10646 } 10647 // Sanity-check shift operands 10648 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10649 10650 // "The type of the result is that of the promoted left operand." 10651 return LHSType; 10652 } 10653 10654 /// Diagnose bad pointer comparisons. 10655 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10656 ExprResult &LHS, ExprResult &RHS, 10657 bool IsError) { 10658 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10659 : diag::ext_typecheck_comparison_of_distinct_pointers) 10660 << LHS.get()->getType() << RHS.get()->getType() 10661 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10662 } 10663 10664 /// Returns false if the pointers are converted to a composite type, 10665 /// true otherwise. 10666 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10667 ExprResult &LHS, ExprResult &RHS) { 10668 // C++ [expr.rel]p2: 10669 // [...] Pointer conversions (4.10) and qualification 10670 // conversions (4.4) are performed on pointer operands (or on 10671 // a pointer operand and a null pointer constant) to bring 10672 // them to their composite pointer type. [...] 10673 // 10674 // C++ [expr.eq]p1 uses the same notion for (in)equality 10675 // comparisons of pointers. 10676 10677 QualType LHSType = LHS.get()->getType(); 10678 QualType RHSType = RHS.get()->getType(); 10679 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10680 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10681 10682 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10683 if (T.isNull()) { 10684 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10685 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10686 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10687 else 10688 S.InvalidOperands(Loc, LHS, RHS); 10689 return true; 10690 } 10691 10692 return false; 10693 } 10694 10695 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10696 ExprResult &LHS, 10697 ExprResult &RHS, 10698 bool IsError) { 10699 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10700 : diag::ext_typecheck_comparison_of_fptr_to_void) 10701 << LHS.get()->getType() << RHS.get()->getType() 10702 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10703 } 10704 10705 static bool isObjCObjectLiteral(ExprResult &E) { 10706 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10707 case Stmt::ObjCArrayLiteralClass: 10708 case Stmt::ObjCDictionaryLiteralClass: 10709 case Stmt::ObjCStringLiteralClass: 10710 case Stmt::ObjCBoxedExprClass: 10711 return true; 10712 default: 10713 // Note that ObjCBoolLiteral is NOT an object literal! 10714 return false; 10715 } 10716 } 10717 10718 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10719 const ObjCObjectPointerType *Type = 10720 LHS->getType()->getAs<ObjCObjectPointerType>(); 10721 10722 // If this is not actually an Objective-C object, bail out. 10723 if (!Type) 10724 return false; 10725 10726 // Get the LHS object's interface type. 10727 QualType InterfaceType = Type->getPointeeType(); 10728 10729 // If the RHS isn't an Objective-C object, bail out. 10730 if (!RHS->getType()->isObjCObjectPointerType()) 10731 return false; 10732 10733 // Try to find the -isEqual: method. 10734 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10735 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10736 InterfaceType, 10737 /*IsInstance=*/true); 10738 if (!Method) { 10739 if (Type->isObjCIdType()) { 10740 // For 'id', just check the global pool. 10741 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10742 /*receiverId=*/true); 10743 } else { 10744 // Check protocols. 10745 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10746 /*IsInstance=*/true); 10747 } 10748 } 10749 10750 if (!Method) 10751 return false; 10752 10753 QualType T = Method->parameters()[0]->getType(); 10754 if (!T->isObjCObjectPointerType()) 10755 return false; 10756 10757 QualType R = Method->getReturnType(); 10758 if (!R->isScalarType()) 10759 return false; 10760 10761 return true; 10762 } 10763 10764 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10765 FromE = FromE->IgnoreParenImpCasts(); 10766 switch (FromE->getStmtClass()) { 10767 default: 10768 break; 10769 case Stmt::ObjCStringLiteralClass: 10770 // "string literal" 10771 return LK_String; 10772 case Stmt::ObjCArrayLiteralClass: 10773 // "array literal" 10774 return LK_Array; 10775 case Stmt::ObjCDictionaryLiteralClass: 10776 // "dictionary literal" 10777 return LK_Dictionary; 10778 case Stmt::BlockExprClass: 10779 return LK_Block; 10780 case Stmt::ObjCBoxedExprClass: { 10781 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10782 switch (Inner->getStmtClass()) { 10783 case Stmt::IntegerLiteralClass: 10784 case Stmt::FloatingLiteralClass: 10785 case Stmt::CharacterLiteralClass: 10786 case Stmt::ObjCBoolLiteralExprClass: 10787 case Stmt::CXXBoolLiteralExprClass: 10788 // "numeric literal" 10789 return LK_Numeric; 10790 case Stmt::ImplicitCastExprClass: { 10791 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10792 // Boolean literals can be represented by implicit casts. 10793 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10794 return LK_Numeric; 10795 break; 10796 } 10797 default: 10798 break; 10799 } 10800 return LK_Boxed; 10801 } 10802 } 10803 return LK_None; 10804 } 10805 10806 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10807 ExprResult &LHS, ExprResult &RHS, 10808 BinaryOperator::Opcode Opc){ 10809 Expr *Literal; 10810 Expr *Other; 10811 if (isObjCObjectLiteral(LHS)) { 10812 Literal = LHS.get(); 10813 Other = RHS.get(); 10814 } else { 10815 Literal = RHS.get(); 10816 Other = LHS.get(); 10817 } 10818 10819 // Don't warn on comparisons against nil. 10820 Other = Other->IgnoreParenCasts(); 10821 if (Other->isNullPointerConstant(S.getASTContext(), 10822 Expr::NPC_ValueDependentIsNotNull)) 10823 return; 10824 10825 // This should be kept in sync with warn_objc_literal_comparison. 10826 // LK_String should always be after the other literals, since it has its own 10827 // warning flag. 10828 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10829 assert(LiteralKind != Sema::LK_Block); 10830 if (LiteralKind == Sema::LK_None) { 10831 llvm_unreachable("Unknown Objective-C object literal kind"); 10832 } 10833 10834 if (LiteralKind == Sema::LK_String) 10835 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10836 << Literal->getSourceRange(); 10837 else 10838 S.Diag(Loc, diag::warn_objc_literal_comparison) 10839 << LiteralKind << Literal->getSourceRange(); 10840 10841 if (BinaryOperator::isEqualityOp(Opc) && 10842 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10843 SourceLocation Start = LHS.get()->getBeginLoc(); 10844 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10845 CharSourceRange OpRange = 10846 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10847 10848 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10849 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10850 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10851 << FixItHint::CreateInsertion(End, "]"); 10852 } 10853 } 10854 10855 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10856 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10857 ExprResult &RHS, SourceLocation Loc, 10858 BinaryOperatorKind Opc) { 10859 // Check that left hand side is !something. 10860 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10861 if (!UO || UO->getOpcode() != UO_LNot) return; 10862 10863 // Only check if the right hand side is non-bool arithmetic type. 10864 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10865 10866 // Make sure that the something in !something is not bool. 10867 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10868 if (SubExpr->isKnownToHaveBooleanValue()) return; 10869 10870 // Emit warning. 10871 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10872 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10873 << Loc << IsBitwiseOp; 10874 10875 // First note suggest !(x < y) 10876 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10877 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10878 FirstClose = S.getLocForEndOfToken(FirstClose); 10879 if (FirstClose.isInvalid()) 10880 FirstOpen = SourceLocation(); 10881 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10882 << IsBitwiseOp 10883 << FixItHint::CreateInsertion(FirstOpen, "(") 10884 << FixItHint::CreateInsertion(FirstClose, ")"); 10885 10886 // Second note suggests (!x) < y 10887 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10888 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10889 SecondClose = S.getLocForEndOfToken(SecondClose); 10890 if (SecondClose.isInvalid()) 10891 SecondOpen = SourceLocation(); 10892 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10893 << FixItHint::CreateInsertion(SecondOpen, "(") 10894 << FixItHint::CreateInsertion(SecondClose, ")"); 10895 } 10896 10897 // Returns true if E refers to a non-weak array. 10898 static bool checkForArray(const Expr *E) { 10899 const ValueDecl *D = nullptr; 10900 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10901 D = DR->getDecl(); 10902 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10903 if (Mem->isImplicitAccess()) 10904 D = Mem->getMemberDecl(); 10905 } 10906 if (!D) 10907 return false; 10908 return D->getType()->isArrayType() && !D->isWeak(); 10909 } 10910 10911 /// Diagnose some forms of syntactically-obvious tautological comparison. 10912 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10913 Expr *LHS, Expr *RHS, 10914 BinaryOperatorKind Opc) { 10915 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10916 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10917 10918 QualType LHSType = LHS->getType(); 10919 QualType RHSType = RHS->getType(); 10920 if (LHSType->hasFloatingRepresentation() || 10921 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10922 S.inTemplateInstantiation()) 10923 return; 10924 10925 // Comparisons between two array types are ill-formed for operator<=>, so 10926 // we shouldn't emit any additional warnings about it. 10927 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10928 return; 10929 10930 // For non-floating point types, check for self-comparisons of the form 10931 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10932 // often indicate logic errors in the program. 10933 // 10934 // NOTE: Don't warn about comparison expressions resulting from macro 10935 // expansion. Also don't warn about comparisons which are only self 10936 // comparisons within a template instantiation. The warnings should catch 10937 // obvious cases in the definition of the template anyways. The idea is to 10938 // warn when the typed comparison operator will always evaluate to the same 10939 // result. 10940 10941 // Used for indexing into %select in warn_comparison_always 10942 enum { 10943 AlwaysConstant, 10944 AlwaysTrue, 10945 AlwaysFalse, 10946 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10947 }; 10948 10949 // C++2a [depr.array.comp]: 10950 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10951 // operands of array type are deprecated. 10952 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10953 RHSStripped->getType()->isArrayType()) { 10954 S.Diag(Loc, diag::warn_depr_array_comparison) 10955 << LHS->getSourceRange() << RHS->getSourceRange() 10956 << LHSStripped->getType() << RHSStripped->getType(); 10957 // Carry on to produce the tautological comparison warning, if this 10958 // expression is potentially-evaluated, we can resolve the array to a 10959 // non-weak declaration, and so on. 10960 } 10961 10962 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10963 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10964 unsigned Result; 10965 switch (Opc) { 10966 case BO_EQ: 10967 case BO_LE: 10968 case BO_GE: 10969 Result = AlwaysTrue; 10970 break; 10971 case BO_NE: 10972 case BO_LT: 10973 case BO_GT: 10974 Result = AlwaysFalse; 10975 break; 10976 case BO_Cmp: 10977 Result = AlwaysEqual; 10978 break; 10979 default: 10980 Result = AlwaysConstant; 10981 break; 10982 } 10983 S.DiagRuntimeBehavior(Loc, nullptr, 10984 S.PDiag(diag::warn_comparison_always) 10985 << 0 /*self-comparison*/ 10986 << Result); 10987 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10988 // What is it always going to evaluate to? 10989 unsigned Result; 10990 switch (Opc) { 10991 case BO_EQ: // e.g. array1 == array2 10992 Result = AlwaysFalse; 10993 break; 10994 case BO_NE: // e.g. array1 != array2 10995 Result = AlwaysTrue; 10996 break; 10997 default: // e.g. array1 <= array2 10998 // The best we can say is 'a constant' 10999 Result = AlwaysConstant; 11000 break; 11001 } 11002 S.DiagRuntimeBehavior(Loc, nullptr, 11003 S.PDiag(diag::warn_comparison_always) 11004 << 1 /*array comparison*/ 11005 << Result); 11006 } 11007 } 11008 11009 if (isa<CastExpr>(LHSStripped)) 11010 LHSStripped = LHSStripped->IgnoreParenCasts(); 11011 if (isa<CastExpr>(RHSStripped)) 11012 RHSStripped = RHSStripped->IgnoreParenCasts(); 11013 11014 // Warn about comparisons against a string constant (unless the other 11015 // operand is null); the user probably wants string comparison function. 11016 Expr *LiteralString = nullptr; 11017 Expr *LiteralStringStripped = nullptr; 11018 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11019 !RHSStripped->isNullPointerConstant(S.Context, 11020 Expr::NPC_ValueDependentIsNull)) { 11021 LiteralString = LHS; 11022 LiteralStringStripped = LHSStripped; 11023 } else if ((isa<StringLiteral>(RHSStripped) || 11024 isa<ObjCEncodeExpr>(RHSStripped)) && 11025 !LHSStripped->isNullPointerConstant(S.Context, 11026 Expr::NPC_ValueDependentIsNull)) { 11027 LiteralString = RHS; 11028 LiteralStringStripped = RHSStripped; 11029 } 11030 11031 if (LiteralString) { 11032 S.DiagRuntimeBehavior(Loc, nullptr, 11033 S.PDiag(diag::warn_stringcompare) 11034 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11035 << LiteralString->getSourceRange()); 11036 } 11037 } 11038 11039 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11040 switch (CK) { 11041 default: { 11042 #ifndef NDEBUG 11043 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11044 << "\n"; 11045 #endif 11046 llvm_unreachable("unhandled cast kind"); 11047 } 11048 case CK_UserDefinedConversion: 11049 return ICK_Identity; 11050 case CK_LValueToRValue: 11051 return ICK_Lvalue_To_Rvalue; 11052 case CK_ArrayToPointerDecay: 11053 return ICK_Array_To_Pointer; 11054 case CK_FunctionToPointerDecay: 11055 return ICK_Function_To_Pointer; 11056 case CK_IntegralCast: 11057 return ICK_Integral_Conversion; 11058 case CK_FloatingCast: 11059 return ICK_Floating_Conversion; 11060 case CK_IntegralToFloating: 11061 case CK_FloatingToIntegral: 11062 return ICK_Floating_Integral; 11063 case CK_IntegralComplexCast: 11064 case CK_FloatingComplexCast: 11065 case CK_FloatingComplexToIntegralComplex: 11066 case CK_IntegralComplexToFloatingComplex: 11067 return ICK_Complex_Conversion; 11068 case CK_FloatingComplexToReal: 11069 case CK_FloatingRealToComplex: 11070 case CK_IntegralComplexToReal: 11071 case CK_IntegralRealToComplex: 11072 return ICK_Complex_Real; 11073 } 11074 } 11075 11076 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11077 QualType FromType, 11078 SourceLocation Loc) { 11079 // Check for a narrowing implicit conversion. 11080 StandardConversionSequence SCS; 11081 SCS.setAsIdentityConversion(); 11082 SCS.setToType(0, FromType); 11083 SCS.setToType(1, ToType); 11084 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11085 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11086 11087 APValue PreNarrowingValue; 11088 QualType PreNarrowingType; 11089 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11090 PreNarrowingType, 11091 /*IgnoreFloatToIntegralConversion*/ true)) { 11092 case NK_Dependent_Narrowing: 11093 // Implicit conversion to a narrower type, but the expression is 11094 // value-dependent so we can't tell whether it's actually narrowing. 11095 case NK_Not_Narrowing: 11096 return false; 11097 11098 case NK_Constant_Narrowing: 11099 // Implicit conversion to a narrower type, and the value is not a constant 11100 // expression. 11101 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11102 << /*Constant*/ 1 11103 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11104 return true; 11105 11106 case NK_Variable_Narrowing: 11107 // Implicit conversion to a narrower type, and the value is not a constant 11108 // expression. 11109 case NK_Type_Narrowing: 11110 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11111 << /*Constant*/ 0 << FromType << ToType; 11112 // TODO: It's not a constant expression, but what if the user intended it 11113 // to be? Can we produce notes to help them figure out why it isn't? 11114 return true; 11115 } 11116 llvm_unreachable("unhandled case in switch"); 11117 } 11118 11119 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11120 ExprResult &LHS, 11121 ExprResult &RHS, 11122 SourceLocation Loc) { 11123 QualType LHSType = LHS.get()->getType(); 11124 QualType RHSType = RHS.get()->getType(); 11125 // Dig out the original argument type and expression before implicit casts 11126 // were applied. These are the types/expressions we need to check the 11127 // [expr.spaceship] requirements against. 11128 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11129 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11130 QualType LHSStrippedType = LHSStripped.get()->getType(); 11131 QualType RHSStrippedType = RHSStripped.get()->getType(); 11132 11133 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11134 // other is not, the program is ill-formed. 11135 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11136 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11137 return QualType(); 11138 } 11139 11140 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11141 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11142 RHSStrippedType->isEnumeralType(); 11143 if (NumEnumArgs == 1) { 11144 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11145 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11146 if (OtherTy->hasFloatingRepresentation()) { 11147 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11148 return QualType(); 11149 } 11150 } 11151 if (NumEnumArgs == 2) { 11152 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11153 // type E, the operator yields the result of converting the operands 11154 // to the underlying type of E and applying <=> to the converted operands. 11155 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11156 S.InvalidOperands(Loc, LHS, RHS); 11157 return QualType(); 11158 } 11159 QualType IntType = 11160 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11161 assert(IntType->isArithmeticType()); 11162 11163 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11164 // promote the boolean type, and all other promotable integer types, to 11165 // avoid this. 11166 if (IntType->isPromotableIntegerType()) 11167 IntType = S.Context.getPromotedIntegerType(IntType); 11168 11169 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11170 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11171 LHSType = RHSType = IntType; 11172 } 11173 11174 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11175 // usual arithmetic conversions are applied to the operands. 11176 QualType Type = 11177 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11178 if (LHS.isInvalid() || RHS.isInvalid()) 11179 return QualType(); 11180 if (Type.isNull()) 11181 return S.InvalidOperands(Loc, LHS, RHS); 11182 11183 Optional<ComparisonCategoryType> CCT = 11184 getComparisonCategoryForBuiltinCmp(Type); 11185 if (!CCT) 11186 return S.InvalidOperands(Loc, LHS, RHS); 11187 11188 bool HasNarrowing = checkThreeWayNarrowingConversion( 11189 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11190 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11191 RHS.get()->getBeginLoc()); 11192 if (HasNarrowing) 11193 return QualType(); 11194 11195 assert(!Type.isNull() && "composite type for <=> has not been set"); 11196 11197 return S.CheckComparisonCategoryType( 11198 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11199 } 11200 11201 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11202 ExprResult &RHS, 11203 SourceLocation Loc, 11204 BinaryOperatorKind Opc) { 11205 if (Opc == BO_Cmp) 11206 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11207 11208 // C99 6.5.8p3 / C99 6.5.9p4 11209 QualType Type = 11210 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11211 if (LHS.isInvalid() || RHS.isInvalid()) 11212 return QualType(); 11213 if (Type.isNull()) 11214 return S.InvalidOperands(Loc, LHS, RHS); 11215 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11216 11217 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11218 return S.InvalidOperands(Loc, LHS, RHS); 11219 11220 // Check for comparisons of floating point operands using != and ==. 11221 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11222 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11223 11224 // The result of comparisons is 'bool' in C++, 'int' in C. 11225 return S.Context.getLogicalOperationType(); 11226 } 11227 11228 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11229 if (!NullE.get()->getType()->isAnyPointerType()) 11230 return; 11231 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11232 if (!E.get()->getType()->isAnyPointerType() && 11233 E.get()->isNullPointerConstant(Context, 11234 Expr::NPC_ValueDependentIsNotNull) == 11235 Expr::NPCK_ZeroExpression) { 11236 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11237 if (CL->getValue() == 0) 11238 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11239 << NullValue 11240 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11241 NullValue ? "NULL" : "(void *)0"); 11242 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11243 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11244 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11245 if (T == Context.CharTy) 11246 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11247 << NullValue 11248 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11249 NullValue ? "NULL" : "(void *)0"); 11250 } 11251 } 11252 } 11253 11254 // C99 6.5.8, C++ [expr.rel] 11255 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11256 SourceLocation Loc, 11257 BinaryOperatorKind Opc) { 11258 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11259 bool IsThreeWay = Opc == BO_Cmp; 11260 bool IsOrdered = IsRelational || IsThreeWay; 11261 auto IsAnyPointerType = [](ExprResult E) { 11262 QualType Ty = E.get()->getType(); 11263 return Ty->isPointerType() || Ty->isMemberPointerType(); 11264 }; 11265 11266 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11267 // type, array-to-pointer, ..., conversions are performed on both operands to 11268 // bring them to their composite type. 11269 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11270 // any type-related checks. 11271 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11272 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11273 if (LHS.isInvalid()) 11274 return QualType(); 11275 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11276 if (RHS.isInvalid()) 11277 return QualType(); 11278 } else { 11279 LHS = DefaultLvalueConversion(LHS.get()); 11280 if (LHS.isInvalid()) 11281 return QualType(); 11282 RHS = DefaultLvalueConversion(RHS.get()); 11283 if (RHS.isInvalid()) 11284 return QualType(); 11285 } 11286 11287 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11288 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11289 CheckPtrComparisonWithNullChar(LHS, RHS); 11290 CheckPtrComparisonWithNullChar(RHS, LHS); 11291 } 11292 11293 // Handle vector comparisons separately. 11294 if (LHS.get()->getType()->isVectorType() || 11295 RHS.get()->getType()->isVectorType()) 11296 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11297 11298 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11299 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11300 11301 QualType LHSType = LHS.get()->getType(); 11302 QualType RHSType = RHS.get()->getType(); 11303 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11304 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11305 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11306 11307 const Expr::NullPointerConstantKind LHSNullKind = 11308 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11309 const Expr::NullPointerConstantKind RHSNullKind = 11310 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11311 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11312 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11313 11314 auto computeResultTy = [&]() { 11315 if (Opc != BO_Cmp) 11316 return Context.getLogicalOperationType(); 11317 assert(getLangOpts().CPlusPlus); 11318 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11319 11320 QualType CompositeTy = LHS.get()->getType(); 11321 assert(!CompositeTy->isReferenceType()); 11322 11323 Optional<ComparisonCategoryType> CCT = 11324 getComparisonCategoryForBuiltinCmp(CompositeTy); 11325 if (!CCT) 11326 return InvalidOperands(Loc, LHS, RHS); 11327 11328 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11329 // P0946R0: Comparisons between a null pointer constant and an object 11330 // pointer result in std::strong_equality, which is ill-formed under 11331 // P1959R0. 11332 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11333 << (LHSIsNull ? LHS.get()->getSourceRange() 11334 : RHS.get()->getSourceRange()); 11335 return QualType(); 11336 } 11337 11338 return CheckComparisonCategoryType( 11339 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11340 }; 11341 11342 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11343 bool IsEquality = Opc == BO_EQ; 11344 if (RHSIsNull) 11345 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11346 RHS.get()->getSourceRange()); 11347 else 11348 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11349 LHS.get()->getSourceRange()); 11350 } 11351 11352 if ((LHSType->isIntegerType() && !LHSIsNull) || 11353 (RHSType->isIntegerType() && !RHSIsNull)) { 11354 // Skip normal pointer conversion checks in this case; we have better 11355 // diagnostics for this below. 11356 } else if (getLangOpts().CPlusPlus) { 11357 // Equality comparison of a function pointer to a void pointer is invalid, 11358 // but we allow it as an extension. 11359 // FIXME: If we really want to allow this, should it be part of composite 11360 // pointer type computation so it works in conditionals too? 11361 if (!IsOrdered && 11362 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11363 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11364 // This is a gcc extension compatibility comparison. 11365 // In a SFINAE context, we treat this as a hard error to maintain 11366 // conformance with the C++ standard. 11367 diagnoseFunctionPointerToVoidComparison( 11368 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11369 11370 if (isSFINAEContext()) 11371 return QualType(); 11372 11373 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11374 return computeResultTy(); 11375 } 11376 11377 // C++ [expr.eq]p2: 11378 // If at least one operand is a pointer [...] bring them to their 11379 // composite pointer type. 11380 // C++ [expr.spaceship]p6 11381 // If at least one of the operands is of pointer type, [...] bring them 11382 // to their composite pointer type. 11383 // C++ [expr.rel]p2: 11384 // If both operands are pointers, [...] bring them to their composite 11385 // pointer type. 11386 // For <=>, the only valid non-pointer types are arrays and functions, and 11387 // we already decayed those, so this is really the same as the relational 11388 // comparison rule. 11389 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11390 (IsOrdered ? 2 : 1) && 11391 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11392 RHSType->isObjCObjectPointerType()))) { 11393 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11394 return QualType(); 11395 return computeResultTy(); 11396 } 11397 } else if (LHSType->isPointerType() && 11398 RHSType->isPointerType()) { // C99 6.5.8p2 11399 // All of the following pointer-related warnings are GCC extensions, except 11400 // when handling null pointer constants. 11401 QualType LCanPointeeTy = 11402 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11403 QualType RCanPointeeTy = 11404 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11405 11406 // C99 6.5.9p2 and C99 6.5.8p2 11407 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11408 RCanPointeeTy.getUnqualifiedType())) { 11409 // Valid unless a relational comparison of function pointers 11410 if (IsRelational && LCanPointeeTy->isFunctionType()) { 11411 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11412 << LHSType << RHSType << LHS.get()->getSourceRange() 11413 << RHS.get()->getSourceRange(); 11414 } 11415 } else if (!IsRelational && 11416 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11417 // Valid unless comparison between non-null pointer and function pointer 11418 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11419 && !LHSIsNull && !RHSIsNull) 11420 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11421 /*isError*/false); 11422 } else { 11423 // Invalid 11424 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11425 } 11426 if (LCanPointeeTy != RCanPointeeTy) { 11427 // Treat NULL constant as a special case in OpenCL. 11428 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11429 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 11430 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 11431 Diag(Loc, 11432 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11433 << LHSType << RHSType << 0 /* comparison */ 11434 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11435 } 11436 } 11437 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11438 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11439 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11440 : CK_BitCast; 11441 if (LHSIsNull && !RHSIsNull) 11442 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11443 else 11444 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11445 } 11446 return computeResultTy(); 11447 } 11448 11449 if (getLangOpts().CPlusPlus) { 11450 // C++ [expr.eq]p4: 11451 // Two operands of type std::nullptr_t or one operand of type 11452 // std::nullptr_t and the other a null pointer constant compare equal. 11453 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11454 if (LHSType->isNullPtrType()) { 11455 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11456 return computeResultTy(); 11457 } 11458 if (RHSType->isNullPtrType()) { 11459 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11460 return computeResultTy(); 11461 } 11462 } 11463 11464 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11465 // These aren't covered by the composite pointer type rules. 11466 if (!IsOrdered && RHSType->isNullPtrType() && 11467 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11468 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11469 return computeResultTy(); 11470 } 11471 if (!IsOrdered && LHSType->isNullPtrType() && 11472 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11473 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11474 return computeResultTy(); 11475 } 11476 11477 if (IsRelational && 11478 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11479 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11480 // HACK: Relational comparison of nullptr_t against a pointer type is 11481 // invalid per DR583, but we allow it within std::less<> and friends, 11482 // since otherwise common uses of it break. 11483 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11484 // friends to have std::nullptr_t overload candidates. 11485 DeclContext *DC = CurContext; 11486 if (isa<FunctionDecl>(DC)) 11487 DC = DC->getParent(); 11488 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11489 if (CTSD->isInStdNamespace() && 11490 llvm::StringSwitch<bool>(CTSD->getName()) 11491 .Cases("less", "less_equal", "greater", "greater_equal", true) 11492 .Default(false)) { 11493 if (RHSType->isNullPtrType()) 11494 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11495 else 11496 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11497 return computeResultTy(); 11498 } 11499 } 11500 } 11501 11502 // C++ [expr.eq]p2: 11503 // If at least one operand is a pointer to member, [...] bring them to 11504 // their composite pointer type. 11505 if (!IsOrdered && 11506 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11507 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11508 return QualType(); 11509 else 11510 return computeResultTy(); 11511 } 11512 } 11513 11514 // Handle block pointer types. 11515 if (!IsOrdered && LHSType->isBlockPointerType() && 11516 RHSType->isBlockPointerType()) { 11517 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11518 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11519 11520 if (!LHSIsNull && !RHSIsNull && 11521 !Context.typesAreCompatible(lpointee, rpointee)) { 11522 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11523 << LHSType << RHSType << LHS.get()->getSourceRange() 11524 << RHS.get()->getSourceRange(); 11525 } 11526 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11527 return computeResultTy(); 11528 } 11529 11530 // Allow block pointers to be compared with null pointer constants. 11531 if (!IsOrdered 11532 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11533 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11534 if (!LHSIsNull && !RHSIsNull) { 11535 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11536 ->getPointeeType()->isVoidType()) 11537 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11538 ->getPointeeType()->isVoidType()))) 11539 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11540 << LHSType << RHSType << LHS.get()->getSourceRange() 11541 << RHS.get()->getSourceRange(); 11542 } 11543 if (LHSIsNull && !RHSIsNull) 11544 LHS = ImpCastExprToType(LHS.get(), RHSType, 11545 RHSType->isPointerType() ? CK_BitCast 11546 : CK_AnyPointerToBlockPointerCast); 11547 else 11548 RHS = ImpCastExprToType(RHS.get(), LHSType, 11549 LHSType->isPointerType() ? CK_BitCast 11550 : CK_AnyPointerToBlockPointerCast); 11551 return computeResultTy(); 11552 } 11553 11554 if (LHSType->isObjCObjectPointerType() || 11555 RHSType->isObjCObjectPointerType()) { 11556 const PointerType *LPT = LHSType->getAs<PointerType>(); 11557 const PointerType *RPT = RHSType->getAs<PointerType>(); 11558 if (LPT || RPT) { 11559 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11560 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11561 11562 if (!LPtrToVoid && !RPtrToVoid && 11563 !Context.typesAreCompatible(LHSType, RHSType)) { 11564 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11565 /*isError*/false); 11566 } 11567 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11568 // the RHS, but we have test coverage for this behavior. 11569 // FIXME: Consider using convertPointersToCompositeType in C++. 11570 if (LHSIsNull && !RHSIsNull) { 11571 Expr *E = LHS.get(); 11572 if (getLangOpts().ObjCAutoRefCount) 11573 CheckObjCConversion(SourceRange(), RHSType, E, 11574 CCK_ImplicitConversion); 11575 LHS = ImpCastExprToType(E, RHSType, 11576 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11577 } 11578 else { 11579 Expr *E = RHS.get(); 11580 if (getLangOpts().ObjCAutoRefCount) 11581 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11582 /*Diagnose=*/true, 11583 /*DiagnoseCFAudited=*/false, Opc); 11584 RHS = ImpCastExprToType(E, LHSType, 11585 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11586 } 11587 return computeResultTy(); 11588 } 11589 if (LHSType->isObjCObjectPointerType() && 11590 RHSType->isObjCObjectPointerType()) { 11591 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11592 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11593 /*isError*/false); 11594 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11595 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11596 11597 if (LHSIsNull && !RHSIsNull) 11598 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11599 else 11600 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11601 return computeResultTy(); 11602 } 11603 11604 if (!IsOrdered && LHSType->isBlockPointerType() && 11605 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11606 LHS = ImpCastExprToType(LHS.get(), RHSType, 11607 CK_BlockPointerToObjCPointerCast); 11608 return computeResultTy(); 11609 } else if (!IsOrdered && 11610 LHSType->isBlockCompatibleObjCPointerType(Context) && 11611 RHSType->isBlockPointerType()) { 11612 RHS = ImpCastExprToType(RHS.get(), LHSType, 11613 CK_BlockPointerToObjCPointerCast); 11614 return computeResultTy(); 11615 } 11616 } 11617 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11618 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11619 unsigned DiagID = 0; 11620 bool isError = false; 11621 if (LangOpts.DebuggerSupport) { 11622 // Under a debugger, allow the comparison of pointers to integers, 11623 // since users tend to want to compare addresses. 11624 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11625 (RHSIsNull && RHSType->isIntegerType())) { 11626 if (IsOrdered) { 11627 isError = getLangOpts().CPlusPlus; 11628 DiagID = 11629 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11630 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11631 } 11632 } else if (getLangOpts().CPlusPlus) { 11633 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11634 isError = true; 11635 } else if (IsOrdered) 11636 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11637 else 11638 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11639 11640 if (DiagID) { 11641 Diag(Loc, DiagID) 11642 << LHSType << RHSType << LHS.get()->getSourceRange() 11643 << RHS.get()->getSourceRange(); 11644 if (isError) 11645 return QualType(); 11646 } 11647 11648 if (LHSType->isIntegerType()) 11649 LHS = ImpCastExprToType(LHS.get(), RHSType, 11650 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11651 else 11652 RHS = ImpCastExprToType(RHS.get(), LHSType, 11653 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11654 return computeResultTy(); 11655 } 11656 11657 // Handle block pointers. 11658 if (!IsOrdered && RHSIsNull 11659 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11660 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11661 return computeResultTy(); 11662 } 11663 if (!IsOrdered && LHSIsNull 11664 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11665 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11666 return computeResultTy(); 11667 } 11668 11669 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11670 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11671 return computeResultTy(); 11672 } 11673 11674 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11675 return computeResultTy(); 11676 } 11677 11678 if (LHSIsNull && RHSType->isQueueT()) { 11679 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11680 return computeResultTy(); 11681 } 11682 11683 if (LHSType->isQueueT() && RHSIsNull) { 11684 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11685 return computeResultTy(); 11686 } 11687 } 11688 11689 return InvalidOperands(Loc, LHS, RHS); 11690 } 11691 11692 // Return a signed ext_vector_type that is of identical size and number of 11693 // elements. For floating point vectors, return an integer type of identical 11694 // size and number of elements. In the non ext_vector_type case, search from 11695 // the largest type to the smallest type to avoid cases where long long == long, 11696 // where long gets picked over long long. 11697 QualType Sema::GetSignedVectorType(QualType V) { 11698 const VectorType *VTy = V->castAs<VectorType>(); 11699 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11700 11701 if (isa<ExtVectorType>(VTy)) { 11702 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11703 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11704 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11705 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11706 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11707 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11708 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11709 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11710 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11711 "Unhandled vector element size in vector compare"); 11712 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11713 } 11714 11715 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11716 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11717 VectorType::GenericVector); 11718 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11719 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11720 VectorType::GenericVector); 11721 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11722 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11723 VectorType::GenericVector); 11724 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11725 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11726 VectorType::GenericVector); 11727 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11728 "Unhandled vector element size in vector compare"); 11729 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11730 VectorType::GenericVector); 11731 } 11732 11733 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11734 /// operates on extended vector types. Instead of producing an IntTy result, 11735 /// like a scalar comparison, a vector comparison produces a vector of integer 11736 /// types. 11737 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11738 SourceLocation Loc, 11739 BinaryOperatorKind Opc) { 11740 if (Opc == BO_Cmp) { 11741 Diag(Loc, diag::err_three_way_vector_comparison); 11742 return QualType(); 11743 } 11744 11745 // Check to make sure we're operating on vectors of the same type and width, 11746 // Allowing one side to be a scalar of element type. 11747 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11748 /*AllowBothBool*/true, 11749 /*AllowBoolConversions*/getLangOpts().ZVector); 11750 if (vType.isNull()) 11751 return vType; 11752 11753 QualType LHSType = LHS.get()->getType(); 11754 11755 // If AltiVec, the comparison results in a numeric type, i.e. 11756 // bool for C++, int for C 11757 if (getLangOpts().AltiVec && 11758 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11759 return Context.getLogicalOperationType(); 11760 11761 // For non-floating point types, check for self-comparisons of the form 11762 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11763 // often indicate logic errors in the program. 11764 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11765 11766 // Check for comparisons of floating point operands using != and ==. 11767 if (BinaryOperator::isEqualityOp(Opc) && 11768 LHSType->hasFloatingRepresentation()) { 11769 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11770 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11771 } 11772 11773 // Return a signed type for the vector. 11774 return GetSignedVectorType(vType); 11775 } 11776 11777 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11778 const ExprResult &XorRHS, 11779 const SourceLocation Loc) { 11780 // Do not diagnose macros. 11781 if (Loc.isMacroID()) 11782 return; 11783 11784 bool Negative = false; 11785 bool ExplicitPlus = false; 11786 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11787 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11788 11789 if (!LHSInt) 11790 return; 11791 if (!RHSInt) { 11792 // Check negative literals. 11793 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11794 UnaryOperatorKind Opc = UO->getOpcode(); 11795 if (Opc != UO_Minus && Opc != UO_Plus) 11796 return; 11797 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11798 if (!RHSInt) 11799 return; 11800 Negative = (Opc == UO_Minus); 11801 ExplicitPlus = !Negative; 11802 } else { 11803 return; 11804 } 11805 } 11806 11807 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11808 llvm::APInt RightSideValue = RHSInt->getValue(); 11809 if (LeftSideValue != 2 && LeftSideValue != 10) 11810 return; 11811 11812 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11813 return; 11814 11815 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11816 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11817 llvm::StringRef ExprStr = 11818 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11819 11820 CharSourceRange XorRange = 11821 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11822 llvm::StringRef XorStr = 11823 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11824 // Do not diagnose if xor keyword/macro is used. 11825 if (XorStr == "xor") 11826 return; 11827 11828 std::string LHSStr = std::string(Lexer::getSourceText( 11829 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11830 S.getSourceManager(), S.getLangOpts())); 11831 std::string RHSStr = std::string(Lexer::getSourceText( 11832 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11833 S.getSourceManager(), S.getLangOpts())); 11834 11835 if (Negative) { 11836 RightSideValue = -RightSideValue; 11837 RHSStr = "-" + RHSStr; 11838 } else if (ExplicitPlus) { 11839 RHSStr = "+" + RHSStr; 11840 } 11841 11842 StringRef LHSStrRef = LHSStr; 11843 StringRef RHSStrRef = RHSStr; 11844 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11845 // literals. 11846 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11847 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11848 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11849 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11850 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11851 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11852 LHSStrRef.find('\'') != StringRef::npos || 11853 RHSStrRef.find('\'') != StringRef::npos) 11854 return; 11855 11856 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11857 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11858 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11859 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11860 std::string SuggestedExpr = "1 << " + RHSStr; 11861 bool Overflow = false; 11862 llvm::APInt One = (LeftSideValue - 1); 11863 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11864 if (Overflow) { 11865 if (RightSideIntValue < 64) 11866 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11867 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11868 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11869 else if (RightSideIntValue == 64) 11870 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11871 else 11872 return; 11873 } else { 11874 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11875 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11876 << PowValue.toString(10, true) 11877 << FixItHint::CreateReplacement( 11878 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11879 } 11880 11881 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11882 } else if (LeftSideValue == 10) { 11883 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11884 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11885 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11886 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11887 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11888 } 11889 } 11890 11891 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11892 SourceLocation Loc) { 11893 // Ensure that either both operands are of the same vector type, or 11894 // one operand is of a vector type and the other is of its element type. 11895 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11896 /*AllowBothBool*/true, 11897 /*AllowBoolConversions*/false); 11898 if (vType.isNull()) 11899 return InvalidOperands(Loc, LHS, RHS); 11900 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11901 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11902 return InvalidOperands(Loc, LHS, RHS); 11903 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11904 // usage of the logical operators && and || with vectors in C. This 11905 // check could be notionally dropped. 11906 if (!getLangOpts().CPlusPlus && 11907 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11908 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11909 11910 return GetSignedVectorType(LHS.get()->getType()); 11911 } 11912 11913 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11914 SourceLocation Loc, 11915 BinaryOperatorKind Opc) { 11916 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11917 11918 bool IsCompAssign = 11919 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11920 11921 if (LHS.get()->getType()->isVectorType() || 11922 RHS.get()->getType()->isVectorType()) { 11923 if (LHS.get()->getType()->hasIntegerRepresentation() && 11924 RHS.get()->getType()->hasIntegerRepresentation()) 11925 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11926 /*AllowBothBool*/true, 11927 /*AllowBoolConversions*/getLangOpts().ZVector); 11928 return InvalidOperands(Loc, LHS, RHS); 11929 } 11930 11931 if (Opc == BO_And) 11932 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11933 11934 if (LHS.get()->getType()->hasFloatingRepresentation() || 11935 RHS.get()->getType()->hasFloatingRepresentation()) 11936 return InvalidOperands(Loc, LHS, RHS); 11937 11938 ExprResult LHSResult = LHS, RHSResult = RHS; 11939 QualType compType = UsualArithmeticConversions( 11940 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11941 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11942 return QualType(); 11943 LHS = LHSResult.get(); 11944 RHS = RHSResult.get(); 11945 11946 if (Opc == BO_Xor) 11947 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11948 11949 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11950 return compType; 11951 return InvalidOperands(Loc, LHS, RHS); 11952 } 11953 11954 // C99 6.5.[13,14] 11955 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11956 SourceLocation Loc, 11957 BinaryOperatorKind Opc) { 11958 // Check vector operands differently. 11959 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11960 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11961 11962 bool EnumConstantInBoolContext = false; 11963 for (const ExprResult &HS : {LHS, RHS}) { 11964 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11965 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11966 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11967 EnumConstantInBoolContext = true; 11968 } 11969 } 11970 11971 if (EnumConstantInBoolContext) 11972 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11973 11974 // Diagnose cases where the user write a logical and/or but probably meant a 11975 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11976 // is a constant. 11977 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11978 !LHS.get()->getType()->isBooleanType() && 11979 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11980 // Don't warn in macros or template instantiations. 11981 !Loc.isMacroID() && !inTemplateInstantiation()) { 11982 // If the RHS can be constant folded, and if it constant folds to something 11983 // that isn't 0 or 1 (which indicate a potential logical operation that 11984 // happened to fold to true/false) then warn. 11985 // Parens on the RHS are ignored. 11986 Expr::EvalResult EVResult; 11987 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11988 llvm::APSInt Result = EVResult.Val.getInt(); 11989 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11990 !RHS.get()->getExprLoc().isMacroID()) || 11991 (Result != 0 && Result != 1)) { 11992 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11993 << RHS.get()->getSourceRange() 11994 << (Opc == BO_LAnd ? "&&" : "||"); 11995 // Suggest replacing the logical operator with the bitwise version 11996 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11997 << (Opc == BO_LAnd ? "&" : "|") 11998 << FixItHint::CreateReplacement(SourceRange( 11999 Loc, getLocForEndOfToken(Loc)), 12000 Opc == BO_LAnd ? "&" : "|"); 12001 if (Opc == BO_LAnd) 12002 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12003 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12004 << FixItHint::CreateRemoval( 12005 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12006 RHS.get()->getEndLoc())); 12007 } 12008 } 12009 } 12010 12011 if (!Context.getLangOpts().CPlusPlus) { 12012 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12013 // not operate on the built-in scalar and vector float types. 12014 if (Context.getLangOpts().OpenCL && 12015 Context.getLangOpts().OpenCLVersion < 120) { 12016 if (LHS.get()->getType()->isFloatingType() || 12017 RHS.get()->getType()->isFloatingType()) 12018 return InvalidOperands(Loc, LHS, RHS); 12019 } 12020 12021 LHS = UsualUnaryConversions(LHS.get()); 12022 if (LHS.isInvalid()) 12023 return QualType(); 12024 12025 RHS = UsualUnaryConversions(RHS.get()); 12026 if (RHS.isInvalid()) 12027 return QualType(); 12028 12029 if (!LHS.get()->getType()->isScalarType() || 12030 !RHS.get()->getType()->isScalarType()) 12031 return InvalidOperands(Loc, LHS, RHS); 12032 12033 return Context.IntTy; 12034 } 12035 12036 // The following is safe because we only use this method for 12037 // non-overloadable operands. 12038 12039 // C++ [expr.log.and]p1 12040 // C++ [expr.log.or]p1 12041 // The operands are both contextually converted to type bool. 12042 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12043 if (LHSRes.isInvalid()) 12044 return InvalidOperands(Loc, LHS, RHS); 12045 LHS = LHSRes; 12046 12047 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12048 if (RHSRes.isInvalid()) 12049 return InvalidOperands(Loc, LHS, RHS); 12050 RHS = RHSRes; 12051 12052 // C++ [expr.log.and]p2 12053 // C++ [expr.log.or]p2 12054 // The result is a bool. 12055 return Context.BoolTy; 12056 } 12057 12058 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12059 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12060 if (!ME) return false; 12061 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12062 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12063 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12064 if (!Base) return false; 12065 return Base->getMethodDecl() != nullptr; 12066 } 12067 12068 /// Is the given expression (which must be 'const') a reference to a 12069 /// variable which was originally non-const, but which has become 12070 /// 'const' due to being captured within a block? 12071 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12072 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12073 assert(E->isLValue() && E->getType().isConstQualified()); 12074 E = E->IgnoreParens(); 12075 12076 // Must be a reference to a declaration from an enclosing scope. 12077 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12078 if (!DRE) return NCCK_None; 12079 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12080 12081 // The declaration must be a variable which is not declared 'const'. 12082 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12083 if (!var) return NCCK_None; 12084 if (var->getType().isConstQualified()) return NCCK_None; 12085 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12086 12087 // Decide whether the first capture was for a block or a lambda. 12088 DeclContext *DC = S.CurContext, *Prev = nullptr; 12089 // Decide whether the first capture was for a block or a lambda. 12090 while (DC) { 12091 // For init-capture, it is possible that the variable belongs to the 12092 // template pattern of the current context. 12093 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12094 if (var->isInitCapture() && 12095 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12096 break; 12097 if (DC == var->getDeclContext()) 12098 break; 12099 Prev = DC; 12100 DC = DC->getParent(); 12101 } 12102 // Unless we have an init-capture, we've gone one step too far. 12103 if (!var->isInitCapture()) 12104 DC = Prev; 12105 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12106 } 12107 12108 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12109 Ty = Ty.getNonReferenceType(); 12110 if (IsDereference && Ty->isPointerType()) 12111 Ty = Ty->getPointeeType(); 12112 return !Ty.isConstQualified(); 12113 } 12114 12115 // Update err_typecheck_assign_const and note_typecheck_assign_const 12116 // when this enum is changed. 12117 enum { 12118 ConstFunction, 12119 ConstVariable, 12120 ConstMember, 12121 ConstMethod, 12122 NestedConstMember, 12123 ConstUnknown, // Keep as last element 12124 }; 12125 12126 /// Emit the "read-only variable not assignable" error and print notes to give 12127 /// more information about why the variable is not assignable, such as pointing 12128 /// to the declaration of a const variable, showing that a method is const, or 12129 /// that the function is returning a const reference. 12130 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12131 SourceLocation Loc) { 12132 SourceRange ExprRange = E->getSourceRange(); 12133 12134 // Only emit one error on the first const found. All other consts will emit 12135 // a note to the error. 12136 bool DiagnosticEmitted = false; 12137 12138 // Track if the current expression is the result of a dereference, and if the 12139 // next checked expression is the result of a dereference. 12140 bool IsDereference = false; 12141 bool NextIsDereference = false; 12142 12143 // Loop to process MemberExpr chains. 12144 while (true) { 12145 IsDereference = NextIsDereference; 12146 12147 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12148 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12149 NextIsDereference = ME->isArrow(); 12150 const ValueDecl *VD = ME->getMemberDecl(); 12151 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12152 // Mutable fields can be modified even if the class is const. 12153 if (Field->isMutable()) { 12154 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12155 break; 12156 } 12157 12158 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12159 if (!DiagnosticEmitted) { 12160 S.Diag(Loc, diag::err_typecheck_assign_const) 12161 << ExprRange << ConstMember << false /*static*/ << Field 12162 << Field->getType(); 12163 DiagnosticEmitted = true; 12164 } 12165 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12166 << ConstMember << false /*static*/ << Field << Field->getType() 12167 << Field->getSourceRange(); 12168 } 12169 E = ME->getBase(); 12170 continue; 12171 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12172 if (VDecl->getType().isConstQualified()) { 12173 if (!DiagnosticEmitted) { 12174 S.Diag(Loc, diag::err_typecheck_assign_const) 12175 << ExprRange << ConstMember << true /*static*/ << VDecl 12176 << VDecl->getType(); 12177 DiagnosticEmitted = true; 12178 } 12179 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12180 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12181 << VDecl->getSourceRange(); 12182 } 12183 // Static fields do not inherit constness from parents. 12184 break; 12185 } 12186 break; // End MemberExpr 12187 } else if (const ArraySubscriptExpr *ASE = 12188 dyn_cast<ArraySubscriptExpr>(E)) { 12189 E = ASE->getBase()->IgnoreParenImpCasts(); 12190 continue; 12191 } else if (const ExtVectorElementExpr *EVE = 12192 dyn_cast<ExtVectorElementExpr>(E)) { 12193 E = EVE->getBase()->IgnoreParenImpCasts(); 12194 continue; 12195 } 12196 break; 12197 } 12198 12199 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12200 // Function calls 12201 const FunctionDecl *FD = CE->getDirectCallee(); 12202 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12203 if (!DiagnosticEmitted) { 12204 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12205 << ConstFunction << FD; 12206 DiagnosticEmitted = true; 12207 } 12208 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12209 diag::note_typecheck_assign_const) 12210 << ConstFunction << FD << FD->getReturnType() 12211 << FD->getReturnTypeSourceRange(); 12212 } 12213 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12214 // Point to variable declaration. 12215 if (const ValueDecl *VD = DRE->getDecl()) { 12216 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12217 if (!DiagnosticEmitted) { 12218 S.Diag(Loc, diag::err_typecheck_assign_const) 12219 << ExprRange << ConstVariable << VD << VD->getType(); 12220 DiagnosticEmitted = true; 12221 } 12222 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12223 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12224 } 12225 } 12226 } else if (isa<CXXThisExpr>(E)) { 12227 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12228 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12229 if (MD->isConst()) { 12230 if (!DiagnosticEmitted) { 12231 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12232 << ConstMethod << MD; 12233 DiagnosticEmitted = true; 12234 } 12235 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12236 << ConstMethod << MD << MD->getSourceRange(); 12237 } 12238 } 12239 } 12240 } 12241 12242 if (DiagnosticEmitted) 12243 return; 12244 12245 // Can't determine a more specific message, so display the generic error. 12246 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12247 } 12248 12249 enum OriginalExprKind { 12250 OEK_Variable, 12251 OEK_Member, 12252 OEK_LValue 12253 }; 12254 12255 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12256 const RecordType *Ty, 12257 SourceLocation Loc, SourceRange Range, 12258 OriginalExprKind OEK, 12259 bool &DiagnosticEmitted) { 12260 std::vector<const RecordType *> RecordTypeList; 12261 RecordTypeList.push_back(Ty); 12262 unsigned NextToCheckIndex = 0; 12263 // We walk the record hierarchy breadth-first to ensure that we print 12264 // diagnostics in field nesting order. 12265 while (RecordTypeList.size() > NextToCheckIndex) { 12266 bool IsNested = NextToCheckIndex > 0; 12267 for (const FieldDecl *Field : 12268 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12269 // First, check every field for constness. 12270 QualType FieldTy = Field->getType(); 12271 if (FieldTy.isConstQualified()) { 12272 if (!DiagnosticEmitted) { 12273 S.Diag(Loc, diag::err_typecheck_assign_const) 12274 << Range << NestedConstMember << OEK << VD 12275 << IsNested << Field; 12276 DiagnosticEmitted = true; 12277 } 12278 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12279 << NestedConstMember << IsNested << Field 12280 << FieldTy << Field->getSourceRange(); 12281 } 12282 12283 // Then we append it to the list to check next in order. 12284 FieldTy = FieldTy.getCanonicalType(); 12285 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12286 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12287 RecordTypeList.push_back(FieldRecTy); 12288 } 12289 } 12290 ++NextToCheckIndex; 12291 } 12292 } 12293 12294 /// Emit an error for the case where a record we are trying to assign to has a 12295 /// const-qualified field somewhere in its hierarchy. 12296 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12297 SourceLocation Loc) { 12298 QualType Ty = E->getType(); 12299 assert(Ty->isRecordType() && "lvalue was not record?"); 12300 SourceRange Range = E->getSourceRange(); 12301 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12302 bool DiagEmitted = false; 12303 12304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12305 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12306 Range, OEK_Member, DiagEmitted); 12307 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12308 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12309 Range, OEK_Variable, DiagEmitted); 12310 else 12311 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12312 Range, OEK_LValue, DiagEmitted); 12313 if (!DiagEmitted) 12314 DiagnoseConstAssignment(S, E, Loc); 12315 } 12316 12317 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12318 /// emit an error and return true. If so, return false. 12319 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12320 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12321 12322 S.CheckShadowingDeclModification(E, Loc); 12323 12324 SourceLocation OrigLoc = Loc; 12325 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12326 &Loc); 12327 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12328 IsLV = Expr::MLV_InvalidMessageExpression; 12329 if (IsLV == Expr::MLV_Valid) 12330 return false; 12331 12332 unsigned DiagID = 0; 12333 bool NeedType = false; 12334 switch (IsLV) { // C99 6.5.16p2 12335 case Expr::MLV_ConstQualified: 12336 // Use a specialized diagnostic when we're assigning to an object 12337 // from an enclosing function or block. 12338 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12339 if (NCCK == NCCK_Block) 12340 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12341 else 12342 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12343 break; 12344 } 12345 12346 // In ARC, use some specialized diagnostics for occasions where we 12347 // infer 'const'. These are always pseudo-strong variables. 12348 if (S.getLangOpts().ObjCAutoRefCount) { 12349 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12350 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12351 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12352 12353 // Use the normal diagnostic if it's pseudo-__strong but the 12354 // user actually wrote 'const'. 12355 if (var->isARCPseudoStrong() && 12356 (!var->getTypeSourceInfo() || 12357 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12358 // There are three pseudo-strong cases: 12359 // - self 12360 ObjCMethodDecl *method = S.getCurMethodDecl(); 12361 if (method && var == method->getSelfDecl()) { 12362 DiagID = method->isClassMethod() 12363 ? diag::err_typecheck_arc_assign_self_class_method 12364 : diag::err_typecheck_arc_assign_self; 12365 12366 // - Objective-C externally_retained attribute. 12367 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12368 isa<ParmVarDecl>(var)) { 12369 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12370 12371 // - fast enumeration variables 12372 } else { 12373 DiagID = diag::err_typecheck_arr_assign_enumeration; 12374 } 12375 12376 SourceRange Assign; 12377 if (Loc != OrigLoc) 12378 Assign = SourceRange(OrigLoc, OrigLoc); 12379 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12380 // We need to preserve the AST regardless, so migration tool 12381 // can do its job. 12382 return false; 12383 } 12384 } 12385 } 12386 12387 // If none of the special cases above are triggered, then this is a 12388 // simple const assignment. 12389 if (DiagID == 0) { 12390 DiagnoseConstAssignment(S, E, Loc); 12391 return true; 12392 } 12393 12394 break; 12395 case Expr::MLV_ConstAddrSpace: 12396 DiagnoseConstAssignment(S, E, Loc); 12397 return true; 12398 case Expr::MLV_ConstQualifiedField: 12399 DiagnoseRecursiveConstFields(S, E, Loc); 12400 return true; 12401 case Expr::MLV_ArrayType: 12402 case Expr::MLV_ArrayTemporary: 12403 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12404 NeedType = true; 12405 break; 12406 case Expr::MLV_NotObjectType: 12407 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12408 NeedType = true; 12409 break; 12410 case Expr::MLV_LValueCast: 12411 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12412 break; 12413 case Expr::MLV_Valid: 12414 llvm_unreachable("did not take early return for MLV_Valid"); 12415 case Expr::MLV_InvalidExpression: 12416 case Expr::MLV_MemberFunction: 12417 case Expr::MLV_ClassTemporary: 12418 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12419 break; 12420 case Expr::MLV_IncompleteType: 12421 case Expr::MLV_IncompleteVoidType: 12422 return S.RequireCompleteType(Loc, E->getType(), 12423 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12424 case Expr::MLV_DuplicateVectorComponents: 12425 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12426 break; 12427 case Expr::MLV_NoSetterProperty: 12428 llvm_unreachable("readonly properties should be processed differently"); 12429 case Expr::MLV_InvalidMessageExpression: 12430 DiagID = diag::err_readonly_message_assignment; 12431 break; 12432 case Expr::MLV_SubObjCPropertySetting: 12433 DiagID = diag::err_no_subobject_property_setting; 12434 break; 12435 } 12436 12437 SourceRange Assign; 12438 if (Loc != OrigLoc) 12439 Assign = SourceRange(OrigLoc, OrigLoc); 12440 if (NeedType) 12441 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12442 else 12443 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12444 return true; 12445 } 12446 12447 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12448 SourceLocation Loc, 12449 Sema &Sema) { 12450 if (Sema.inTemplateInstantiation()) 12451 return; 12452 if (Sema.isUnevaluatedContext()) 12453 return; 12454 if (Loc.isInvalid() || Loc.isMacroID()) 12455 return; 12456 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12457 return; 12458 12459 // C / C++ fields 12460 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12461 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12462 if (ML && MR) { 12463 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12464 return; 12465 const ValueDecl *LHSDecl = 12466 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12467 const ValueDecl *RHSDecl = 12468 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12469 if (LHSDecl != RHSDecl) 12470 return; 12471 if (LHSDecl->getType().isVolatileQualified()) 12472 return; 12473 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12474 if (RefTy->getPointeeType().isVolatileQualified()) 12475 return; 12476 12477 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12478 } 12479 12480 // Objective-C instance variables 12481 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12482 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12483 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12484 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12485 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12486 if (RL && RR && RL->getDecl() == RR->getDecl()) 12487 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12488 } 12489 } 12490 12491 // C99 6.5.16.1 12492 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12493 SourceLocation Loc, 12494 QualType CompoundType) { 12495 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12496 12497 // Verify that LHS is a modifiable lvalue, and emit error if not. 12498 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12499 return QualType(); 12500 12501 QualType LHSType = LHSExpr->getType(); 12502 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12503 CompoundType; 12504 // OpenCL v1.2 s6.1.1.1 p2: 12505 // The half data type can only be used to declare a pointer to a buffer that 12506 // contains half values 12507 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12508 LHSType->isHalfType()) { 12509 Diag(Loc, diag::err_opencl_half_load_store) << 1 12510 << LHSType.getUnqualifiedType(); 12511 return QualType(); 12512 } 12513 12514 AssignConvertType ConvTy; 12515 if (CompoundType.isNull()) { 12516 Expr *RHSCheck = RHS.get(); 12517 12518 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12519 12520 QualType LHSTy(LHSType); 12521 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12522 if (RHS.isInvalid()) 12523 return QualType(); 12524 // Special case of NSObject attributes on c-style pointer types. 12525 if (ConvTy == IncompatiblePointer && 12526 ((Context.isObjCNSObjectType(LHSType) && 12527 RHSType->isObjCObjectPointerType()) || 12528 (Context.isObjCNSObjectType(RHSType) && 12529 LHSType->isObjCObjectPointerType()))) 12530 ConvTy = Compatible; 12531 12532 if (ConvTy == Compatible && 12533 LHSType->isObjCObjectType()) 12534 Diag(Loc, diag::err_objc_object_assignment) 12535 << LHSType; 12536 12537 // If the RHS is a unary plus or minus, check to see if they = and + are 12538 // right next to each other. If so, the user may have typo'd "x =+ 4" 12539 // instead of "x += 4". 12540 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12541 RHSCheck = ICE->getSubExpr(); 12542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12543 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12544 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12545 // Only if the two operators are exactly adjacent. 12546 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12547 // And there is a space or other character before the subexpr of the 12548 // unary +/-. We don't want to warn on "x=-1". 12549 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12550 UO->getSubExpr()->getBeginLoc().isFileID()) { 12551 Diag(Loc, diag::warn_not_compound_assign) 12552 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12553 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12554 } 12555 } 12556 12557 if (ConvTy == Compatible) { 12558 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12559 // Warn about retain cycles where a block captures the LHS, but 12560 // not if the LHS is a simple variable into which the block is 12561 // being stored...unless that variable can be captured by reference! 12562 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12563 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12564 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12565 checkRetainCycles(LHSExpr, RHS.get()); 12566 } 12567 12568 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12569 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12570 // It is safe to assign a weak reference into a strong variable. 12571 // Although this code can still have problems: 12572 // id x = self.weakProp; 12573 // id y = self.weakProp; 12574 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12575 // paths through the function. This should be revisited if 12576 // -Wrepeated-use-of-weak is made flow-sensitive. 12577 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12578 // variable, which will be valid for the current autorelease scope. 12579 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12580 RHS.get()->getBeginLoc())) 12581 getCurFunction()->markSafeWeakUse(RHS.get()); 12582 12583 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12584 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12585 } 12586 } 12587 } else { 12588 // Compound assignment "x += y" 12589 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12590 } 12591 12592 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12593 RHS.get(), AA_Assigning)) 12594 return QualType(); 12595 12596 CheckForNullPointerDereference(*this, LHSExpr); 12597 12598 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12599 if (CompoundType.isNull()) { 12600 // C++2a [expr.ass]p5: 12601 // A simple-assignment whose left operand is of a volatile-qualified 12602 // type is deprecated unless the assignment is either a discarded-value 12603 // expression or an unevaluated operand 12604 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12605 } else { 12606 // C++2a [expr.ass]p6: 12607 // [Compound-assignment] expressions are deprecated if E1 has 12608 // volatile-qualified type 12609 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12610 } 12611 } 12612 12613 // C99 6.5.16p3: The type of an assignment expression is the type of the 12614 // left operand unless the left operand has qualified type, in which case 12615 // it is the unqualified version of the type of the left operand. 12616 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12617 // is converted to the type of the assignment expression (above). 12618 // C++ 5.17p1: the type of the assignment expression is that of its left 12619 // operand. 12620 return (getLangOpts().CPlusPlus 12621 ? LHSType : LHSType.getUnqualifiedType()); 12622 } 12623 12624 // Only ignore explicit casts to void. 12625 static bool IgnoreCommaOperand(const Expr *E) { 12626 E = E->IgnoreParens(); 12627 12628 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12629 if (CE->getCastKind() == CK_ToVoid) { 12630 return true; 12631 } 12632 12633 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12634 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12635 CE->getSubExpr()->getType()->isDependentType()) { 12636 return true; 12637 } 12638 } 12639 12640 return false; 12641 } 12642 12643 // Look for instances where it is likely the comma operator is confused with 12644 // another operator. There is a whitelist of acceptable expressions for the 12645 // left hand side of the comma operator, otherwise emit a warning. 12646 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12647 // No warnings in macros 12648 if (Loc.isMacroID()) 12649 return; 12650 12651 // Don't warn in template instantiations. 12652 if (inTemplateInstantiation()) 12653 return; 12654 12655 // Scope isn't fine-grained enough to whitelist the specific cases, so 12656 // instead, skip more than needed, then call back into here with the 12657 // CommaVisitor in SemaStmt.cpp. 12658 // The whitelisted locations are the initialization and increment portions 12659 // of a for loop. The additional checks are on the condition of 12660 // if statements, do/while loops, and for loops. 12661 // Differences in scope flags for C89 mode requires the extra logic. 12662 const unsigned ForIncrementFlags = 12663 getLangOpts().C99 || getLangOpts().CPlusPlus 12664 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12665 : Scope::ContinueScope | Scope::BreakScope; 12666 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12667 const unsigned ScopeFlags = getCurScope()->getFlags(); 12668 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12669 (ScopeFlags & ForInitFlags) == ForInitFlags) 12670 return; 12671 12672 // If there are multiple comma operators used together, get the RHS of the 12673 // of the comma operator as the LHS. 12674 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12675 if (BO->getOpcode() != BO_Comma) 12676 break; 12677 LHS = BO->getRHS(); 12678 } 12679 12680 // Only allow some expressions on LHS to not warn. 12681 if (IgnoreCommaOperand(LHS)) 12682 return; 12683 12684 Diag(Loc, diag::warn_comma_operator); 12685 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12686 << LHS->getSourceRange() 12687 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12688 LangOpts.CPlusPlus ? "static_cast<void>(" 12689 : "(void)(") 12690 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12691 ")"); 12692 } 12693 12694 // C99 6.5.17 12695 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12696 SourceLocation Loc) { 12697 LHS = S.CheckPlaceholderExpr(LHS.get()); 12698 RHS = S.CheckPlaceholderExpr(RHS.get()); 12699 if (LHS.isInvalid() || RHS.isInvalid()) 12700 return QualType(); 12701 12702 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12703 // operands, but not unary promotions. 12704 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12705 12706 // So we treat the LHS as a ignored value, and in C++ we allow the 12707 // containing site to determine what should be done with the RHS. 12708 LHS = S.IgnoredValueConversions(LHS.get()); 12709 if (LHS.isInvalid()) 12710 return QualType(); 12711 12712 S.DiagnoseUnusedExprResult(LHS.get()); 12713 12714 if (!S.getLangOpts().CPlusPlus) { 12715 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12716 if (RHS.isInvalid()) 12717 return QualType(); 12718 if (!RHS.get()->getType()->isVoidType()) 12719 S.RequireCompleteType(Loc, RHS.get()->getType(), 12720 diag::err_incomplete_type); 12721 } 12722 12723 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12724 S.DiagnoseCommaOperator(LHS.get(), Loc); 12725 12726 return RHS.get()->getType(); 12727 } 12728 12729 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12730 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12731 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12732 ExprValueKind &VK, 12733 ExprObjectKind &OK, 12734 SourceLocation OpLoc, 12735 bool IsInc, bool IsPrefix) { 12736 if (Op->isTypeDependent()) 12737 return S.Context.DependentTy; 12738 12739 QualType ResType = Op->getType(); 12740 // Atomic types can be used for increment / decrement where the non-atomic 12741 // versions can, so ignore the _Atomic() specifier for the purpose of 12742 // checking. 12743 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12744 ResType = ResAtomicType->getValueType(); 12745 12746 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12747 12748 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12749 // Decrement of bool is not allowed. 12750 if (!IsInc) { 12751 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12752 return QualType(); 12753 } 12754 // Increment of bool sets it to true, but is deprecated. 12755 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12756 : diag::warn_increment_bool) 12757 << Op->getSourceRange(); 12758 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12759 // Error on enum increments and decrements in C++ mode 12760 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12761 return QualType(); 12762 } else if (ResType->isRealType()) { 12763 // OK! 12764 } else if (ResType->isPointerType()) { 12765 // C99 6.5.2.4p2, 6.5.6p2 12766 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12767 return QualType(); 12768 } else if (ResType->isObjCObjectPointerType()) { 12769 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12770 // Otherwise, we just need a complete type. 12771 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12772 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12773 return QualType(); 12774 } else if (ResType->isAnyComplexType()) { 12775 // C99 does not support ++/-- on complex types, we allow as an extension. 12776 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12777 << ResType << Op->getSourceRange(); 12778 } else if (ResType->isPlaceholderType()) { 12779 ExprResult PR = S.CheckPlaceholderExpr(Op); 12780 if (PR.isInvalid()) return QualType(); 12781 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12782 IsInc, IsPrefix); 12783 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12784 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12785 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12786 (ResType->castAs<VectorType>()->getVectorKind() != 12787 VectorType::AltiVecBool)) { 12788 // The z vector extensions allow ++ and -- for non-bool vectors. 12789 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12790 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12791 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12792 } else { 12793 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12794 << ResType << int(IsInc) << Op->getSourceRange(); 12795 return QualType(); 12796 } 12797 // At this point, we know we have a real, complex or pointer type. 12798 // Now make sure the operand is a modifiable lvalue. 12799 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12800 return QualType(); 12801 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12802 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12803 // An operand with volatile-qualified type is deprecated 12804 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12805 << IsInc << ResType; 12806 } 12807 // In C++, a prefix increment is the same type as the operand. Otherwise 12808 // (in C or with postfix), the increment is the unqualified type of the 12809 // operand. 12810 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12811 VK = VK_LValue; 12812 OK = Op->getObjectKind(); 12813 return ResType; 12814 } else { 12815 VK = VK_RValue; 12816 return ResType.getUnqualifiedType(); 12817 } 12818 } 12819 12820 12821 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12822 /// This routine allows us to typecheck complex/recursive expressions 12823 /// where the declaration is needed for type checking. We only need to 12824 /// handle cases when the expression references a function designator 12825 /// or is an lvalue. Here are some examples: 12826 /// - &(x) => x 12827 /// - &*****f => f for f a function designator. 12828 /// - &s.xx => s 12829 /// - &s.zz[1].yy -> s, if zz is an array 12830 /// - *(x + 1) -> x, if x is an array 12831 /// - &"123"[2] -> 0 12832 /// - & __real__ x -> x 12833 /// 12834 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 12835 /// members. 12836 static ValueDecl *getPrimaryDecl(Expr *E) { 12837 switch (E->getStmtClass()) { 12838 case Stmt::DeclRefExprClass: 12839 return cast<DeclRefExpr>(E)->getDecl(); 12840 case Stmt::MemberExprClass: 12841 // If this is an arrow operator, the address is an offset from 12842 // the base's value, so the object the base refers to is 12843 // irrelevant. 12844 if (cast<MemberExpr>(E)->isArrow()) 12845 return nullptr; 12846 // Otherwise, the expression refers to a part of the base 12847 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12848 case Stmt::ArraySubscriptExprClass: { 12849 // FIXME: This code shouldn't be necessary! We should catch the implicit 12850 // promotion of register arrays earlier. 12851 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12852 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12853 if (ICE->getSubExpr()->getType()->isArrayType()) 12854 return getPrimaryDecl(ICE->getSubExpr()); 12855 } 12856 return nullptr; 12857 } 12858 case Stmt::UnaryOperatorClass: { 12859 UnaryOperator *UO = cast<UnaryOperator>(E); 12860 12861 switch(UO->getOpcode()) { 12862 case UO_Real: 12863 case UO_Imag: 12864 case UO_Extension: 12865 return getPrimaryDecl(UO->getSubExpr()); 12866 default: 12867 return nullptr; 12868 } 12869 } 12870 case Stmt::ParenExprClass: 12871 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12872 case Stmt::ImplicitCastExprClass: 12873 // If the result of an implicit cast is an l-value, we care about 12874 // the sub-expression; otherwise, the result here doesn't matter. 12875 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12876 case Stmt::CXXUuidofExprClass: 12877 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 12878 default: 12879 return nullptr; 12880 } 12881 } 12882 12883 namespace { 12884 enum { 12885 AO_Bit_Field = 0, 12886 AO_Vector_Element = 1, 12887 AO_Property_Expansion = 2, 12888 AO_Register_Variable = 3, 12889 AO_No_Error = 4 12890 }; 12891 } 12892 /// Diagnose invalid operand for address of operations. 12893 /// 12894 /// \param Type The type of operand which cannot have its address taken. 12895 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12896 Expr *E, unsigned Type) { 12897 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12898 } 12899 12900 /// CheckAddressOfOperand - The operand of & must be either a function 12901 /// designator or an lvalue designating an object. If it is an lvalue, the 12902 /// object cannot be declared with storage class register or be a bit field. 12903 /// Note: The usual conversions are *not* applied to the operand of the & 12904 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12905 /// In C++, the operand might be an overloaded function name, in which case 12906 /// we allow the '&' but retain the overloaded-function type. 12907 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12908 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12909 if (PTy->getKind() == BuiltinType::Overload) { 12910 Expr *E = OrigOp.get()->IgnoreParens(); 12911 if (!isa<OverloadExpr>(E)) { 12912 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12913 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12914 << OrigOp.get()->getSourceRange(); 12915 return QualType(); 12916 } 12917 12918 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12919 if (isa<UnresolvedMemberExpr>(Ovl)) 12920 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12921 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12922 << OrigOp.get()->getSourceRange(); 12923 return QualType(); 12924 } 12925 12926 return Context.OverloadTy; 12927 } 12928 12929 if (PTy->getKind() == BuiltinType::UnknownAny) 12930 return Context.UnknownAnyTy; 12931 12932 if (PTy->getKind() == BuiltinType::BoundMember) { 12933 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12934 << OrigOp.get()->getSourceRange(); 12935 return QualType(); 12936 } 12937 12938 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12939 if (OrigOp.isInvalid()) return QualType(); 12940 } 12941 12942 if (OrigOp.get()->isTypeDependent()) 12943 return Context.DependentTy; 12944 12945 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12946 12947 // Make sure to ignore parentheses in subsequent checks 12948 Expr *op = OrigOp.get()->IgnoreParens(); 12949 12950 // In OpenCL captures for blocks called as lambda functions 12951 // are located in the private address space. Blocks used in 12952 // enqueue_kernel can be located in a different address space 12953 // depending on a vendor implementation. Thus preventing 12954 // taking an address of the capture to avoid invalid AS casts. 12955 if (LangOpts.OpenCL) { 12956 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12957 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12958 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12959 return QualType(); 12960 } 12961 } 12962 12963 if (getLangOpts().C99) { 12964 // Implement C99-only parts of addressof rules. 12965 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12966 if (uOp->getOpcode() == UO_Deref) 12967 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12968 // (assuming the deref expression is valid). 12969 return uOp->getSubExpr()->getType(); 12970 } 12971 // Technically, there should be a check for array subscript 12972 // expressions here, but the result of one is always an lvalue anyway. 12973 } 12974 ValueDecl *dcl = getPrimaryDecl(op); 12975 12976 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12977 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12978 op->getBeginLoc())) 12979 return QualType(); 12980 12981 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12982 unsigned AddressOfError = AO_No_Error; 12983 12984 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12985 bool sfinae = (bool)isSFINAEContext(); 12986 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12987 : diag::ext_typecheck_addrof_temporary) 12988 << op->getType() << op->getSourceRange(); 12989 if (sfinae) 12990 return QualType(); 12991 // Materialize the temporary as an lvalue so that we can take its address. 12992 OrigOp = op = 12993 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12994 } else if (isa<ObjCSelectorExpr>(op)) { 12995 return Context.getPointerType(op->getType()); 12996 } else if (lval == Expr::LV_MemberFunction) { 12997 // If it's an instance method, make a member pointer. 12998 // The expression must have exactly the form &A::foo. 12999 13000 // If the underlying expression isn't a decl ref, give up. 13001 if (!isa<DeclRefExpr>(op)) { 13002 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13003 << OrigOp.get()->getSourceRange(); 13004 return QualType(); 13005 } 13006 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13007 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13008 13009 // The id-expression was parenthesized. 13010 if (OrigOp.get() != DRE) { 13011 Diag(OpLoc, diag::err_parens_pointer_member_function) 13012 << OrigOp.get()->getSourceRange(); 13013 13014 // The method was named without a qualifier. 13015 } else if (!DRE->getQualifier()) { 13016 if (MD->getParent()->getName().empty()) 13017 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13018 << op->getSourceRange(); 13019 else { 13020 SmallString<32> Str; 13021 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13022 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13023 << op->getSourceRange() 13024 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13025 } 13026 } 13027 13028 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13029 if (isa<CXXDestructorDecl>(MD)) 13030 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13031 13032 QualType MPTy = Context.getMemberPointerType( 13033 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13034 // Under the MS ABI, lock down the inheritance model now. 13035 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13036 (void)isCompleteType(OpLoc, MPTy); 13037 return MPTy; 13038 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13039 // C99 6.5.3.2p1 13040 // The operand must be either an l-value or a function designator 13041 if (!op->getType()->isFunctionType()) { 13042 // Use a special diagnostic for loads from property references. 13043 if (isa<PseudoObjectExpr>(op)) { 13044 AddressOfError = AO_Property_Expansion; 13045 } else { 13046 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13047 << op->getType() << op->getSourceRange(); 13048 return QualType(); 13049 } 13050 } 13051 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13052 // The operand cannot be a bit-field 13053 AddressOfError = AO_Bit_Field; 13054 } else if (op->getObjectKind() == OK_VectorComponent) { 13055 // The operand cannot be an element of a vector 13056 AddressOfError = AO_Vector_Element; 13057 } else if (dcl) { // C99 6.5.3.2p1 13058 // We have an lvalue with a decl. Make sure the decl is not declared 13059 // with the register storage-class specifier. 13060 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13061 // in C++ it is not error to take address of a register 13062 // variable (c++03 7.1.1P3) 13063 if (vd->getStorageClass() == SC_Register && 13064 !getLangOpts().CPlusPlus) { 13065 AddressOfError = AO_Register_Variable; 13066 } 13067 } else if (isa<MSPropertyDecl>(dcl)) { 13068 AddressOfError = AO_Property_Expansion; 13069 } else if (isa<FunctionTemplateDecl>(dcl)) { 13070 return Context.OverloadTy; 13071 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13072 // Okay: we can take the address of a field. 13073 // Could be a pointer to member, though, if there is an explicit 13074 // scope qualifier for the class. 13075 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13076 DeclContext *Ctx = dcl->getDeclContext(); 13077 if (Ctx && Ctx->isRecord()) { 13078 if (dcl->getType()->isReferenceType()) { 13079 Diag(OpLoc, 13080 diag::err_cannot_form_pointer_to_member_of_reference_type) 13081 << dcl->getDeclName() << dcl->getType(); 13082 return QualType(); 13083 } 13084 13085 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13086 Ctx = Ctx->getParent(); 13087 13088 QualType MPTy = Context.getMemberPointerType( 13089 op->getType(), 13090 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13091 // Under the MS ABI, lock down the inheritance model now. 13092 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13093 (void)isCompleteType(OpLoc, MPTy); 13094 return MPTy; 13095 } 13096 } 13097 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13098 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13099 llvm_unreachable("Unknown/unexpected decl type"); 13100 } 13101 13102 if (AddressOfError != AO_No_Error) { 13103 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13104 return QualType(); 13105 } 13106 13107 if (lval == Expr::LV_IncompleteVoidType) { 13108 // Taking the address of a void variable is technically illegal, but we 13109 // allow it in cases which are otherwise valid. 13110 // Example: "extern void x; void* y = &x;". 13111 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13112 } 13113 13114 // If the operand has type "type", the result has type "pointer to type". 13115 if (op->getType()->isObjCObjectType()) 13116 return Context.getObjCObjectPointerType(op->getType()); 13117 13118 CheckAddressOfPackedMember(op); 13119 13120 return Context.getPointerType(op->getType()); 13121 } 13122 13123 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13124 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13125 if (!DRE) 13126 return; 13127 const Decl *D = DRE->getDecl(); 13128 if (!D) 13129 return; 13130 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13131 if (!Param) 13132 return; 13133 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13134 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13135 return; 13136 if (FunctionScopeInfo *FD = S.getCurFunction()) 13137 if (!FD->ModifiedNonNullParams.count(Param)) 13138 FD->ModifiedNonNullParams.insert(Param); 13139 } 13140 13141 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13142 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13143 SourceLocation OpLoc) { 13144 if (Op->isTypeDependent()) 13145 return S.Context.DependentTy; 13146 13147 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13148 if (ConvResult.isInvalid()) 13149 return QualType(); 13150 Op = ConvResult.get(); 13151 QualType OpTy = Op->getType(); 13152 QualType Result; 13153 13154 if (isa<CXXReinterpretCastExpr>(Op)) { 13155 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13156 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13157 Op->getSourceRange()); 13158 } 13159 13160 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13161 { 13162 Result = PT->getPointeeType(); 13163 } 13164 else if (const ObjCObjectPointerType *OPT = 13165 OpTy->getAs<ObjCObjectPointerType>()) 13166 Result = OPT->getPointeeType(); 13167 else { 13168 ExprResult PR = S.CheckPlaceholderExpr(Op); 13169 if (PR.isInvalid()) return QualType(); 13170 if (PR.get() != Op) 13171 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13172 } 13173 13174 if (Result.isNull()) { 13175 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13176 << OpTy << Op->getSourceRange(); 13177 return QualType(); 13178 } 13179 13180 // Note that per both C89 and C99, indirection is always legal, even if Result 13181 // is an incomplete type or void. It would be possible to warn about 13182 // dereferencing a void pointer, but it's completely well-defined, and such a 13183 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13184 // for pointers to 'void' but is fine for any other pointer type: 13185 // 13186 // C++ [expr.unary.op]p1: 13187 // [...] the expression to which [the unary * operator] is applied shall 13188 // be a pointer to an object type, or a pointer to a function type 13189 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13190 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13191 << OpTy << Op->getSourceRange(); 13192 13193 // Dereferences are usually l-values... 13194 VK = VK_LValue; 13195 13196 // ...except that certain expressions are never l-values in C. 13197 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13198 VK = VK_RValue; 13199 13200 return Result; 13201 } 13202 13203 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13204 BinaryOperatorKind Opc; 13205 switch (Kind) { 13206 default: llvm_unreachable("Unknown binop!"); 13207 case tok::periodstar: Opc = BO_PtrMemD; break; 13208 case tok::arrowstar: Opc = BO_PtrMemI; break; 13209 case tok::star: Opc = BO_Mul; break; 13210 case tok::slash: Opc = BO_Div; break; 13211 case tok::percent: Opc = BO_Rem; break; 13212 case tok::plus: Opc = BO_Add; break; 13213 case tok::minus: Opc = BO_Sub; break; 13214 case tok::lessless: Opc = BO_Shl; break; 13215 case tok::greatergreater: Opc = BO_Shr; break; 13216 case tok::lessequal: Opc = BO_LE; break; 13217 case tok::less: Opc = BO_LT; break; 13218 case tok::greaterequal: Opc = BO_GE; break; 13219 case tok::greater: Opc = BO_GT; break; 13220 case tok::exclaimequal: Opc = BO_NE; break; 13221 case tok::equalequal: Opc = BO_EQ; break; 13222 case tok::spaceship: Opc = BO_Cmp; break; 13223 case tok::amp: Opc = BO_And; break; 13224 case tok::caret: Opc = BO_Xor; break; 13225 case tok::pipe: Opc = BO_Or; break; 13226 case tok::ampamp: Opc = BO_LAnd; break; 13227 case tok::pipepipe: Opc = BO_LOr; break; 13228 case tok::equal: Opc = BO_Assign; break; 13229 case tok::starequal: Opc = BO_MulAssign; break; 13230 case tok::slashequal: Opc = BO_DivAssign; break; 13231 case tok::percentequal: Opc = BO_RemAssign; break; 13232 case tok::plusequal: Opc = BO_AddAssign; break; 13233 case tok::minusequal: Opc = BO_SubAssign; break; 13234 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13235 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13236 case tok::ampequal: Opc = BO_AndAssign; break; 13237 case tok::caretequal: Opc = BO_XorAssign; break; 13238 case tok::pipeequal: Opc = BO_OrAssign; break; 13239 case tok::comma: Opc = BO_Comma; break; 13240 } 13241 return Opc; 13242 } 13243 13244 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13245 tok::TokenKind Kind) { 13246 UnaryOperatorKind Opc; 13247 switch (Kind) { 13248 default: llvm_unreachable("Unknown unary op!"); 13249 case tok::plusplus: Opc = UO_PreInc; break; 13250 case tok::minusminus: Opc = UO_PreDec; break; 13251 case tok::amp: Opc = UO_AddrOf; break; 13252 case tok::star: Opc = UO_Deref; break; 13253 case tok::plus: Opc = UO_Plus; break; 13254 case tok::minus: Opc = UO_Minus; break; 13255 case tok::tilde: Opc = UO_Not; break; 13256 case tok::exclaim: Opc = UO_LNot; break; 13257 case tok::kw___real: Opc = UO_Real; break; 13258 case tok::kw___imag: Opc = UO_Imag; break; 13259 case tok::kw___extension__: Opc = UO_Extension; break; 13260 } 13261 return Opc; 13262 } 13263 13264 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13265 /// This warning suppressed in the event of macro expansions. 13266 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13267 SourceLocation OpLoc, bool IsBuiltin) { 13268 if (S.inTemplateInstantiation()) 13269 return; 13270 if (S.isUnevaluatedContext()) 13271 return; 13272 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13273 return; 13274 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13275 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13276 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13277 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13278 if (!LHSDeclRef || !RHSDeclRef || 13279 LHSDeclRef->getLocation().isMacroID() || 13280 RHSDeclRef->getLocation().isMacroID()) 13281 return; 13282 const ValueDecl *LHSDecl = 13283 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13284 const ValueDecl *RHSDecl = 13285 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13286 if (LHSDecl != RHSDecl) 13287 return; 13288 if (LHSDecl->getType().isVolatileQualified()) 13289 return; 13290 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13291 if (RefTy->getPointeeType().isVolatileQualified()) 13292 return; 13293 13294 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13295 : diag::warn_self_assignment_overloaded) 13296 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13297 << RHSExpr->getSourceRange(); 13298 } 13299 13300 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13301 /// is usually indicative of introspection within the Objective-C pointer. 13302 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13303 SourceLocation OpLoc) { 13304 if (!S.getLangOpts().ObjC) 13305 return; 13306 13307 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13308 const Expr *LHS = L.get(); 13309 const Expr *RHS = R.get(); 13310 13311 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13312 ObjCPointerExpr = LHS; 13313 OtherExpr = RHS; 13314 } 13315 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13316 ObjCPointerExpr = RHS; 13317 OtherExpr = LHS; 13318 } 13319 13320 // This warning is deliberately made very specific to reduce false 13321 // positives with logic that uses '&' for hashing. This logic mainly 13322 // looks for code trying to introspect into tagged pointers, which 13323 // code should generally never do. 13324 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13325 unsigned Diag = diag::warn_objc_pointer_masking; 13326 // Determine if we are introspecting the result of performSelectorXXX. 13327 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13328 // Special case messages to -performSelector and friends, which 13329 // can return non-pointer values boxed in a pointer value. 13330 // Some clients may wish to silence warnings in this subcase. 13331 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13332 Selector S = ME->getSelector(); 13333 StringRef SelArg0 = S.getNameForSlot(0); 13334 if (SelArg0.startswith("performSelector")) 13335 Diag = diag::warn_objc_pointer_masking_performSelector; 13336 } 13337 13338 S.Diag(OpLoc, Diag) 13339 << ObjCPointerExpr->getSourceRange(); 13340 } 13341 } 13342 13343 static NamedDecl *getDeclFromExpr(Expr *E) { 13344 if (!E) 13345 return nullptr; 13346 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13347 return DRE->getDecl(); 13348 if (auto *ME = dyn_cast<MemberExpr>(E)) 13349 return ME->getMemberDecl(); 13350 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13351 return IRE->getDecl(); 13352 return nullptr; 13353 } 13354 13355 // This helper function promotes a binary operator's operands (which are of a 13356 // half vector type) to a vector of floats and then truncates the result to 13357 // a vector of either half or short. 13358 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13359 BinaryOperatorKind Opc, QualType ResultTy, 13360 ExprValueKind VK, ExprObjectKind OK, 13361 bool IsCompAssign, SourceLocation OpLoc, 13362 FPOptions FPFeatures) { 13363 auto &Context = S.getASTContext(); 13364 assert((isVector(ResultTy, Context.HalfTy) || 13365 isVector(ResultTy, Context.ShortTy)) && 13366 "Result must be a vector of half or short"); 13367 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13368 isVector(RHS.get()->getType(), Context.HalfTy) && 13369 "both operands expected to be a half vector"); 13370 13371 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13372 QualType BinOpResTy = RHS.get()->getType(); 13373 13374 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13375 // change BinOpResTy to a vector of ints. 13376 if (isVector(ResultTy, Context.ShortTy)) 13377 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13378 13379 if (IsCompAssign) 13380 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13381 ResultTy, VK, OK, OpLoc, FPFeatures, 13382 BinOpResTy, BinOpResTy); 13383 13384 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13385 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13386 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13387 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13388 } 13389 13390 static std::pair<ExprResult, ExprResult> 13391 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13392 Expr *RHSExpr) { 13393 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13394 if (!S.getLangOpts().CPlusPlus) { 13395 // C cannot handle TypoExpr nodes on either side of a binop because it 13396 // doesn't handle dependent types properly, so make sure any TypoExprs have 13397 // been dealt with before checking the operands. 13398 LHS = S.CorrectDelayedTyposInExpr(LHS); 13399 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 13400 if (Opc != BO_Assign) 13401 return ExprResult(E); 13402 // Avoid correcting the RHS to the same Expr as the LHS. 13403 Decl *D = getDeclFromExpr(E); 13404 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13405 }); 13406 } 13407 return std::make_pair(LHS, RHS); 13408 } 13409 13410 /// Returns true if conversion between vectors of halfs and vectors of floats 13411 /// is needed. 13412 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13413 Expr *E0, Expr *E1 = nullptr) { 13414 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13415 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13416 return false; 13417 13418 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13419 QualType Ty = E->IgnoreImplicit()->getType(); 13420 13421 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13422 // to vectors of floats. Although the element type of the vectors is __fp16, 13423 // the vectors shouldn't be treated as storage-only types. See the 13424 // discussion here: https://reviews.llvm.org/rG825235c140e7 13425 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13426 if (VT->getVectorKind() == VectorType::NeonVector) 13427 return false; 13428 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13429 } 13430 return false; 13431 }; 13432 13433 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13434 } 13435 13436 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13437 /// operator @p Opc at location @c TokLoc. This routine only supports 13438 /// built-in operations; ActOnBinOp handles overloaded operators. 13439 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13440 BinaryOperatorKind Opc, 13441 Expr *LHSExpr, Expr *RHSExpr) { 13442 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13443 // The syntax only allows initializer lists on the RHS of assignment, 13444 // so we don't need to worry about accepting invalid code for 13445 // non-assignment operators. 13446 // C++11 5.17p9: 13447 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13448 // of x = {} is x = T(). 13449 InitializationKind Kind = InitializationKind::CreateDirectList( 13450 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13451 InitializedEntity Entity = 13452 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13453 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13454 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13455 if (Init.isInvalid()) 13456 return Init; 13457 RHSExpr = Init.get(); 13458 } 13459 13460 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13461 QualType ResultTy; // Result type of the binary operator. 13462 // The following two variables are used for compound assignment operators 13463 QualType CompLHSTy; // Type of LHS after promotions for computation 13464 QualType CompResultTy; // Type of computation result 13465 ExprValueKind VK = VK_RValue; 13466 ExprObjectKind OK = OK_Ordinary; 13467 bool ConvertHalfVec = false; 13468 13469 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13470 if (!LHS.isUsable() || !RHS.isUsable()) 13471 return ExprError(); 13472 13473 if (getLangOpts().OpenCL) { 13474 QualType LHSTy = LHSExpr->getType(); 13475 QualType RHSTy = RHSExpr->getType(); 13476 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13477 // the ATOMIC_VAR_INIT macro. 13478 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13479 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13480 if (BO_Assign == Opc) 13481 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13482 else 13483 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13484 return ExprError(); 13485 } 13486 13487 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13488 // only with a builtin functions and therefore should be disallowed here. 13489 if (LHSTy->isImageType() || RHSTy->isImageType() || 13490 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13491 LHSTy->isPipeType() || RHSTy->isPipeType() || 13492 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13493 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13494 return ExprError(); 13495 } 13496 } 13497 13498 // Diagnose operations on the unsupported types for OpenMP device compilation. 13499 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13500 if (Opc != BO_Assign && Opc != BO_Comma) { 13501 checkOpenMPDeviceExpr(LHSExpr); 13502 checkOpenMPDeviceExpr(RHSExpr); 13503 } 13504 } 13505 13506 switch (Opc) { 13507 case BO_Assign: 13508 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13509 if (getLangOpts().CPlusPlus && 13510 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13511 VK = LHS.get()->getValueKind(); 13512 OK = LHS.get()->getObjectKind(); 13513 } 13514 if (!ResultTy.isNull()) { 13515 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13516 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13517 13518 // Avoid copying a block to the heap if the block is assigned to a local 13519 // auto variable that is declared in the same scope as the block. This 13520 // optimization is unsafe if the local variable is declared in an outer 13521 // scope. For example: 13522 // 13523 // BlockTy b; 13524 // { 13525 // b = ^{...}; 13526 // } 13527 // // It is unsafe to invoke the block here if it wasn't copied to the 13528 // // heap. 13529 // b(); 13530 13531 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13532 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13533 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13534 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13535 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13536 13537 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13538 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13539 NTCUC_Assignment, NTCUK_Copy); 13540 } 13541 RecordModifiableNonNullParam(*this, LHS.get()); 13542 break; 13543 case BO_PtrMemD: 13544 case BO_PtrMemI: 13545 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13546 Opc == BO_PtrMemI); 13547 break; 13548 case BO_Mul: 13549 case BO_Div: 13550 ConvertHalfVec = true; 13551 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13552 Opc == BO_Div); 13553 break; 13554 case BO_Rem: 13555 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13556 break; 13557 case BO_Add: 13558 ConvertHalfVec = true; 13559 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13560 break; 13561 case BO_Sub: 13562 ConvertHalfVec = true; 13563 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13564 break; 13565 case BO_Shl: 13566 case BO_Shr: 13567 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13568 break; 13569 case BO_LE: 13570 case BO_LT: 13571 case BO_GE: 13572 case BO_GT: 13573 ConvertHalfVec = true; 13574 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13575 break; 13576 case BO_EQ: 13577 case BO_NE: 13578 ConvertHalfVec = true; 13579 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13580 break; 13581 case BO_Cmp: 13582 ConvertHalfVec = true; 13583 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13584 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13585 break; 13586 case BO_And: 13587 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13588 LLVM_FALLTHROUGH; 13589 case BO_Xor: 13590 case BO_Or: 13591 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13592 break; 13593 case BO_LAnd: 13594 case BO_LOr: 13595 ConvertHalfVec = true; 13596 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13597 break; 13598 case BO_MulAssign: 13599 case BO_DivAssign: 13600 ConvertHalfVec = true; 13601 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13602 Opc == BO_DivAssign); 13603 CompLHSTy = CompResultTy; 13604 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13605 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13606 break; 13607 case BO_RemAssign: 13608 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13609 CompLHSTy = CompResultTy; 13610 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13611 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13612 break; 13613 case BO_AddAssign: 13614 ConvertHalfVec = true; 13615 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13616 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13617 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13618 break; 13619 case BO_SubAssign: 13620 ConvertHalfVec = true; 13621 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13622 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13623 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13624 break; 13625 case BO_ShlAssign: 13626 case BO_ShrAssign: 13627 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13628 CompLHSTy = CompResultTy; 13629 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13630 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13631 break; 13632 case BO_AndAssign: 13633 case BO_OrAssign: // fallthrough 13634 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13635 LLVM_FALLTHROUGH; 13636 case BO_XorAssign: 13637 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13638 CompLHSTy = CompResultTy; 13639 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13640 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13641 break; 13642 case BO_Comma: 13643 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13644 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13645 VK = RHS.get()->getValueKind(); 13646 OK = RHS.get()->getObjectKind(); 13647 } 13648 break; 13649 } 13650 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13651 return ExprError(); 13652 13653 if (ResultTy->isRealFloatingType() && 13654 (getLangOpts().getFPRoundingMode() != RoundingMode::NearestTiesToEven || 13655 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13656 // Mark the current function as usng floating point constrained intrinsics 13657 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13658 F->setUsesFPIntrin(true); 13659 } 13660 13661 // Some of the binary operations require promoting operands of half vector to 13662 // float vectors and truncating the result back to half vector. For now, we do 13663 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13664 // arm64). 13665 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13666 isVector(LHS.get()->getType(), Context.HalfTy) && 13667 "both sides are half vectors or neither sides are"); 13668 ConvertHalfVec = 13669 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13670 13671 // Check for array bounds violations for both sides of the BinaryOperator 13672 CheckArrayAccess(LHS.get()); 13673 CheckArrayAccess(RHS.get()); 13674 13675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13676 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13677 &Context.Idents.get("object_setClass"), 13678 SourceLocation(), LookupOrdinaryName); 13679 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13680 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13681 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13682 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13683 "object_setClass(") 13684 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13685 ",") 13686 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13687 } 13688 else 13689 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13690 } 13691 else if (const ObjCIvarRefExpr *OIRE = 13692 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13693 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13694 13695 // Opc is not a compound assignment if CompResultTy is null. 13696 if (CompResultTy.isNull()) { 13697 if (ConvertHalfVec) 13698 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13699 OpLoc, CurFPFeatures); 13700 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13701 VK, OK, OpLoc, CurFPFeatures); 13702 } 13703 13704 // Handle compound assignments. 13705 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13706 OK_ObjCProperty) { 13707 VK = VK_LValue; 13708 OK = LHS.get()->getObjectKind(); 13709 } 13710 13711 // The LHS is not converted to the result type for fixed-point compound 13712 // assignment as the common type is computed on demand. Reset the CompLHSTy 13713 // to the LHS type we would have gotten after unary conversions. 13714 if (CompResultTy->isFixedPointType()) 13715 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13716 13717 if (ConvertHalfVec) 13718 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13719 OpLoc, CurFPFeatures); 13720 13721 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13722 ResultTy, VK, OK, OpLoc, CurFPFeatures, 13723 CompLHSTy, CompResultTy); 13724 } 13725 13726 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13727 /// operators are mixed in a way that suggests that the programmer forgot that 13728 /// comparison operators have higher precedence. The most typical example of 13729 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13730 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13731 SourceLocation OpLoc, Expr *LHSExpr, 13732 Expr *RHSExpr) { 13733 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13734 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13735 13736 // Check that one of the sides is a comparison operator and the other isn't. 13737 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13738 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13739 if (isLeftComp == isRightComp) 13740 return; 13741 13742 // Bitwise operations are sometimes used as eager logical ops. 13743 // Don't diagnose this. 13744 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13745 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13746 if (isLeftBitwise || isRightBitwise) 13747 return; 13748 13749 SourceRange DiagRange = isLeftComp 13750 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13751 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13752 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13753 SourceRange ParensRange = 13754 isLeftComp 13755 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13756 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13757 13758 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13759 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13760 SuggestParentheses(Self, OpLoc, 13761 Self.PDiag(diag::note_precedence_silence) << OpStr, 13762 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13763 SuggestParentheses(Self, OpLoc, 13764 Self.PDiag(diag::note_precedence_bitwise_first) 13765 << BinaryOperator::getOpcodeStr(Opc), 13766 ParensRange); 13767 } 13768 13769 /// It accepts a '&&' expr that is inside a '||' one. 13770 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13771 /// in parentheses. 13772 static void 13773 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13774 BinaryOperator *Bop) { 13775 assert(Bop->getOpcode() == BO_LAnd); 13776 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13777 << Bop->getSourceRange() << OpLoc; 13778 SuggestParentheses(Self, Bop->getOperatorLoc(), 13779 Self.PDiag(diag::note_precedence_silence) 13780 << Bop->getOpcodeStr(), 13781 Bop->getSourceRange()); 13782 } 13783 13784 /// Returns true if the given expression can be evaluated as a constant 13785 /// 'true'. 13786 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13787 bool Res; 13788 return !E->isValueDependent() && 13789 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13790 } 13791 13792 /// Returns true if the given expression can be evaluated as a constant 13793 /// 'false'. 13794 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13795 bool Res; 13796 return !E->isValueDependent() && 13797 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13798 } 13799 13800 /// Look for '&&' in the left hand of a '||' expr. 13801 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13802 Expr *LHSExpr, Expr *RHSExpr) { 13803 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13804 if (Bop->getOpcode() == BO_LAnd) { 13805 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13806 if (EvaluatesAsFalse(S, RHSExpr)) 13807 return; 13808 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13809 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13810 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13811 } else if (Bop->getOpcode() == BO_LOr) { 13812 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13813 // If it's "a || b && 1 || c" we didn't warn earlier for 13814 // "a || b && 1", but warn now. 13815 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13816 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13817 } 13818 } 13819 } 13820 } 13821 13822 /// Look for '&&' in the right hand of a '||' expr. 13823 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13824 Expr *LHSExpr, Expr *RHSExpr) { 13825 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13826 if (Bop->getOpcode() == BO_LAnd) { 13827 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13828 if (EvaluatesAsFalse(S, LHSExpr)) 13829 return; 13830 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13831 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13832 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13833 } 13834 } 13835 } 13836 13837 /// Look for bitwise op in the left or right hand of a bitwise op with 13838 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13839 /// the '&' expression in parentheses. 13840 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13841 SourceLocation OpLoc, Expr *SubExpr) { 13842 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13843 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13844 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13845 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13846 << Bop->getSourceRange() << OpLoc; 13847 SuggestParentheses(S, Bop->getOperatorLoc(), 13848 S.PDiag(diag::note_precedence_silence) 13849 << Bop->getOpcodeStr(), 13850 Bop->getSourceRange()); 13851 } 13852 } 13853 } 13854 13855 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13856 Expr *SubExpr, StringRef Shift) { 13857 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13858 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13859 StringRef Op = Bop->getOpcodeStr(); 13860 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13861 << Bop->getSourceRange() << OpLoc << Shift << Op; 13862 SuggestParentheses(S, Bop->getOperatorLoc(), 13863 S.PDiag(diag::note_precedence_silence) << Op, 13864 Bop->getSourceRange()); 13865 } 13866 } 13867 } 13868 13869 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13870 Expr *LHSExpr, Expr *RHSExpr) { 13871 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13872 if (!OCE) 13873 return; 13874 13875 FunctionDecl *FD = OCE->getDirectCallee(); 13876 if (!FD || !FD->isOverloadedOperator()) 13877 return; 13878 13879 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13880 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13881 return; 13882 13883 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13884 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13885 << (Kind == OO_LessLess); 13886 SuggestParentheses(S, OCE->getOperatorLoc(), 13887 S.PDiag(diag::note_precedence_silence) 13888 << (Kind == OO_LessLess ? "<<" : ">>"), 13889 OCE->getSourceRange()); 13890 SuggestParentheses( 13891 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13892 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13893 } 13894 13895 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13896 /// precedence. 13897 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13898 SourceLocation OpLoc, Expr *LHSExpr, 13899 Expr *RHSExpr){ 13900 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13901 if (BinaryOperator::isBitwiseOp(Opc)) 13902 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13903 13904 // Diagnose "arg1 & arg2 | arg3" 13905 if ((Opc == BO_Or || Opc == BO_Xor) && 13906 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13907 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13908 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13909 } 13910 13911 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13912 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13913 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13914 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13915 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13916 } 13917 13918 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13919 || Opc == BO_Shr) { 13920 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13921 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13922 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13923 } 13924 13925 // Warn on overloaded shift operators and comparisons, such as: 13926 // cout << 5 == 4; 13927 if (BinaryOperator::isComparisonOp(Opc)) 13928 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13929 } 13930 13931 // Binary Operators. 'Tok' is the token for the operator. 13932 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13933 tok::TokenKind Kind, 13934 Expr *LHSExpr, Expr *RHSExpr) { 13935 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13936 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13937 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13938 13939 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13940 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13941 13942 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13943 } 13944 13945 /// Build an overloaded binary operator expression in the given scope. 13946 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13947 BinaryOperatorKind Opc, 13948 Expr *LHS, Expr *RHS) { 13949 switch (Opc) { 13950 case BO_Assign: 13951 case BO_DivAssign: 13952 case BO_RemAssign: 13953 case BO_SubAssign: 13954 case BO_AndAssign: 13955 case BO_OrAssign: 13956 case BO_XorAssign: 13957 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13958 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13959 break; 13960 default: 13961 break; 13962 } 13963 13964 // Find all of the overloaded operators visible from this 13965 // point. We perform both an operator-name lookup from the local 13966 // scope and an argument-dependent lookup based on the types of 13967 // the arguments. 13968 UnresolvedSet<16> Functions; 13969 OverloadedOperatorKind OverOp 13970 = BinaryOperator::getOverloadedOperator(Opc); 13971 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13972 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13973 RHS->getType(), Functions); 13974 13975 // In C++20 onwards, we may have a second operator to look up. 13976 if (S.getLangOpts().CPlusPlus2a) { 13977 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13978 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13979 RHS->getType(), Functions); 13980 } 13981 13982 // Build the (potentially-overloaded, potentially-dependent) 13983 // binary operation. 13984 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13985 } 13986 13987 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13988 BinaryOperatorKind Opc, 13989 Expr *LHSExpr, Expr *RHSExpr) { 13990 ExprResult LHS, RHS; 13991 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13992 if (!LHS.isUsable() || !RHS.isUsable()) 13993 return ExprError(); 13994 LHSExpr = LHS.get(); 13995 RHSExpr = RHS.get(); 13996 13997 // We want to end up calling one of checkPseudoObjectAssignment 13998 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13999 // both expressions are overloadable or either is type-dependent), 14000 // or CreateBuiltinBinOp (in any other case). We also want to get 14001 // any placeholder types out of the way. 14002 14003 // Handle pseudo-objects in the LHS. 14004 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14005 // Assignments with a pseudo-object l-value need special analysis. 14006 if (pty->getKind() == BuiltinType::PseudoObject && 14007 BinaryOperator::isAssignmentOp(Opc)) 14008 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14009 14010 // Don't resolve overloads if the other type is overloadable. 14011 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14012 // We can't actually test that if we still have a placeholder, 14013 // though. Fortunately, none of the exceptions we see in that 14014 // code below are valid when the LHS is an overload set. Note 14015 // that an overload set can be dependently-typed, but it never 14016 // instantiates to having an overloadable type. 14017 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14018 if (resolvedRHS.isInvalid()) return ExprError(); 14019 RHSExpr = resolvedRHS.get(); 14020 14021 if (RHSExpr->isTypeDependent() || 14022 RHSExpr->getType()->isOverloadableType()) 14023 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14024 } 14025 14026 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14027 // template, diagnose the missing 'template' keyword instead of diagnosing 14028 // an invalid use of a bound member function. 14029 // 14030 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14031 // to C++1z [over.over]/1.4, but we already checked for that case above. 14032 if (Opc == BO_LT && inTemplateInstantiation() && 14033 (pty->getKind() == BuiltinType::BoundMember || 14034 pty->getKind() == BuiltinType::Overload)) { 14035 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14036 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14037 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14038 return isa<FunctionTemplateDecl>(ND); 14039 })) { 14040 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14041 : OE->getNameLoc(), 14042 diag::err_template_kw_missing) 14043 << OE->getName().getAsString() << ""; 14044 return ExprError(); 14045 } 14046 } 14047 14048 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14049 if (LHS.isInvalid()) return ExprError(); 14050 LHSExpr = LHS.get(); 14051 } 14052 14053 // Handle pseudo-objects in the RHS. 14054 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14055 // An overload in the RHS can potentially be resolved by the type 14056 // being assigned to. 14057 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14058 if (getLangOpts().CPlusPlus && 14059 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14060 LHSExpr->getType()->isOverloadableType())) 14061 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14062 14063 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14064 } 14065 14066 // Don't resolve overloads if the other type is overloadable. 14067 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14068 LHSExpr->getType()->isOverloadableType()) 14069 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14070 14071 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14072 if (!resolvedRHS.isUsable()) return ExprError(); 14073 RHSExpr = resolvedRHS.get(); 14074 } 14075 14076 if (getLangOpts().CPlusPlus) { 14077 // If either expression is type-dependent, always build an 14078 // overloaded op. 14079 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14080 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14081 14082 // Otherwise, build an overloaded op if either expression has an 14083 // overloadable type. 14084 if (LHSExpr->getType()->isOverloadableType() || 14085 RHSExpr->getType()->isOverloadableType()) 14086 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14087 } 14088 14089 // Build a built-in binary operation. 14090 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14091 } 14092 14093 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14094 if (T.isNull() || T->isDependentType()) 14095 return false; 14096 14097 if (!T->isPromotableIntegerType()) 14098 return true; 14099 14100 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14101 } 14102 14103 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14104 UnaryOperatorKind Opc, 14105 Expr *InputExpr) { 14106 ExprResult Input = InputExpr; 14107 ExprValueKind VK = VK_RValue; 14108 ExprObjectKind OK = OK_Ordinary; 14109 QualType resultType; 14110 bool CanOverflow = false; 14111 14112 bool ConvertHalfVec = false; 14113 if (getLangOpts().OpenCL) { 14114 QualType Ty = InputExpr->getType(); 14115 // The only legal unary operation for atomics is '&'. 14116 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14117 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14118 // only with a builtin functions and therefore should be disallowed here. 14119 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14120 || Ty->isBlockPointerType())) { 14121 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14122 << InputExpr->getType() 14123 << Input.get()->getSourceRange()); 14124 } 14125 } 14126 // Diagnose operations on the unsupported types for OpenMP device compilation. 14127 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 14128 if (UnaryOperator::isIncrementDecrementOp(Opc) || 14129 UnaryOperator::isArithmeticOp(Opc)) 14130 checkOpenMPDeviceExpr(InputExpr); 14131 } 14132 14133 switch (Opc) { 14134 case UO_PreInc: 14135 case UO_PreDec: 14136 case UO_PostInc: 14137 case UO_PostDec: 14138 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14139 OpLoc, 14140 Opc == UO_PreInc || 14141 Opc == UO_PostInc, 14142 Opc == UO_PreInc || 14143 Opc == UO_PreDec); 14144 CanOverflow = isOverflowingIntegerType(Context, resultType); 14145 break; 14146 case UO_AddrOf: 14147 resultType = CheckAddressOfOperand(Input, OpLoc); 14148 CheckAddressOfNoDeref(InputExpr); 14149 RecordModifiableNonNullParam(*this, InputExpr); 14150 break; 14151 case UO_Deref: { 14152 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14153 if (Input.isInvalid()) return ExprError(); 14154 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14155 break; 14156 } 14157 case UO_Plus: 14158 case UO_Minus: 14159 CanOverflow = Opc == UO_Minus && 14160 isOverflowingIntegerType(Context, Input.get()->getType()); 14161 Input = UsualUnaryConversions(Input.get()); 14162 if (Input.isInvalid()) return ExprError(); 14163 // Unary plus and minus require promoting an operand of half vector to a 14164 // float vector and truncating the result back to a half vector. For now, we 14165 // do this only when HalfArgsAndReturns is set (that is, when the target is 14166 // arm or arm64). 14167 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14168 14169 // If the operand is a half vector, promote it to a float vector. 14170 if (ConvertHalfVec) 14171 Input = convertVector(Input.get(), Context.FloatTy, *this); 14172 resultType = Input.get()->getType(); 14173 if (resultType->isDependentType()) 14174 break; 14175 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14176 break; 14177 else if (resultType->isVectorType() && 14178 // The z vector extensions don't allow + or - with bool vectors. 14179 (!Context.getLangOpts().ZVector || 14180 resultType->castAs<VectorType>()->getVectorKind() != 14181 VectorType::AltiVecBool)) 14182 break; 14183 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14184 Opc == UO_Plus && 14185 resultType->isPointerType()) 14186 break; 14187 14188 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14189 << resultType << Input.get()->getSourceRange()); 14190 14191 case UO_Not: // bitwise complement 14192 Input = UsualUnaryConversions(Input.get()); 14193 if (Input.isInvalid()) 14194 return ExprError(); 14195 resultType = Input.get()->getType(); 14196 if (resultType->isDependentType()) 14197 break; 14198 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14199 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14200 // C99 does not support '~' for complex conjugation. 14201 Diag(OpLoc, diag::ext_integer_complement_complex) 14202 << resultType << Input.get()->getSourceRange(); 14203 else if (resultType->hasIntegerRepresentation()) 14204 break; 14205 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14206 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14207 // on vector float types. 14208 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14209 if (!T->isIntegerType()) 14210 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14211 << resultType << Input.get()->getSourceRange()); 14212 } else { 14213 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14214 << resultType << Input.get()->getSourceRange()); 14215 } 14216 break; 14217 14218 case UO_LNot: // logical negation 14219 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14220 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14221 if (Input.isInvalid()) return ExprError(); 14222 resultType = Input.get()->getType(); 14223 14224 // Though we still have to promote half FP to float... 14225 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14226 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14227 resultType = Context.FloatTy; 14228 } 14229 14230 if (resultType->isDependentType()) 14231 break; 14232 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14233 // C99 6.5.3.3p1: ok, fallthrough; 14234 if (Context.getLangOpts().CPlusPlus) { 14235 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14236 // operand contextually converted to bool. 14237 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14238 ScalarTypeToBooleanCastKind(resultType)); 14239 } else if (Context.getLangOpts().OpenCL && 14240 Context.getLangOpts().OpenCLVersion < 120) { 14241 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14242 // operate on scalar float types. 14243 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14244 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14245 << resultType << Input.get()->getSourceRange()); 14246 } 14247 } else if (resultType->isExtVectorType()) { 14248 if (Context.getLangOpts().OpenCL && 14249 Context.getLangOpts().OpenCLVersion < 120 && 14250 !Context.getLangOpts().OpenCLCPlusPlus) { 14251 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14252 // operate on vector float types. 14253 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14254 if (!T->isIntegerType()) 14255 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14256 << resultType << Input.get()->getSourceRange()); 14257 } 14258 // Vector logical not returns the signed variant of the operand type. 14259 resultType = GetSignedVectorType(resultType); 14260 break; 14261 } else { 14262 // FIXME: GCC's vector extension permits the usage of '!' with a vector 14263 // type in C++. We should allow that here too. 14264 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14265 << resultType << Input.get()->getSourceRange()); 14266 } 14267 14268 // LNot always has type int. C99 6.5.3.3p5. 14269 // In C++, it's bool. C++ 5.3.1p8 14270 resultType = Context.getLogicalOperationType(); 14271 break; 14272 case UO_Real: 14273 case UO_Imag: 14274 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14275 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14276 // complex l-values to ordinary l-values and all other values to r-values. 14277 if (Input.isInvalid()) return ExprError(); 14278 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14279 if (Input.get()->getValueKind() != VK_RValue && 14280 Input.get()->getObjectKind() == OK_Ordinary) 14281 VK = Input.get()->getValueKind(); 14282 } else if (!getLangOpts().CPlusPlus) { 14283 // In C, a volatile scalar is read by __imag. In C++, it is not. 14284 Input = DefaultLvalueConversion(Input.get()); 14285 } 14286 break; 14287 case UO_Extension: 14288 resultType = Input.get()->getType(); 14289 VK = Input.get()->getValueKind(); 14290 OK = Input.get()->getObjectKind(); 14291 break; 14292 case UO_Coawait: 14293 // It's unnecessary to represent the pass-through operator co_await in the 14294 // AST; just return the input expression instead. 14295 assert(!Input.get()->getType()->isDependentType() && 14296 "the co_await expression must be non-dependant before " 14297 "building operator co_await"); 14298 return Input; 14299 } 14300 if (resultType.isNull() || Input.isInvalid()) 14301 return ExprError(); 14302 14303 // Check for array bounds violations in the operand of the UnaryOperator, 14304 // except for the '*' and '&' operators that have to be handled specially 14305 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14306 // that are explicitly defined as valid by the standard). 14307 if (Opc != UO_AddrOf && Opc != UO_Deref) 14308 CheckArrayAccess(Input.get()); 14309 14310 auto *UO = new (Context) 14311 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 14312 14313 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14314 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14315 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14316 14317 // Convert the result back to a half vector. 14318 if (ConvertHalfVec) 14319 return convertVector(UO, Context.HalfTy, *this); 14320 return UO; 14321 } 14322 14323 /// Determine whether the given expression is a qualified member 14324 /// access expression, of a form that could be turned into a pointer to member 14325 /// with the address-of operator. 14326 bool Sema::isQualifiedMemberAccess(Expr *E) { 14327 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14328 if (!DRE->getQualifier()) 14329 return false; 14330 14331 ValueDecl *VD = DRE->getDecl(); 14332 if (!VD->isCXXClassMember()) 14333 return false; 14334 14335 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14336 return true; 14337 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14338 return Method->isInstance(); 14339 14340 return false; 14341 } 14342 14343 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14344 if (!ULE->getQualifier()) 14345 return false; 14346 14347 for (NamedDecl *D : ULE->decls()) { 14348 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14349 if (Method->isInstance()) 14350 return true; 14351 } else { 14352 // Overload set does not contain methods. 14353 break; 14354 } 14355 } 14356 14357 return false; 14358 } 14359 14360 return false; 14361 } 14362 14363 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14364 UnaryOperatorKind Opc, Expr *Input) { 14365 // First things first: handle placeholders so that the 14366 // overloaded-operator check considers the right type. 14367 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14368 // Increment and decrement of pseudo-object references. 14369 if (pty->getKind() == BuiltinType::PseudoObject && 14370 UnaryOperator::isIncrementDecrementOp(Opc)) 14371 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14372 14373 // extension is always a builtin operator. 14374 if (Opc == UO_Extension) 14375 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14376 14377 // & gets special logic for several kinds of placeholder. 14378 // The builtin code knows what to do. 14379 if (Opc == UO_AddrOf && 14380 (pty->getKind() == BuiltinType::Overload || 14381 pty->getKind() == BuiltinType::UnknownAny || 14382 pty->getKind() == BuiltinType::BoundMember)) 14383 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14384 14385 // Anything else needs to be handled now. 14386 ExprResult Result = CheckPlaceholderExpr(Input); 14387 if (Result.isInvalid()) return ExprError(); 14388 Input = Result.get(); 14389 } 14390 14391 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14392 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14393 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14394 // Find all of the overloaded operators visible from this 14395 // point. We perform both an operator-name lookup from the local 14396 // scope and an argument-dependent lookup based on the types of 14397 // the arguments. 14398 UnresolvedSet<16> Functions; 14399 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14400 if (S && OverOp != OO_None) 14401 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14402 Functions); 14403 14404 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14405 } 14406 14407 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14408 } 14409 14410 // Unary Operators. 'Tok' is the token for the operator. 14411 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14412 tok::TokenKind Op, Expr *Input) { 14413 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14414 } 14415 14416 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14417 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14418 LabelDecl *TheDecl) { 14419 TheDecl->markUsed(Context); 14420 // Create the AST node. The address of a label always has type 'void*'. 14421 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14422 Context.getPointerType(Context.VoidTy)); 14423 } 14424 14425 void Sema::ActOnStartStmtExpr() { 14426 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14427 } 14428 14429 void Sema::ActOnStmtExprError() { 14430 // Note that function is also called by TreeTransform when leaving a 14431 // StmtExpr scope without rebuilding anything. 14432 14433 DiscardCleanupsInEvaluationContext(); 14434 PopExpressionEvaluationContext(); 14435 } 14436 14437 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14438 SourceLocation RPLoc) { 14439 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14440 } 14441 14442 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14443 SourceLocation RPLoc, unsigned TemplateDepth) { 14444 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14445 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14446 14447 if (hasAnyUnrecoverableErrorsInThisFunction()) 14448 DiscardCleanupsInEvaluationContext(); 14449 assert(!Cleanup.exprNeedsCleanups() && 14450 "cleanups within StmtExpr not correctly bound!"); 14451 PopExpressionEvaluationContext(); 14452 14453 // FIXME: there are a variety of strange constraints to enforce here, for 14454 // example, it is not possible to goto into a stmt expression apparently. 14455 // More semantic analysis is needed. 14456 14457 // If there are sub-stmts in the compound stmt, take the type of the last one 14458 // as the type of the stmtexpr. 14459 QualType Ty = Context.VoidTy; 14460 bool StmtExprMayBindToTemp = false; 14461 if (!Compound->body_empty()) { 14462 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14463 if (const auto *LastStmt = 14464 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14465 if (const Expr *Value = LastStmt->getExprStmt()) { 14466 StmtExprMayBindToTemp = true; 14467 Ty = Value->getType(); 14468 } 14469 } 14470 } 14471 14472 // FIXME: Check that expression type is complete/non-abstract; statement 14473 // expressions are not lvalues. 14474 Expr *ResStmtExpr = 14475 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14476 if (StmtExprMayBindToTemp) 14477 return MaybeBindToTemporary(ResStmtExpr); 14478 return ResStmtExpr; 14479 } 14480 14481 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14482 if (ER.isInvalid()) 14483 return ExprError(); 14484 14485 // Do function/array conversion on the last expression, but not 14486 // lvalue-to-rvalue. However, initialize an unqualified type. 14487 ER = DefaultFunctionArrayConversion(ER.get()); 14488 if (ER.isInvalid()) 14489 return ExprError(); 14490 Expr *E = ER.get(); 14491 14492 if (E->isTypeDependent()) 14493 return E; 14494 14495 // In ARC, if the final expression ends in a consume, splice 14496 // the consume out and bind it later. In the alternate case 14497 // (when dealing with a retainable type), the result 14498 // initialization will create a produce. In both cases the 14499 // result will be +1, and we'll need to balance that out with 14500 // a bind. 14501 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14502 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14503 return Cast->getSubExpr(); 14504 14505 // FIXME: Provide a better location for the initialization. 14506 return PerformCopyInitialization( 14507 InitializedEntity::InitializeStmtExprResult( 14508 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14509 SourceLocation(), E); 14510 } 14511 14512 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14513 TypeSourceInfo *TInfo, 14514 ArrayRef<OffsetOfComponent> Components, 14515 SourceLocation RParenLoc) { 14516 QualType ArgTy = TInfo->getType(); 14517 bool Dependent = ArgTy->isDependentType(); 14518 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14519 14520 // We must have at least one component that refers to the type, and the first 14521 // one is known to be a field designator. Verify that the ArgTy represents 14522 // a struct/union/class. 14523 if (!Dependent && !ArgTy->isRecordType()) 14524 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14525 << ArgTy << TypeRange); 14526 14527 // Type must be complete per C99 7.17p3 because a declaring a variable 14528 // with an incomplete type would be ill-formed. 14529 if (!Dependent 14530 && RequireCompleteType(BuiltinLoc, ArgTy, 14531 diag::err_offsetof_incomplete_type, TypeRange)) 14532 return ExprError(); 14533 14534 bool DidWarnAboutNonPOD = false; 14535 QualType CurrentType = ArgTy; 14536 SmallVector<OffsetOfNode, 4> Comps; 14537 SmallVector<Expr*, 4> Exprs; 14538 for (const OffsetOfComponent &OC : Components) { 14539 if (OC.isBrackets) { 14540 // Offset of an array sub-field. TODO: Should we allow vector elements? 14541 if (!CurrentType->isDependentType()) { 14542 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14543 if(!AT) 14544 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14545 << CurrentType); 14546 CurrentType = AT->getElementType(); 14547 } else 14548 CurrentType = Context.DependentTy; 14549 14550 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14551 if (IdxRval.isInvalid()) 14552 return ExprError(); 14553 Expr *Idx = IdxRval.get(); 14554 14555 // The expression must be an integral expression. 14556 // FIXME: An integral constant expression? 14557 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14558 !Idx->getType()->isIntegerType()) 14559 return ExprError( 14560 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14561 << Idx->getSourceRange()); 14562 14563 // Record this array index. 14564 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14565 Exprs.push_back(Idx); 14566 continue; 14567 } 14568 14569 // Offset of a field. 14570 if (CurrentType->isDependentType()) { 14571 // We have the offset of a field, but we can't look into the dependent 14572 // type. Just record the identifier of the field. 14573 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14574 CurrentType = Context.DependentTy; 14575 continue; 14576 } 14577 14578 // We need to have a complete type to look into. 14579 if (RequireCompleteType(OC.LocStart, CurrentType, 14580 diag::err_offsetof_incomplete_type)) 14581 return ExprError(); 14582 14583 // Look for the designated field. 14584 const RecordType *RC = CurrentType->getAs<RecordType>(); 14585 if (!RC) 14586 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14587 << CurrentType); 14588 RecordDecl *RD = RC->getDecl(); 14589 14590 // C++ [lib.support.types]p5: 14591 // The macro offsetof accepts a restricted set of type arguments in this 14592 // International Standard. type shall be a POD structure or a POD union 14593 // (clause 9). 14594 // C++11 [support.types]p4: 14595 // If type is not a standard-layout class (Clause 9), the results are 14596 // undefined. 14597 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14598 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14599 unsigned DiagID = 14600 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14601 : diag::ext_offsetof_non_pod_type; 14602 14603 if (!IsSafe && !DidWarnAboutNonPOD && 14604 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14605 PDiag(DiagID) 14606 << SourceRange(Components[0].LocStart, OC.LocEnd) 14607 << CurrentType)) 14608 DidWarnAboutNonPOD = true; 14609 } 14610 14611 // Look for the field. 14612 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14613 LookupQualifiedName(R, RD); 14614 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14615 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14616 if (!MemberDecl) { 14617 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14618 MemberDecl = IndirectMemberDecl->getAnonField(); 14619 } 14620 14621 if (!MemberDecl) 14622 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14623 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14624 OC.LocEnd)); 14625 14626 // C99 7.17p3: 14627 // (If the specified member is a bit-field, the behavior is undefined.) 14628 // 14629 // We diagnose this as an error. 14630 if (MemberDecl->isBitField()) { 14631 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14632 << MemberDecl->getDeclName() 14633 << SourceRange(BuiltinLoc, RParenLoc); 14634 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14635 return ExprError(); 14636 } 14637 14638 RecordDecl *Parent = MemberDecl->getParent(); 14639 if (IndirectMemberDecl) 14640 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14641 14642 // If the member was found in a base class, introduce OffsetOfNodes for 14643 // the base class indirections. 14644 CXXBasePaths Paths; 14645 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14646 Paths)) { 14647 if (Paths.getDetectedVirtual()) { 14648 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14649 << MemberDecl->getDeclName() 14650 << SourceRange(BuiltinLoc, RParenLoc); 14651 return ExprError(); 14652 } 14653 14654 CXXBasePath &Path = Paths.front(); 14655 for (const CXXBasePathElement &B : Path) 14656 Comps.push_back(OffsetOfNode(B.Base)); 14657 } 14658 14659 if (IndirectMemberDecl) { 14660 for (auto *FI : IndirectMemberDecl->chain()) { 14661 assert(isa<FieldDecl>(FI)); 14662 Comps.push_back(OffsetOfNode(OC.LocStart, 14663 cast<FieldDecl>(FI), OC.LocEnd)); 14664 } 14665 } else 14666 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14667 14668 CurrentType = MemberDecl->getType().getNonReferenceType(); 14669 } 14670 14671 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14672 Comps, Exprs, RParenLoc); 14673 } 14674 14675 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14676 SourceLocation BuiltinLoc, 14677 SourceLocation TypeLoc, 14678 ParsedType ParsedArgTy, 14679 ArrayRef<OffsetOfComponent> Components, 14680 SourceLocation RParenLoc) { 14681 14682 TypeSourceInfo *ArgTInfo; 14683 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14684 if (ArgTy.isNull()) 14685 return ExprError(); 14686 14687 if (!ArgTInfo) 14688 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14689 14690 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14691 } 14692 14693 14694 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14695 Expr *CondExpr, 14696 Expr *LHSExpr, Expr *RHSExpr, 14697 SourceLocation RPLoc) { 14698 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14699 14700 ExprValueKind VK = VK_RValue; 14701 ExprObjectKind OK = OK_Ordinary; 14702 QualType resType; 14703 bool CondIsTrue = false; 14704 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14705 resType = Context.DependentTy; 14706 } else { 14707 // The conditional expression is required to be a constant expression. 14708 llvm::APSInt condEval(32); 14709 ExprResult CondICE 14710 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14711 diag::err_typecheck_choose_expr_requires_constant, false); 14712 if (CondICE.isInvalid()) 14713 return ExprError(); 14714 CondExpr = CondICE.get(); 14715 CondIsTrue = condEval.getZExtValue(); 14716 14717 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14718 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14719 14720 resType = ActiveExpr->getType(); 14721 VK = ActiveExpr->getValueKind(); 14722 OK = ActiveExpr->getObjectKind(); 14723 } 14724 14725 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14726 resType, VK, OK, RPLoc, CondIsTrue); 14727 } 14728 14729 //===----------------------------------------------------------------------===// 14730 // Clang Extensions. 14731 //===----------------------------------------------------------------------===// 14732 14733 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14734 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14735 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14736 14737 if (LangOpts.CPlusPlus) { 14738 MangleNumberingContext *MCtx; 14739 Decl *ManglingContextDecl; 14740 std::tie(MCtx, ManglingContextDecl) = 14741 getCurrentMangleNumberContext(Block->getDeclContext()); 14742 if (MCtx) { 14743 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14744 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14745 } 14746 } 14747 14748 PushBlockScope(CurScope, Block); 14749 CurContext->addDecl(Block); 14750 if (CurScope) 14751 PushDeclContext(CurScope, Block); 14752 else 14753 CurContext = Block; 14754 14755 getCurBlock()->HasImplicitReturnType = true; 14756 14757 // Enter a new evaluation context to insulate the block from any 14758 // cleanups from the enclosing full-expression. 14759 PushExpressionEvaluationContext( 14760 ExpressionEvaluationContext::PotentiallyEvaluated); 14761 } 14762 14763 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14764 Scope *CurScope) { 14765 assert(ParamInfo.getIdentifier() == nullptr && 14766 "block-id should have no identifier!"); 14767 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14768 BlockScopeInfo *CurBlock = getCurBlock(); 14769 14770 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14771 QualType T = Sig->getType(); 14772 14773 // FIXME: We should allow unexpanded parameter packs here, but that would, 14774 // in turn, make the block expression contain unexpanded parameter packs. 14775 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14776 // Drop the parameters. 14777 FunctionProtoType::ExtProtoInfo EPI; 14778 EPI.HasTrailingReturn = false; 14779 EPI.TypeQuals.addConst(); 14780 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14781 Sig = Context.getTrivialTypeSourceInfo(T); 14782 } 14783 14784 // GetTypeForDeclarator always produces a function type for a block 14785 // literal signature. Furthermore, it is always a FunctionProtoType 14786 // unless the function was written with a typedef. 14787 assert(T->isFunctionType() && 14788 "GetTypeForDeclarator made a non-function block signature"); 14789 14790 // Look for an explicit signature in that function type. 14791 FunctionProtoTypeLoc ExplicitSignature; 14792 14793 if ((ExplicitSignature = Sig->getTypeLoc() 14794 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14795 14796 // Check whether that explicit signature was synthesized by 14797 // GetTypeForDeclarator. If so, don't save that as part of the 14798 // written signature. 14799 if (ExplicitSignature.getLocalRangeBegin() == 14800 ExplicitSignature.getLocalRangeEnd()) { 14801 // This would be much cheaper if we stored TypeLocs instead of 14802 // TypeSourceInfos. 14803 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14804 unsigned Size = Result.getFullDataSize(); 14805 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14806 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14807 14808 ExplicitSignature = FunctionProtoTypeLoc(); 14809 } 14810 } 14811 14812 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14813 CurBlock->FunctionType = T; 14814 14815 const FunctionType *Fn = T->getAs<FunctionType>(); 14816 QualType RetTy = Fn->getReturnType(); 14817 bool isVariadic = 14818 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14819 14820 CurBlock->TheDecl->setIsVariadic(isVariadic); 14821 14822 // Context.DependentTy is used as a placeholder for a missing block 14823 // return type. TODO: what should we do with declarators like: 14824 // ^ * { ... } 14825 // If the answer is "apply template argument deduction".... 14826 if (RetTy != Context.DependentTy) { 14827 CurBlock->ReturnType = RetTy; 14828 CurBlock->TheDecl->setBlockMissingReturnType(false); 14829 CurBlock->HasImplicitReturnType = false; 14830 } 14831 14832 // Push block parameters from the declarator if we had them. 14833 SmallVector<ParmVarDecl*, 8> Params; 14834 if (ExplicitSignature) { 14835 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14836 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14837 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 14838 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 14839 // Diagnose this as an extension in C17 and earlier. 14840 if (!getLangOpts().C2x) 14841 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14842 } 14843 Params.push_back(Param); 14844 } 14845 14846 // Fake up parameter variables if we have a typedef, like 14847 // ^ fntype { ... } 14848 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14849 for (const auto &I : Fn->param_types()) { 14850 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14851 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14852 Params.push_back(Param); 14853 } 14854 } 14855 14856 // Set the parameters on the block decl. 14857 if (!Params.empty()) { 14858 CurBlock->TheDecl->setParams(Params); 14859 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14860 /*CheckParameterNames=*/false); 14861 } 14862 14863 // Finally we can process decl attributes. 14864 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14865 14866 // Put the parameter variables in scope. 14867 for (auto AI : CurBlock->TheDecl->parameters()) { 14868 AI->setOwningFunction(CurBlock->TheDecl); 14869 14870 // If this has an identifier, add it to the scope stack. 14871 if (AI->getIdentifier()) { 14872 CheckShadow(CurBlock->TheScope, AI); 14873 14874 PushOnScopeChains(AI, CurBlock->TheScope); 14875 } 14876 } 14877 } 14878 14879 /// ActOnBlockError - If there is an error parsing a block, this callback 14880 /// is invoked to pop the information about the block from the action impl. 14881 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14882 // Leave the expression-evaluation context. 14883 DiscardCleanupsInEvaluationContext(); 14884 PopExpressionEvaluationContext(); 14885 14886 // Pop off CurBlock, handle nested blocks. 14887 PopDeclContext(); 14888 PopFunctionScopeInfo(); 14889 } 14890 14891 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14892 /// literal was successfully completed. ^(int x){...} 14893 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14894 Stmt *Body, Scope *CurScope) { 14895 // If blocks are disabled, emit an error. 14896 if (!LangOpts.Blocks) 14897 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14898 14899 // Leave the expression-evaluation context. 14900 if (hasAnyUnrecoverableErrorsInThisFunction()) 14901 DiscardCleanupsInEvaluationContext(); 14902 assert(!Cleanup.exprNeedsCleanups() && 14903 "cleanups within block not correctly bound!"); 14904 PopExpressionEvaluationContext(); 14905 14906 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14907 BlockDecl *BD = BSI->TheDecl; 14908 14909 if (BSI->HasImplicitReturnType) 14910 deduceClosureReturnType(*BSI); 14911 14912 QualType RetTy = Context.VoidTy; 14913 if (!BSI->ReturnType.isNull()) 14914 RetTy = BSI->ReturnType; 14915 14916 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14917 QualType BlockTy; 14918 14919 // If the user wrote a function type in some form, try to use that. 14920 if (!BSI->FunctionType.isNull()) { 14921 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14922 14923 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14924 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14925 14926 // Turn protoless block types into nullary block types. 14927 if (isa<FunctionNoProtoType>(FTy)) { 14928 FunctionProtoType::ExtProtoInfo EPI; 14929 EPI.ExtInfo = Ext; 14930 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14931 14932 // Otherwise, if we don't need to change anything about the function type, 14933 // preserve its sugar structure. 14934 } else if (FTy->getReturnType() == RetTy && 14935 (!NoReturn || FTy->getNoReturnAttr())) { 14936 BlockTy = BSI->FunctionType; 14937 14938 // Otherwise, make the minimal modifications to the function type. 14939 } else { 14940 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14941 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14942 EPI.TypeQuals = Qualifiers(); 14943 EPI.ExtInfo = Ext; 14944 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14945 } 14946 14947 // If we don't have a function type, just build one from nothing. 14948 } else { 14949 FunctionProtoType::ExtProtoInfo EPI; 14950 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14951 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14952 } 14953 14954 DiagnoseUnusedParameters(BD->parameters()); 14955 BlockTy = Context.getBlockPointerType(BlockTy); 14956 14957 // If needed, diagnose invalid gotos and switches in the block. 14958 if (getCurFunction()->NeedsScopeChecking() && 14959 !PP.isCodeCompletionEnabled()) 14960 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14961 14962 BD->setBody(cast<CompoundStmt>(Body)); 14963 14964 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14965 DiagnoseUnguardedAvailabilityViolations(BD); 14966 14967 // Try to apply the named return value optimization. We have to check again 14968 // if we can do this, though, because blocks keep return statements around 14969 // to deduce an implicit return type. 14970 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14971 !BD->isDependentContext()) 14972 computeNRVO(Body, BSI); 14973 14974 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14975 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14976 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14977 NTCUK_Destruct|NTCUK_Copy); 14978 14979 PopDeclContext(); 14980 14981 // Pop the block scope now but keep it alive to the end of this function. 14982 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14983 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14984 14985 // Set the captured variables on the block. 14986 SmallVector<BlockDecl::Capture, 4> Captures; 14987 for (Capture &Cap : BSI->Captures) { 14988 if (Cap.isInvalid() || Cap.isThisCapture()) 14989 continue; 14990 14991 VarDecl *Var = Cap.getVariable(); 14992 Expr *CopyExpr = nullptr; 14993 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14994 if (const RecordType *Record = 14995 Cap.getCaptureType()->getAs<RecordType>()) { 14996 // The capture logic needs the destructor, so make sure we mark it. 14997 // Usually this is unnecessary because most local variables have 14998 // their destructors marked at declaration time, but parameters are 14999 // an exception because it's technically only the call site that 15000 // actually requires the destructor. 15001 if (isa<ParmVarDecl>(Var)) 15002 FinalizeVarWithDestructor(Var, Record); 15003 15004 // Enter a separate potentially-evaluated context while building block 15005 // initializers to isolate their cleanups from those of the block 15006 // itself. 15007 // FIXME: Is this appropriate even when the block itself occurs in an 15008 // unevaluated operand? 15009 EnterExpressionEvaluationContext EvalContext( 15010 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15011 15012 SourceLocation Loc = Cap.getLocation(); 15013 15014 ExprResult Result = BuildDeclarationNameExpr( 15015 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15016 15017 // According to the blocks spec, the capture of a variable from 15018 // the stack requires a const copy constructor. This is not true 15019 // of the copy/move done to move a __block variable to the heap. 15020 if (!Result.isInvalid() && 15021 !Result.get()->getType().isConstQualified()) { 15022 Result = ImpCastExprToType(Result.get(), 15023 Result.get()->getType().withConst(), 15024 CK_NoOp, VK_LValue); 15025 } 15026 15027 if (!Result.isInvalid()) { 15028 Result = PerformCopyInitialization( 15029 InitializedEntity::InitializeBlock(Var->getLocation(), 15030 Cap.getCaptureType(), false), 15031 Loc, Result.get()); 15032 } 15033 15034 // Build a full-expression copy expression if initialization 15035 // succeeded and used a non-trivial constructor. Recover from 15036 // errors by pretending that the copy isn't necessary. 15037 if (!Result.isInvalid() && 15038 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15039 ->isTrivial()) { 15040 Result = MaybeCreateExprWithCleanups(Result); 15041 CopyExpr = Result.get(); 15042 } 15043 } 15044 } 15045 15046 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15047 CopyExpr); 15048 Captures.push_back(NewCap); 15049 } 15050 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15051 15052 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15053 15054 // If the block isn't obviously global, i.e. it captures anything at 15055 // all, then we need to do a few things in the surrounding context: 15056 if (Result->getBlockDecl()->hasCaptures()) { 15057 // First, this expression has a new cleanup object. 15058 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15059 Cleanup.setExprNeedsCleanups(true); 15060 15061 // It also gets a branch-protected scope if any of the captured 15062 // variables needs destruction. 15063 for (const auto &CI : Result->getBlockDecl()->captures()) { 15064 const VarDecl *var = CI.getVariable(); 15065 if (var->getType().isDestructedType() != QualType::DK_none) { 15066 setFunctionHasBranchProtectedScope(); 15067 break; 15068 } 15069 } 15070 } 15071 15072 if (getCurFunction()) 15073 getCurFunction()->addBlock(BD); 15074 15075 return Result; 15076 } 15077 15078 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15079 SourceLocation RPLoc) { 15080 TypeSourceInfo *TInfo; 15081 GetTypeFromParser(Ty, &TInfo); 15082 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15083 } 15084 15085 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15086 Expr *E, TypeSourceInfo *TInfo, 15087 SourceLocation RPLoc) { 15088 Expr *OrigExpr = E; 15089 bool IsMS = false; 15090 15091 // CUDA device code does not support varargs. 15092 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15093 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15094 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15095 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15096 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15097 } 15098 } 15099 15100 // NVPTX does not support va_arg expression. 15101 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15102 Context.getTargetInfo().getTriple().isNVPTX()) 15103 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15104 15105 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15106 // as Microsoft ABI on an actual Microsoft platform, where 15107 // __builtin_ms_va_list and __builtin_va_list are the same.) 15108 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15109 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15110 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15111 if (Context.hasSameType(MSVaListType, E->getType())) { 15112 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15113 return ExprError(); 15114 IsMS = true; 15115 } 15116 } 15117 15118 // Get the va_list type 15119 QualType VaListType = Context.getBuiltinVaListType(); 15120 if (!IsMS) { 15121 if (VaListType->isArrayType()) { 15122 // Deal with implicit array decay; for example, on x86-64, 15123 // va_list is an array, but it's supposed to decay to 15124 // a pointer for va_arg. 15125 VaListType = Context.getArrayDecayedType(VaListType); 15126 // Make sure the input expression also decays appropriately. 15127 ExprResult Result = UsualUnaryConversions(E); 15128 if (Result.isInvalid()) 15129 return ExprError(); 15130 E = Result.get(); 15131 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15132 // If va_list is a record type and we are compiling in C++ mode, 15133 // check the argument using reference binding. 15134 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15135 Context, Context.getLValueReferenceType(VaListType), false); 15136 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15137 if (Init.isInvalid()) 15138 return ExprError(); 15139 E = Init.getAs<Expr>(); 15140 } else { 15141 // Otherwise, the va_list argument must be an l-value because 15142 // it is modified by va_arg. 15143 if (!E->isTypeDependent() && 15144 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15145 return ExprError(); 15146 } 15147 } 15148 15149 if (!IsMS && !E->isTypeDependent() && 15150 !Context.hasSameType(VaListType, E->getType())) 15151 return ExprError( 15152 Diag(E->getBeginLoc(), 15153 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15154 << OrigExpr->getType() << E->getSourceRange()); 15155 15156 if (!TInfo->getType()->isDependentType()) { 15157 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15158 diag::err_second_parameter_to_va_arg_incomplete, 15159 TInfo->getTypeLoc())) 15160 return ExprError(); 15161 15162 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15163 TInfo->getType(), 15164 diag::err_second_parameter_to_va_arg_abstract, 15165 TInfo->getTypeLoc())) 15166 return ExprError(); 15167 15168 if (!TInfo->getType().isPODType(Context)) { 15169 Diag(TInfo->getTypeLoc().getBeginLoc(), 15170 TInfo->getType()->isObjCLifetimeType() 15171 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15172 : diag::warn_second_parameter_to_va_arg_not_pod) 15173 << TInfo->getType() 15174 << TInfo->getTypeLoc().getSourceRange(); 15175 } 15176 15177 // Check for va_arg where arguments of the given type will be promoted 15178 // (i.e. this va_arg is guaranteed to have undefined behavior). 15179 QualType PromoteType; 15180 if (TInfo->getType()->isPromotableIntegerType()) { 15181 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15182 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15183 PromoteType = QualType(); 15184 } 15185 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15186 PromoteType = Context.DoubleTy; 15187 if (!PromoteType.isNull()) 15188 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15189 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15190 << TInfo->getType() 15191 << PromoteType 15192 << TInfo->getTypeLoc().getSourceRange()); 15193 } 15194 15195 QualType T = TInfo->getType().getNonLValueExprType(Context); 15196 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15197 } 15198 15199 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15200 // The type of __null will be int or long, depending on the size of 15201 // pointers on the target. 15202 QualType Ty; 15203 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15204 if (pw == Context.getTargetInfo().getIntWidth()) 15205 Ty = Context.IntTy; 15206 else if (pw == Context.getTargetInfo().getLongWidth()) 15207 Ty = Context.LongTy; 15208 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15209 Ty = Context.LongLongTy; 15210 else { 15211 llvm_unreachable("I don't know size of pointer!"); 15212 } 15213 15214 return new (Context) GNUNullExpr(Ty, TokenLoc); 15215 } 15216 15217 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15218 SourceLocation BuiltinLoc, 15219 SourceLocation RPLoc) { 15220 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15221 } 15222 15223 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15224 SourceLocation BuiltinLoc, 15225 SourceLocation RPLoc, 15226 DeclContext *ParentContext) { 15227 return new (Context) 15228 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15229 } 15230 15231 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 15232 bool Diagnose) { 15233 if (!getLangOpts().ObjC) 15234 return false; 15235 15236 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15237 if (!PT) 15238 return false; 15239 15240 if (!PT->isObjCIdType()) { 15241 // Check if the destination is the 'NSString' interface. 15242 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15243 if (!ID || !ID->getIdentifier()->isStr("NSString")) 15244 return false; 15245 } 15246 15247 // Ignore any parens, implicit casts (should only be 15248 // array-to-pointer decays), and not-so-opaque values. The last is 15249 // important for making this trigger for property assignments. 15250 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15251 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15252 if (OV->getSourceExpr()) 15253 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15254 15255 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 15256 if (!SL || !SL->isAscii()) 15257 return false; 15258 if (Diagnose) { 15259 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15260 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15261 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15262 } 15263 return true; 15264 } 15265 15266 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15267 const Expr *SrcExpr) { 15268 if (!DstType->isFunctionPointerType() || 15269 !SrcExpr->getType()->isFunctionType()) 15270 return false; 15271 15272 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15273 if (!DRE) 15274 return false; 15275 15276 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15277 if (!FD) 15278 return false; 15279 15280 return !S.checkAddressOfFunctionIsAvailable(FD, 15281 /*Complain=*/true, 15282 SrcExpr->getBeginLoc()); 15283 } 15284 15285 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15286 SourceLocation Loc, 15287 QualType DstType, QualType SrcType, 15288 Expr *SrcExpr, AssignmentAction Action, 15289 bool *Complained) { 15290 if (Complained) 15291 *Complained = false; 15292 15293 // Decode the result (notice that AST's are still created for extensions). 15294 bool CheckInferredResultType = false; 15295 bool isInvalid = false; 15296 unsigned DiagKind = 0; 15297 FixItHint Hint; 15298 ConversionFixItGenerator ConvHints; 15299 bool MayHaveConvFixit = false; 15300 bool MayHaveFunctionDiff = false; 15301 const ObjCInterfaceDecl *IFace = nullptr; 15302 const ObjCProtocolDecl *PDecl = nullptr; 15303 15304 switch (ConvTy) { 15305 case Compatible: 15306 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15307 return false; 15308 15309 case PointerToInt: 15310 if (getLangOpts().CPlusPlus) { 15311 DiagKind = diag::err_typecheck_convert_pointer_int; 15312 isInvalid = true; 15313 } else { 15314 DiagKind = diag::ext_typecheck_convert_pointer_int; 15315 } 15316 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15317 MayHaveConvFixit = true; 15318 break; 15319 case IntToPointer: 15320 if (getLangOpts().CPlusPlus) { 15321 DiagKind = diag::err_typecheck_convert_int_pointer; 15322 isInvalid = true; 15323 } else { 15324 DiagKind = diag::ext_typecheck_convert_int_pointer; 15325 } 15326 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15327 MayHaveConvFixit = true; 15328 break; 15329 case IncompatibleFunctionPointer: 15330 if (getLangOpts().CPlusPlus) { 15331 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15332 isInvalid = true; 15333 } else { 15334 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15335 } 15336 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15337 MayHaveConvFixit = true; 15338 break; 15339 case IncompatiblePointer: 15340 if (Action == AA_Passing_CFAudited) { 15341 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15342 } else if (getLangOpts().CPlusPlus) { 15343 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15344 isInvalid = true; 15345 } else { 15346 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15347 } 15348 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15349 SrcType->isObjCObjectPointerType(); 15350 if (Hint.isNull() && !CheckInferredResultType) { 15351 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15352 } 15353 else if (CheckInferredResultType) { 15354 SrcType = SrcType.getUnqualifiedType(); 15355 DstType = DstType.getUnqualifiedType(); 15356 } 15357 MayHaveConvFixit = true; 15358 break; 15359 case IncompatiblePointerSign: 15360 if (getLangOpts().CPlusPlus) { 15361 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15362 isInvalid = true; 15363 } else { 15364 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15365 } 15366 break; 15367 case FunctionVoidPointer: 15368 if (getLangOpts().CPlusPlus) { 15369 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15370 isInvalid = true; 15371 } else { 15372 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15373 } 15374 break; 15375 case IncompatiblePointerDiscardsQualifiers: { 15376 // Perform array-to-pointer decay if necessary. 15377 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15378 15379 isInvalid = true; 15380 15381 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15382 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15383 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15384 DiagKind = diag::err_typecheck_incompatible_address_space; 15385 break; 15386 15387 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15388 DiagKind = diag::err_typecheck_incompatible_ownership; 15389 break; 15390 } 15391 15392 llvm_unreachable("unknown error case for discarding qualifiers!"); 15393 // fallthrough 15394 } 15395 case CompatiblePointerDiscardsQualifiers: 15396 // If the qualifiers lost were because we were applying the 15397 // (deprecated) C++ conversion from a string literal to a char* 15398 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15399 // Ideally, this check would be performed in 15400 // checkPointerTypesForAssignment. However, that would require a 15401 // bit of refactoring (so that the second argument is an 15402 // expression, rather than a type), which should be done as part 15403 // of a larger effort to fix checkPointerTypesForAssignment for 15404 // C++ semantics. 15405 if (getLangOpts().CPlusPlus && 15406 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15407 return false; 15408 if (getLangOpts().CPlusPlus) { 15409 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15410 isInvalid = true; 15411 } else { 15412 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15413 } 15414 15415 break; 15416 case IncompatibleNestedPointerQualifiers: 15417 if (getLangOpts().CPlusPlus) { 15418 isInvalid = true; 15419 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15420 } else { 15421 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15422 } 15423 break; 15424 case IncompatibleNestedPointerAddressSpaceMismatch: 15425 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15426 isInvalid = true; 15427 break; 15428 case IntToBlockPointer: 15429 DiagKind = diag::err_int_to_block_pointer; 15430 isInvalid = true; 15431 break; 15432 case IncompatibleBlockPointer: 15433 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15434 isInvalid = true; 15435 break; 15436 case IncompatibleObjCQualifiedId: { 15437 if (SrcType->isObjCQualifiedIdType()) { 15438 const ObjCObjectPointerType *srcOPT = 15439 SrcType->castAs<ObjCObjectPointerType>(); 15440 for (auto *srcProto : srcOPT->quals()) { 15441 PDecl = srcProto; 15442 break; 15443 } 15444 if (const ObjCInterfaceType *IFaceT = 15445 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15446 IFace = IFaceT->getDecl(); 15447 } 15448 else if (DstType->isObjCQualifiedIdType()) { 15449 const ObjCObjectPointerType *dstOPT = 15450 DstType->castAs<ObjCObjectPointerType>(); 15451 for (auto *dstProto : dstOPT->quals()) { 15452 PDecl = dstProto; 15453 break; 15454 } 15455 if (const ObjCInterfaceType *IFaceT = 15456 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15457 IFace = IFaceT->getDecl(); 15458 } 15459 if (getLangOpts().CPlusPlus) { 15460 DiagKind = diag::err_incompatible_qualified_id; 15461 isInvalid = true; 15462 } else { 15463 DiagKind = diag::warn_incompatible_qualified_id; 15464 } 15465 break; 15466 } 15467 case IncompatibleVectors: 15468 if (getLangOpts().CPlusPlus) { 15469 DiagKind = diag::err_incompatible_vectors; 15470 isInvalid = true; 15471 } else { 15472 DiagKind = diag::warn_incompatible_vectors; 15473 } 15474 break; 15475 case IncompatibleObjCWeakRef: 15476 DiagKind = diag::err_arc_weak_unavailable_assign; 15477 isInvalid = true; 15478 break; 15479 case Incompatible: 15480 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15481 if (Complained) 15482 *Complained = true; 15483 return true; 15484 } 15485 15486 DiagKind = diag::err_typecheck_convert_incompatible; 15487 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15488 MayHaveConvFixit = true; 15489 isInvalid = true; 15490 MayHaveFunctionDiff = true; 15491 break; 15492 } 15493 15494 QualType FirstType, SecondType; 15495 switch (Action) { 15496 case AA_Assigning: 15497 case AA_Initializing: 15498 // The destination type comes first. 15499 FirstType = DstType; 15500 SecondType = SrcType; 15501 break; 15502 15503 case AA_Returning: 15504 case AA_Passing: 15505 case AA_Passing_CFAudited: 15506 case AA_Converting: 15507 case AA_Sending: 15508 case AA_Casting: 15509 // The source type comes first. 15510 FirstType = SrcType; 15511 SecondType = DstType; 15512 break; 15513 } 15514 15515 PartialDiagnostic FDiag = PDiag(DiagKind); 15516 if (Action == AA_Passing_CFAudited) 15517 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15518 else 15519 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15520 15521 // If we can fix the conversion, suggest the FixIts. 15522 assert(ConvHints.isNull() || Hint.isNull()); 15523 if (!ConvHints.isNull()) { 15524 for (FixItHint &H : ConvHints.Hints) 15525 FDiag << H; 15526 } else { 15527 FDiag << Hint; 15528 } 15529 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15530 15531 if (MayHaveFunctionDiff) 15532 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15533 15534 Diag(Loc, FDiag); 15535 if ((DiagKind == diag::warn_incompatible_qualified_id || 15536 DiagKind == diag::err_incompatible_qualified_id) && 15537 PDecl && IFace && !IFace->hasDefinition()) 15538 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15539 << IFace << PDecl; 15540 15541 if (SecondType == Context.OverloadTy) 15542 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15543 FirstType, /*TakingAddress=*/true); 15544 15545 if (CheckInferredResultType) 15546 EmitRelatedResultTypeNote(SrcExpr); 15547 15548 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15549 EmitRelatedResultTypeNoteForReturn(DstType); 15550 15551 if (Complained) 15552 *Complained = true; 15553 return isInvalid; 15554 } 15555 15556 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15557 llvm::APSInt *Result) { 15558 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15559 public: 15560 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15561 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15562 } 15563 } Diagnoser; 15564 15565 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15566 } 15567 15568 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15569 llvm::APSInt *Result, 15570 unsigned DiagID, 15571 bool AllowFold) { 15572 class IDDiagnoser : public VerifyICEDiagnoser { 15573 unsigned DiagID; 15574 15575 public: 15576 IDDiagnoser(unsigned DiagID) 15577 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15578 15579 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15580 S.Diag(Loc, DiagID) << SR; 15581 } 15582 } Diagnoser(DiagID); 15583 15584 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15585 } 15586 15587 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15588 SourceRange SR) { 15589 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15590 } 15591 15592 ExprResult 15593 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15594 VerifyICEDiagnoser &Diagnoser, 15595 bool AllowFold) { 15596 SourceLocation DiagLoc = E->getBeginLoc(); 15597 15598 if (getLangOpts().CPlusPlus11) { 15599 // C++11 [expr.const]p5: 15600 // If an expression of literal class type is used in a context where an 15601 // integral constant expression is required, then that class type shall 15602 // have a single non-explicit conversion function to an integral or 15603 // unscoped enumeration type 15604 ExprResult Converted; 15605 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15606 public: 15607 CXX11ConvertDiagnoser(bool Silent) 15608 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15609 Silent, true) {} 15610 15611 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15612 QualType T) override { 15613 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15614 } 15615 15616 SemaDiagnosticBuilder diagnoseIncomplete( 15617 Sema &S, SourceLocation Loc, QualType T) override { 15618 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15619 } 15620 15621 SemaDiagnosticBuilder diagnoseExplicitConv( 15622 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15623 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15624 } 15625 15626 SemaDiagnosticBuilder noteExplicitConv( 15627 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15628 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15629 << ConvTy->isEnumeralType() << ConvTy; 15630 } 15631 15632 SemaDiagnosticBuilder diagnoseAmbiguous( 15633 Sema &S, SourceLocation Loc, QualType T) override { 15634 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15635 } 15636 15637 SemaDiagnosticBuilder noteAmbiguous( 15638 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15639 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15640 << ConvTy->isEnumeralType() << ConvTy; 15641 } 15642 15643 SemaDiagnosticBuilder diagnoseConversion( 15644 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15645 llvm_unreachable("conversion functions are permitted"); 15646 } 15647 } ConvertDiagnoser(Diagnoser.Suppress); 15648 15649 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15650 ConvertDiagnoser); 15651 if (Converted.isInvalid()) 15652 return Converted; 15653 E = Converted.get(); 15654 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15655 return ExprError(); 15656 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15657 // An ICE must be of integral or unscoped enumeration type. 15658 if (!Diagnoser.Suppress) 15659 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15660 return ExprError(); 15661 } 15662 15663 ExprResult RValueExpr = DefaultLvalueConversion(E); 15664 if (RValueExpr.isInvalid()) 15665 return ExprError(); 15666 15667 E = RValueExpr.get(); 15668 15669 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15670 // in the non-ICE case. 15671 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15672 if (Result) 15673 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15674 if (!isa<ConstantExpr>(E)) 15675 E = ConstantExpr::Create(Context, E); 15676 return E; 15677 } 15678 15679 Expr::EvalResult EvalResult; 15680 SmallVector<PartialDiagnosticAt, 8> Notes; 15681 EvalResult.Diag = &Notes; 15682 15683 // Try to evaluate the expression, and produce diagnostics explaining why it's 15684 // not a constant expression as a side-effect. 15685 bool Folded = 15686 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15687 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15688 15689 if (!isa<ConstantExpr>(E)) 15690 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15691 15692 // In C++11, we can rely on diagnostics being produced for any expression 15693 // which is not a constant expression. If no diagnostics were produced, then 15694 // this is a constant expression. 15695 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15696 if (Result) 15697 *Result = EvalResult.Val.getInt(); 15698 return E; 15699 } 15700 15701 // If our only note is the usual "invalid subexpression" note, just point 15702 // the caret at its location rather than producing an essentially 15703 // redundant note. 15704 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15705 diag::note_invalid_subexpr_in_const_expr) { 15706 DiagLoc = Notes[0].first; 15707 Notes.clear(); 15708 } 15709 15710 if (!Folded || !AllowFold) { 15711 if (!Diagnoser.Suppress) { 15712 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15713 for (const PartialDiagnosticAt &Note : Notes) 15714 Diag(Note.first, Note.second); 15715 } 15716 15717 return ExprError(); 15718 } 15719 15720 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15721 for (const PartialDiagnosticAt &Note : Notes) 15722 Diag(Note.first, Note.second); 15723 15724 if (Result) 15725 *Result = EvalResult.Val.getInt(); 15726 return E; 15727 } 15728 15729 namespace { 15730 // Handle the case where we conclude a expression which we speculatively 15731 // considered to be unevaluated is actually evaluated. 15732 class TransformToPE : public TreeTransform<TransformToPE> { 15733 typedef TreeTransform<TransformToPE> BaseTransform; 15734 15735 public: 15736 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15737 15738 // Make sure we redo semantic analysis 15739 bool AlwaysRebuild() { return true; } 15740 bool ReplacingOriginal() { return true; } 15741 15742 // We need to special-case DeclRefExprs referring to FieldDecls which 15743 // are not part of a member pointer formation; normal TreeTransforming 15744 // doesn't catch this case because of the way we represent them in the AST. 15745 // FIXME: This is a bit ugly; is it really the best way to handle this 15746 // case? 15747 // 15748 // Error on DeclRefExprs referring to FieldDecls. 15749 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15750 if (isa<FieldDecl>(E->getDecl()) && 15751 !SemaRef.isUnevaluatedContext()) 15752 return SemaRef.Diag(E->getLocation(), 15753 diag::err_invalid_non_static_member_use) 15754 << E->getDecl() << E->getSourceRange(); 15755 15756 return BaseTransform::TransformDeclRefExpr(E); 15757 } 15758 15759 // Exception: filter out member pointer formation 15760 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15761 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15762 return E; 15763 15764 return BaseTransform::TransformUnaryOperator(E); 15765 } 15766 15767 // The body of a lambda-expression is in a separate expression evaluation 15768 // context so never needs to be transformed. 15769 // FIXME: Ideally we wouldn't transform the closure type either, and would 15770 // just recreate the capture expressions and lambda expression. 15771 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15772 return SkipLambdaBody(E, Body); 15773 } 15774 }; 15775 } 15776 15777 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15778 assert(isUnevaluatedContext() && 15779 "Should only transform unevaluated expressions"); 15780 ExprEvalContexts.back().Context = 15781 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15782 if (isUnevaluatedContext()) 15783 return E; 15784 return TransformToPE(*this).TransformExpr(E); 15785 } 15786 15787 void 15788 Sema::PushExpressionEvaluationContext( 15789 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15790 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15791 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15792 LambdaContextDecl, ExprContext); 15793 Cleanup.reset(); 15794 if (!MaybeODRUseExprs.empty()) 15795 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15796 } 15797 15798 void 15799 Sema::PushExpressionEvaluationContext( 15800 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15801 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15802 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15803 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15804 } 15805 15806 namespace { 15807 15808 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15809 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15810 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15811 if (E->getOpcode() == UO_Deref) 15812 return CheckPossibleDeref(S, E->getSubExpr()); 15813 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15814 return CheckPossibleDeref(S, E->getBase()); 15815 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15816 return CheckPossibleDeref(S, E->getBase()); 15817 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15818 QualType Inner; 15819 QualType Ty = E->getType(); 15820 if (const auto *Ptr = Ty->getAs<PointerType>()) 15821 Inner = Ptr->getPointeeType(); 15822 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15823 Inner = Arr->getElementType(); 15824 else 15825 return nullptr; 15826 15827 if (Inner->hasAttr(attr::NoDeref)) 15828 return E; 15829 } 15830 return nullptr; 15831 } 15832 15833 } // namespace 15834 15835 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15836 for (const Expr *E : Rec.PossibleDerefs) { 15837 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15838 if (DeclRef) { 15839 const ValueDecl *Decl = DeclRef->getDecl(); 15840 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15841 << Decl->getName() << E->getSourceRange(); 15842 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15843 } else { 15844 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15845 << E->getSourceRange(); 15846 } 15847 } 15848 Rec.PossibleDerefs.clear(); 15849 } 15850 15851 /// Check whether E, which is either a discarded-value expression or an 15852 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15853 /// and if so, remove it from the list of volatile-qualified assignments that 15854 /// we are going to warn are deprecated. 15855 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15856 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15857 return; 15858 15859 // Note: ignoring parens here is not justified by the standard rules, but 15860 // ignoring parentheses seems like a more reasonable approach, and this only 15861 // drives a deprecation warning so doesn't affect conformance. 15862 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15863 if (BO->getOpcode() == BO_Assign) { 15864 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15865 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15866 LHSs.end()); 15867 } 15868 } 15869 } 15870 15871 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15872 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15873 RebuildingImmediateInvocation) 15874 return E; 15875 15876 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15877 /// It's OK if this fails; we'll also remove this in 15878 /// HandleImmediateInvocations, but catching it here allows us to avoid 15879 /// walking the AST looking for it in simple cases. 15880 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15881 if (auto *DeclRef = 15882 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15883 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15884 15885 E = MaybeCreateExprWithCleanups(E); 15886 15887 ConstantExpr *Res = ConstantExpr::Create( 15888 getASTContext(), E.get(), 15889 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15890 getASTContext()), 15891 /*IsImmediateInvocation*/ true); 15892 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15893 return Res; 15894 } 15895 15896 static void EvaluateAndDiagnoseImmediateInvocation( 15897 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15898 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15899 Expr::EvalResult Eval; 15900 Eval.Diag = &Notes; 15901 ConstantExpr *CE = Candidate.getPointer(); 15902 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15903 SemaRef.getASTContext(), true); 15904 if (!Result || !Notes.empty()) { 15905 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15906 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 15907 InnerExpr = FunctionalCast->getSubExpr(); 15908 FunctionDecl *FD = nullptr; 15909 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15910 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15911 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15912 FD = Call->getConstructor(); 15913 else 15914 llvm_unreachable("unhandled decl kind"); 15915 assert(FD->isConsteval()); 15916 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15917 for (auto &Note : Notes) 15918 SemaRef.Diag(Note.first, Note.second); 15919 return; 15920 } 15921 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15922 } 15923 15924 static void RemoveNestedImmediateInvocation( 15925 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15926 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15927 struct ComplexRemove : TreeTransform<ComplexRemove> { 15928 using Base = TreeTransform<ComplexRemove>; 15929 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15930 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15931 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15932 CurrentII; 15933 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15934 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15935 SmallVector<Sema::ImmediateInvocationCandidate, 15936 4>::reverse_iterator Current) 15937 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15938 void RemoveImmediateInvocation(ConstantExpr* E) { 15939 auto It = std::find_if(CurrentII, IISet.rend(), 15940 [E](Sema::ImmediateInvocationCandidate Elem) { 15941 return Elem.getPointer() == E; 15942 }); 15943 assert(It != IISet.rend() && 15944 "ConstantExpr marked IsImmediateInvocation should " 15945 "be present"); 15946 It->setInt(1); // Mark as deleted 15947 } 15948 ExprResult TransformConstantExpr(ConstantExpr *E) { 15949 if (!E->isImmediateInvocation()) 15950 return Base::TransformConstantExpr(E); 15951 RemoveImmediateInvocation(E); 15952 return Base::TransformExpr(E->getSubExpr()); 15953 } 15954 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15955 /// we need to remove its DeclRefExpr from the DRSet. 15956 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15957 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15958 return Base::TransformCXXOperatorCallExpr(E); 15959 } 15960 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15961 /// here. 15962 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15963 if (!Init) 15964 return Init; 15965 /// ConstantExpr are the first layer of implicit node to be removed so if 15966 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15967 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 15968 if (CE->isImmediateInvocation()) 15969 RemoveImmediateInvocation(CE); 15970 return Base::TransformInitializer(Init, NotCopyInit); 15971 } 15972 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15973 DRSet.erase(E); 15974 return E; 15975 } 15976 bool AlwaysRebuild() { return false; } 15977 bool ReplacingOriginal() { return true; } 15978 bool AllowSkippingCXXConstructExpr() { 15979 bool Res = AllowSkippingFirstCXXConstructExpr; 15980 AllowSkippingFirstCXXConstructExpr = true; 15981 return Res; 15982 } 15983 bool AllowSkippingFirstCXXConstructExpr = true; 15984 } Transformer(SemaRef, Rec.ReferenceToConsteval, 15985 Rec.ImmediateInvocationCandidates, It); 15986 15987 /// CXXConstructExpr with a single argument are getting skipped by 15988 /// TreeTransform in some situtation because they could be implicit. This 15989 /// can only occur for the top-level CXXConstructExpr because it is used 15990 /// nowhere in the expression being transformed therefore will not be rebuilt. 15991 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 15992 /// skipping the first CXXConstructExpr. 15993 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 15994 Transformer.AllowSkippingFirstCXXConstructExpr = false; 15995 15996 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 15997 assert(Res.isUsable()); 15998 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 15999 It->getPointer()->setSubExpr(Res.get()); 16000 } 16001 16002 static void 16003 HandleImmediateInvocations(Sema &SemaRef, 16004 Sema::ExpressionEvaluationContextRecord &Rec) { 16005 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16006 Rec.ReferenceToConsteval.size() == 0) || 16007 SemaRef.RebuildingImmediateInvocation) 16008 return; 16009 16010 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16011 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16012 /// need to remove ReferenceToConsteval in the immediate invocation. 16013 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16014 16015 /// Prevent sema calls during the tree transform from adding pointers that 16016 /// are already in the sets. 16017 llvm::SaveAndRestore<bool> DisableIITracking( 16018 SemaRef.RebuildingImmediateInvocation, true); 16019 16020 /// Prevent diagnostic during tree transfrom as they are duplicates 16021 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16022 16023 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16024 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16025 if (!It->getInt()) 16026 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16027 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16028 Rec.ReferenceToConsteval.size()) { 16029 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16030 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16031 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16032 bool VisitDeclRefExpr(DeclRefExpr *E) { 16033 DRSet.erase(E); 16034 return DRSet.size(); 16035 } 16036 } Visitor(Rec.ReferenceToConsteval); 16037 Visitor.TraverseStmt( 16038 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16039 } 16040 for (auto CE : Rec.ImmediateInvocationCandidates) 16041 if (!CE.getInt()) 16042 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16043 for (auto DR : Rec.ReferenceToConsteval) { 16044 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16045 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16046 << FD; 16047 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16048 } 16049 } 16050 16051 void Sema::PopExpressionEvaluationContext() { 16052 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16053 unsigned NumTypos = Rec.NumTypos; 16054 16055 if (!Rec.Lambdas.empty()) { 16056 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16057 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16058 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16059 unsigned D; 16060 if (Rec.isUnevaluated()) { 16061 // C++11 [expr.prim.lambda]p2: 16062 // A lambda-expression shall not appear in an unevaluated operand 16063 // (Clause 5). 16064 D = diag::err_lambda_unevaluated_operand; 16065 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16066 // C++1y [expr.const]p2: 16067 // A conditional-expression e is a core constant expression unless the 16068 // evaluation of e, following the rules of the abstract machine, would 16069 // evaluate [...] a lambda-expression. 16070 D = diag::err_lambda_in_constant_expression; 16071 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16072 // C++17 [expr.prim.lamda]p2: 16073 // A lambda-expression shall not appear [...] in a template-argument. 16074 D = diag::err_lambda_in_invalid_context; 16075 } else 16076 llvm_unreachable("Couldn't infer lambda error message."); 16077 16078 for (const auto *L : Rec.Lambdas) 16079 Diag(L->getBeginLoc(), D); 16080 } 16081 } 16082 16083 WarnOnPendingNoDerefs(Rec); 16084 HandleImmediateInvocations(*this, Rec); 16085 16086 // Warn on any volatile-qualified simple-assignments that are not discarded- 16087 // value expressions nor unevaluated operands (those cases get removed from 16088 // this list by CheckUnusedVolatileAssignment). 16089 for (auto *BO : Rec.VolatileAssignmentLHSs) 16090 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16091 << BO->getType(); 16092 16093 // When are coming out of an unevaluated context, clear out any 16094 // temporaries that we may have created as part of the evaluation of 16095 // the expression in that context: they aren't relevant because they 16096 // will never be constructed. 16097 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16098 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16099 ExprCleanupObjects.end()); 16100 Cleanup = Rec.ParentCleanup; 16101 CleanupVarDeclMarking(); 16102 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16103 // Otherwise, merge the contexts together. 16104 } else { 16105 Cleanup.mergeFrom(Rec.ParentCleanup); 16106 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16107 Rec.SavedMaybeODRUseExprs.end()); 16108 } 16109 16110 // Pop the current expression evaluation context off the stack. 16111 ExprEvalContexts.pop_back(); 16112 16113 // The global expression evaluation context record is never popped. 16114 ExprEvalContexts.back().NumTypos += NumTypos; 16115 } 16116 16117 void Sema::DiscardCleanupsInEvaluationContext() { 16118 ExprCleanupObjects.erase( 16119 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16120 ExprCleanupObjects.end()); 16121 Cleanup.reset(); 16122 MaybeODRUseExprs.clear(); 16123 } 16124 16125 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16126 ExprResult Result = CheckPlaceholderExpr(E); 16127 if (Result.isInvalid()) 16128 return ExprError(); 16129 E = Result.get(); 16130 if (!E->getType()->isVariablyModifiedType()) 16131 return E; 16132 return TransformToPotentiallyEvaluated(E); 16133 } 16134 16135 /// Are we in a context that is potentially constant evaluated per C++20 16136 /// [expr.const]p12? 16137 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16138 /// C++2a [expr.const]p12: 16139 // An expression or conversion is potentially constant evaluated if it is 16140 switch (SemaRef.ExprEvalContexts.back().Context) { 16141 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16142 // -- a manifestly constant-evaluated expression, 16143 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16144 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16145 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16146 // -- a potentially-evaluated expression, 16147 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16148 // -- an immediate subexpression of a braced-init-list, 16149 16150 // -- [FIXME] an expression of the form & cast-expression that occurs 16151 // within a templated entity 16152 // -- a subexpression of one of the above that is not a subexpression of 16153 // a nested unevaluated operand. 16154 return true; 16155 16156 case Sema::ExpressionEvaluationContext::Unevaluated: 16157 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16158 // Expressions in this context are never evaluated. 16159 return false; 16160 } 16161 llvm_unreachable("Invalid context"); 16162 } 16163 16164 /// Return true if this function has a calling convention that requires mangling 16165 /// in the size of the parameter pack. 16166 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16167 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16168 // we don't need parameter type sizes. 16169 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16170 if (!TT.isOSWindows() || !TT.isX86()) 16171 return false; 16172 16173 // If this is C++ and this isn't an extern "C" function, parameters do not 16174 // need to be complete. In this case, C++ mangling will apply, which doesn't 16175 // use the size of the parameters. 16176 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16177 return false; 16178 16179 // Stdcall, fastcall, and vectorcall need this special treatment. 16180 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16181 switch (CC) { 16182 case CC_X86StdCall: 16183 case CC_X86FastCall: 16184 case CC_X86VectorCall: 16185 return true; 16186 default: 16187 break; 16188 } 16189 return false; 16190 } 16191 16192 /// Require that all of the parameter types of function be complete. Normally, 16193 /// parameter types are only required to be complete when a function is called 16194 /// or defined, but to mangle functions with certain calling conventions, the 16195 /// mangler needs to know the size of the parameter list. In this situation, 16196 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16197 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16198 /// result in a linker error. Clang doesn't implement this behavior, and instead 16199 /// attempts to error at compile time. 16200 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16201 SourceLocation Loc) { 16202 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16203 FunctionDecl *FD; 16204 ParmVarDecl *Param; 16205 16206 public: 16207 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16208 : FD(FD), Param(Param) {} 16209 16210 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16211 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16212 StringRef CCName; 16213 switch (CC) { 16214 case CC_X86StdCall: 16215 CCName = "stdcall"; 16216 break; 16217 case CC_X86FastCall: 16218 CCName = "fastcall"; 16219 break; 16220 case CC_X86VectorCall: 16221 CCName = "vectorcall"; 16222 break; 16223 default: 16224 llvm_unreachable("CC does not need mangling"); 16225 } 16226 16227 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16228 << Param->getDeclName() << FD->getDeclName() << CCName; 16229 } 16230 }; 16231 16232 for (ParmVarDecl *Param : FD->parameters()) { 16233 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16234 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16235 } 16236 } 16237 16238 namespace { 16239 enum class OdrUseContext { 16240 /// Declarations in this context are not odr-used. 16241 None, 16242 /// Declarations in this context are formally odr-used, but this is a 16243 /// dependent context. 16244 Dependent, 16245 /// Declarations in this context are odr-used but not actually used (yet). 16246 FormallyOdrUsed, 16247 /// Declarations in this context are used. 16248 Used 16249 }; 16250 } 16251 16252 /// Are we within a context in which references to resolved functions or to 16253 /// variables result in odr-use? 16254 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16255 OdrUseContext Result; 16256 16257 switch (SemaRef.ExprEvalContexts.back().Context) { 16258 case Sema::ExpressionEvaluationContext::Unevaluated: 16259 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16260 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16261 return OdrUseContext::None; 16262 16263 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16264 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16265 Result = OdrUseContext::Used; 16266 break; 16267 16268 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16269 Result = OdrUseContext::FormallyOdrUsed; 16270 break; 16271 16272 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16273 // A default argument formally results in odr-use, but doesn't actually 16274 // result in a use in any real sense until it itself is used. 16275 Result = OdrUseContext::FormallyOdrUsed; 16276 break; 16277 } 16278 16279 if (SemaRef.CurContext->isDependentContext()) 16280 return OdrUseContext::Dependent; 16281 16282 return Result; 16283 } 16284 16285 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16286 return Func->isConstexpr() && 16287 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16288 } 16289 16290 /// Mark a function referenced, and check whether it is odr-used 16291 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16292 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16293 bool MightBeOdrUse) { 16294 assert(Func && "No function?"); 16295 16296 Func->setReferenced(); 16297 16298 // Recursive functions aren't really used until they're used from some other 16299 // context. 16300 bool IsRecursiveCall = CurContext == Func; 16301 16302 // C++11 [basic.def.odr]p3: 16303 // A function whose name appears as a potentially-evaluated expression is 16304 // odr-used if it is the unique lookup result or the selected member of a 16305 // set of overloaded functions [...]. 16306 // 16307 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16308 // can just check that here. 16309 OdrUseContext OdrUse = 16310 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16311 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16312 OdrUse = OdrUseContext::FormallyOdrUsed; 16313 16314 // Trivial default constructors and destructors are never actually used. 16315 // FIXME: What about other special members? 16316 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16317 OdrUse == OdrUseContext::Used) { 16318 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16319 if (Constructor->isDefaultConstructor()) 16320 OdrUse = OdrUseContext::FormallyOdrUsed; 16321 if (isa<CXXDestructorDecl>(Func)) 16322 OdrUse = OdrUseContext::FormallyOdrUsed; 16323 } 16324 16325 // C++20 [expr.const]p12: 16326 // A function [...] is needed for constant evaluation if it is [...] a 16327 // constexpr function that is named by an expression that is potentially 16328 // constant evaluated 16329 bool NeededForConstantEvaluation = 16330 isPotentiallyConstantEvaluatedContext(*this) && 16331 isImplicitlyDefinableConstexprFunction(Func); 16332 16333 // Determine whether we require a function definition to exist, per 16334 // C++11 [temp.inst]p3: 16335 // Unless a function template specialization has been explicitly 16336 // instantiated or explicitly specialized, the function template 16337 // specialization is implicitly instantiated when the specialization is 16338 // referenced in a context that requires a function definition to exist. 16339 // C++20 [temp.inst]p7: 16340 // The existence of a definition of a [...] function is considered to 16341 // affect the semantics of the program if the [...] function is needed for 16342 // constant evaluation by an expression 16343 // C++20 [basic.def.odr]p10: 16344 // Every program shall contain exactly one definition of every non-inline 16345 // function or variable that is odr-used in that program outside of a 16346 // discarded statement 16347 // C++20 [special]p1: 16348 // The implementation will implicitly define [defaulted special members] 16349 // if they are odr-used or needed for constant evaluation. 16350 // 16351 // Note that we skip the implicit instantiation of templates that are only 16352 // used in unused default arguments or by recursive calls to themselves. 16353 // This is formally non-conforming, but seems reasonable in practice. 16354 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16355 NeededForConstantEvaluation); 16356 16357 // C++14 [temp.expl.spec]p6: 16358 // If a template [...] is explicitly specialized then that specialization 16359 // shall be declared before the first use of that specialization that would 16360 // cause an implicit instantiation to take place, in every translation unit 16361 // in which such a use occurs 16362 if (NeedDefinition && 16363 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16364 Func->getMemberSpecializationInfo())) 16365 checkSpecializationVisibility(Loc, Func); 16366 16367 if (getLangOpts().CUDA) 16368 CheckCUDACall(Loc, Func); 16369 16370 // If we need a definition, try to create one. 16371 if (NeedDefinition && !Func->getBody()) { 16372 runWithSufficientStackSpace(Loc, [&] { 16373 if (CXXConstructorDecl *Constructor = 16374 dyn_cast<CXXConstructorDecl>(Func)) { 16375 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16376 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16377 if (Constructor->isDefaultConstructor()) { 16378 if (Constructor->isTrivial() && 16379 !Constructor->hasAttr<DLLExportAttr>()) 16380 return; 16381 DefineImplicitDefaultConstructor(Loc, Constructor); 16382 } else if (Constructor->isCopyConstructor()) { 16383 DefineImplicitCopyConstructor(Loc, Constructor); 16384 } else if (Constructor->isMoveConstructor()) { 16385 DefineImplicitMoveConstructor(Loc, Constructor); 16386 } 16387 } else if (Constructor->getInheritedConstructor()) { 16388 DefineInheritingConstructor(Loc, Constructor); 16389 } 16390 } else if (CXXDestructorDecl *Destructor = 16391 dyn_cast<CXXDestructorDecl>(Func)) { 16392 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16393 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16394 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16395 return; 16396 DefineImplicitDestructor(Loc, Destructor); 16397 } 16398 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16399 MarkVTableUsed(Loc, Destructor->getParent()); 16400 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16401 if (MethodDecl->isOverloadedOperator() && 16402 MethodDecl->getOverloadedOperator() == OO_Equal) { 16403 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16404 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16405 if (MethodDecl->isCopyAssignmentOperator()) 16406 DefineImplicitCopyAssignment(Loc, MethodDecl); 16407 else if (MethodDecl->isMoveAssignmentOperator()) 16408 DefineImplicitMoveAssignment(Loc, MethodDecl); 16409 } 16410 } else if (isa<CXXConversionDecl>(MethodDecl) && 16411 MethodDecl->getParent()->isLambda()) { 16412 CXXConversionDecl *Conversion = 16413 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16414 if (Conversion->isLambdaToBlockPointerConversion()) 16415 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16416 else 16417 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16418 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16419 MarkVTableUsed(Loc, MethodDecl->getParent()); 16420 } 16421 16422 if (Func->isDefaulted() && !Func->isDeleted()) { 16423 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16424 if (DCK != DefaultedComparisonKind::None) 16425 DefineDefaultedComparison(Loc, Func, DCK); 16426 } 16427 16428 // Implicit instantiation of function templates and member functions of 16429 // class templates. 16430 if (Func->isImplicitlyInstantiable()) { 16431 TemplateSpecializationKind TSK = 16432 Func->getTemplateSpecializationKindForInstantiation(); 16433 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16434 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16435 if (FirstInstantiation) { 16436 PointOfInstantiation = Loc; 16437 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16438 } else if (TSK != TSK_ImplicitInstantiation) { 16439 // Use the point of use as the point of instantiation, instead of the 16440 // point of explicit instantiation (which we track as the actual point 16441 // of instantiation). This gives better backtraces in diagnostics. 16442 PointOfInstantiation = Loc; 16443 } 16444 16445 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16446 Func->isConstexpr()) { 16447 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16448 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16449 CodeSynthesisContexts.size()) 16450 PendingLocalImplicitInstantiations.push_back( 16451 std::make_pair(Func, PointOfInstantiation)); 16452 else if (Func->isConstexpr()) 16453 // Do not defer instantiations of constexpr functions, to avoid the 16454 // expression evaluator needing to call back into Sema if it sees a 16455 // call to such a function. 16456 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16457 else { 16458 Func->setInstantiationIsPending(true); 16459 PendingInstantiations.push_back( 16460 std::make_pair(Func, PointOfInstantiation)); 16461 // Notify the consumer that a function was implicitly instantiated. 16462 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16463 } 16464 } 16465 } else { 16466 // Walk redefinitions, as some of them may be instantiable. 16467 for (auto i : Func->redecls()) { 16468 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16469 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16470 } 16471 } 16472 }); 16473 } 16474 16475 // C++14 [except.spec]p17: 16476 // An exception-specification is considered to be needed when: 16477 // - the function is odr-used or, if it appears in an unevaluated operand, 16478 // would be odr-used if the expression were potentially-evaluated; 16479 // 16480 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16481 // function is a pure virtual function we're calling, and in that case the 16482 // function was selected by overload resolution and we need to resolve its 16483 // exception specification for a different reason. 16484 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16485 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16486 ResolveExceptionSpec(Loc, FPT); 16487 16488 // If this is the first "real" use, act on that. 16489 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16490 // Keep track of used but undefined functions. 16491 if (!Func->isDefined()) { 16492 if (mightHaveNonExternalLinkage(Func)) 16493 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16494 else if (Func->getMostRecentDecl()->isInlined() && 16495 !LangOpts.GNUInline && 16496 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16497 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16498 else if (isExternalWithNoLinkageType(Func)) 16499 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16500 } 16501 16502 // Some x86 Windows calling conventions mangle the size of the parameter 16503 // pack into the name. Computing the size of the parameters requires the 16504 // parameter types to be complete. Check that now. 16505 if (funcHasParameterSizeMangling(*this, Func)) 16506 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16507 16508 // In the MS C++ ABI, the compiler emits destructor variants where they are 16509 // used. If the destructor is used here but defined elsewhere, mark the 16510 // virtual base destructors referenced. If those virtual base destructors 16511 // are inline, this will ensure they are defined when emitting the complete 16512 // destructor variant. This checking may be redundant if the destructor is 16513 // provided later in this TU. 16514 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16515 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16516 CXXRecordDecl *Parent = Dtor->getParent(); 16517 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16518 CheckCompleteDestructorVariant(Loc, Dtor); 16519 } 16520 } 16521 16522 Func->markUsed(Context); 16523 } 16524 } 16525 16526 /// Directly mark a variable odr-used. Given a choice, prefer to use 16527 /// MarkVariableReferenced since it does additional checks and then 16528 /// calls MarkVarDeclODRUsed. 16529 /// If the variable must be captured: 16530 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16531 /// - else capture it in the DeclContext that maps to the 16532 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16533 static void 16534 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16535 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16536 // Keep track of used but undefined variables. 16537 // FIXME: We shouldn't suppress this warning for static data members. 16538 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16539 (!Var->isExternallyVisible() || Var->isInline() || 16540 SemaRef.isExternalWithNoLinkageType(Var)) && 16541 !(Var->isStaticDataMember() && Var->hasInit())) { 16542 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16543 if (old.isInvalid()) 16544 old = Loc; 16545 } 16546 QualType CaptureType, DeclRefType; 16547 if (SemaRef.LangOpts.OpenMP) 16548 SemaRef.tryCaptureOpenMPLambdas(Var); 16549 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16550 /*EllipsisLoc*/ SourceLocation(), 16551 /*BuildAndDiagnose*/ true, 16552 CaptureType, DeclRefType, 16553 FunctionScopeIndexToStopAt); 16554 16555 Var->markUsed(SemaRef.Context); 16556 } 16557 16558 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16559 SourceLocation Loc, 16560 unsigned CapturingScopeIndex) { 16561 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16562 } 16563 16564 static void 16565 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16566 ValueDecl *var, DeclContext *DC) { 16567 DeclContext *VarDC = var->getDeclContext(); 16568 16569 // If the parameter still belongs to the translation unit, then 16570 // we're actually just using one parameter in the declaration of 16571 // the next. 16572 if (isa<ParmVarDecl>(var) && 16573 isa<TranslationUnitDecl>(VarDC)) 16574 return; 16575 16576 // For C code, don't diagnose about capture if we're not actually in code 16577 // right now; it's impossible to write a non-constant expression outside of 16578 // function context, so we'll get other (more useful) diagnostics later. 16579 // 16580 // For C++, things get a bit more nasty... it would be nice to suppress this 16581 // diagnostic for certain cases like using a local variable in an array bound 16582 // for a member of a local class, but the correct predicate is not obvious. 16583 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16584 return; 16585 16586 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16587 unsigned ContextKind = 3; // unknown 16588 if (isa<CXXMethodDecl>(VarDC) && 16589 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16590 ContextKind = 2; 16591 } else if (isa<FunctionDecl>(VarDC)) { 16592 ContextKind = 0; 16593 } else if (isa<BlockDecl>(VarDC)) { 16594 ContextKind = 1; 16595 } 16596 16597 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16598 << var << ValueKind << ContextKind << VarDC; 16599 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16600 << var; 16601 16602 // FIXME: Add additional diagnostic info about class etc. which prevents 16603 // capture. 16604 } 16605 16606 16607 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16608 bool &SubCapturesAreNested, 16609 QualType &CaptureType, 16610 QualType &DeclRefType) { 16611 // Check whether we've already captured it. 16612 if (CSI->CaptureMap.count(Var)) { 16613 // If we found a capture, any subcaptures are nested. 16614 SubCapturesAreNested = true; 16615 16616 // Retrieve the capture type for this variable. 16617 CaptureType = CSI->getCapture(Var).getCaptureType(); 16618 16619 // Compute the type of an expression that refers to this variable. 16620 DeclRefType = CaptureType.getNonReferenceType(); 16621 16622 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16623 // are mutable in the sense that user can change their value - they are 16624 // private instances of the captured declarations. 16625 const Capture &Cap = CSI->getCapture(Var); 16626 if (Cap.isCopyCapture() && 16627 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16628 !(isa<CapturedRegionScopeInfo>(CSI) && 16629 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16630 DeclRefType.addConst(); 16631 return true; 16632 } 16633 return false; 16634 } 16635 16636 // Only block literals, captured statements, and lambda expressions can 16637 // capture; other scopes don't work. 16638 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16639 SourceLocation Loc, 16640 const bool Diagnose, Sema &S) { 16641 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16642 return getLambdaAwareParentOfDeclContext(DC); 16643 else if (Var->hasLocalStorage()) { 16644 if (Diagnose) 16645 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16646 } 16647 return nullptr; 16648 } 16649 16650 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16651 // certain types of variables (unnamed, variably modified types etc.) 16652 // so check for eligibility. 16653 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16654 SourceLocation Loc, 16655 const bool Diagnose, Sema &S) { 16656 16657 bool IsBlock = isa<BlockScopeInfo>(CSI); 16658 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16659 16660 // Lambdas are not allowed to capture unnamed variables 16661 // (e.g. anonymous unions). 16662 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16663 // assuming that's the intent. 16664 if (IsLambda && !Var->getDeclName()) { 16665 if (Diagnose) { 16666 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16667 S.Diag(Var->getLocation(), diag::note_declared_at); 16668 } 16669 return false; 16670 } 16671 16672 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16673 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16674 if (Diagnose) { 16675 S.Diag(Loc, diag::err_ref_vm_type); 16676 S.Diag(Var->getLocation(), diag::note_previous_decl) 16677 << Var->getDeclName(); 16678 } 16679 return false; 16680 } 16681 // Prohibit structs with flexible array members too. 16682 // We cannot capture what is in the tail end of the struct. 16683 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16684 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16685 if (Diagnose) { 16686 if (IsBlock) 16687 S.Diag(Loc, diag::err_ref_flexarray_type); 16688 else 16689 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16690 << Var->getDeclName(); 16691 S.Diag(Var->getLocation(), diag::note_previous_decl) 16692 << Var->getDeclName(); 16693 } 16694 return false; 16695 } 16696 } 16697 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16698 // Lambdas and captured statements are not allowed to capture __block 16699 // variables; they don't support the expected semantics. 16700 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16701 if (Diagnose) { 16702 S.Diag(Loc, diag::err_capture_block_variable) 16703 << Var->getDeclName() << !IsLambda; 16704 S.Diag(Var->getLocation(), diag::note_previous_decl) 16705 << Var->getDeclName(); 16706 } 16707 return false; 16708 } 16709 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16710 if (S.getLangOpts().OpenCL && IsBlock && 16711 Var->getType()->isBlockPointerType()) { 16712 if (Diagnose) 16713 S.Diag(Loc, diag::err_opencl_block_ref_block); 16714 return false; 16715 } 16716 16717 return true; 16718 } 16719 16720 // Returns true if the capture by block was successful. 16721 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16722 SourceLocation Loc, 16723 const bool BuildAndDiagnose, 16724 QualType &CaptureType, 16725 QualType &DeclRefType, 16726 const bool Nested, 16727 Sema &S, bool Invalid) { 16728 bool ByRef = false; 16729 16730 // Blocks are not allowed to capture arrays, excepting OpenCL. 16731 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16732 // (decayed to pointers). 16733 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16734 if (BuildAndDiagnose) { 16735 S.Diag(Loc, diag::err_ref_array_type); 16736 S.Diag(Var->getLocation(), diag::note_previous_decl) 16737 << Var->getDeclName(); 16738 Invalid = true; 16739 } else { 16740 return false; 16741 } 16742 } 16743 16744 // Forbid the block-capture of autoreleasing variables. 16745 if (!Invalid && 16746 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16747 if (BuildAndDiagnose) { 16748 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16749 << /*block*/ 0; 16750 S.Diag(Var->getLocation(), diag::note_previous_decl) 16751 << Var->getDeclName(); 16752 Invalid = true; 16753 } else { 16754 return false; 16755 } 16756 } 16757 16758 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16759 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16760 QualType PointeeTy = PT->getPointeeType(); 16761 16762 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16763 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16764 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16765 if (BuildAndDiagnose) { 16766 SourceLocation VarLoc = Var->getLocation(); 16767 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16768 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16769 } 16770 } 16771 } 16772 16773 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16774 if (HasBlocksAttr || CaptureType->isReferenceType() || 16775 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16776 // Block capture by reference does not change the capture or 16777 // declaration reference types. 16778 ByRef = true; 16779 } else { 16780 // Block capture by copy introduces 'const'. 16781 CaptureType = CaptureType.getNonReferenceType().withConst(); 16782 DeclRefType = CaptureType; 16783 } 16784 16785 // Actually capture the variable. 16786 if (BuildAndDiagnose) 16787 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16788 CaptureType, Invalid); 16789 16790 return !Invalid; 16791 } 16792 16793 16794 /// Capture the given variable in the captured region. 16795 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16796 VarDecl *Var, 16797 SourceLocation Loc, 16798 const bool BuildAndDiagnose, 16799 QualType &CaptureType, 16800 QualType &DeclRefType, 16801 const bool RefersToCapturedVariable, 16802 Sema &S, bool Invalid) { 16803 // By default, capture variables by reference. 16804 bool ByRef = true; 16805 // Using an LValue reference type is consistent with Lambdas (see below). 16806 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16807 if (S.isOpenMPCapturedDecl(Var)) { 16808 bool HasConst = DeclRefType.isConstQualified(); 16809 DeclRefType = DeclRefType.getUnqualifiedType(); 16810 // Don't lose diagnostics about assignments to const. 16811 if (HasConst) 16812 DeclRefType.addConst(); 16813 } 16814 // Do not capture firstprivates in tasks. 16815 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 16816 OMPC_unknown) 16817 return true; 16818 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16819 RSI->OpenMPCaptureLevel); 16820 } 16821 16822 if (ByRef) 16823 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16824 else 16825 CaptureType = DeclRefType; 16826 16827 // Actually capture the variable. 16828 if (BuildAndDiagnose) 16829 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16830 Loc, SourceLocation(), CaptureType, Invalid); 16831 16832 return !Invalid; 16833 } 16834 16835 /// Capture the given variable in the lambda. 16836 static bool captureInLambda(LambdaScopeInfo *LSI, 16837 VarDecl *Var, 16838 SourceLocation Loc, 16839 const bool BuildAndDiagnose, 16840 QualType &CaptureType, 16841 QualType &DeclRefType, 16842 const bool RefersToCapturedVariable, 16843 const Sema::TryCaptureKind Kind, 16844 SourceLocation EllipsisLoc, 16845 const bool IsTopScope, 16846 Sema &S, bool Invalid) { 16847 // Determine whether we are capturing by reference or by value. 16848 bool ByRef = false; 16849 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16850 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16851 } else { 16852 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16853 } 16854 16855 // Compute the type of the field that will capture this variable. 16856 if (ByRef) { 16857 // C++11 [expr.prim.lambda]p15: 16858 // An entity is captured by reference if it is implicitly or 16859 // explicitly captured but not captured by copy. It is 16860 // unspecified whether additional unnamed non-static data 16861 // members are declared in the closure type for entities 16862 // captured by reference. 16863 // 16864 // FIXME: It is not clear whether we want to build an lvalue reference 16865 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16866 // to do the former, while EDG does the latter. Core issue 1249 will 16867 // clarify, but for now we follow GCC because it's a more permissive and 16868 // easily defensible position. 16869 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16870 } else { 16871 // C++11 [expr.prim.lambda]p14: 16872 // For each entity captured by copy, an unnamed non-static 16873 // data member is declared in the closure type. The 16874 // declaration order of these members is unspecified. The type 16875 // of such a data member is the type of the corresponding 16876 // captured entity if the entity is not a reference to an 16877 // object, or the referenced type otherwise. [Note: If the 16878 // captured entity is a reference to a function, the 16879 // corresponding data member is also a reference to a 16880 // function. - end note ] 16881 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16882 if (!RefType->getPointeeType()->isFunctionType()) 16883 CaptureType = RefType->getPointeeType(); 16884 } 16885 16886 // Forbid the lambda copy-capture of autoreleasing variables. 16887 if (!Invalid && 16888 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16889 if (BuildAndDiagnose) { 16890 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16891 S.Diag(Var->getLocation(), diag::note_previous_decl) 16892 << Var->getDeclName(); 16893 Invalid = true; 16894 } else { 16895 return false; 16896 } 16897 } 16898 16899 // Make sure that by-copy captures are of a complete and non-abstract type. 16900 if (!Invalid && BuildAndDiagnose) { 16901 if (!CaptureType->isDependentType() && 16902 S.RequireCompleteSizedType( 16903 Loc, CaptureType, 16904 diag::err_capture_of_incomplete_or_sizeless_type, 16905 Var->getDeclName())) 16906 Invalid = true; 16907 else if (S.RequireNonAbstractType(Loc, CaptureType, 16908 diag::err_capture_of_abstract_type)) 16909 Invalid = true; 16910 } 16911 } 16912 16913 // Compute the type of a reference to this captured variable. 16914 if (ByRef) 16915 DeclRefType = CaptureType.getNonReferenceType(); 16916 else { 16917 // C++ [expr.prim.lambda]p5: 16918 // The closure type for a lambda-expression has a public inline 16919 // function call operator [...]. This function call operator is 16920 // declared const (9.3.1) if and only if the lambda-expression's 16921 // parameter-declaration-clause is not followed by mutable. 16922 DeclRefType = CaptureType.getNonReferenceType(); 16923 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16924 DeclRefType.addConst(); 16925 } 16926 16927 // Add the capture. 16928 if (BuildAndDiagnose) 16929 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16930 Loc, EllipsisLoc, CaptureType, Invalid); 16931 16932 return !Invalid; 16933 } 16934 16935 bool Sema::tryCaptureVariable( 16936 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16937 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16938 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16939 // An init-capture is notionally from the context surrounding its 16940 // declaration, but its parent DC is the lambda class. 16941 DeclContext *VarDC = Var->getDeclContext(); 16942 if (Var->isInitCapture()) 16943 VarDC = VarDC->getParent(); 16944 16945 DeclContext *DC = CurContext; 16946 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16947 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16948 // We need to sync up the Declaration Context with the 16949 // FunctionScopeIndexToStopAt 16950 if (FunctionScopeIndexToStopAt) { 16951 unsigned FSIndex = FunctionScopes.size() - 1; 16952 while (FSIndex != MaxFunctionScopesIndex) { 16953 DC = getLambdaAwareParentOfDeclContext(DC); 16954 --FSIndex; 16955 } 16956 } 16957 16958 16959 // If the variable is declared in the current context, there is no need to 16960 // capture it. 16961 if (VarDC == DC) return true; 16962 16963 // Capture global variables if it is required to use private copy of this 16964 // variable. 16965 bool IsGlobal = !Var->hasLocalStorage(); 16966 if (IsGlobal && 16967 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16968 MaxFunctionScopesIndex))) 16969 return true; 16970 Var = Var->getCanonicalDecl(); 16971 16972 // Walk up the stack to determine whether we can capture the variable, 16973 // performing the "simple" checks that don't depend on type. We stop when 16974 // we've either hit the declared scope of the variable or find an existing 16975 // capture of that variable. We start from the innermost capturing-entity 16976 // (the DC) and ensure that all intervening capturing-entities 16977 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16978 // declcontext can either capture the variable or have already captured 16979 // the variable. 16980 CaptureType = Var->getType(); 16981 DeclRefType = CaptureType.getNonReferenceType(); 16982 bool Nested = false; 16983 bool Explicit = (Kind != TryCapture_Implicit); 16984 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16985 do { 16986 // Only block literals, captured statements, and lambda expressions can 16987 // capture; other scopes don't work. 16988 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16989 ExprLoc, 16990 BuildAndDiagnose, 16991 *this); 16992 // We need to check for the parent *first* because, if we *have* 16993 // private-captured a global variable, we need to recursively capture it in 16994 // intermediate blocks, lambdas, etc. 16995 if (!ParentDC) { 16996 if (IsGlobal) { 16997 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16998 break; 16999 } 17000 return true; 17001 } 17002 17003 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17004 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17005 17006 17007 // Check whether we've already captured it. 17008 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17009 DeclRefType)) { 17010 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17011 break; 17012 } 17013 // If we are instantiating a generic lambda call operator body, 17014 // we do not want to capture new variables. What was captured 17015 // during either a lambdas transformation or initial parsing 17016 // should be used. 17017 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17018 if (BuildAndDiagnose) { 17019 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17020 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17021 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17022 Diag(Var->getLocation(), diag::note_previous_decl) 17023 << Var->getDeclName(); 17024 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17025 } else 17026 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17027 } 17028 return true; 17029 } 17030 17031 // Try to capture variable-length arrays types. 17032 if (Var->getType()->isVariablyModifiedType()) { 17033 // We're going to walk down into the type and look for VLA 17034 // expressions. 17035 QualType QTy = Var->getType(); 17036 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17037 QTy = PVD->getOriginalType(); 17038 captureVariablyModifiedType(Context, QTy, CSI); 17039 } 17040 17041 if (getLangOpts().OpenMP) { 17042 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17043 // OpenMP private variables should not be captured in outer scope, so 17044 // just break here. Similarly, global variables that are captured in a 17045 // target region should not be captured outside the scope of the region. 17046 if (RSI->CapRegionKind == CR_OpenMP) { 17047 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17048 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17049 // If the variable is private (i.e. not captured) and has variably 17050 // modified type, we still need to capture the type for correct 17051 // codegen in all regions, associated with the construct. Currently, 17052 // it is captured in the innermost captured region only. 17053 if (IsOpenMPPrivateDecl != OMPC_unknown && 17054 Var->getType()->isVariablyModifiedType()) { 17055 QualType QTy = Var->getType(); 17056 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17057 QTy = PVD->getOriginalType(); 17058 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17059 I < E; ++I) { 17060 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17061 FunctionScopes[FunctionScopesIndex - I]); 17062 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17063 "Wrong number of captured regions associated with the " 17064 "OpenMP construct."); 17065 captureVariablyModifiedType(Context, QTy, OuterRSI); 17066 } 17067 } 17068 bool IsTargetCap = 17069 IsOpenMPPrivateDecl != OMPC_private && 17070 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17071 RSI->OpenMPCaptureLevel); 17072 // Do not capture global if it is not privatized in outer regions. 17073 bool IsGlobalCap = 17074 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17075 RSI->OpenMPCaptureLevel); 17076 17077 // When we detect target captures we are looking from inside the 17078 // target region, therefore we need to propagate the capture from the 17079 // enclosing region. Therefore, the capture is not initially nested. 17080 if (IsTargetCap) 17081 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17082 17083 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17084 (IsGlobal && !IsGlobalCap)) { 17085 Nested = !IsTargetCap; 17086 DeclRefType = DeclRefType.getUnqualifiedType(); 17087 CaptureType = Context.getLValueReferenceType(DeclRefType); 17088 break; 17089 } 17090 } 17091 } 17092 } 17093 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17094 // No capture-default, and this is not an explicit capture 17095 // so cannot capture this variable. 17096 if (BuildAndDiagnose) { 17097 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17098 Diag(Var->getLocation(), diag::note_previous_decl) 17099 << Var->getDeclName(); 17100 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17101 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17102 diag::note_lambda_decl); 17103 // FIXME: If we error out because an outer lambda can not implicitly 17104 // capture a variable that an inner lambda explicitly captures, we 17105 // should have the inner lambda do the explicit capture - because 17106 // it makes for cleaner diagnostics later. This would purely be done 17107 // so that the diagnostic does not misleadingly claim that a variable 17108 // can not be captured by a lambda implicitly even though it is captured 17109 // explicitly. Suggestion: 17110 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17111 // at the function head 17112 // - cache the StartingDeclContext - this must be a lambda 17113 // - captureInLambda in the innermost lambda the variable. 17114 } 17115 return true; 17116 } 17117 17118 FunctionScopesIndex--; 17119 DC = ParentDC; 17120 Explicit = false; 17121 } while (!VarDC->Equals(DC)); 17122 17123 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17124 // computing the type of the capture at each step, checking type-specific 17125 // requirements, and adding captures if requested. 17126 // If the variable had already been captured previously, we start capturing 17127 // at the lambda nested within that one. 17128 bool Invalid = false; 17129 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17130 ++I) { 17131 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17132 17133 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17134 // certain types of variables (unnamed, variably modified types etc.) 17135 // so check for eligibility. 17136 if (!Invalid) 17137 Invalid = 17138 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17139 17140 // After encountering an error, if we're actually supposed to capture, keep 17141 // capturing in nested contexts to suppress any follow-on diagnostics. 17142 if (Invalid && !BuildAndDiagnose) 17143 return true; 17144 17145 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17146 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17147 DeclRefType, Nested, *this, Invalid); 17148 Nested = true; 17149 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17150 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17151 CaptureType, DeclRefType, Nested, 17152 *this, Invalid); 17153 Nested = true; 17154 } else { 17155 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17156 Invalid = 17157 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17158 DeclRefType, Nested, Kind, EllipsisLoc, 17159 /*IsTopScope*/ I == N - 1, *this, Invalid); 17160 Nested = true; 17161 } 17162 17163 if (Invalid && !BuildAndDiagnose) 17164 return true; 17165 } 17166 return Invalid; 17167 } 17168 17169 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17170 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17171 QualType CaptureType; 17172 QualType DeclRefType; 17173 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17174 /*BuildAndDiagnose=*/true, CaptureType, 17175 DeclRefType, nullptr); 17176 } 17177 17178 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17179 QualType CaptureType; 17180 QualType DeclRefType; 17181 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17182 /*BuildAndDiagnose=*/false, CaptureType, 17183 DeclRefType, nullptr); 17184 } 17185 17186 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17187 QualType CaptureType; 17188 QualType DeclRefType; 17189 17190 // Determine whether we can capture this variable. 17191 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17192 /*BuildAndDiagnose=*/false, CaptureType, 17193 DeclRefType, nullptr)) 17194 return QualType(); 17195 17196 return DeclRefType; 17197 } 17198 17199 namespace { 17200 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17201 // The produced TemplateArgumentListInfo* points to data stored within this 17202 // object, so should only be used in contexts where the pointer will not be 17203 // used after the CopiedTemplateArgs object is destroyed. 17204 class CopiedTemplateArgs { 17205 bool HasArgs; 17206 TemplateArgumentListInfo TemplateArgStorage; 17207 public: 17208 template<typename RefExpr> 17209 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17210 if (HasArgs) 17211 E->copyTemplateArgumentsInto(TemplateArgStorage); 17212 } 17213 operator TemplateArgumentListInfo*() 17214 #ifdef __has_cpp_attribute 17215 #if __has_cpp_attribute(clang::lifetimebound) 17216 [[clang::lifetimebound]] 17217 #endif 17218 #endif 17219 { 17220 return HasArgs ? &TemplateArgStorage : nullptr; 17221 } 17222 }; 17223 } 17224 17225 /// Walk the set of potential results of an expression and mark them all as 17226 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17227 /// 17228 /// \return A new expression if we found any potential results, ExprEmpty() if 17229 /// not, and ExprError() if we diagnosed an error. 17230 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17231 NonOdrUseReason NOUR) { 17232 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17233 // an object that satisfies the requirements for appearing in a 17234 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17235 // is immediately applied." This function handles the lvalue-to-rvalue 17236 // conversion part. 17237 // 17238 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17239 // transform it into the relevant kind of non-odr-use node and rebuild the 17240 // tree of nodes leading to it. 17241 // 17242 // This is a mini-TreeTransform that only transforms a restricted subset of 17243 // nodes (and only certain operands of them). 17244 17245 // Rebuild a subexpression. 17246 auto Rebuild = [&](Expr *Sub) { 17247 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17248 }; 17249 17250 // Check whether a potential result satisfies the requirements of NOUR. 17251 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17252 // Any entity other than a VarDecl is always odr-used whenever it's named 17253 // in a potentially-evaluated expression. 17254 auto *VD = dyn_cast<VarDecl>(D); 17255 if (!VD) 17256 return true; 17257 17258 // C++2a [basic.def.odr]p4: 17259 // A variable x whose name appears as a potentially-evalauted expression 17260 // e is odr-used by e unless 17261 // -- x is a reference that is usable in constant expressions, or 17262 // -- x is a variable of non-reference type that is usable in constant 17263 // expressions and has no mutable subobjects, and e is an element of 17264 // the set of potential results of an expression of 17265 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17266 // conversion is applied, or 17267 // -- x is a variable of non-reference type, and e is an element of the 17268 // set of potential results of a discarded-value expression to which 17269 // the lvalue-to-rvalue conversion is not applied 17270 // 17271 // We check the first bullet and the "potentially-evaluated" condition in 17272 // BuildDeclRefExpr. We check the type requirements in the second bullet 17273 // in CheckLValueToRValueConversionOperand below. 17274 switch (NOUR) { 17275 case NOUR_None: 17276 case NOUR_Unevaluated: 17277 llvm_unreachable("unexpected non-odr-use-reason"); 17278 17279 case NOUR_Constant: 17280 // Constant references were handled when they were built. 17281 if (VD->getType()->isReferenceType()) 17282 return true; 17283 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17284 if (RD->hasMutableFields()) 17285 return true; 17286 if (!VD->isUsableInConstantExpressions(S.Context)) 17287 return true; 17288 break; 17289 17290 case NOUR_Discarded: 17291 if (VD->getType()->isReferenceType()) 17292 return true; 17293 break; 17294 } 17295 return false; 17296 }; 17297 17298 // Mark that this expression does not constitute an odr-use. 17299 auto MarkNotOdrUsed = [&] { 17300 S.MaybeODRUseExprs.erase(E); 17301 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17302 LSI->markVariableExprAsNonODRUsed(E); 17303 }; 17304 17305 // C++2a [basic.def.odr]p2: 17306 // The set of potential results of an expression e is defined as follows: 17307 switch (E->getStmtClass()) { 17308 // -- If e is an id-expression, ... 17309 case Expr::DeclRefExprClass: { 17310 auto *DRE = cast<DeclRefExpr>(E); 17311 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17312 break; 17313 17314 // Rebuild as a non-odr-use DeclRefExpr. 17315 MarkNotOdrUsed(); 17316 return DeclRefExpr::Create( 17317 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17318 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17319 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17320 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17321 } 17322 17323 case Expr::FunctionParmPackExprClass: { 17324 auto *FPPE = cast<FunctionParmPackExpr>(E); 17325 // If any of the declarations in the pack is odr-used, then the expression 17326 // as a whole constitutes an odr-use. 17327 for (VarDecl *D : *FPPE) 17328 if (IsPotentialResultOdrUsed(D)) 17329 return ExprEmpty(); 17330 17331 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17332 // nothing cares about whether we marked this as an odr-use, but it might 17333 // be useful for non-compiler tools. 17334 MarkNotOdrUsed(); 17335 break; 17336 } 17337 17338 // -- If e is a subscripting operation with an array operand... 17339 case Expr::ArraySubscriptExprClass: { 17340 auto *ASE = cast<ArraySubscriptExpr>(E); 17341 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17342 if (!OldBase->getType()->isArrayType()) 17343 break; 17344 ExprResult Base = Rebuild(OldBase); 17345 if (!Base.isUsable()) 17346 return Base; 17347 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17348 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17349 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17350 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17351 ASE->getRBracketLoc()); 17352 } 17353 17354 case Expr::MemberExprClass: { 17355 auto *ME = cast<MemberExpr>(E); 17356 // -- If e is a class member access expression [...] naming a non-static 17357 // data member... 17358 if (isa<FieldDecl>(ME->getMemberDecl())) { 17359 ExprResult Base = Rebuild(ME->getBase()); 17360 if (!Base.isUsable()) 17361 return Base; 17362 return MemberExpr::Create( 17363 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17364 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17365 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17366 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17367 ME->getObjectKind(), ME->isNonOdrUse()); 17368 } 17369 17370 if (ME->getMemberDecl()->isCXXInstanceMember()) 17371 break; 17372 17373 // -- If e is a class member access expression naming a static data member, 17374 // ... 17375 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17376 break; 17377 17378 // Rebuild as a non-odr-use MemberExpr. 17379 MarkNotOdrUsed(); 17380 return MemberExpr::Create( 17381 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17382 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17383 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17384 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17385 return ExprEmpty(); 17386 } 17387 17388 case Expr::BinaryOperatorClass: { 17389 auto *BO = cast<BinaryOperator>(E); 17390 Expr *LHS = BO->getLHS(); 17391 Expr *RHS = BO->getRHS(); 17392 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17393 if (BO->getOpcode() == BO_PtrMemD) { 17394 ExprResult Sub = Rebuild(LHS); 17395 if (!Sub.isUsable()) 17396 return Sub; 17397 LHS = Sub.get(); 17398 // -- If e is a comma expression, ... 17399 } else if (BO->getOpcode() == BO_Comma) { 17400 ExprResult Sub = Rebuild(RHS); 17401 if (!Sub.isUsable()) 17402 return Sub; 17403 RHS = Sub.get(); 17404 } else { 17405 break; 17406 } 17407 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17408 LHS, RHS); 17409 } 17410 17411 // -- If e has the form (e1)... 17412 case Expr::ParenExprClass: { 17413 auto *PE = cast<ParenExpr>(E); 17414 ExprResult Sub = Rebuild(PE->getSubExpr()); 17415 if (!Sub.isUsable()) 17416 return Sub; 17417 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17418 } 17419 17420 // -- If e is a glvalue conditional expression, ... 17421 // We don't apply this to a binary conditional operator. FIXME: Should we? 17422 case Expr::ConditionalOperatorClass: { 17423 auto *CO = cast<ConditionalOperator>(E); 17424 ExprResult LHS = Rebuild(CO->getLHS()); 17425 if (LHS.isInvalid()) 17426 return ExprError(); 17427 ExprResult RHS = Rebuild(CO->getRHS()); 17428 if (RHS.isInvalid()) 17429 return ExprError(); 17430 if (!LHS.isUsable() && !RHS.isUsable()) 17431 return ExprEmpty(); 17432 if (!LHS.isUsable()) 17433 LHS = CO->getLHS(); 17434 if (!RHS.isUsable()) 17435 RHS = CO->getRHS(); 17436 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17437 CO->getCond(), LHS.get(), RHS.get()); 17438 } 17439 17440 // [Clang extension] 17441 // -- If e has the form __extension__ e1... 17442 case Expr::UnaryOperatorClass: { 17443 auto *UO = cast<UnaryOperator>(E); 17444 if (UO->getOpcode() != UO_Extension) 17445 break; 17446 ExprResult Sub = Rebuild(UO->getSubExpr()); 17447 if (!Sub.isUsable()) 17448 return Sub; 17449 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17450 Sub.get()); 17451 } 17452 17453 // [Clang extension] 17454 // -- If e has the form _Generic(...), the set of potential results is the 17455 // union of the sets of potential results of the associated expressions. 17456 case Expr::GenericSelectionExprClass: { 17457 auto *GSE = cast<GenericSelectionExpr>(E); 17458 17459 SmallVector<Expr *, 4> AssocExprs; 17460 bool AnyChanged = false; 17461 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17462 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17463 if (AssocExpr.isInvalid()) 17464 return ExprError(); 17465 if (AssocExpr.isUsable()) { 17466 AssocExprs.push_back(AssocExpr.get()); 17467 AnyChanged = true; 17468 } else { 17469 AssocExprs.push_back(OrigAssocExpr); 17470 } 17471 } 17472 17473 return AnyChanged ? S.CreateGenericSelectionExpr( 17474 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17475 GSE->getRParenLoc(), GSE->getControllingExpr(), 17476 GSE->getAssocTypeSourceInfos(), AssocExprs) 17477 : ExprEmpty(); 17478 } 17479 17480 // [Clang extension] 17481 // -- If e has the form __builtin_choose_expr(...), the set of potential 17482 // results is the union of the sets of potential results of the 17483 // second and third subexpressions. 17484 case Expr::ChooseExprClass: { 17485 auto *CE = cast<ChooseExpr>(E); 17486 17487 ExprResult LHS = Rebuild(CE->getLHS()); 17488 if (LHS.isInvalid()) 17489 return ExprError(); 17490 17491 ExprResult RHS = Rebuild(CE->getLHS()); 17492 if (RHS.isInvalid()) 17493 return ExprError(); 17494 17495 if (!LHS.get() && !RHS.get()) 17496 return ExprEmpty(); 17497 if (!LHS.isUsable()) 17498 LHS = CE->getLHS(); 17499 if (!RHS.isUsable()) 17500 RHS = CE->getRHS(); 17501 17502 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17503 RHS.get(), CE->getRParenLoc()); 17504 } 17505 17506 // Step through non-syntactic nodes. 17507 case Expr::ConstantExprClass: { 17508 auto *CE = cast<ConstantExpr>(E); 17509 ExprResult Sub = Rebuild(CE->getSubExpr()); 17510 if (!Sub.isUsable()) 17511 return Sub; 17512 return ConstantExpr::Create(S.Context, Sub.get()); 17513 } 17514 17515 // We could mostly rely on the recursive rebuilding to rebuild implicit 17516 // casts, but not at the top level, so rebuild them here. 17517 case Expr::ImplicitCastExprClass: { 17518 auto *ICE = cast<ImplicitCastExpr>(E); 17519 // Only step through the narrow set of cast kinds we expect to encounter. 17520 // Anything else suggests we've left the region in which potential results 17521 // can be found. 17522 switch (ICE->getCastKind()) { 17523 case CK_NoOp: 17524 case CK_DerivedToBase: 17525 case CK_UncheckedDerivedToBase: { 17526 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17527 if (!Sub.isUsable()) 17528 return Sub; 17529 CXXCastPath Path(ICE->path()); 17530 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17531 ICE->getValueKind(), &Path); 17532 } 17533 17534 default: 17535 break; 17536 } 17537 break; 17538 } 17539 17540 default: 17541 break; 17542 } 17543 17544 // Can't traverse through this node. Nothing to do. 17545 return ExprEmpty(); 17546 } 17547 17548 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17549 // Check whether the operand is or contains an object of non-trivial C union 17550 // type. 17551 if (E->getType().isVolatileQualified() && 17552 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17553 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17554 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17555 Sema::NTCUC_LValueToRValueVolatile, 17556 NTCUK_Destruct|NTCUK_Copy); 17557 17558 // C++2a [basic.def.odr]p4: 17559 // [...] an expression of non-volatile-qualified non-class type to which 17560 // the lvalue-to-rvalue conversion is applied [...] 17561 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17562 return E; 17563 17564 ExprResult Result = 17565 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17566 if (Result.isInvalid()) 17567 return ExprError(); 17568 return Result.get() ? Result : E; 17569 } 17570 17571 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17572 Res = CorrectDelayedTyposInExpr(Res); 17573 17574 if (!Res.isUsable()) 17575 return Res; 17576 17577 // If a constant-expression is a reference to a variable where we delay 17578 // deciding whether it is an odr-use, just assume we will apply the 17579 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17580 // (a non-type template argument), we have special handling anyway. 17581 return CheckLValueToRValueConversionOperand(Res.get()); 17582 } 17583 17584 void Sema::CleanupVarDeclMarking() { 17585 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17586 // call. 17587 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17588 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17589 17590 for (Expr *E : LocalMaybeODRUseExprs) { 17591 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17592 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17593 DRE->getLocation(), *this); 17594 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17595 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17596 *this); 17597 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17598 for (VarDecl *VD : *FP) 17599 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17600 } else { 17601 llvm_unreachable("Unexpected expression"); 17602 } 17603 } 17604 17605 assert(MaybeODRUseExprs.empty() && 17606 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17607 } 17608 17609 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17610 VarDecl *Var, Expr *E) { 17611 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17612 isa<FunctionParmPackExpr>(E)) && 17613 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17614 Var->setReferenced(); 17615 17616 if (Var->isInvalidDecl()) 17617 return; 17618 17619 auto *MSI = Var->getMemberSpecializationInfo(); 17620 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17621 : Var->getTemplateSpecializationKind(); 17622 17623 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17624 bool UsableInConstantExpr = 17625 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17626 17627 // C++20 [expr.const]p12: 17628 // A variable [...] is needed for constant evaluation if it is [...] a 17629 // variable whose name appears as a potentially constant evaluated 17630 // expression that is either a contexpr variable or is of non-volatile 17631 // const-qualified integral type or of reference type 17632 bool NeededForConstantEvaluation = 17633 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17634 17635 bool NeedDefinition = 17636 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17637 17638 VarTemplateSpecializationDecl *VarSpec = 17639 dyn_cast<VarTemplateSpecializationDecl>(Var); 17640 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17641 "Can't instantiate a partial template specialization."); 17642 17643 // If this might be a member specialization of a static data member, check 17644 // the specialization is visible. We already did the checks for variable 17645 // template specializations when we created them. 17646 if (NeedDefinition && TSK != TSK_Undeclared && 17647 !isa<VarTemplateSpecializationDecl>(Var)) 17648 SemaRef.checkSpecializationVisibility(Loc, Var); 17649 17650 // Perform implicit instantiation of static data members, static data member 17651 // templates of class templates, and variable template specializations. Delay 17652 // instantiations of variable templates, except for those that could be used 17653 // in a constant expression. 17654 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17655 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17656 // instantiation declaration if a variable is usable in a constant 17657 // expression (among other cases). 17658 bool TryInstantiating = 17659 TSK == TSK_ImplicitInstantiation || 17660 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17661 17662 if (TryInstantiating) { 17663 SourceLocation PointOfInstantiation = 17664 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17665 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17666 if (FirstInstantiation) { 17667 PointOfInstantiation = Loc; 17668 if (MSI) 17669 MSI->setPointOfInstantiation(PointOfInstantiation); 17670 else 17671 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17672 } 17673 17674 bool InstantiationDependent = false; 17675 bool IsNonDependent = 17676 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17677 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17678 : true; 17679 17680 // Do not instantiate specializations that are still type-dependent. 17681 if (IsNonDependent) { 17682 if (UsableInConstantExpr) { 17683 // Do not defer instantiations of variables that could be used in a 17684 // constant expression. 17685 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17686 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17687 }); 17688 } else if (FirstInstantiation || 17689 isa<VarTemplateSpecializationDecl>(Var)) { 17690 // FIXME: For a specialization of a variable template, we don't 17691 // distinguish between "declaration and type implicitly instantiated" 17692 // and "implicit instantiation of definition requested", so we have 17693 // no direct way to avoid enqueueing the pending instantiation 17694 // multiple times. 17695 SemaRef.PendingInstantiations 17696 .push_back(std::make_pair(Var, PointOfInstantiation)); 17697 } 17698 } 17699 } 17700 } 17701 17702 // C++2a [basic.def.odr]p4: 17703 // A variable x whose name appears as a potentially-evaluated expression e 17704 // is odr-used by e unless 17705 // -- x is a reference that is usable in constant expressions 17706 // -- x is a variable of non-reference type that is usable in constant 17707 // expressions and has no mutable subobjects [FIXME], and e is an 17708 // element of the set of potential results of an expression of 17709 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17710 // conversion is applied 17711 // -- x is a variable of non-reference type, and e is an element of the set 17712 // of potential results of a discarded-value expression to which the 17713 // lvalue-to-rvalue conversion is not applied [FIXME] 17714 // 17715 // We check the first part of the second bullet here, and 17716 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17717 // FIXME: To get the third bullet right, we need to delay this even for 17718 // variables that are not usable in constant expressions. 17719 17720 // If we already know this isn't an odr-use, there's nothing more to do. 17721 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17722 if (DRE->isNonOdrUse()) 17723 return; 17724 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17725 if (ME->isNonOdrUse()) 17726 return; 17727 17728 switch (OdrUse) { 17729 case OdrUseContext::None: 17730 assert((!E || isa<FunctionParmPackExpr>(E)) && 17731 "missing non-odr-use marking for unevaluated decl ref"); 17732 break; 17733 17734 case OdrUseContext::FormallyOdrUsed: 17735 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17736 // behavior. 17737 break; 17738 17739 case OdrUseContext::Used: 17740 // If we might later find that this expression isn't actually an odr-use, 17741 // delay the marking. 17742 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17743 SemaRef.MaybeODRUseExprs.insert(E); 17744 else 17745 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17746 break; 17747 17748 case OdrUseContext::Dependent: 17749 // If this is a dependent context, we don't need to mark variables as 17750 // odr-used, but we may still need to track them for lambda capture. 17751 // FIXME: Do we also need to do this inside dependent typeid expressions 17752 // (which are modeled as unevaluated at this point)? 17753 const bool RefersToEnclosingScope = 17754 (SemaRef.CurContext != Var->getDeclContext() && 17755 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17756 if (RefersToEnclosingScope) { 17757 LambdaScopeInfo *const LSI = 17758 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17759 if (LSI && (!LSI->CallOperator || 17760 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17761 // If a variable could potentially be odr-used, defer marking it so 17762 // until we finish analyzing the full expression for any 17763 // lvalue-to-rvalue 17764 // or discarded value conversions that would obviate odr-use. 17765 // Add it to the list of potential captures that will be analyzed 17766 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17767 // unless the variable is a reference that was initialized by a constant 17768 // expression (this will never need to be captured or odr-used). 17769 // 17770 // FIXME: We can simplify this a lot after implementing P0588R1. 17771 assert(E && "Capture variable should be used in an expression."); 17772 if (!Var->getType()->isReferenceType() || 17773 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17774 LSI->addPotentialCapture(E->IgnoreParens()); 17775 } 17776 } 17777 break; 17778 } 17779 } 17780 17781 /// Mark a variable referenced, and check whether it is odr-used 17782 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17783 /// used directly for normal expressions referring to VarDecl. 17784 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17785 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17786 } 17787 17788 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17789 Decl *D, Expr *E, bool MightBeOdrUse) { 17790 if (SemaRef.isInOpenMPDeclareTargetContext()) 17791 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17792 17793 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17794 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17795 return; 17796 } 17797 17798 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17799 17800 // If this is a call to a method via a cast, also mark the method in the 17801 // derived class used in case codegen can devirtualize the call. 17802 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17803 if (!ME) 17804 return; 17805 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17806 if (!MD) 17807 return; 17808 // Only attempt to devirtualize if this is truly a virtual call. 17809 bool IsVirtualCall = MD->isVirtual() && 17810 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17811 if (!IsVirtualCall) 17812 return; 17813 17814 // If it's possible to devirtualize the call, mark the called function 17815 // referenced. 17816 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17817 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17818 if (DM) 17819 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17820 } 17821 17822 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17823 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17824 // TODO: update this with DR# once a defect report is filed. 17825 // C++11 defect. The address of a pure member should not be an ODR use, even 17826 // if it's a qualified reference. 17827 bool OdrUse = true; 17828 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17829 if (Method->isVirtual() && 17830 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17831 OdrUse = false; 17832 17833 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17834 if (!isConstantEvaluated() && FD->isConsteval() && 17835 !RebuildingImmediateInvocation) 17836 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17837 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17838 } 17839 17840 /// Perform reference-marking and odr-use handling for a MemberExpr. 17841 void Sema::MarkMemberReferenced(MemberExpr *E) { 17842 // C++11 [basic.def.odr]p2: 17843 // A non-overloaded function whose name appears as a potentially-evaluated 17844 // expression or a member of a set of candidate functions, if selected by 17845 // overload resolution when referred to from a potentially-evaluated 17846 // expression, is odr-used, unless it is a pure virtual function and its 17847 // name is not explicitly qualified. 17848 bool MightBeOdrUse = true; 17849 if (E->performsVirtualDispatch(getLangOpts())) { 17850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17851 if (Method->isPure()) 17852 MightBeOdrUse = false; 17853 } 17854 SourceLocation Loc = 17855 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17856 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17857 } 17858 17859 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17860 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17861 for (VarDecl *VD : *E) 17862 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17863 } 17864 17865 /// Perform marking for a reference to an arbitrary declaration. It 17866 /// marks the declaration referenced, and performs odr-use checking for 17867 /// functions and variables. This method should not be used when building a 17868 /// normal expression which refers to a variable. 17869 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17870 bool MightBeOdrUse) { 17871 if (MightBeOdrUse) { 17872 if (auto *VD = dyn_cast<VarDecl>(D)) { 17873 MarkVariableReferenced(Loc, VD); 17874 return; 17875 } 17876 } 17877 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17878 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17879 return; 17880 } 17881 D->setReferenced(); 17882 } 17883 17884 namespace { 17885 // Mark all of the declarations used by a type as referenced. 17886 // FIXME: Not fully implemented yet! We need to have a better understanding 17887 // of when we're entering a context we should not recurse into. 17888 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17889 // TreeTransforms rebuilding the type in a new context. Rather than 17890 // duplicating the TreeTransform logic, we should consider reusing it here. 17891 // Currently that causes problems when rebuilding LambdaExprs. 17892 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17893 Sema &S; 17894 SourceLocation Loc; 17895 17896 public: 17897 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17898 17899 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17900 17901 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17902 }; 17903 } 17904 17905 bool MarkReferencedDecls::TraverseTemplateArgument( 17906 const TemplateArgument &Arg) { 17907 { 17908 // A non-type template argument is a constant-evaluated context. 17909 EnterExpressionEvaluationContext Evaluated( 17910 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17911 if (Arg.getKind() == TemplateArgument::Declaration) { 17912 if (Decl *D = Arg.getAsDecl()) 17913 S.MarkAnyDeclReferenced(Loc, D, true); 17914 } else if (Arg.getKind() == TemplateArgument::Expression) { 17915 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17916 } 17917 } 17918 17919 return Inherited::TraverseTemplateArgument(Arg); 17920 } 17921 17922 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17923 MarkReferencedDecls Marker(*this, Loc); 17924 Marker.TraverseType(T); 17925 } 17926 17927 namespace { 17928 /// Helper class that marks all of the declarations referenced by 17929 /// potentially-evaluated subexpressions as "referenced". 17930 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 17931 public: 17932 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 17933 bool SkipLocalVariables; 17934 17935 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17936 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 17937 17938 void visitUsedDecl(SourceLocation Loc, Decl *D) { 17939 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 17940 } 17941 17942 void VisitDeclRefExpr(DeclRefExpr *E) { 17943 // If we were asked not to visit local variables, don't. 17944 if (SkipLocalVariables) { 17945 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17946 if (VD->hasLocalStorage()) 17947 return; 17948 } 17949 S.MarkDeclRefReferenced(E); 17950 } 17951 17952 void VisitMemberExpr(MemberExpr *E) { 17953 S.MarkMemberReferenced(E); 17954 Visit(E->getBase()); 17955 } 17956 }; 17957 } // namespace 17958 17959 /// Mark any declarations that appear within this expression or any 17960 /// potentially-evaluated subexpressions as "referenced". 17961 /// 17962 /// \param SkipLocalVariables If true, don't mark local variables as 17963 /// 'referenced'. 17964 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17965 bool SkipLocalVariables) { 17966 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17967 } 17968 17969 /// Emit a diagnostic that describes an effect on the run-time behavior 17970 /// of the program being compiled. 17971 /// 17972 /// This routine emits the given diagnostic when the code currently being 17973 /// type-checked is "potentially evaluated", meaning that there is a 17974 /// possibility that the code will actually be executable. Code in sizeof() 17975 /// expressions, code used only during overload resolution, etc., are not 17976 /// potentially evaluated. This routine will suppress such diagnostics or, 17977 /// in the absolutely nutty case of potentially potentially evaluated 17978 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17979 /// later. 17980 /// 17981 /// This routine should be used for all diagnostics that describe the run-time 17982 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17983 /// Failure to do so will likely result in spurious diagnostics or failures 17984 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17985 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17986 const PartialDiagnostic &PD) { 17987 switch (ExprEvalContexts.back().Context) { 17988 case ExpressionEvaluationContext::Unevaluated: 17989 case ExpressionEvaluationContext::UnevaluatedList: 17990 case ExpressionEvaluationContext::UnevaluatedAbstract: 17991 case ExpressionEvaluationContext::DiscardedStatement: 17992 // The argument will never be evaluated, so don't complain. 17993 break; 17994 17995 case ExpressionEvaluationContext::ConstantEvaluated: 17996 // Relevant diagnostics should be produced by constant evaluation. 17997 break; 17998 17999 case ExpressionEvaluationContext::PotentiallyEvaluated: 18000 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18001 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18002 FunctionScopes.back()->PossiblyUnreachableDiags. 18003 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18004 return true; 18005 } 18006 18007 // The initializer of a constexpr variable or of the first declaration of a 18008 // static data member is not syntactically a constant evaluated constant, 18009 // but nonetheless is always required to be a constant expression, so we 18010 // can skip diagnosing. 18011 // FIXME: Using the mangling context here is a hack. 18012 if (auto *VD = dyn_cast_or_null<VarDecl>( 18013 ExprEvalContexts.back().ManglingContextDecl)) { 18014 if (VD->isConstexpr() || 18015 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18016 break; 18017 // FIXME: For any other kind of variable, we should build a CFG for its 18018 // initializer and check whether the context in question is reachable. 18019 } 18020 18021 Diag(Loc, PD); 18022 return true; 18023 } 18024 18025 return false; 18026 } 18027 18028 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18029 const PartialDiagnostic &PD) { 18030 return DiagRuntimeBehavior( 18031 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18032 } 18033 18034 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18035 CallExpr *CE, FunctionDecl *FD) { 18036 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18037 return false; 18038 18039 // If we're inside a decltype's expression, don't check for a valid return 18040 // type or construct temporaries until we know whether this is the last call. 18041 if (ExprEvalContexts.back().ExprContext == 18042 ExpressionEvaluationContextRecord::EK_Decltype) { 18043 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18044 return false; 18045 } 18046 18047 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18048 FunctionDecl *FD; 18049 CallExpr *CE; 18050 18051 public: 18052 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18053 : FD(FD), CE(CE) { } 18054 18055 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18056 if (!FD) { 18057 S.Diag(Loc, diag::err_call_incomplete_return) 18058 << T << CE->getSourceRange(); 18059 return; 18060 } 18061 18062 S.Diag(Loc, diag::err_call_function_incomplete_return) 18063 << CE->getSourceRange() << FD->getDeclName() << T; 18064 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18065 << FD->getDeclName(); 18066 } 18067 } Diagnoser(FD, CE); 18068 18069 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18070 return true; 18071 18072 return false; 18073 } 18074 18075 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18076 // will prevent this condition from triggering, which is what we want. 18077 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18078 SourceLocation Loc; 18079 18080 unsigned diagnostic = diag::warn_condition_is_assignment; 18081 bool IsOrAssign = false; 18082 18083 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18084 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18085 return; 18086 18087 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18088 18089 // Greylist some idioms by putting them into a warning subcategory. 18090 if (ObjCMessageExpr *ME 18091 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18092 Selector Sel = ME->getSelector(); 18093 18094 // self = [<foo> init...] 18095 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18096 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18097 18098 // <foo> = [<bar> nextObject] 18099 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18100 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18101 } 18102 18103 Loc = Op->getOperatorLoc(); 18104 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18105 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18106 return; 18107 18108 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18109 Loc = Op->getOperatorLoc(); 18110 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18111 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18112 else { 18113 // Not an assignment. 18114 return; 18115 } 18116 18117 Diag(Loc, diagnostic) << E->getSourceRange(); 18118 18119 SourceLocation Open = E->getBeginLoc(); 18120 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18121 Diag(Loc, diag::note_condition_assign_silence) 18122 << FixItHint::CreateInsertion(Open, "(") 18123 << FixItHint::CreateInsertion(Close, ")"); 18124 18125 if (IsOrAssign) 18126 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18127 << FixItHint::CreateReplacement(Loc, "!="); 18128 else 18129 Diag(Loc, diag::note_condition_assign_to_comparison) 18130 << FixItHint::CreateReplacement(Loc, "=="); 18131 } 18132 18133 /// Redundant parentheses over an equality comparison can indicate 18134 /// that the user intended an assignment used as condition. 18135 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18136 // Don't warn if the parens came from a macro. 18137 SourceLocation parenLoc = ParenE->getBeginLoc(); 18138 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18139 return; 18140 // Don't warn for dependent expressions. 18141 if (ParenE->isTypeDependent()) 18142 return; 18143 18144 Expr *E = ParenE->IgnoreParens(); 18145 18146 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18147 if (opE->getOpcode() == BO_EQ && 18148 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18149 == Expr::MLV_Valid) { 18150 SourceLocation Loc = opE->getOperatorLoc(); 18151 18152 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18153 SourceRange ParenERange = ParenE->getSourceRange(); 18154 Diag(Loc, diag::note_equality_comparison_silence) 18155 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18156 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18157 Diag(Loc, diag::note_equality_comparison_to_assign) 18158 << FixItHint::CreateReplacement(Loc, "="); 18159 } 18160 } 18161 18162 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18163 bool IsConstexpr) { 18164 DiagnoseAssignmentAsCondition(E); 18165 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18166 DiagnoseEqualityWithExtraParens(parenE); 18167 18168 ExprResult result = CheckPlaceholderExpr(E); 18169 if (result.isInvalid()) return ExprError(); 18170 E = result.get(); 18171 18172 if (!E->isTypeDependent()) { 18173 if (getLangOpts().CPlusPlus) 18174 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18175 18176 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18177 if (ERes.isInvalid()) 18178 return ExprError(); 18179 E = ERes.get(); 18180 18181 QualType T = E->getType(); 18182 if (!T->isScalarType()) { // C99 6.8.4.1p1 18183 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18184 << T << E->getSourceRange(); 18185 return ExprError(); 18186 } 18187 CheckBoolLikeConversion(E, Loc); 18188 } 18189 18190 return E; 18191 } 18192 18193 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18194 Expr *SubExpr, ConditionKind CK) { 18195 // Empty conditions are valid in for-statements. 18196 if (!SubExpr) 18197 return ConditionResult(); 18198 18199 ExprResult Cond; 18200 switch (CK) { 18201 case ConditionKind::Boolean: 18202 Cond = CheckBooleanCondition(Loc, SubExpr); 18203 break; 18204 18205 case ConditionKind::ConstexprIf: 18206 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18207 break; 18208 18209 case ConditionKind::Switch: 18210 Cond = CheckSwitchCondition(Loc, SubExpr); 18211 break; 18212 } 18213 if (Cond.isInvalid()) 18214 return ConditionError(); 18215 18216 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18217 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18218 if (!FullExpr.get()) 18219 return ConditionError(); 18220 18221 return ConditionResult(*this, nullptr, FullExpr, 18222 CK == ConditionKind::ConstexprIf); 18223 } 18224 18225 namespace { 18226 /// A visitor for rebuilding a call to an __unknown_any expression 18227 /// to have an appropriate type. 18228 struct RebuildUnknownAnyFunction 18229 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18230 18231 Sema &S; 18232 18233 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18234 18235 ExprResult VisitStmt(Stmt *S) { 18236 llvm_unreachable("unexpected statement!"); 18237 } 18238 18239 ExprResult VisitExpr(Expr *E) { 18240 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18241 << E->getSourceRange(); 18242 return ExprError(); 18243 } 18244 18245 /// Rebuild an expression which simply semantically wraps another 18246 /// expression which it shares the type and value kind of. 18247 template <class T> ExprResult rebuildSugarExpr(T *E) { 18248 ExprResult SubResult = Visit(E->getSubExpr()); 18249 if (SubResult.isInvalid()) return ExprError(); 18250 18251 Expr *SubExpr = SubResult.get(); 18252 E->setSubExpr(SubExpr); 18253 E->setType(SubExpr->getType()); 18254 E->setValueKind(SubExpr->getValueKind()); 18255 assert(E->getObjectKind() == OK_Ordinary); 18256 return E; 18257 } 18258 18259 ExprResult VisitParenExpr(ParenExpr *E) { 18260 return rebuildSugarExpr(E); 18261 } 18262 18263 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18264 return rebuildSugarExpr(E); 18265 } 18266 18267 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18268 ExprResult SubResult = Visit(E->getSubExpr()); 18269 if (SubResult.isInvalid()) return ExprError(); 18270 18271 Expr *SubExpr = SubResult.get(); 18272 E->setSubExpr(SubExpr); 18273 E->setType(S.Context.getPointerType(SubExpr->getType())); 18274 assert(E->getValueKind() == VK_RValue); 18275 assert(E->getObjectKind() == OK_Ordinary); 18276 return E; 18277 } 18278 18279 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18280 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18281 18282 E->setType(VD->getType()); 18283 18284 assert(E->getValueKind() == VK_RValue); 18285 if (S.getLangOpts().CPlusPlus && 18286 !(isa<CXXMethodDecl>(VD) && 18287 cast<CXXMethodDecl>(VD)->isInstance())) 18288 E->setValueKind(VK_LValue); 18289 18290 return E; 18291 } 18292 18293 ExprResult VisitMemberExpr(MemberExpr *E) { 18294 return resolveDecl(E, E->getMemberDecl()); 18295 } 18296 18297 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18298 return resolveDecl(E, E->getDecl()); 18299 } 18300 }; 18301 } 18302 18303 /// Given a function expression of unknown-any type, try to rebuild it 18304 /// to have a function type. 18305 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18306 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18307 if (Result.isInvalid()) return ExprError(); 18308 return S.DefaultFunctionArrayConversion(Result.get()); 18309 } 18310 18311 namespace { 18312 /// A visitor for rebuilding an expression of type __unknown_anytype 18313 /// into one which resolves the type directly on the referring 18314 /// expression. Strict preservation of the original source 18315 /// structure is not a goal. 18316 struct RebuildUnknownAnyExpr 18317 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18318 18319 Sema &S; 18320 18321 /// The current destination type. 18322 QualType DestType; 18323 18324 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18325 : S(S), DestType(CastType) {} 18326 18327 ExprResult VisitStmt(Stmt *S) { 18328 llvm_unreachable("unexpected statement!"); 18329 } 18330 18331 ExprResult VisitExpr(Expr *E) { 18332 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18333 << E->getSourceRange(); 18334 return ExprError(); 18335 } 18336 18337 ExprResult VisitCallExpr(CallExpr *E); 18338 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18339 18340 /// Rebuild an expression which simply semantically wraps another 18341 /// expression which it shares the type and value kind of. 18342 template <class T> ExprResult rebuildSugarExpr(T *E) { 18343 ExprResult SubResult = Visit(E->getSubExpr()); 18344 if (SubResult.isInvalid()) return ExprError(); 18345 Expr *SubExpr = SubResult.get(); 18346 E->setSubExpr(SubExpr); 18347 E->setType(SubExpr->getType()); 18348 E->setValueKind(SubExpr->getValueKind()); 18349 assert(E->getObjectKind() == OK_Ordinary); 18350 return E; 18351 } 18352 18353 ExprResult VisitParenExpr(ParenExpr *E) { 18354 return rebuildSugarExpr(E); 18355 } 18356 18357 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18358 return rebuildSugarExpr(E); 18359 } 18360 18361 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18362 const PointerType *Ptr = DestType->getAs<PointerType>(); 18363 if (!Ptr) { 18364 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18365 << E->getSourceRange(); 18366 return ExprError(); 18367 } 18368 18369 if (isa<CallExpr>(E->getSubExpr())) { 18370 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18371 << E->getSourceRange(); 18372 return ExprError(); 18373 } 18374 18375 assert(E->getValueKind() == VK_RValue); 18376 assert(E->getObjectKind() == OK_Ordinary); 18377 E->setType(DestType); 18378 18379 // Build the sub-expression as if it were an object of the pointee type. 18380 DestType = Ptr->getPointeeType(); 18381 ExprResult SubResult = Visit(E->getSubExpr()); 18382 if (SubResult.isInvalid()) return ExprError(); 18383 E->setSubExpr(SubResult.get()); 18384 return E; 18385 } 18386 18387 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18388 18389 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18390 18391 ExprResult VisitMemberExpr(MemberExpr *E) { 18392 return resolveDecl(E, E->getMemberDecl()); 18393 } 18394 18395 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18396 return resolveDecl(E, E->getDecl()); 18397 } 18398 }; 18399 } 18400 18401 /// Rebuilds a call expression which yielded __unknown_anytype. 18402 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18403 Expr *CalleeExpr = E->getCallee(); 18404 18405 enum FnKind { 18406 FK_MemberFunction, 18407 FK_FunctionPointer, 18408 FK_BlockPointer 18409 }; 18410 18411 FnKind Kind; 18412 QualType CalleeType = CalleeExpr->getType(); 18413 if (CalleeType == S.Context.BoundMemberTy) { 18414 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18415 Kind = FK_MemberFunction; 18416 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18417 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18418 CalleeType = Ptr->getPointeeType(); 18419 Kind = FK_FunctionPointer; 18420 } else { 18421 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18422 Kind = FK_BlockPointer; 18423 } 18424 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18425 18426 // Verify that this is a legal result type of a function. 18427 if (DestType->isArrayType() || DestType->isFunctionType()) { 18428 unsigned diagID = diag::err_func_returning_array_function; 18429 if (Kind == FK_BlockPointer) 18430 diagID = diag::err_block_returning_array_function; 18431 18432 S.Diag(E->getExprLoc(), diagID) 18433 << DestType->isFunctionType() << DestType; 18434 return ExprError(); 18435 } 18436 18437 // Otherwise, go ahead and set DestType as the call's result. 18438 E->setType(DestType.getNonLValueExprType(S.Context)); 18439 E->setValueKind(Expr::getValueKindForType(DestType)); 18440 assert(E->getObjectKind() == OK_Ordinary); 18441 18442 // Rebuild the function type, replacing the result type with DestType. 18443 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18444 if (Proto) { 18445 // __unknown_anytype(...) is a special case used by the debugger when 18446 // it has no idea what a function's signature is. 18447 // 18448 // We want to build this call essentially under the K&R 18449 // unprototyped rules, but making a FunctionNoProtoType in C++ 18450 // would foul up all sorts of assumptions. However, we cannot 18451 // simply pass all arguments as variadic arguments, nor can we 18452 // portably just call the function under a non-variadic type; see 18453 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18454 // However, it turns out that in practice it is generally safe to 18455 // call a function declared as "A foo(B,C,D);" under the prototype 18456 // "A foo(B,C,D,...);". The only known exception is with the 18457 // Windows ABI, where any variadic function is implicitly cdecl 18458 // regardless of its normal CC. Therefore we change the parameter 18459 // types to match the types of the arguments. 18460 // 18461 // This is a hack, but it is far superior to moving the 18462 // corresponding target-specific code from IR-gen to Sema/AST. 18463 18464 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18465 SmallVector<QualType, 8> ArgTypes; 18466 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18467 ArgTypes.reserve(E->getNumArgs()); 18468 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18469 Expr *Arg = E->getArg(i); 18470 QualType ArgType = Arg->getType(); 18471 if (E->isLValue()) { 18472 ArgType = S.Context.getLValueReferenceType(ArgType); 18473 } else if (E->isXValue()) { 18474 ArgType = S.Context.getRValueReferenceType(ArgType); 18475 } 18476 ArgTypes.push_back(ArgType); 18477 } 18478 ParamTypes = ArgTypes; 18479 } 18480 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18481 Proto->getExtProtoInfo()); 18482 } else { 18483 DestType = S.Context.getFunctionNoProtoType(DestType, 18484 FnType->getExtInfo()); 18485 } 18486 18487 // Rebuild the appropriate pointer-to-function type. 18488 switch (Kind) { 18489 case FK_MemberFunction: 18490 // Nothing to do. 18491 break; 18492 18493 case FK_FunctionPointer: 18494 DestType = S.Context.getPointerType(DestType); 18495 break; 18496 18497 case FK_BlockPointer: 18498 DestType = S.Context.getBlockPointerType(DestType); 18499 break; 18500 } 18501 18502 // Finally, we can recurse. 18503 ExprResult CalleeResult = Visit(CalleeExpr); 18504 if (!CalleeResult.isUsable()) return ExprError(); 18505 E->setCallee(CalleeResult.get()); 18506 18507 // Bind a temporary if necessary. 18508 return S.MaybeBindToTemporary(E); 18509 } 18510 18511 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18512 // Verify that this is a legal result type of a call. 18513 if (DestType->isArrayType() || DestType->isFunctionType()) { 18514 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18515 << DestType->isFunctionType() << DestType; 18516 return ExprError(); 18517 } 18518 18519 // Rewrite the method result type if available. 18520 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18521 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18522 Method->setReturnType(DestType); 18523 } 18524 18525 // Change the type of the message. 18526 E->setType(DestType.getNonReferenceType()); 18527 E->setValueKind(Expr::getValueKindForType(DestType)); 18528 18529 return S.MaybeBindToTemporary(E); 18530 } 18531 18532 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18533 // The only case we should ever see here is a function-to-pointer decay. 18534 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18535 assert(E->getValueKind() == VK_RValue); 18536 assert(E->getObjectKind() == OK_Ordinary); 18537 18538 E->setType(DestType); 18539 18540 // Rebuild the sub-expression as the pointee (function) type. 18541 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18542 18543 ExprResult Result = Visit(E->getSubExpr()); 18544 if (!Result.isUsable()) return ExprError(); 18545 18546 E->setSubExpr(Result.get()); 18547 return E; 18548 } else if (E->getCastKind() == CK_LValueToRValue) { 18549 assert(E->getValueKind() == VK_RValue); 18550 assert(E->getObjectKind() == OK_Ordinary); 18551 18552 assert(isa<BlockPointerType>(E->getType())); 18553 18554 E->setType(DestType); 18555 18556 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18557 DestType = S.Context.getLValueReferenceType(DestType); 18558 18559 ExprResult Result = Visit(E->getSubExpr()); 18560 if (!Result.isUsable()) return ExprError(); 18561 18562 E->setSubExpr(Result.get()); 18563 return E; 18564 } else { 18565 llvm_unreachable("Unhandled cast type!"); 18566 } 18567 } 18568 18569 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18570 ExprValueKind ValueKind = VK_LValue; 18571 QualType Type = DestType; 18572 18573 // We know how to make this work for certain kinds of decls: 18574 18575 // - functions 18576 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18577 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18578 DestType = Ptr->getPointeeType(); 18579 ExprResult Result = resolveDecl(E, VD); 18580 if (Result.isInvalid()) return ExprError(); 18581 return S.ImpCastExprToType(Result.get(), Type, 18582 CK_FunctionToPointerDecay, VK_RValue); 18583 } 18584 18585 if (!Type->isFunctionType()) { 18586 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18587 << VD << E->getSourceRange(); 18588 return ExprError(); 18589 } 18590 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18591 // We must match the FunctionDecl's type to the hack introduced in 18592 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18593 // type. See the lengthy commentary in that routine. 18594 QualType FDT = FD->getType(); 18595 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18596 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18597 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18598 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18599 SourceLocation Loc = FD->getLocation(); 18600 FunctionDecl *NewFD = FunctionDecl::Create( 18601 S.Context, FD->getDeclContext(), Loc, Loc, 18602 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18603 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18604 /*ConstexprKind*/ CSK_unspecified); 18605 18606 if (FD->getQualifier()) 18607 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18608 18609 SmallVector<ParmVarDecl*, 16> Params; 18610 for (const auto &AI : FT->param_types()) { 18611 ParmVarDecl *Param = 18612 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18613 Param->setScopeInfo(0, Params.size()); 18614 Params.push_back(Param); 18615 } 18616 NewFD->setParams(Params); 18617 DRE->setDecl(NewFD); 18618 VD = DRE->getDecl(); 18619 } 18620 } 18621 18622 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18623 if (MD->isInstance()) { 18624 ValueKind = VK_RValue; 18625 Type = S.Context.BoundMemberTy; 18626 } 18627 18628 // Function references aren't l-values in C. 18629 if (!S.getLangOpts().CPlusPlus) 18630 ValueKind = VK_RValue; 18631 18632 // - variables 18633 } else if (isa<VarDecl>(VD)) { 18634 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18635 Type = RefTy->getPointeeType(); 18636 } else if (Type->isFunctionType()) { 18637 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18638 << VD << E->getSourceRange(); 18639 return ExprError(); 18640 } 18641 18642 // - nothing else 18643 } else { 18644 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18645 << VD << E->getSourceRange(); 18646 return ExprError(); 18647 } 18648 18649 // Modifying the declaration like this is friendly to IR-gen but 18650 // also really dangerous. 18651 VD->setType(DestType); 18652 E->setType(Type); 18653 E->setValueKind(ValueKind); 18654 return E; 18655 } 18656 18657 /// Check a cast of an unknown-any type. We intentionally only 18658 /// trigger this for C-style casts. 18659 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18660 Expr *CastExpr, CastKind &CastKind, 18661 ExprValueKind &VK, CXXCastPath &Path) { 18662 // The type we're casting to must be either void or complete. 18663 if (!CastType->isVoidType() && 18664 RequireCompleteType(TypeRange.getBegin(), CastType, 18665 diag::err_typecheck_cast_to_incomplete)) 18666 return ExprError(); 18667 18668 // Rewrite the casted expression from scratch. 18669 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18670 if (!result.isUsable()) return ExprError(); 18671 18672 CastExpr = result.get(); 18673 VK = CastExpr->getValueKind(); 18674 CastKind = CK_NoOp; 18675 18676 return CastExpr; 18677 } 18678 18679 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18680 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18681 } 18682 18683 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18684 Expr *arg, QualType ¶mType) { 18685 // If the syntactic form of the argument is not an explicit cast of 18686 // any sort, just do default argument promotion. 18687 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18688 if (!castArg) { 18689 ExprResult result = DefaultArgumentPromotion(arg); 18690 if (result.isInvalid()) return ExprError(); 18691 paramType = result.get()->getType(); 18692 return result; 18693 } 18694 18695 // Otherwise, use the type that was written in the explicit cast. 18696 assert(!arg->hasPlaceholderType()); 18697 paramType = castArg->getTypeAsWritten(); 18698 18699 // Copy-initialize a parameter of that type. 18700 InitializedEntity entity = 18701 InitializedEntity::InitializeParameter(Context, paramType, 18702 /*consumed*/ false); 18703 return PerformCopyInitialization(entity, callLoc, arg); 18704 } 18705 18706 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18707 Expr *orig = E; 18708 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18709 while (true) { 18710 E = E->IgnoreParenImpCasts(); 18711 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18712 E = call->getCallee(); 18713 diagID = diag::err_uncasted_call_of_unknown_any; 18714 } else { 18715 break; 18716 } 18717 } 18718 18719 SourceLocation loc; 18720 NamedDecl *d; 18721 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18722 loc = ref->getLocation(); 18723 d = ref->getDecl(); 18724 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18725 loc = mem->getMemberLoc(); 18726 d = mem->getMemberDecl(); 18727 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18728 diagID = diag::err_uncasted_call_of_unknown_any; 18729 loc = msg->getSelectorStartLoc(); 18730 d = msg->getMethodDecl(); 18731 if (!d) { 18732 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18733 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18734 << orig->getSourceRange(); 18735 return ExprError(); 18736 } 18737 } else { 18738 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18739 << E->getSourceRange(); 18740 return ExprError(); 18741 } 18742 18743 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18744 18745 // Never recoverable. 18746 return ExprError(); 18747 } 18748 18749 /// Check for operands with placeholder types and complain if found. 18750 /// Returns ExprError() if there was an error and no recovery was possible. 18751 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18752 if (!getLangOpts().CPlusPlus) { 18753 // C cannot handle TypoExpr nodes on either side of a binop because it 18754 // doesn't handle dependent types properly, so make sure any TypoExprs have 18755 // been dealt with before checking the operands. 18756 ExprResult Result = CorrectDelayedTyposInExpr(E); 18757 if (!Result.isUsable()) return ExprError(); 18758 E = Result.get(); 18759 } 18760 18761 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18762 if (!placeholderType) return E; 18763 18764 switch (placeholderType->getKind()) { 18765 18766 // Overloaded expressions. 18767 case BuiltinType::Overload: { 18768 // Try to resolve a single function template specialization. 18769 // This is obligatory. 18770 ExprResult Result = E; 18771 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18772 return Result; 18773 18774 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18775 // leaves Result unchanged on failure. 18776 Result = E; 18777 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18778 return Result; 18779 18780 // If that failed, try to recover with a call. 18781 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18782 /*complain*/ true); 18783 return Result; 18784 } 18785 18786 // Bound member functions. 18787 case BuiltinType::BoundMember: { 18788 ExprResult result = E; 18789 const Expr *BME = E->IgnoreParens(); 18790 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18791 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18792 if (isa<CXXPseudoDestructorExpr>(BME)) { 18793 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18794 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18795 if (ME->getMemberNameInfo().getName().getNameKind() == 18796 DeclarationName::CXXDestructorName) 18797 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18798 } 18799 tryToRecoverWithCall(result, PD, 18800 /*complain*/ true); 18801 return result; 18802 } 18803 18804 // ARC unbridged casts. 18805 case BuiltinType::ARCUnbridgedCast: { 18806 Expr *realCast = stripARCUnbridgedCast(E); 18807 diagnoseARCUnbridgedCast(realCast); 18808 return realCast; 18809 } 18810 18811 // Expressions of unknown type. 18812 case BuiltinType::UnknownAny: 18813 return diagnoseUnknownAnyExpr(*this, E); 18814 18815 // Pseudo-objects. 18816 case BuiltinType::PseudoObject: 18817 return checkPseudoObjectRValue(E); 18818 18819 case BuiltinType::BuiltinFn: { 18820 // Accept __noop without parens by implicitly converting it to a call expr. 18821 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18822 if (DRE) { 18823 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18824 if (FD->getBuiltinID() == Builtin::BI__noop) { 18825 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18826 CK_BuiltinFnToFnPtr) 18827 .get(); 18828 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18829 VK_RValue, SourceLocation()); 18830 } 18831 } 18832 18833 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18834 return ExprError(); 18835 } 18836 18837 // Expressions of unknown type. 18838 case BuiltinType::OMPArraySection: 18839 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18840 return ExprError(); 18841 18842 // Expressions of unknown type. 18843 case BuiltinType::OMPArrayShaping: 18844 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 18845 18846 case BuiltinType::OMPIterator: 18847 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 18848 18849 // Everything else should be impossible. 18850 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18851 case BuiltinType::Id: 18852 #include "clang/Basic/OpenCLImageTypes.def" 18853 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18854 case BuiltinType::Id: 18855 #include "clang/Basic/OpenCLExtensionTypes.def" 18856 #define SVE_TYPE(Name, Id, SingletonId) \ 18857 case BuiltinType::Id: 18858 #include "clang/Basic/AArch64SVEACLETypes.def" 18859 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18860 #define PLACEHOLDER_TYPE(Id, SingletonId) 18861 #include "clang/AST/BuiltinTypes.def" 18862 break; 18863 } 18864 18865 llvm_unreachable("invalid placeholder type!"); 18866 } 18867 18868 bool Sema::CheckCaseExpression(Expr *E) { 18869 if (E->isTypeDependent()) 18870 return true; 18871 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18872 return E->getType()->isIntegralOrEnumerationType(); 18873 return false; 18874 } 18875 18876 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18877 ExprResult 18878 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18879 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18880 "Unknown Objective-C Boolean value!"); 18881 QualType BoolT = Context.ObjCBuiltinBoolTy; 18882 if (!Context.getBOOLDecl()) { 18883 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18884 Sema::LookupOrdinaryName); 18885 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18886 NamedDecl *ND = Result.getFoundDecl(); 18887 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18888 Context.setBOOLDecl(TD); 18889 } 18890 } 18891 if (Context.getBOOLDecl()) 18892 BoolT = Context.getBOOLType(); 18893 return new (Context) 18894 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18895 } 18896 18897 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18898 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18899 SourceLocation RParen) { 18900 18901 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18902 18903 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18904 return Spec.getPlatform() == Platform; 18905 }); 18906 18907 VersionTuple Version; 18908 if (Spec != AvailSpecs.end()) 18909 Version = Spec->getVersion(); 18910 18911 // The use of `@available` in the enclosing function should be analyzed to 18912 // warn when it's used inappropriately (i.e. not if(@available)). 18913 if (getCurFunctionOrMethodDecl()) 18914 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18915 else if (getCurBlock() || getCurLambda()) 18916 getCurFunction()->HasPotentialAvailabilityViolations = true; 18917 18918 return new (Context) 18919 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18920 } 18921 18922 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18923 assert(E->isTypeDependent()); 18924 return isa<UnresolvedLookupExpr>(E); 18925 } 18926 18927 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 18928 ArrayRef<Expr *> SubExprs) { 18929 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 18930 // bogus diagnostics and this trick does not work in C. 18931 // FIXME: use containsErrors() to suppress unwanted diags in C. 18932 if (!Context.getLangOpts().RecoveryAST) 18933 return ExprError(); 18934 18935 if (isSFINAEContext()) 18936 return ExprError(); 18937 18938 return RecoveryExpr::Create(Context, Begin, End, SubExprs); 18939 } 18940