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 // lvalue-to-rvalue conversion cannot be applied to function or array types. 610 if (T->isFunctionType() || T->isArrayType()) 611 return E; 612 613 // We don't want to throw lvalue-to-rvalue casts on top of 614 // expressions of certain types in C++. 615 if (getLangOpts().CPlusPlus && 616 (E->getType() == Context.OverloadTy || 617 T->isDependentType() || 618 T->isRecordType())) 619 return E; 620 621 // The C standard is actually really unclear on this point, and 622 // DR106 tells us what the result should be but not why. It's 623 // generally best to say that void types just doesn't undergo 624 // lvalue-to-rvalue at all. Note that expressions of unqualified 625 // 'void' type are never l-values, but qualified void can be. 626 if (T->isVoidType()) 627 return E; 628 629 // OpenCL usually rejects direct accesses to values of 'half' type. 630 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 631 T->isHalfType()) { 632 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 633 << 0 << T; 634 return ExprError(); 635 } 636 637 CheckForNullPointerDereference(*this, E); 638 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 639 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 640 &Context.Idents.get("object_getClass"), 641 SourceLocation(), LookupOrdinaryName); 642 if (ObjectGetClass) 643 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 644 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 645 << FixItHint::CreateReplacement( 646 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 647 else 648 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 649 } 650 else if (const ObjCIvarRefExpr *OIRE = 651 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 652 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 653 654 // C++ [conv.lval]p1: 655 // [...] If T is a non-class type, the type of the prvalue is the 656 // cv-unqualified version of T. Otherwise, the type of the 657 // rvalue is T. 658 // 659 // C99 6.3.2.1p2: 660 // If the lvalue has qualified type, the value has the unqualified 661 // version of the type of the lvalue; otherwise, the value has the 662 // type of the lvalue. 663 if (T.hasQualifiers()) 664 T = T.getUnqualifiedType(); 665 666 // Under the MS ABI, lock down the inheritance model now. 667 if (T->isMemberPointerType() && 668 Context.getTargetInfo().getCXXABI().isMicrosoft()) 669 (void)isCompleteType(E->getExprLoc(), T); 670 671 ExprResult Res = CheckLValueToRValueConversionOperand(E); 672 if (Res.isInvalid()) 673 return Res; 674 E = Res.get(); 675 676 // Loading a __weak object implicitly retains the value, so we need a cleanup to 677 // balance that. 678 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 679 Cleanup.setExprNeedsCleanups(true); 680 681 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 682 Cleanup.setExprNeedsCleanups(true); 683 684 // C++ [conv.lval]p3: 685 // If T is cv std::nullptr_t, the result is a null pointer constant. 686 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 687 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 688 689 // C11 6.3.2.1p2: 690 // ... if the lvalue has atomic type, the value has the non-atomic version 691 // of the type of the lvalue ... 692 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 693 T = Atomic->getValueType().getUnqualifiedType(); 694 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 695 nullptr, VK_RValue); 696 } 697 698 return Res; 699 } 700 701 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 702 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 703 if (Res.isInvalid()) 704 return ExprError(); 705 Res = DefaultLvalueConversion(Res.get()); 706 if (Res.isInvalid()) 707 return ExprError(); 708 return Res; 709 } 710 711 /// CallExprUnaryConversions - a special case of an unary conversion 712 /// performed on a function designator of a call expression. 713 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 714 QualType Ty = E->getType(); 715 ExprResult Res = E; 716 // Only do implicit cast for a function type, but not for a pointer 717 // to function type. 718 if (Ty->isFunctionType()) { 719 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 720 CK_FunctionToPointerDecay).get(); 721 if (Res.isInvalid()) 722 return ExprError(); 723 } 724 Res = DefaultLvalueConversion(Res.get()); 725 if (Res.isInvalid()) 726 return ExprError(); 727 return Res.get(); 728 } 729 730 /// UsualUnaryConversions - Performs various conversions that are common to most 731 /// operators (C99 6.3). The conversions of array and function types are 732 /// sometimes suppressed. For example, the array->pointer conversion doesn't 733 /// apply if the array is an argument to the sizeof or address (&) operators. 734 /// In these instances, this routine should *not* be called. 735 ExprResult Sema::UsualUnaryConversions(Expr *E) { 736 // First, convert to an r-value. 737 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 738 if (Res.isInvalid()) 739 return ExprError(); 740 E = Res.get(); 741 742 QualType Ty = E->getType(); 743 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 744 745 // Half FP have to be promoted to float unless it is natively supported 746 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 747 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 748 749 // Try to perform integral promotions if the object has a theoretically 750 // promotable type. 751 if (Ty->isIntegralOrUnscopedEnumerationType()) { 752 // C99 6.3.1.1p2: 753 // 754 // The following may be used in an expression wherever an int or 755 // unsigned int may be used: 756 // - an object or expression with an integer type whose integer 757 // conversion rank is less than or equal to the rank of int 758 // and unsigned int. 759 // - A bit-field of type _Bool, int, signed int, or unsigned int. 760 // 761 // If an int can represent all values of the original type, the 762 // value is converted to an int; otherwise, it is converted to an 763 // unsigned int. These are called the integer promotions. All 764 // other types are unchanged by the integer promotions. 765 766 QualType PTy = Context.isPromotableBitField(E); 767 if (!PTy.isNull()) { 768 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 769 return E; 770 } 771 if (Ty->isPromotableIntegerType()) { 772 QualType PT = Context.getPromotedIntegerType(Ty); 773 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 774 return E; 775 } 776 } 777 return E; 778 } 779 780 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 781 /// do not have a prototype. Arguments that have type float or __fp16 782 /// are promoted to double. All other argument types are converted by 783 /// UsualUnaryConversions(). 784 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 785 QualType Ty = E->getType(); 786 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 787 788 ExprResult Res = UsualUnaryConversions(E); 789 if (Res.isInvalid()) 790 return ExprError(); 791 E = Res.get(); 792 793 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 794 // promote to double. 795 // Note that default argument promotion applies only to float (and 796 // half/fp16); it does not apply to _Float16. 797 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 798 if (BTy && (BTy->getKind() == BuiltinType::Half || 799 BTy->getKind() == BuiltinType::Float)) { 800 if (getLangOpts().OpenCL && 801 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 802 if (BTy->getKind() == BuiltinType::Half) { 803 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 804 } 805 } else { 806 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 807 } 808 } 809 810 // C++ performs lvalue-to-rvalue conversion as a default argument 811 // promotion, even on class types, but note: 812 // C++11 [conv.lval]p2: 813 // When an lvalue-to-rvalue conversion occurs in an unevaluated 814 // operand or a subexpression thereof the value contained in the 815 // referenced object is not accessed. Otherwise, if the glvalue 816 // has a class type, the conversion copy-initializes a temporary 817 // of type T from the glvalue and the result of the conversion 818 // is a prvalue for the temporary. 819 // FIXME: add some way to gate this entire thing for correctness in 820 // potentially potentially evaluated contexts. 821 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 822 ExprResult Temp = PerformCopyInitialization( 823 InitializedEntity::InitializeTemporary(E->getType()), 824 E->getExprLoc(), E); 825 if (Temp.isInvalid()) 826 return ExprError(); 827 E = Temp.get(); 828 } 829 830 return E; 831 } 832 833 /// Determine the degree of POD-ness for an expression. 834 /// Incomplete types are considered POD, since this check can be performed 835 /// when we're in an unevaluated context. 836 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 837 if (Ty->isIncompleteType()) { 838 // C++11 [expr.call]p7: 839 // After these conversions, if the argument does not have arithmetic, 840 // enumeration, pointer, pointer to member, or class type, the program 841 // is ill-formed. 842 // 843 // Since we've already performed array-to-pointer and function-to-pointer 844 // decay, the only such type in C++ is cv void. This also handles 845 // initializer lists as variadic arguments. 846 if (Ty->isVoidType()) 847 return VAK_Invalid; 848 849 if (Ty->isObjCObjectType()) 850 return VAK_Invalid; 851 return VAK_Valid; 852 } 853 854 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 855 return VAK_Invalid; 856 857 if (Ty.isCXX98PODType(Context)) 858 return VAK_Valid; 859 860 // C++11 [expr.call]p7: 861 // Passing a potentially-evaluated argument of class type (Clause 9) 862 // having a non-trivial copy constructor, a non-trivial move constructor, 863 // or a non-trivial destructor, with no corresponding parameter, 864 // is conditionally-supported with implementation-defined semantics. 865 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 866 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 867 if (!Record->hasNonTrivialCopyConstructor() && 868 !Record->hasNonTrivialMoveConstructor() && 869 !Record->hasNonTrivialDestructor()) 870 return VAK_ValidInCXX11; 871 872 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 873 return VAK_Valid; 874 875 if (Ty->isObjCObjectType()) 876 return VAK_Invalid; 877 878 if (getLangOpts().MSVCCompat) 879 return VAK_MSVCUndefined; 880 881 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 882 // permitted to reject them. We should consider doing so. 883 return VAK_Undefined; 884 } 885 886 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 887 // Don't allow one to pass an Objective-C interface to a vararg. 888 const QualType &Ty = E->getType(); 889 VarArgKind VAK = isValidVarArgType(Ty); 890 891 // Complain about passing non-POD types through varargs. 892 switch (VAK) { 893 case VAK_ValidInCXX11: 894 DiagRuntimeBehavior( 895 E->getBeginLoc(), nullptr, 896 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 897 LLVM_FALLTHROUGH; 898 case VAK_Valid: 899 if (Ty->isRecordType()) { 900 // This is unlikely to be what the user intended. If the class has a 901 // 'c_str' member function, the user probably meant to call that. 902 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 903 PDiag(diag::warn_pass_class_arg_to_vararg) 904 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 905 } 906 break; 907 908 case VAK_Undefined: 909 case VAK_MSVCUndefined: 910 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 911 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 912 << getLangOpts().CPlusPlus11 << Ty << CT); 913 break; 914 915 case VAK_Invalid: 916 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 917 Diag(E->getBeginLoc(), 918 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 919 << Ty << CT; 920 else if (Ty->isObjCObjectType()) 921 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 922 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 923 << Ty << CT); 924 else 925 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 926 << isa<InitListExpr>(E) << Ty << CT; 927 break; 928 } 929 } 930 931 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 932 /// will create a trap if the resulting type is not a POD type. 933 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 934 FunctionDecl *FDecl) { 935 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 936 // Strip the unbridged-cast placeholder expression off, if applicable. 937 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 938 (CT == VariadicMethod || 939 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 940 E = stripARCUnbridgedCast(E); 941 942 // Otherwise, do normal placeholder checking. 943 } else { 944 ExprResult ExprRes = CheckPlaceholderExpr(E); 945 if (ExprRes.isInvalid()) 946 return ExprError(); 947 E = ExprRes.get(); 948 } 949 } 950 951 ExprResult ExprRes = DefaultArgumentPromotion(E); 952 if (ExprRes.isInvalid()) 953 return ExprError(); 954 E = ExprRes.get(); 955 956 // Diagnostics regarding non-POD argument types are 957 // emitted along with format string checking in Sema::CheckFunctionCall(). 958 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 959 // Turn this into a trap. 960 CXXScopeSpec SS; 961 SourceLocation TemplateKWLoc; 962 UnqualifiedId Name; 963 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 964 E->getBeginLoc()); 965 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 966 /*HasTrailingLParen=*/true, 967 /*IsAddressOfOperand=*/false); 968 if (TrapFn.isInvalid()) 969 return ExprError(); 970 971 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 972 None, E->getEndLoc()); 973 if (Call.isInvalid()) 974 return ExprError(); 975 976 ExprResult Comma = 977 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 978 if (Comma.isInvalid()) 979 return ExprError(); 980 return Comma.get(); 981 } 982 983 if (!getLangOpts().CPlusPlus && 984 RequireCompleteType(E->getExprLoc(), E->getType(), 985 diag::err_call_incomplete_argument)) 986 return ExprError(); 987 988 return E; 989 } 990 991 /// Converts an integer to complex float type. Helper function of 992 /// UsualArithmeticConversions() 993 /// 994 /// \return false if the integer expression is an integer type and is 995 /// successfully converted to the complex type. 996 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 997 ExprResult &ComplexExpr, 998 QualType IntTy, 999 QualType ComplexTy, 1000 bool SkipCast) { 1001 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1002 if (SkipCast) return false; 1003 if (IntTy->isIntegerType()) { 1004 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1005 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1007 CK_FloatingRealToComplex); 1008 } else { 1009 assert(IntTy->isComplexIntegerType()); 1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1011 CK_IntegralComplexToFloatingComplex); 1012 } 1013 return false; 1014 } 1015 1016 /// Handle arithmetic conversion with complex types. Helper function of 1017 /// UsualArithmeticConversions() 1018 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1019 ExprResult &RHS, QualType LHSType, 1020 QualType RHSType, 1021 bool IsCompAssign) { 1022 // if we have an integer operand, the result is the complex type. 1023 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1024 /*skipCast*/false)) 1025 return LHSType; 1026 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1027 /*skipCast*/IsCompAssign)) 1028 return RHSType; 1029 1030 // This handles complex/complex, complex/float, or float/complex. 1031 // When both operands are complex, the shorter operand is converted to the 1032 // type of the longer, and that is the type of the result. This corresponds 1033 // to what is done when combining two real floating-point operands. 1034 // The fun begins when size promotion occur across type domains. 1035 // From H&S 6.3.4: When one operand is complex and the other is a real 1036 // floating-point type, the less precise type is converted, within it's 1037 // real or complex domain, to the precision of the other type. For example, 1038 // when combining a "long double" with a "double _Complex", the 1039 // "double _Complex" is promoted to "long double _Complex". 1040 1041 // Compute the rank of the two types, regardless of whether they are complex. 1042 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1043 1044 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1045 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1046 QualType LHSElementType = 1047 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1048 QualType RHSElementType = 1049 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1050 1051 QualType ResultType = S.Context.getComplexType(LHSElementType); 1052 if (Order < 0) { 1053 // Promote the precision of the LHS if not an assignment. 1054 ResultType = S.Context.getComplexType(RHSElementType); 1055 if (!IsCompAssign) { 1056 if (LHSComplexType) 1057 LHS = 1058 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1059 else 1060 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1061 } 1062 } else if (Order > 0) { 1063 // Promote the precision of the RHS. 1064 if (RHSComplexType) 1065 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1066 else 1067 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1068 } 1069 return ResultType; 1070 } 1071 1072 /// Handle arithmetic conversion from integer to float. Helper function 1073 /// of UsualArithmeticConversions() 1074 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1075 ExprResult &IntExpr, 1076 QualType FloatTy, QualType IntTy, 1077 bool ConvertFloat, bool ConvertInt) { 1078 if (IntTy->isIntegerType()) { 1079 if (ConvertInt) 1080 // Convert intExpr to the lhs floating point type. 1081 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1082 CK_IntegralToFloating); 1083 return FloatTy; 1084 } 1085 1086 // Convert both sides to the appropriate complex float. 1087 assert(IntTy->isComplexIntegerType()); 1088 QualType result = S.Context.getComplexType(FloatTy); 1089 1090 // _Complex int -> _Complex float 1091 if (ConvertInt) 1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1093 CK_IntegralComplexToFloatingComplex); 1094 1095 // float -> _Complex float 1096 if (ConvertFloat) 1097 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1098 CK_FloatingRealToComplex); 1099 1100 return result; 1101 } 1102 1103 /// Handle arithmethic conversion with floating point types. Helper 1104 /// function of UsualArithmeticConversions() 1105 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1106 ExprResult &RHS, QualType LHSType, 1107 QualType RHSType, bool IsCompAssign) { 1108 bool LHSFloat = LHSType->isRealFloatingType(); 1109 bool RHSFloat = RHSType->isRealFloatingType(); 1110 1111 // If we have two real floating types, convert the smaller operand 1112 // to the bigger result. 1113 if (LHSFloat && RHSFloat) { 1114 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1115 if (order > 0) { 1116 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1117 return LHSType; 1118 } 1119 1120 assert(order < 0 && "illegal float comparison"); 1121 if (!IsCompAssign) 1122 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1123 return RHSType; 1124 } 1125 1126 if (LHSFloat) { 1127 // Half FP has to be promoted to float unless it is natively supported 1128 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1129 LHSType = S.Context.FloatTy; 1130 1131 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1132 /*ConvertFloat=*/!IsCompAssign, 1133 /*ConvertInt=*/ true); 1134 } 1135 assert(RHSFloat); 1136 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1137 /*convertInt=*/ true, 1138 /*convertFloat=*/!IsCompAssign); 1139 } 1140 1141 /// Diagnose attempts to convert between __float128 and long double if 1142 /// there is no support for such conversion. Helper function of 1143 /// UsualArithmeticConversions(). 1144 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1145 QualType RHSType) { 1146 /* No issue converting if at least one of the types is not a floating point 1147 type or the two types have the same rank. 1148 */ 1149 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1150 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1151 return false; 1152 1153 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1154 "The remaining types must be floating point types."); 1155 1156 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1157 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1158 1159 QualType LHSElemType = LHSComplex ? 1160 LHSComplex->getElementType() : LHSType; 1161 QualType RHSElemType = RHSComplex ? 1162 RHSComplex->getElementType() : RHSType; 1163 1164 // No issue if the two types have the same representation 1165 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1166 &S.Context.getFloatTypeSemantics(RHSElemType)) 1167 return false; 1168 1169 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1170 RHSElemType == S.Context.LongDoubleTy); 1171 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1172 RHSElemType == S.Context.Float128Ty); 1173 1174 // We've handled the situation where __float128 and long double have the same 1175 // representation. We allow all conversions for all possible long double types 1176 // except PPC's double double. 1177 return Float128AndLongDouble && 1178 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1179 &llvm::APFloat::PPCDoubleDouble()); 1180 } 1181 1182 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1183 1184 namespace { 1185 /// These helper callbacks are placed in an anonymous namespace to 1186 /// permit their use as function template parameters. 1187 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1188 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1189 } 1190 1191 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1192 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1193 CK_IntegralComplexCast); 1194 } 1195 } 1196 1197 /// Handle integer arithmetic conversions. Helper function of 1198 /// UsualArithmeticConversions() 1199 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1200 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1201 ExprResult &RHS, QualType LHSType, 1202 QualType RHSType, bool IsCompAssign) { 1203 // The rules for this case are in C99 6.3.1.8 1204 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1205 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1206 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1207 if (LHSSigned == RHSSigned) { 1208 // Same signedness; use the higher-ranked type 1209 if (order >= 0) { 1210 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1211 return LHSType; 1212 } else if (!IsCompAssign) 1213 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1214 return RHSType; 1215 } else if (order != (LHSSigned ? 1 : -1)) { 1216 // The unsigned type has greater than or equal rank to the 1217 // signed type, so use the unsigned type 1218 if (RHSSigned) { 1219 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1220 return LHSType; 1221 } else if (!IsCompAssign) 1222 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1223 return RHSType; 1224 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1225 // The two types are different widths; if we are here, that 1226 // means the signed type is larger than the unsigned type, so 1227 // use the signed type. 1228 if (LHSSigned) { 1229 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1230 return LHSType; 1231 } else if (!IsCompAssign) 1232 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1233 return RHSType; 1234 } else { 1235 // The signed type is higher-ranked than the unsigned type, 1236 // but isn't actually any bigger (like unsigned int and long 1237 // on most 32-bit systems). Use the unsigned type corresponding 1238 // to the signed type. 1239 QualType result = 1240 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1241 RHS = (*doRHSCast)(S, RHS.get(), result); 1242 if (!IsCompAssign) 1243 LHS = (*doLHSCast)(S, LHS.get(), result); 1244 return result; 1245 } 1246 } 1247 1248 /// Handle conversions with GCC complex int extension. Helper function 1249 /// of UsualArithmeticConversions() 1250 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1251 ExprResult &RHS, QualType LHSType, 1252 QualType RHSType, 1253 bool IsCompAssign) { 1254 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1255 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1256 1257 if (LHSComplexInt && RHSComplexInt) { 1258 QualType LHSEltType = LHSComplexInt->getElementType(); 1259 QualType RHSEltType = RHSComplexInt->getElementType(); 1260 QualType ScalarType = 1261 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1262 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1263 1264 return S.Context.getComplexType(ScalarType); 1265 } 1266 1267 if (LHSComplexInt) { 1268 QualType LHSEltType = LHSComplexInt->getElementType(); 1269 QualType ScalarType = 1270 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1271 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1272 QualType ComplexType = S.Context.getComplexType(ScalarType); 1273 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1274 CK_IntegralRealToComplex); 1275 1276 return ComplexType; 1277 } 1278 1279 assert(RHSComplexInt); 1280 1281 QualType RHSEltType = RHSComplexInt->getElementType(); 1282 QualType ScalarType = 1283 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1284 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1285 QualType ComplexType = S.Context.getComplexType(ScalarType); 1286 1287 if (!IsCompAssign) 1288 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1289 CK_IntegralRealToComplex); 1290 return ComplexType; 1291 } 1292 1293 /// Return the rank of a given fixed point or integer type. The value itself 1294 /// doesn't matter, but the values must be increasing with proper increasing 1295 /// rank as described in N1169 4.1.1. 1296 static unsigned GetFixedPointRank(QualType Ty) { 1297 const auto *BTy = Ty->getAs<BuiltinType>(); 1298 assert(BTy && "Expected a builtin type."); 1299 1300 switch (BTy->getKind()) { 1301 case BuiltinType::ShortFract: 1302 case BuiltinType::UShortFract: 1303 case BuiltinType::SatShortFract: 1304 case BuiltinType::SatUShortFract: 1305 return 1; 1306 case BuiltinType::Fract: 1307 case BuiltinType::UFract: 1308 case BuiltinType::SatFract: 1309 case BuiltinType::SatUFract: 1310 return 2; 1311 case BuiltinType::LongFract: 1312 case BuiltinType::ULongFract: 1313 case BuiltinType::SatLongFract: 1314 case BuiltinType::SatULongFract: 1315 return 3; 1316 case BuiltinType::ShortAccum: 1317 case BuiltinType::UShortAccum: 1318 case BuiltinType::SatShortAccum: 1319 case BuiltinType::SatUShortAccum: 1320 return 4; 1321 case BuiltinType::Accum: 1322 case BuiltinType::UAccum: 1323 case BuiltinType::SatAccum: 1324 case BuiltinType::SatUAccum: 1325 return 5; 1326 case BuiltinType::LongAccum: 1327 case BuiltinType::ULongAccum: 1328 case BuiltinType::SatLongAccum: 1329 case BuiltinType::SatULongAccum: 1330 return 6; 1331 default: 1332 if (BTy->isInteger()) 1333 return 0; 1334 llvm_unreachable("Unexpected fixed point or integer type"); 1335 } 1336 } 1337 1338 /// handleFixedPointConversion - Fixed point operations between fixed 1339 /// point types and integers or other fixed point types do not fall under 1340 /// usual arithmetic conversion since these conversions could result in loss 1341 /// of precsision (N1169 4.1.4). These operations should be calculated with 1342 /// the full precision of their result type (N1169 4.1.6.2.1). 1343 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1344 QualType RHSTy) { 1345 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1346 "Expected at least one of the operands to be a fixed point type"); 1347 assert((LHSTy->isFixedPointOrIntegerType() || 1348 RHSTy->isFixedPointOrIntegerType()) && 1349 "Special fixed point arithmetic operation conversions are only " 1350 "applied to ints or other fixed point types"); 1351 1352 // If one operand has signed fixed-point type and the other operand has 1353 // unsigned fixed-point type, then the unsigned fixed-point operand is 1354 // converted to its corresponding signed fixed-point type and the resulting 1355 // type is the type of the converted operand. 1356 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1357 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1358 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1359 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1360 1361 // The result type is the type with the highest rank, whereby a fixed-point 1362 // conversion rank is always greater than an integer conversion rank; if the 1363 // type of either of the operands is a saturating fixedpoint type, the result 1364 // type shall be the saturating fixed-point type corresponding to the type 1365 // with the highest rank; the resulting value is converted (taking into 1366 // account rounding and overflow) to the precision of the resulting type. 1367 // Same ranks between signed and unsigned types are resolved earlier, so both 1368 // types are either signed or both unsigned at this point. 1369 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1370 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1371 1372 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1373 1374 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1375 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1376 1377 return ResultTy; 1378 } 1379 1380 /// Check that the usual arithmetic conversions can be performed on this pair of 1381 /// expressions that might be of enumeration type. 1382 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1383 SourceLocation Loc, 1384 Sema::ArithConvKind ACK) { 1385 // C++2a [expr.arith.conv]p1: 1386 // If one operand is of enumeration type and the other operand is of a 1387 // different enumeration type or a floating-point type, this behavior is 1388 // deprecated ([depr.arith.conv.enum]). 1389 // 1390 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1391 // Eventually we will presumably reject these cases (in C++23 onwards?). 1392 QualType L = LHS->getType(), R = RHS->getType(); 1393 bool LEnum = L->isUnscopedEnumerationType(), 1394 REnum = R->isUnscopedEnumerationType(); 1395 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1396 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1397 (REnum && L->isFloatingType())) { 1398 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1399 ? diag::warn_arith_conv_enum_float_cxx20 1400 : diag::warn_arith_conv_enum_float) 1401 << LHS->getSourceRange() << RHS->getSourceRange() 1402 << (int)ACK << LEnum << L << R; 1403 } else if (!IsCompAssign && LEnum && REnum && 1404 !S.Context.hasSameUnqualifiedType(L, R)) { 1405 unsigned DiagID; 1406 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1407 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1408 // If either enumeration type is unnamed, it's less likely that the 1409 // user cares about this, but this situation is still deprecated in 1410 // C++2a. Use a different warning group. 1411 DiagID = S.getLangOpts().CPlusPlus20 1412 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1413 : diag::warn_arith_conv_mixed_anon_enum_types; 1414 } else if (ACK == Sema::ACK_Conditional) { 1415 // Conditional expressions are separated out because they have 1416 // historically had a different warning flag. 1417 DiagID = S.getLangOpts().CPlusPlus20 1418 ? diag::warn_conditional_mixed_enum_types_cxx20 1419 : diag::warn_conditional_mixed_enum_types; 1420 } else if (ACK == Sema::ACK_Comparison) { 1421 // Comparison expressions are separated out because they have 1422 // historically had a different warning flag. 1423 DiagID = S.getLangOpts().CPlusPlus20 1424 ? diag::warn_comparison_mixed_enum_types_cxx20 1425 : diag::warn_comparison_mixed_enum_types; 1426 } else { 1427 DiagID = S.getLangOpts().CPlusPlus20 1428 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1429 : diag::warn_arith_conv_mixed_enum_types; 1430 } 1431 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1432 << (int)ACK << L << R; 1433 } 1434 } 1435 1436 /// UsualArithmeticConversions - Performs various conversions that are common to 1437 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1438 /// routine returns the first non-arithmetic type found. The client is 1439 /// responsible for emitting appropriate error diagnostics. 1440 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1441 SourceLocation Loc, 1442 ArithConvKind ACK) { 1443 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1444 1445 if (ACK != ACK_CompAssign) { 1446 LHS = UsualUnaryConversions(LHS.get()); 1447 if (LHS.isInvalid()) 1448 return QualType(); 1449 } 1450 1451 RHS = UsualUnaryConversions(RHS.get()); 1452 if (RHS.isInvalid()) 1453 return QualType(); 1454 1455 // For conversion purposes, we ignore any qualifiers. 1456 // For example, "const float" and "float" are equivalent. 1457 QualType LHSType = 1458 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1459 QualType RHSType = 1460 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1461 1462 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1463 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1464 LHSType = AtomicLHS->getValueType(); 1465 1466 // If both types are identical, no conversion is needed. 1467 if (LHSType == RHSType) 1468 return LHSType; 1469 1470 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1471 // The caller can deal with this (e.g. pointer + int). 1472 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1473 return QualType(); 1474 1475 // Apply unary and bitfield promotions to the LHS's type. 1476 QualType LHSUnpromotedType = LHSType; 1477 if (LHSType->isPromotableIntegerType()) 1478 LHSType = Context.getPromotedIntegerType(LHSType); 1479 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1480 if (!LHSBitfieldPromoteTy.isNull()) 1481 LHSType = LHSBitfieldPromoteTy; 1482 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1483 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1484 1485 // If both types are identical, no conversion is needed. 1486 if (LHSType == RHSType) 1487 return LHSType; 1488 1489 // ExtInt types aren't subject to conversions between them or normal integers, 1490 // so this fails. 1491 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1492 return QualType(); 1493 1494 // At this point, we have two different arithmetic types. 1495 1496 // Diagnose attempts to convert between __float128 and long double where 1497 // such conversions currently can't be handled. 1498 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1499 return QualType(); 1500 1501 // Handle complex types first (C99 6.3.1.8p1). 1502 if (LHSType->isComplexType() || RHSType->isComplexType()) 1503 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1504 ACK == ACK_CompAssign); 1505 1506 // Now handle "real" floating types (i.e. float, double, long double). 1507 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1508 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1509 ACK == ACK_CompAssign); 1510 1511 // Handle GCC complex int extension. 1512 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1513 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1514 ACK == ACK_CompAssign); 1515 1516 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1517 return handleFixedPointConversion(*this, LHSType, RHSType); 1518 1519 // Finally, we have two differing integer types. 1520 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1521 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1522 } 1523 1524 //===----------------------------------------------------------------------===// 1525 // Semantic Analysis for various Expression Types 1526 //===----------------------------------------------------------------------===// 1527 1528 1529 ExprResult 1530 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1531 SourceLocation DefaultLoc, 1532 SourceLocation RParenLoc, 1533 Expr *ControllingExpr, 1534 ArrayRef<ParsedType> ArgTypes, 1535 ArrayRef<Expr *> ArgExprs) { 1536 unsigned NumAssocs = ArgTypes.size(); 1537 assert(NumAssocs == ArgExprs.size()); 1538 1539 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1540 for (unsigned i = 0; i < NumAssocs; ++i) { 1541 if (ArgTypes[i]) 1542 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1543 else 1544 Types[i] = nullptr; 1545 } 1546 1547 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1548 ControllingExpr, 1549 llvm::makeArrayRef(Types, NumAssocs), 1550 ArgExprs); 1551 delete [] Types; 1552 return ER; 1553 } 1554 1555 ExprResult 1556 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1557 SourceLocation DefaultLoc, 1558 SourceLocation RParenLoc, 1559 Expr *ControllingExpr, 1560 ArrayRef<TypeSourceInfo *> Types, 1561 ArrayRef<Expr *> Exprs) { 1562 unsigned NumAssocs = Types.size(); 1563 assert(NumAssocs == Exprs.size()); 1564 1565 // Decay and strip qualifiers for the controlling expression type, and handle 1566 // placeholder type replacement. See committee discussion from WG14 DR423. 1567 { 1568 EnterExpressionEvaluationContext Unevaluated( 1569 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1570 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1571 if (R.isInvalid()) 1572 return ExprError(); 1573 ControllingExpr = R.get(); 1574 } 1575 1576 // The controlling expression is an unevaluated operand, so side effects are 1577 // likely unintended. 1578 if (!inTemplateInstantiation() && 1579 ControllingExpr->HasSideEffects(Context, false)) 1580 Diag(ControllingExpr->getExprLoc(), 1581 diag::warn_side_effects_unevaluated_context); 1582 1583 bool TypeErrorFound = false, 1584 IsResultDependent = ControllingExpr->isTypeDependent(), 1585 ContainsUnexpandedParameterPack 1586 = ControllingExpr->containsUnexpandedParameterPack(); 1587 1588 for (unsigned i = 0; i < NumAssocs; ++i) { 1589 if (Exprs[i]->containsUnexpandedParameterPack()) 1590 ContainsUnexpandedParameterPack = true; 1591 1592 if (Types[i]) { 1593 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1594 ContainsUnexpandedParameterPack = true; 1595 1596 if (Types[i]->getType()->isDependentType()) { 1597 IsResultDependent = true; 1598 } else { 1599 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1600 // complete object type other than a variably modified type." 1601 unsigned D = 0; 1602 if (Types[i]->getType()->isIncompleteType()) 1603 D = diag::err_assoc_type_incomplete; 1604 else if (!Types[i]->getType()->isObjectType()) 1605 D = diag::err_assoc_type_nonobject; 1606 else if (Types[i]->getType()->isVariablyModifiedType()) 1607 D = diag::err_assoc_type_variably_modified; 1608 1609 if (D != 0) { 1610 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1611 << Types[i]->getTypeLoc().getSourceRange() 1612 << Types[i]->getType(); 1613 TypeErrorFound = true; 1614 } 1615 1616 // C11 6.5.1.1p2 "No two generic associations in the same generic 1617 // selection shall specify compatible types." 1618 for (unsigned j = i+1; j < NumAssocs; ++j) 1619 if (Types[j] && !Types[j]->getType()->isDependentType() && 1620 Context.typesAreCompatible(Types[i]->getType(), 1621 Types[j]->getType())) { 1622 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1623 diag::err_assoc_compatible_types) 1624 << Types[j]->getTypeLoc().getSourceRange() 1625 << Types[j]->getType() 1626 << Types[i]->getType(); 1627 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1628 diag::note_compat_assoc) 1629 << Types[i]->getTypeLoc().getSourceRange() 1630 << Types[i]->getType(); 1631 TypeErrorFound = true; 1632 } 1633 } 1634 } 1635 } 1636 if (TypeErrorFound) 1637 return ExprError(); 1638 1639 // If we determined that the generic selection is result-dependent, don't 1640 // try to compute the result expression. 1641 if (IsResultDependent) 1642 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1643 Exprs, DefaultLoc, RParenLoc, 1644 ContainsUnexpandedParameterPack); 1645 1646 SmallVector<unsigned, 1> CompatIndices; 1647 unsigned DefaultIndex = -1U; 1648 for (unsigned i = 0; i < NumAssocs; ++i) { 1649 if (!Types[i]) 1650 DefaultIndex = i; 1651 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1652 Types[i]->getType())) 1653 CompatIndices.push_back(i); 1654 } 1655 1656 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1657 // type compatible with at most one of the types named in its generic 1658 // association list." 1659 if (CompatIndices.size() > 1) { 1660 // We strip parens here because the controlling expression is typically 1661 // parenthesized in macro definitions. 1662 ControllingExpr = ControllingExpr->IgnoreParens(); 1663 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1664 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1665 << (unsigned)CompatIndices.size(); 1666 for (unsigned I : CompatIndices) { 1667 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1668 diag::note_compat_assoc) 1669 << Types[I]->getTypeLoc().getSourceRange() 1670 << Types[I]->getType(); 1671 } 1672 return ExprError(); 1673 } 1674 1675 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1676 // its controlling expression shall have type compatible with exactly one of 1677 // the types named in its generic association list." 1678 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1679 // We strip parens here because the controlling expression is typically 1680 // parenthesized in macro definitions. 1681 ControllingExpr = ControllingExpr->IgnoreParens(); 1682 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1683 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1684 return ExprError(); 1685 } 1686 1687 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1688 // type name that is compatible with the type of the controlling expression, 1689 // then the result expression of the generic selection is the expression 1690 // in that generic association. Otherwise, the result expression of the 1691 // generic selection is the expression in the default generic association." 1692 unsigned ResultIndex = 1693 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1694 1695 return GenericSelectionExpr::Create( 1696 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1697 ContainsUnexpandedParameterPack, ResultIndex); 1698 } 1699 1700 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1701 /// location of the token and the offset of the ud-suffix within it. 1702 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1703 unsigned Offset) { 1704 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1705 S.getLangOpts()); 1706 } 1707 1708 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1709 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1710 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1711 IdentifierInfo *UDSuffix, 1712 SourceLocation UDSuffixLoc, 1713 ArrayRef<Expr*> Args, 1714 SourceLocation LitEndLoc) { 1715 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1716 1717 QualType ArgTy[2]; 1718 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1719 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1720 if (ArgTy[ArgIdx]->isArrayType()) 1721 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1722 } 1723 1724 DeclarationName OpName = 1725 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1726 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1727 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1728 1729 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1730 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1731 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1732 /*AllowStringTemplate*/ false, 1733 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1734 return ExprError(); 1735 1736 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1737 } 1738 1739 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1740 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1741 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1742 /// multiple tokens. However, the common case is that StringToks points to one 1743 /// string. 1744 /// 1745 ExprResult 1746 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1747 assert(!StringToks.empty() && "Must have at least one string!"); 1748 1749 StringLiteralParser Literal(StringToks, PP); 1750 if (Literal.hadError) 1751 return ExprError(); 1752 1753 SmallVector<SourceLocation, 4> StringTokLocs; 1754 for (const Token &Tok : StringToks) 1755 StringTokLocs.push_back(Tok.getLocation()); 1756 1757 QualType CharTy = Context.CharTy; 1758 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1759 if (Literal.isWide()) { 1760 CharTy = Context.getWideCharType(); 1761 Kind = StringLiteral::Wide; 1762 } else if (Literal.isUTF8()) { 1763 if (getLangOpts().Char8) 1764 CharTy = Context.Char8Ty; 1765 Kind = StringLiteral::UTF8; 1766 } else if (Literal.isUTF16()) { 1767 CharTy = Context.Char16Ty; 1768 Kind = StringLiteral::UTF16; 1769 } else if (Literal.isUTF32()) { 1770 CharTy = Context.Char32Ty; 1771 Kind = StringLiteral::UTF32; 1772 } else if (Literal.isPascal()) { 1773 CharTy = Context.UnsignedCharTy; 1774 } 1775 1776 // Warn on initializing an array of char from a u8 string literal; this 1777 // becomes ill-formed in C++2a. 1778 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1779 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1780 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1781 1782 // Create removals for all 'u8' prefixes in the string literal(s). This 1783 // ensures C++2a compatibility (but may change the program behavior when 1784 // built by non-Clang compilers for which the execution character set is 1785 // not always UTF-8). 1786 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1787 SourceLocation RemovalDiagLoc; 1788 for (const Token &Tok : StringToks) { 1789 if (Tok.getKind() == tok::utf8_string_literal) { 1790 if (RemovalDiagLoc.isInvalid()) 1791 RemovalDiagLoc = Tok.getLocation(); 1792 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1793 Tok.getLocation(), 1794 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1795 getSourceManager(), getLangOpts()))); 1796 } 1797 } 1798 Diag(RemovalDiagLoc, RemovalDiag); 1799 } 1800 1801 QualType StrTy = 1802 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1803 1804 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1805 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1806 Kind, Literal.Pascal, StrTy, 1807 &StringTokLocs[0], 1808 StringTokLocs.size()); 1809 if (Literal.getUDSuffix().empty()) 1810 return Lit; 1811 1812 // We're building a user-defined literal. 1813 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1814 SourceLocation UDSuffixLoc = 1815 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1816 Literal.getUDSuffixOffset()); 1817 1818 // Make sure we're allowed user-defined literals here. 1819 if (!UDLScope) 1820 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1821 1822 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1823 // operator "" X (str, len) 1824 QualType SizeType = Context.getSizeType(); 1825 1826 DeclarationName OpName = 1827 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1828 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1829 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1830 1831 QualType ArgTy[] = { 1832 Context.getArrayDecayedType(StrTy), SizeType 1833 }; 1834 1835 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1836 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1837 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1838 /*AllowStringTemplate*/ true, 1839 /*DiagnoseMissing*/ true)) { 1840 1841 case LOLR_Cooked: { 1842 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1843 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1844 StringTokLocs[0]); 1845 Expr *Args[] = { Lit, LenArg }; 1846 1847 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1848 } 1849 1850 case LOLR_StringTemplate: { 1851 TemplateArgumentListInfo ExplicitArgs; 1852 1853 unsigned CharBits = Context.getIntWidth(CharTy); 1854 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1855 llvm::APSInt Value(CharBits, CharIsUnsigned); 1856 1857 TemplateArgument TypeArg(CharTy); 1858 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1859 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1860 1861 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1862 Value = Lit->getCodeUnit(I); 1863 TemplateArgument Arg(Context, Value, CharTy); 1864 TemplateArgumentLocInfo ArgInfo; 1865 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1866 } 1867 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1868 &ExplicitArgs); 1869 } 1870 case LOLR_Raw: 1871 case LOLR_Template: 1872 case LOLR_ErrorNoDiagnostic: 1873 llvm_unreachable("unexpected literal operator lookup result"); 1874 case LOLR_Error: 1875 return ExprError(); 1876 } 1877 llvm_unreachable("unexpected literal operator lookup result"); 1878 } 1879 1880 DeclRefExpr * 1881 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1882 SourceLocation Loc, 1883 const CXXScopeSpec *SS) { 1884 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1885 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1886 } 1887 1888 DeclRefExpr * 1889 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1890 const DeclarationNameInfo &NameInfo, 1891 const CXXScopeSpec *SS, NamedDecl *FoundD, 1892 SourceLocation TemplateKWLoc, 1893 const TemplateArgumentListInfo *TemplateArgs) { 1894 NestedNameSpecifierLoc NNS = 1895 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1896 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1897 TemplateArgs); 1898 } 1899 1900 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1901 // A declaration named in an unevaluated operand never constitutes an odr-use. 1902 if (isUnevaluatedContext()) 1903 return NOUR_Unevaluated; 1904 1905 // C++2a [basic.def.odr]p4: 1906 // A variable x whose name appears as a potentially-evaluated expression e 1907 // is odr-used by e unless [...] x is a reference that is usable in 1908 // constant expressions. 1909 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1910 if (VD->getType()->isReferenceType() && 1911 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1912 VD->isUsableInConstantExpressions(Context)) 1913 return NOUR_Constant; 1914 } 1915 1916 // All remaining non-variable cases constitute an odr-use. For variables, we 1917 // need to wait and see how the expression is used. 1918 return NOUR_None; 1919 } 1920 1921 /// BuildDeclRefExpr - Build an expression that references a 1922 /// declaration that does not require a closure capture. 1923 DeclRefExpr * 1924 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1925 const DeclarationNameInfo &NameInfo, 1926 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1927 SourceLocation TemplateKWLoc, 1928 const TemplateArgumentListInfo *TemplateArgs) { 1929 bool RefersToCapturedVariable = 1930 isa<VarDecl>(D) && 1931 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1932 1933 DeclRefExpr *E = DeclRefExpr::Create( 1934 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1935 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1936 MarkDeclRefReferenced(E); 1937 1938 // C++ [except.spec]p17: 1939 // An exception-specification is considered to be needed when: 1940 // - in an expression, the function is the unique lookup result or 1941 // the selected member of a set of overloaded functions. 1942 // 1943 // We delay doing this until after we've built the function reference and 1944 // marked it as used so that: 1945 // a) if the function is defaulted, we get errors from defining it before / 1946 // instead of errors from computing its exception specification, and 1947 // b) if the function is a defaulted comparison, we can use the body we 1948 // build when defining it as input to the exception specification 1949 // computation rather than computing a new body. 1950 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1951 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1952 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1953 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1954 } 1955 } 1956 1957 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1958 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1959 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1960 getCurFunction()->recordUseOfWeak(E); 1961 1962 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1963 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1964 FD = IFD->getAnonField(); 1965 if (FD) { 1966 UnusedPrivateFields.remove(FD); 1967 // Just in case we're building an illegal pointer-to-member. 1968 if (FD->isBitField()) 1969 E->setObjectKind(OK_BitField); 1970 } 1971 1972 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1973 // designates a bit-field. 1974 if (auto *BD = dyn_cast<BindingDecl>(D)) 1975 if (auto *BE = BD->getBinding()) 1976 E->setObjectKind(BE->getObjectKind()); 1977 1978 return E; 1979 } 1980 1981 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1982 /// possibly a list of template arguments. 1983 /// 1984 /// If this produces template arguments, it is permitted to call 1985 /// DecomposeTemplateName. 1986 /// 1987 /// This actually loses a lot of source location information for 1988 /// non-standard name kinds; we should consider preserving that in 1989 /// some way. 1990 void 1991 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1992 TemplateArgumentListInfo &Buffer, 1993 DeclarationNameInfo &NameInfo, 1994 const TemplateArgumentListInfo *&TemplateArgs) { 1995 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1996 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1997 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1998 1999 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2000 Id.TemplateId->NumArgs); 2001 translateTemplateArguments(TemplateArgsPtr, Buffer); 2002 2003 TemplateName TName = Id.TemplateId->Template.get(); 2004 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2005 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2006 TemplateArgs = &Buffer; 2007 } else { 2008 NameInfo = GetNameFromUnqualifiedId(Id); 2009 TemplateArgs = nullptr; 2010 } 2011 } 2012 2013 static void emitEmptyLookupTypoDiagnostic( 2014 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2015 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2016 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2017 DeclContext *Ctx = 2018 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2019 if (!TC) { 2020 // Emit a special diagnostic for failed member lookups. 2021 // FIXME: computing the declaration context might fail here (?) 2022 if (Ctx) 2023 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2024 << SS.getRange(); 2025 else 2026 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2027 return; 2028 } 2029 2030 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2031 bool DroppedSpecifier = 2032 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2033 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2034 ? diag::note_implicit_param_decl 2035 : diag::note_previous_decl; 2036 if (!Ctx) 2037 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2038 SemaRef.PDiag(NoteID)); 2039 else 2040 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2041 << Typo << Ctx << DroppedSpecifier 2042 << SS.getRange(), 2043 SemaRef.PDiag(NoteID)); 2044 } 2045 2046 /// Diagnose an empty lookup. 2047 /// 2048 /// \return false if new lookup candidates were found 2049 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2050 CorrectionCandidateCallback &CCC, 2051 TemplateArgumentListInfo *ExplicitTemplateArgs, 2052 ArrayRef<Expr *> Args, TypoExpr **Out) { 2053 DeclarationName Name = R.getLookupName(); 2054 2055 unsigned diagnostic = diag::err_undeclared_var_use; 2056 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2057 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2058 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2059 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2060 diagnostic = diag::err_undeclared_use; 2061 diagnostic_suggest = diag::err_undeclared_use_suggest; 2062 } 2063 2064 // If the original lookup was an unqualified lookup, fake an 2065 // unqualified lookup. This is useful when (for example) the 2066 // original lookup would not have found something because it was a 2067 // dependent name. 2068 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2069 while (DC) { 2070 if (isa<CXXRecordDecl>(DC)) { 2071 LookupQualifiedName(R, DC); 2072 2073 if (!R.empty()) { 2074 // Don't give errors about ambiguities in this lookup. 2075 R.suppressDiagnostics(); 2076 2077 // During a default argument instantiation the CurContext points 2078 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2079 // function parameter list, hence add an explicit check. 2080 bool isDefaultArgument = 2081 !CodeSynthesisContexts.empty() && 2082 CodeSynthesisContexts.back().Kind == 2083 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2084 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2085 bool isInstance = CurMethod && 2086 CurMethod->isInstance() && 2087 DC == CurMethod->getParent() && !isDefaultArgument; 2088 2089 // Give a code modification hint to insert 'this->'. 2090 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2091 // Actually quite difficult! 2092 if (getLangOpts().MSVCCompat) 2093 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2094 if (isInstance) { 2095 Diag(R.getNameLoc(), diagnostic) << Name 2096 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2097 CheckCXXThisCapture(R.getNameLoc()); 2098 } else { 2099 Diag(R.getNameLoc(), diagnostic) << Name; 2100 } 2101 2102 // Do we really want to note all of these? 2103 for (NamedDecl *D : R) 2104 Diag(D->getLocation(), diag::note_dependent_var_use); 2105 2106 // Return true if we are inside a default argument instantiation 2107 // and the found name refers to an instance member function, otherwise 2108 // the function calling DiagnoseEmptyLookup will try to create an 2109 // implicit member call and this is wrong for default argument. 2110 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2111 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2112 return true; 2113 } 2114 2115 // Tell the callee to try to recover. 2116 return false; 2117 } 2118 2119 R.clear(); 2120 } 2121 2122 DC = DC->getLookupParent(); 2123 } 2124 2125 // We didn't find anything, so try to correct for a typo. 2126 TypoCorrection Corrected; 2127 if (S && Out) { 2128 SourceLocation TypoLoc = R.getNameLoc(); 2129 assert(!ExplicitTemplateArgs && 2130 "Diagnosing an empty lookup with explicit template args!"); 2131 *Out = CorrectTypoDelayed( 2132 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2133 [=](const TypoCorrection &TC) { 2134 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2135 diagnostic, diagnostic_suggest); 2136 }, 2137 nullptr, CTK_ErrorRecovery); 2138 if (*Out) 2139 return true; 2140 } else if (S && 2141 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2142 S, &SS, CCC, CTK_ErrorRecovery))) { 2143 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2144 bool DroppedSpecifier = 2145 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2146 R.setLookupName(Corrected.getCorrection()); 2147 2148 bool AcceptableWithRecovery = false; 2149 bool AcceptableWithoutRecovery = false; 2150 NamedDecl *ND = Corrected.getFoundDecl(); 2151 if (ND) { 2152 if (Corrected.isOverloaded()) { 2153 OverloadCandidateSet OCS(R.getNameLoc(), 2154 OverloadCandidateSet::CSK_Normal); 2155 OverloadCandidateSet::iterator Best; 2156 for (NamedDecl *CD : Corrected) { 2157 if (FunctionTemplateDecl *FTD = 2158 dyn_cast<FunctionTemplateDecl>(CD)) 2159 AddTemplateOverloadCandidate( 2160 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2161 Args, OCS); 2162 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2163 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2164 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2165 Args, OCS); 2166 } 2167 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2168 case OR_Success: 2169 ND = Best->FoundDecl; 2170 Corrected.setCorrectionDecl(ND); 2171 break; 2172 default: 2173 // FIXME: Arbitrarily pick the first declaration for the note. 2174 Corrected.setCorrectionDecl(ND); 2175 break; 2176 } 2177 } 2178 R.addDecl(ND); 2179 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2180 CXXRecordDecl *Record = nullptr; 2181 if (Corrected.getCorrectionSpecifier()) { 2182 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2183 Record = Ty->getAsCXXRecordDecl(); 2184 } 2185 if (!Record) 2186 Record = cast<CXXRecordDecl>( 2187 ND->getDeclContext()->getRedeclContext()); 2188 R.setNamingClass(Record); 2189 } 2190 2191 auto *UnderlyingND = ND->getUnderlyingDecl(); 2192 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2193 isa<FunctionTemplateDecl>(UnderlyingND); 2194 // FIXME: If we ended up with a typo for a type name or 2195 // Objective-C class name, we're in trouble because the parser 2196 // is in the wrong place to recover. Suggest the typo 2197 // correction, but don't make it a fix-it since we're not going 2198 // to recover well anyway. 2199 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2200 getAsTypeTemplateDecl(UnderlyingND) || 2201 isa<ObjCInterfaceDecl>(UnderlyingND); 2202 } else { 2203 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2204 // because we aren't able to recover. 2205 AcceptableWithoutRecovery = true; 2206 } 2207 2208 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2209 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2210 ? diag::note_implicit_param_decl 2211 : diag::note_previous_decl; 2212 if (SS.isEmpty()) 2213 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2214 PDiag(NoteID), AcceptableWithRecovery); 2215 else 2216 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2217 << Name << computeDeclContext(SS, false) 2218 << DroppedSpecifier << SS.getRange(), 2219 PDiag(NoteID), AcceptableWithRecovery); 2220 2221 // Tell the callee whether to try to recover. 2222 return !AcceptableWithRecovery; 2223 } 2224 } 2225 R.clear(); 2226 2227 // Emit a special diagnostic for failed member lookups. 2228 // FIXME: computing the declaration context might fail here (?) 2229 if (!SS.isEmpty()) { 2230 Diag(R.getNameLoc(), diag::err_no_member) 2231 << Name << computeDeclContext(SS, false) 2232 << SS.getRange(); 2233 return true; 2234 } 2235 2236 // Give up, we can't recover. 2237 Diag(R.getNameLoc(), diagnostic) << Name; 2238 return true; 2239 } 2240 2241 /// In Microsoft mode, if we are inside a template class whose parent class has 2242 /// dependent base classes, and we can't resolve an unqualified identifier, then 2243 /// assume the identifier is a member of a dependent base class. We can only 2244 /// recover successfully in static methods, instance methods, and other contexts 2245 /// where 'this' is available. This doesn't precisely match MSVC's 2246 /// instantiation model, but it's close enough. 2247 static Expr * 2248 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2249 DeclarationNameInfo &NameInfo, 2250 SourceLocation TemplateKWLoc, 2251 const TemplateArgumentListInfo *TemplateArgs) { 2252 // Only try to recover from lookup into dependent bases in static methods or 2253 // contexts where 'this' is available. 2254 QualType ThisType = S.getCurrentThisType(); 2255 const CXXRecordDecl *RD = nullptr; 2256 if (!ThisType.isNull()) 2257 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2258 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2259 RD = MD->getParent(); 2260 if (!RD || !RD->hasAnyDependentBases()) 2261 return nullptr; 2262 2263 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2264 // is available, suggest inserting 'this->' as a fixit. 2265 SourceLocation Loc = NameInfo.getLoc(); 2266 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2267 DB << NameInfo.getName() << RD; 2268 2269 if (!ThisType.isNull()) { 2270 DB << FixItHint::CreateInsertion(Loc, "this->"); 2271 return CXXDependentScopeMemberExpr::Create( 2272 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2273 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2274 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2275 } 2276 2277 // Synthesize a fake NNS that points to the derived class. This will 2278 // perform name lookup during template instantiation. 2279 CXXScopeSpec SS; 2280 auto *NNS = 2281 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2282 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2283 return DependentScopeDeclRefExpr::Create( 2284 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2285 TemplateArgs); 2286 } 2287 2288 ExprResult 2289 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2290 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2291 bool HasTrailingLParen, bool IsAddressOfOperand, 2292 CorrectionCandidateCallback *CCC, 2293 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2294 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2295 "cannot be direct & operand and have a trailing lparen"); 2296 if (SS.isInvalid()) 2297 return ExprError(); 2298 2299 TemplateArgumentListInfo TemplateArgsBuffer; 2300 2301 // Decompose the UnqualifiedId into the following data. 2302 DeclarationNameInfo NameInfo; 2303 const TemplateArgumentListInfo *TemplateArgs; 2304 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2305 2306 DeclarationName Name = NameInfo.getName(); 2307 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2308 SourceLocation NameLoc = NameInfo.getLoc(); 2309 2310 if (II && II->isEditorPlaceholder()) { 2311 // FIXME: When typed placeholders are supported we can create a typed 2312 // placeholder expression node. 2313 return ExprError(); 2314 } 2315 2316 // C++ [temp.dep.expr]p3: 2317 // An id-expression is type-dependent if it contains: 2318 // -- an identifier that was declared with a dependent type, 2319 // (note: handled after lookup) 2320 // -- a template-id that is dependent, 2321 // (note: handled in BuildTemplateIdExpr) 2322 // -- a conversion-function-id that specifies a dependent type, 2323 // -- a nested-name-specifier that contains a class-name that 2324 // names a dependent type. 2325 // Determine whether this is a member of an unknown specialization; 2326 // we need to handle these differently. 2327 bool DependentID = false; 2328 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2329 Name.getCXXNameType()->isDependentType()) { 2330 DependentID = true; 2331 } else if (SS.isSet()) { 2332 if (DeclContext *DC = computeDeclContext(SS, false)) { 2333 if (RequireCompleteDeclContext(SS, DC)) 2334 return ExprError(); 2335 } else { 2336 DependentID = true; 2337 } 2338 } 2339 2340 if (DependentID) 2341 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2342 IsAddressOfOperand, TemplateArgs); 2343 2344 // Perform the required lookup. 2345 LookupResult R(*this, NameInfo, 2346 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2347 ? LookupObjCImplicitSelfParam 2348 : LookupOrdinaryName); 2349 if (TemplateKWLoc.isValid() || TemplateArgs) { 2350 // Lookup the template name again to correctly establish the context in 2351 // which it was found. This is really unfortunate as we already did the 2352 // lookup to determine that it was a template name in the first place. If 2353 // this becomes a performance hit, we can work harder to preserve those 2354 // results until we get here but it's likely not worth it. 2355 bool MemberOfUnknownSpecialization; 2356 AssumedTemplateKind AssumedTemplate; 2357 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2358 MemberOfUnknownSpecialization, TemplateKWLoc, 2359 &AssumedTemplate)) 2360 return ExprError(); 2361 2362 if (MemberOfUnknownSpecialization || 2363 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2364 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2365 IsAddressOfOperand, TemplateArgs); 2366 } else { 2367 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2368 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2369 2370 // If the result might be in a dependent base class, this is a dependent 2371 // id-expression. 2372 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2373 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2374 IsAddressOfOperand, TemplateArgs); 2375 2376 // If this reference is in an Objective-C method, then we need to do 2377 // some special Objective-C lookup, too. 2378 if (IvarLookupFollowUp) { 2379 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2380 if (E.isInvalid()) 2381 return ExprError(); 2382 2383 if (Expr *Ex = E.getAs<Expr>()) 2384 return Ex; 2385 } 2386 } 2387 2388 if (R.isAmbiguous()) 2389 return ExprError(); 2390 2391 // This could be an implicitly declared function reference (legal in C90, 2392 // extension in C99, forbidden in C++). 2393 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2394 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2395 if (D) R.addDecl(D); 2396 } 2397 2398 // Determine whether this name might be a candidate for 2399 // argument-dependent lookup. 2400 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2401 2402 if (R.empty() && !ADL) { 2403 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2404 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2405 TemplateKWLoc, TemplateArgs)) 2406 return E; 2407 } 2408 2409 // Don't diagnose an empty lookup for inline assembly. 2410 if (IsInlineAsmIdentifier) 2411 return ExprError(); 2412 2413 // If this name wasn't predeclared and if this is not a function 2414 // call, diagnose the problem. 2415 TypoExpr *TE = nullptr; 2416 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2417 : nullptr); 2418 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2419 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2420 "Typo correction callback misconfigured"); 2421 if (CCC) { 2422 // Make sure the callback knows what the typo being diagnosed is. 2423 CCC->setTypoName(II); 2424 if (SS.isValid()) 2425 CCC->setTypoNNS(SS.getScopeRep()); 2426 } 2427 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2428 // a template name, but we happen to have always already looked up the name 2429 // before we get here if it must be a template name. 2430 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2431 None, &TE)) { 2432 if (TE && KeywordReplacement) { 2433 auto &State = getTypoExprState(TE); 2434 auto BestTC = State.Consumer->getNextCorrection(); 2435 if (BestTC.isKeyword()) { 2436 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2437 if (State.DiagHandler) 2438 State.DiagHandler(BestTC); 2439 KeywordReplacement->startToken(); 2440 KeywordReplacement->setKind(II->getTokenID()); 2441 KeywordReplacement->setIdentifierInfo(II); 2442 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2443 // Clean up the state associated with the TypoExpr, since it has 2444 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2445 clearDelayedTypo(TE); 2446 // Signal that a correction to a keyword was performed by returning a 2447 // valid-but-null ExprResult. 2448 return (Expr*)nullptr; 2449 } 2450 State.Consumer->resetCorrectionStream(); 2451 } 2452 return TE ? TE : ExprError(); 2453 } 2454 2455 assert(!R.empty() && 2456 "DiagnoseEmptyLookup returned false but added no results"); 2457 2458 // If we found an Objective-C instance variable, let 2459 // LookupInObjCMethod build the appropriate expression to 2460 // reference the ivar. 2461 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2462 R.clear(); 2463 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2464 // In a hopelessly buggy code, Objective-C instance variable 2465 // lookup fails and no expression will be built to reference it. 2466 if (!E.isInvalid() && !E.get()) 2467 return ExprError(); 2468 return E; 2469 } 2470 } 2471 2472 // This is guaranteed from this point on. 2473 assert(!R.empty() || ADL); 2474 2475 // Check whether this might be a C++ implicit instance member access. 2476 // C++ [class.mfct.non-static]p3: 2477 // When an id-expression that is not part of a class member access 2478 // syntax and not used to form a pointer to member is used in the 2479 // body of a non-static member function of class X, if name lookup 2480 // resolves the name in the id-expression to a non-static non-type 2481 // member of some class C, the id-expression is transformed into a 2482 // class member access expression using (*this) as the 2483 // postfix-expression to the left of the . operator. 2484 // 2485 // But we don't actually need to do this for '&' operands if R 2486 // resolved to a function or overloaded function set, because the 2487 // expression is ill-formed if it actually works out to be a 2488 // non-static member function: 2489 // 2490 // C++ [expr.ref]p4: 2491 // Otherwise, if E1.E2 refers to a non-static member function. . . 2492 // [t]he expression can be used only as the left-hand operand of a 2493 // member function call. 2494 // 2495 // There are other safeguards against such uses, but it's important 2496 // to get this right here so that we don't end up making a 2497 // spuriously dependent expression if we're inside a dependent 2498 // instance method. 2499 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2500 bool MightBeImplicitMember; 2501 if (!IsAddressOfOperand) 2502 MightBeImplicitMember = true; 2503 else if (!SS.isEmpty()) 2504 MightBeImplicitMember = false; 2505 else if (R.isOverloadedResult()) 2506 MightBeImplicitMember = false; 2507 else if (R.isUnresolvableResult()) 2508 MightBeImplicitMember = true; 2509 else 2510 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2511 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2512 isa<MSPropertyDecl>(R.getFoundDecl()); 2513 2514 if (MightBeImplicitMember) 2515 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2516 R, TemplateArgs, S); 2517 } 2518 2519 if (TemplateArgs || TemplateKWLoc.isValid()) { 2520 2521 // In C++1y, if this is a variable template id, then check it 2522 // in BuildTemplateIdExpr(). 2523 // The single lookup result must be a variable template declaration. 2524 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2525 Id.TemplateId->Kind == TNK_Var_template) { 2526 assert(R.getAsSingle<VarTemplateDecl>() && 2527 "There should only be one declaration found."); 2528 } 2529 2530 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2531 } 2532 2533 return BuildDeclarationNameExpr(SS, R, ADL); 2534 } 2535 2536 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2537 /// declaration name, generally during template instantiation. 2538 /// There's a large number of things which don't need to be done along 2539 /// this path. 2540 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2541 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2542 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2543 DeclContext *DC = computeDeclContext(SS, false); 2544 if (!DC) 2545 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2546 NameInfo, /*TemplateArgs=*/nullptr); 2547 2548 if (RequireCompleteDeclContext(SS, DC)) 2549 return ExprError(); 2550 2551 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2552 LookupQualifiedName(R, DC); 2553 2554 if (R.isAmbiguous()) 2555 return ExprError(); 2556 2557 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2558 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2559 NameInfo, /*TemplateArgs=*/nullptr); 2560 2561 if (R.empty()) { 2562 Diag(NameInfo.getLoc(), diag::err_no_member) 2563 << NameInfo.getName() << DC << SS.getRange(); 2564 return ExprError(); 2565 } 2566 2567 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2568 // Diagnose a missing typename if this resolved unambiguously to a type in 2569 // a dependent context. If we can recover with a type, downgrade this to 2570 // a warning in Microsoft compatibility mode. 2571 unsigned DiagID = diag::err_typename_missing; 2572 if (RecoveryTSI && getLangOpts().MSVCCompat) 2573 DiagID = diag::ext_typename_missing; 2574 SourceLocation Loc = SS.getBeginLoc(); 2575 auto D = Diag(Loc, DiagID); 2576 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2577 << SourceRange(Loc, NameInfo.getEndLoc()); 2578 2579 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2580 // context. 2581 if (!RecoveryTSI) 2582 return ExprError(); 2583 2584 // Only issue the fixit if we're prepared to recover. 2585 D << FixItHint::CreateInsertion(Loc, "typename "); 2586 2587 // Recover by pretending this was an elaborated type. 2588 QualType Ty = Context.getTypeDeclType(TD); 2589 TypeLocBuilder TLB; 2590 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2591 2592 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2593 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2594 QTL.setElaboratedKeywordLoc(SourceLocation()); 2595 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2596 2597 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2598 2599 return ExprEmpty(); 2600 } 2601 2602 // Defend against this resolving to an implicit member access. We usually 2603 // won't get here if this might be a legitimate a class member (we end up in 2604 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2605 // a pointer-to-member or in an unevaluated context in C++11. 2606 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2607 return BuildPossibleImplicitMemberExpr(SS, 2608 /*TemplateKWLoc=*/SourceLocation(), 2609 R, /*TemplateArgs=*/nullptr, S); 2610 2611 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2612 } 2613 2614 /// The parser has read a name in, and Sema has detected that we're currently 2615 /// inside an ObjC method. Perform some additional checks and determine if we 2616 /// should form a reference to an ivar. 2617 /// 2618 /// Ideally, most of this would be done by lookup, but there's 2619 /// actually quite a lot of extra work involved. 2620 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2621 IdentifierInfo *II) { 2622 SourceLocation Loc = Lookup.getNameLoc(); 2623 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2624 2625 // Check for error condition which is already reported. 2626 if (!CurMethod) 2627 return DeclResult(true); 2628 2629 // There are two cases to handle here. 1) scoped lookup could have failed, 2630 // in which case we should look for an ivar. 2) scoped lookup could have 2631 // found a decl, but that decl is outside the current instance method (i.e. 2632 // a global variable). In these two cases, we do a lookup for an ivar with 2633 // this name, if the lookup sucedes, we replace it our current decl. 2634 2635 // If we're in a class method, we don't normally want to look for 2636 // ivars. But if we don't find anything else, and there's an 2637 // ivar, that's an error. 2638 bool IsClassMethod = CurMethod->isClassMethod(); 2639 2640 bool LookForIvars; 2641 if (Lookup.empty()) 2642 LookForIvars = true; 2643 else if (IsClassMethod) 2644 LookForIvars = false; 2645 else 2646 LookForIvars = (Lookup.isSingleResult() && 2647 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2648 ObjCInterfaceDecl *IFace = nullptr; 2649 if (LookForIvars) { 2650 IFace = CurMethod->getClassInterface(); 2651 ObjCInterfaceDecl *ClassDeclared; 2652 ObjCIvarDecl *IV = nullptr; 2653 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2654 // Diagnose using an ivar in a class method. 2655 if (IsClassMethod) { 2656 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2657 return DeclResult(true); 2658 } 2659 2660 // Diagnose the use of an ivar outside of the declaring class. 2661 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2662 !declaresSameEntity(ClassDeclared, IFace) && 2663 !getLangOpts().DebuggerSupport) 2664 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2665 2666 // Success. 2667 return IV; 2668 } 2669 } else if (CurMethod->isInstanceMethod()) { 2670 // We should warn if a local variable hides an ivar. 2671 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2672 ObjCInterfaceDecl *ClassDeclared; 2673 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2674 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2675 declaresSameEntity(IFace, ClassDeclared)) 2676 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2677 } 2678 } 2679 } else if (Lookup.isSingleResult() && 2680 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2681 // If accessing a stand-alone ivar in a class method, this is an error. 2682 if (const ObjCIvarDecl *IV = 2683 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2684 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2685 return DeclResult(true); 2686 } 2687 } 2688 2689 // Didn't encounter an error, didn't find an ivar. 2690 return DeclResult(false); 2691 } 2692 2693 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2694 ObjCIvarDecl *IV) { 2695 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2696 assert(CurMethod && CurMethod->isInstanceMethod() && 2697 "should not reference ivar from this context"); 2698 2699 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2700 assert(IFace && "should not reference ivar from this context"); 2701 2702 // If we're referencing an invalid decl, just return this as a silent 2703 // error node. The error diagnostic was already emitted on the decl. 2704 if (IV->isInvalidDecl()) 2705 return ExprError(); 2706 2707 // Check if referencing a field with __attribute__((deprecated)). 2708 if (DiagnoseUseOfDecl(IV, Loc)) 2709 return ExprError(); 2710 2711 // FIXME: This should use a new expr for a direct reference, don't 2712 // turn this into Self->ivar, just return a BareIVarExpr or something. 2713 IdentifierInfo &II = Context.Idents.get("self"); 2714 UnqualifiedId SelfName; 2715 SelfName.setIdentifier(&II, SourceLocation()); 2716 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2717 CXXScopeSpec SelfScopeSpec; 2718 SourceLocation TemplateKWLoc; 2719 ExprResult SelfExpr = 2720 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2721 /*HasTrailingLParen=*/false, 2722 /*IsAddressOfOperand=*/false); 2723 if (SelfExpr.isInvalid()) 2724 return ExprError(); 2725 2726 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2727 if (SelfExpr.isInvalid()) 2728 return ExprError(); 2729 2730 MarkAnyDeclReferenced(Loc, IV, true); 2731 2732 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2733 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2734 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2735 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2736 2737 ObjCIvarRefExpr *Result = new (Context) 2738 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2739 IV->getLocation(), SelfExpr.get(), true, true); 2740 2741 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2742 if (!isUnevaluatedContext() && 2743 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2744 getCurFunction()->recordUseOfWeak(Result); 2745 } 2746 if (getLangOpts().ObjCAutoRefCount) 2747 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2748 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2749 2750 return Result; 2751 } 2752 2753 /// The parser has read a name in, and Sema has detected that we're currently 2754 /// inside an ObjC method. Perform some additional checks and determine if we 2755 /// should form a reference to an ivar. If so, build an expression referencing 2756 /// that ivar. 2757 ExprResult 2758 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2759 IdentifierInfo *II, bool AllowBuiltinCreation) { 2760 // FIXME: Integrate this lookup step into LookupParsedName. 2761 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2762 if (Ivar.isInvalid()) 2763 return ExprError(); 2764 if (Ivar.isUsable()) 2765 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2766 cast<ObjCIvarDecl>(Ivar.get())); 2767 2768 if (Lookup.empty() && II && AllowBuiltinCreation) 2769 LookupBuiltin(Lookup); 2770 2771 // Sentinel value saying that we didn't do anything special. 2772 return ExprResult(false); 2773 } 2774 2775 /// Cast a base object to a member's actual type. 2776 /// 2777 /// Logically this happens in three phases: 2778 /// 2779 /// * First we cast from the base type to the naming class. 2780 /// The naming class is the class into which we were looking 2781 /// when we found the member; it's the qualifier type if a 2782 /// qualifier was provided, and otherwise it's the base type. 2783 /// 2784 /// * Next we cast from the naming class to the declaring class. 2785 /// If the member we found was brought into a class's scope by 2786 /// a using declaration, this is that class; otherwise it's 2787 /// the class declaring the member. 2788 /// 2789 /// * Finally we cast from the declaring class to the "true" 2790 /// declaring class of the member. This conversion does not 2791 /// obey access control. 2792 ExprResult 2793 Sema::PerformObjectMemberConversion(Expr *From, 2794 NestedNameSpecifier *Qualifier, 2795 NamedDecl *FoundDecl, 2796 NamedDecl *Member) { 2797 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2798 if (!RD) 2799 return From; 2800 2801 QualType DestRecordType; 2802 QualType DestType; 2803 QualType FromRecordType; 2804 QualType FromType = From->getType(); 2805 bool PointerConversions = false; 2806 if (isa<FieldDecl>(Member)) { 2807 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2808 auto FromPtrType = FromType->getAs<PointerType>(); 2809 DestRecordType = Context.getAddrSpaceQualType( 2810 DestRecordType, FromPtrType 2811 ? FromType->getPointeeType().getAddressSpace() 2812 : FromType.getAddressSpace()); 2813 2814 if (FromPtrType) { 2815 DestType = Context.getPointerType(DestRecordType); 2816 FromRecordType = FromPtrType->getPointeeType(); 2817 PointerConversions = true; 2818 } else { 2819 DestType = DestRecordType; 2820 FromRecordType = FromType; 2821 } 2822 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2823 if (Method->isStatic()) 2824 return From; 2825 2826 DestType = Method->getThisType(); 2827 DestRecordType = DestType->getPointeeType(); 2828 2829 if (FromType->getAs<PointerType>()) { 2830 FromRecordType = FromType->getPointeeType(); 2831 PointerConversions = true; 2832 } else { 2833 FromRecordType = FromType; 2834 DestType = DestRecordType; 2835 } 2836 2837 LangAS FromAS = FromRecordType.getAddressSpace(); 2838 LangAS DestAS = DestRecordType.getAddressSpace(); 2839 if (FromAS != DestAS) { 2840 QualType FromRecordTypeWithoutAS = 2841 Context.removeAddrSpaceQualType(FromRecordType); 2842 QualType FromTypeWithDestAS = 2843 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2844 if (PointerConversions) 2845 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2846 From = ImpCastExprToType(From, FromTypeWithDestAS, 2847 CK_AddressSpaceConversion, From->getValueKind()) 2848 .get(); 2849 } 2850 } else { 2851 // No conversion necessary. 2852 return From; 2853 } 2854 2855 if (DestType->isDependentType() || FromType->isDependentType()) 2856 return From; 2857 2858 // If the unqualified types are the same, no conversion is necessary. 2859 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2860 return From; 2861 2862 SourceRange FromRange = From->getSourceRange(); 2863 SourceLocation FromLoc = FromRange.getBegin(); 2864 2865 ExprValueKind VK = From->getValueKind(); 2866 2867 // C++ [class.member.lookup]p8: 2868 // [...] Ambiguities can often be resolved by qualifying a name with its 2869 // class name. 2870 // 2871 // If the member was a qualified name and the qualified referred to a 2872 // specific base subobject type, we'll cast to that intermediate type 2873 // first and then to the object in which the member is declared. That allows 2874 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2875 // 2876 // class Base { public: int x; }; 2877 // class Derived1 : public Base { }; 2878 // class Derived2 : public Base { }; 2879 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2880 // 2881 // void VeryDerived::f() { 2882 // x = 17; // error: ambiguous base subobjects 2883 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2884 // } 2885 if (Qualifier && Qualifier->getAsType()) { 2886 QualType QType = QualType(Qualifier->getAsType(), 0); 2887 assert(QType->isRecordType() && "lookup done with non-record type"); 2888 2889 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2890 2891 // In C++98, the qualifier type doesn't actually have to be a base 2892 // type of the object type, in which case we just ignore it. 2893 // Otherwise build the appropriate casts. 2894 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2895 CXXCastPath BasePath; 2896 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2897 FromLoc, FromRange, &BasePath)) 2898 return ExprError(); 2899 2900 if (PointerConversions) 2901 QType = Context.getPointerType(QType); 2902 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2903 VK, &BasePath).get(); 2904 2905 FromType = QType; 2906 FromRecordType = QRecordType; 2907 2908 // If the qualifier type was the same as the destination type, 2909 // we're done. 2910 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2911 return From; 2912 } 2913 } 2914 2915 bool IgnoreAccess = false; 2916 2917 // If we actually found the member through a using declaration, cast 2918 // down to the using declaration's type. 2919 // 2920 // Pointer equality is fine here because only one declaration of a 2921 // class ever has member declarations. 2922 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2923 assert(isa<UsingShadowDecl>(FoundDecl)); 2924 QualType URecordType = Context.getTypeDeclType( 2925 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2926 2927 // We only need to do this if the naming-class to declaring-class 2928 // conversion is non-trivial. 2929 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2930 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2931 CXXCastPath BasePath; 2932 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2933 FromLoc, FromRange, &BasePath)) 2934 return ExprError(); 2935 2936 QualType UType = URecordType; 2937 if (PointerConversions) 2938 UType = Context.getPointerType(UType); 2939 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2940 VK, &BasePath).get(); 2941 FromType = UType; 2942 FromRecordType = URecordType; 2943 } 2944 2945 // We don't do access control for the conversion from the 2946 // declaring class to the true declaring class. 2947 IgnoreAccess = true; 2948 } 2949 2950 CXXCastPath BasePath; 2951 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2952 FromLoc, FromRange, &BasePath, 2953 IgnoreAccess)) 2954 return ExprError(); 2955 2956 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2957 VK, &BasePath); 2958 } 2959 2960 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2961 const LookupResult &R, 2962 bool HasTrailingLParen) { 2963 // Only when used directly as the postfix-expression of a call. 2964 if (!HasTrailingLParen) 2965 return false; 2966 2967 // Never if a scope specifier was provided. 2968 if (SS.isSet()) 2969 return false; 2970 2971 // Only in C++ or ObjC++. 2972 if (!getLangOpts().CPlusPlus) 2973 return false; 2974 2975 // Turn off ADL when we find certain kinds of declarations during 2976 // normal lookup: 2977 for (NamedDecl *D : R) { 2978 // C++0x [basic.lookup.argdep]p3: 2979 // -- a declaration of a class member 2980 // Since using decls preserve this property, we check this on the 2981 // original decl. 2982 if (D->isCXXClassMember()) 2983 return false; 2984 2985 // C++0x [basic.lookup.argdep]p3: 2986 // -- a block-scope function declaration that is not a 2987 // using-declaration 2988 // NOTE: we also trigger this for function templates (in fact, we 2989 // don't check the decl type at all, since all other decl types 2990 // turn off ADL anyway). 2991 if (isa<UsingShadowDecl>(D)) 2992 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2993 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2994 return false; 2995 2996 // C++0x [basic.lookup.argdep]p3: 2997 // -- a declaration that is neither a function or a function 2998 // template 2999 // And also for builtin functions. 3000 if (isa<FunctionDecl>(D)) { 3001 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3002 3003 // But also builtin functions. 3004 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3005 return false; 3006 } else if (!isa<FunctionTemplateDecl>(D)) 3007 return false; 3008 } 3009 3010 return true; 3011 } 3012 3013 3014 /// Diagnoses obvious problems with the use of the given declaration 3015 /// as an expression. This is only actually called for lookups that 3016 /// were not overloaded, and it doesn't promise that the declaration 3017 /// will in fact be used. 3018 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3019 if (D->isInvalidDecl()) 3020 return true; 3021 3022 if (isa<TypedefNameDecl>(D)) { 3023 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3024 return true; 3025 } 3026 3027 if (isa<ObjCInterfaceDecl>(D)) { 3028 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3029 return true; 3030 } 3031 3032 if (isa<NamespaceDecl>(D)) { 3033 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3034 return true; 3035 } 3036 3037 return false; 3038 } 3039 3040 // Certain multiversion types should be treated as overloaded even when there is 3041 // only one result. 3042 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3043 assert(R.isSingleResult() && "Expected only a single result"); 3044 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3045 return FD && 3046 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3047 } 3048 3049 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3050 LookupResult &R, bool NeedsADL, 3051 bool AcceptInvalidDecl) { 3052 // If this is a single, fully-resolved result and we don't need ADL, 3053 // just build an ordinary singleton decl ref. 3054 if (!NeedsADL && R.isSingleResult() && 3055 !R.getAsSingle<FunctionTemplateDecl>() && 3056 !ShouldLookupResultBeMultiVersionOverload(R)) 3057 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3058 R.getRepresentativeDecl(), nullptr, 3059 AcceptInvalidDecl); 3060 3061 // We only need to check the declaration if there's exactly one 3062 // result, because in the overloaded case the results can only be 3063 // functions and function templates. 3064 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3065 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3066 return ExprError(); 3067 3068 // Otherwise, just build an unresolved lookup expression. Suppress 3069 // any lookup-related diagnostics; we'll hash these out later, when 3070 // we've picked a target. 3071 R.suppressDiagnostics(); 3072 3073 UnresolvedLookupExpr *ULE 3074 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3075 SS.getWithLocInContext(Context), 3076 R.getLookupNameInfo(), 3077 NeedsADL, R.isOverloadedResult(), 3078 R.begin(), R.end()); 3079 3080 return ULE; 3081 } 3082 3083 static void 3084 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3085 ValueDecl *var, DeclContext *DC); 3086 3087 /// Complete semantic analysis for a reference to the given declaration. 3088 ExprResult Sema::BuildDeclarationNameExpr( 3089 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3090 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3091 bool AcceptInvalidDecl) { 3092 assert(D && "Cannot refer to a NULL declaration"); 3093 assert(!isa<FunctionTemplateDecl>(D) && 3094 "Cannot refer unambiguously to a function template"); 3095 3096 SourceLocation Loc = NameInfo.getLoc(); 3097 if (CheckDeclInExpr(*this, Loc, D)) 3098 return ExprError(); 3099 3100 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3101 // Specifically diagnose references to class templates that are missing 3102 // a template argument list. 3103 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3104 return ExprError(); 3105 } 3106 3107 // Make sure that we're referring to a value. 3108 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3109 if (!VD) { 3110 Diag(Loc, diag::err_ref_non_value) 3111 << D << SS.getRange(); 3112 Diag(D->getLocation(), diag::note_declared_at); 3113 return ExprError(); 3114 } 3115 3116 // Check whether this declaration can be used. Note that we suppress 3117 // this check when we're going to perform argument-dependent lookup 3118 // on this function name, because this might not be the function 3119 // that overload resolution actually selects. 3120 if (DiagnoseUseOfDecl(VD, Loc)) 3121 return ExprError(); 3122 3123 // Only create DeclRefExpr's for valid Decl's. 3124 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3125 return ExprError(); 3126 3127 // Handle members of anonymous structs and unions. If we got here, 3128 // and the reference is to a class member indirect field, then this 3129 // must be the subject of a pointer-to-member expression. 3130 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3131 if (!indirectField->isCXXClassMember()) 3132 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3133 indirectField); 3134 3135 { 3136 QualType type = VD->getType(); 3137 if (type.isNull()) 3138 return ExprError(); 3139 ExprValueKind valueKind = VK_RValue; 3140 3141 switch (D->getKind()) { 3142 // Ignore all the non-ValueDecl kinds. 3143 #define ABSTRACT_DECL(kind) 3144 #define VALUE(type, base) 3145 #define DECL(type, base) \ 3146 case Decl::type: 3147 #include "clang/AST/DeclNodes.inc" 3148 llvm_unreachable("invalid value decl kind"); 3149 3150 // These shouldn't make it here. 3151 case Decl::ObjCAtDefsField: 3152 llvm_unreachable("forming non-member reference to ivar?"); 3153 3154 // Enum constants are always r-values and never references. 3155 // Unresolved using declarations are dependent. 3156 case Decl::EnumConstant: 3157 case Decl::UnresolvedUsingValue: 3158 case Decl::OMPDeclareReduction: 3159 case Decl::OMPDeclareMapper: 3160 valueKind = VK_RValue; 3161 break; 3162 3163 // Fields and indirect fields that got here must be for 3164 // pointer-to-member expressions; we just call them l-values for 3165 // internal consistency, because this subexpression doesn't really 3166 // exist in the high-level semantics. 3167 case Decl::Field: 3168 case Decl::IndirectField: 3169 case Decl::ObjCIvar: 3170 assert(getLangOpts().CPlusPlus && 3171 "building reference to field in C?"); 3172 3173 // These can't have reference type in well-formed programs, but 3174 // for internal consistency we do this anyway. 3175 type = type.getNonReferenceType(); 3176 valueKind = VK_LValue; 3177 break; 3178 3179 // Non-type template parameters are either l-values or r-values 3180 // depending on the type. 3181 case Decl::NonTypeTemplateParm: { 3182 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3183 type = reftype->getPointeeType(); 3184 valueKind = VK_LValue; // even if the parameter is an r-value reference 3185 break; 3186 } 3187 3188 // For non-references, we need to strip qualifiers just in case 3189 // the template parameter was declared as 'const int' or whatever. 3190 valueKind = VK_RValue; 3191 type = type.getUnqualifiedType(); 3192 break; 3193 } 3194 3195 case Decl::Var: 3196 case Decl::VarTemplateSpecialization: 3197 case Decl::VarTemplatePartialSpecialization: 3198 case Decl::Decomposition: 3199 case Decl::OMPCapturedExpr: 3200 // In C, "extern void blah;" is valid and is an r-value. 3201 if (!getLangOpts().CPlusPlus && 3202 !type.hasQualifiers() && 3203 type->isVoidType()) { 3204 valueKind = VK_RValue; 3205 break; 3206 } 3207 LLVM_FALLTHROUGH; 3208 3209 case Decl::ImplicitParam: 3210 case Decl::ParmVar: { 3211 // These are always l-values. 3212 valueKind = VK_LValue; 3213 type = type.getNonReferenceType(); 3214 3215 // FIXME: Does the addition of const really only apply in 3216 // potentially-evaluated contexts? Since the variable isn't actually 3217 // captured in an unevaluated context, it seems that the answer is no. 3218 if (!isUnevaluatedContext()) { 3219 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3220 if (!CapturedType.isNull()) 3221 type = CapturedType; 3222 } 3223 3224 break; 3225 } 3226 3227 case Decl::Binding: { 3228 // These are always lvalues. 3229 valueKind = VK_LValue; 3230 type = type.getNonReferenceType(); 3231 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3232 // decides how that's supposed to work. 3233 auto *BD = cast<BindingDecl>(VD); 3234 if (BD->getDeclContext() != CurContext) { 3235 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3236 if (DD && DD->hasLocalStorage()) 3237 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3238 } 3239 break; 3240 } 3241 3242 case Decl::Function: { 3243 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3244 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3245 type = Context.BuiltinFnTy; 3246 valueKind = VK_RValue; 3247 break; 3248 } 3249 } 3250 3251 const FunctionType *fty = type->castAs<FunctionType>(); 3252 3253 // If we're referring to a function with an __unknown_anytype 3254 // result type, make the entire expression __unknown_anytype. 3255 if (fty->getReturnType() == Context.UnknownAnyTy) { 3256 type = Context.UnknownAnyTy; 3257 valueKind = VK_RValue; 3258 break; 3259 } 3260 3261 // Functions are l-values in C++. 3262 if (getLangOpts().CPlusPlus) { 3263 valueKind = VK_LValue; 3264 break; 3265 } 3266 3267 // C99 DR 316 says that, if a function type comes from a 3268 // function definition (without a prototype), that type is only 3269 // used for checking compatibility. Therefore, when referencing 3270 // the function, we pretend that we don't have the full function 3271 // type. 3272 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3273 isa<FunctionProtoType>(fty)) 3274 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3275 fty->getExtInfo()); 3276 3277 // Functions are r-values in C. 3278 valueKind = VK_RValue; 3279 break; 3280 } 3281 3282 case Decl::CXXDeductionGuide: 3283 llvm_unreachable("building reference to deduction guide"); 3284 3285 case Decl::MSProperty: 3286 case Decl::MSGuid: 3287 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3288 // or duplicated between host and device? 3289 valueKind = VK_LValue; 3290 break; 3291 3292 case Decl::CXXMethod: 3293 // If we're referring to a method with an __unknown_anytype 3294 // result type, make the entire expression __unknown_anytype. 3295 // This should only be possible with a type written directly. 3296 if (const FunctionProtoType *proto 3297 = dyn_cast<FunctionProtoType>(VD->getType())) 3298 if (proto->getReturnType() == Context.UnknownAnyTy) { 3299 type = Context.UnknownAnyTy; 3300 valueKind = VK_RValue; 3301 break; 3302 } 3303 3304 // C++ methods are l-values if static, r-values if non-static. 3305 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3306 valueKind = VK_LValue; 3307 break; 3308 } 3309 LLVM_FALLTHROUGH; 3310 3311 case Decl::CXXConversion: 3312 case Decl::CXXDestructor: 3313 case Decl::CXXConstructor: 3314 valueKind = VK_RValue; 3315 break; 3316 } 3317 3318 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3319 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3320 TemplateArgs); 3321 } 3322 } 3323 3324 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3325 SmallString<32> &Target) { 3326 Target.resize(CharByteWidth * (Source.size() + 1)); 3327 char *ResultPtr = &Target[0]; 3328 const llvm::UTF8 *ErrorPtr; 3329 bool success = 3330 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3331 (void)success; 3332 assert(success); 3333 Target.resize(ResultPtr - &Target[0]); 3334 } 3335 3336 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3337 PredefinedExpr::IdentKind IK) { 3338 // Pick the current block, lambda, captured statement or function. 3339 Decl *currentDecl = nullptr; 3340 if (const BlockScopeInfo *BSI = getCurBlock()) 3341 currentDecl = BSI->TheDecl; 3342 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3343 currentDecl = LSI->CallOperator; 3344 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3345 currentDecl = CSI->TheCapturedDecl; 3346 else 3347 currentDecl = getCurFunctionOrMethodDecl(); 3348 3349 if (!currentDecl) { 3350 Diag(Loc, diag::ext_predef_outside_function); 3351 currentDecl = Context.getTranslationUnitDecl(); 3352 } 3353 3354 QualType ResTy; 3355 StringLiteral *SL = nullptr; 3356 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3357 ResTy = Context.DependentTy; 3358 else { 3359 // Pre-defined identifiers are of type char[x], where x is the length of 3360 // the string. 3361 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3362 unsigned Length = Str.length(); 3363 3364 llvm::APInt LengthI(32, Length + 1); 3365 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3366 ResTy = 3367 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3368 SmallString<32> RawChars; 3369 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3370 Str, RawChars); 3371 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3372 ArrayType::Normal, 3373 /*IndexTypeQuals*/ 0); 3374 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3375 /*Pascal*/ false, ResTy, Loc); 3376 } else { 3377 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3378 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3379 ArrayType::Normal, 3380 /*IndexTypeQuals*/ 0); 3381 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3382 /*Pascal*/ false, ResTy, Loc); 3383 } 3384 } 3385 3386 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3387 } 3388 3389 static std::pair<QualType, StringLiteral *> 3390 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3391 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3392 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3393 3394 if (OpType->isDependentType()) { 3395 Result.first = Context.DependentTy; 3396 return Result; 3397 } 3398 3399 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3400 llvm::APInt Length(32, Str.length() + 1); 3401 Result.first = 3402 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3403 Result.first = Context.getConstantArrayType( 3404 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3405 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3406 /*Pascal*/ false, Result.first, OpLoc); 3407 return Result; 3408 } 3409 3410 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3411 TypeSourceInfo *Operand) { 3412 QualType ResultTy; 3413 StringLiteral *SL; 3414 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3415 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3416 3417 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3418 PredefinedExpr::UniqueStableNameType, SL, 3419 Operand); 3420 } 3421 3422 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3423 Expr *E) { 3424 QualType ResultTy; 3425 StringLiteral *SL; 3426 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3427 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3428 3429 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3430 PredefinedExpr::UniqueStableNameExpr, SL, E); 3431 } 3432 3433 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3434 SourceLocation L, SourceLocation R, 3435 ParsedType Ty) { 3436 TypeSourceInfo *TInfo = nullptr; 3437 QualType T = GetTypeFromParser(Ty, &TInfo); 3438 3439 if (T.isNull()) 3440 return ExprError(); 3441 if (!TInfo) 3442 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3443 3444 return BuildUniqueStableName(OpLoc, TInfo); 3445 } 3446 3447 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3448 SourceLocation L, SourceLocation R, 3449 Expr *E) { 3450 return BuildUniqueStableName(OpLoc, E); 3451 } 3452 3453 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3454 PredefinedExpr::IdentKind IK; 3455 3456 switch (Kind) { 3457 default: llvm_unreachable("Unknown simple primary expr!"); 3458 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3459 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3460 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3461 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3462 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3463 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3464 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3465 } 3466 3467 return BuildPredefinedExpr(Loc, IK); 3468 } 3469 3470 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3471 SmallString<16> CharBuffer; 3472 bool Invalid = false; 3473 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3474 if (Invalid) 3475 return ExprError(); 3476 3477 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3478 PP, Tok.getKind()); 3479 if (Literal.hadError()) 3480 return ExprError(); 3481 3482 QualType Ty; 3483 if (Literal.isWide()) 3484 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3485 else if (Literal.isUTF8() && getLangOpts().Char8) 3486 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3487 else if (Literal.isUTF16()) 3488 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3489 else if (Literal.isUTF32()) 3490 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3491 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3492 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3493 else 3494 Ty = Context.CharTy; // 'x' -> char in C++ 3495 3496 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3497 if (Literal.isWide()) 3498 Kind = CharacterLiteral::Wide; 3499 else if (Literal.isUTF16()) 3500 Kind = CharacterLiteral::UTF16; 3501 else if (Literal.isUTF32()) 3502 Kind = CharacterLiteral::UTF32; 3503 else if (Literal.isUTF8()) 3504 Kind = CharacterLiteral::UTF8; 3505 3506 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3507 Tok.getLocation()); 3508 3509 if (Literal.getUDSuffix().empty()) 3510 return Lit; 3511 3512 // We're building a user-defined literal. 3513 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3514 SourceLocation UDSuffixLoc = 3515 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3516 3517 // Make sure we're allowed user-defined literals here. 3518 if (!UDLScope) 3519 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3520 3521 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3522 // operator "" X (ch) 3523 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3524 Lit, Tok.getLocation()); 3525 } 3526 3527 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3528 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3529 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3530 Context.IntTy, Loc); 3531 } 3532 3533 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3534 QualType Ty, SourceLocation Loc) { 3535 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3536 3537 using llvm::APFloat; 3538 APFloat Val(Format); 3539 3540 APFloat::opStatus result = Literal.GetFloatValue(Val); 3541 3542 // Overflow is always an error, but underflow is only an error if 3543 // we underflowed to zero (APFloat reports denormals as underflow). 3544 if ((result & APFloat::opOverflow) || 3545 ((result & APFloat::opUnderflow) && Val.isZero())) { 3546 unsigned diagnostic; 3547 SmallString<20> buffer; 3548 if (result & APFloat::opOverflow) { 3549 diagnostic = diag::warn_float_overflow; 3550 APFloat::getLargest(Format).toString(buffer); 3551 } else { 3552 diagnostic = diag::warn_float_underflow; 3553 APFloat::getSmallest(Format).toString(buffer); 3554 } 3555 3556 S.Diag(Loc, diagnostic) 3557 << Ty 3558 << StringRef(buffer.data(), buffer.size()); 3559 } 3560 3561 bool isExact = (result == APFloat::opOK); 3562 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3563 } 3564 3565 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3566 assert(E && "Invalid expression"); 3567 3568 if (E->isValueDependent()) 3569 return false; 3570 3571 QualType QT = E->getType(); 3572 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3573 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3574 return true; 3575 } 3576 3577 llvm::APSInt ValueAPS; 3578 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3579 3580 if (R.isInvalid()) 3581 return true; 3582 3583 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3584 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3585 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3586 << ValueAPS.toString(10) << ValueIsPositive; 3587 return true; 3588 } 3589 3590 return false; 3591 } 3592 3593 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3594 // Fast path for a single digit (which is quite common). A single digit 3595 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3596 if (Tok.getLength() == 1) { 3597 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3598 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3599 } 3600 3601 SmallString<128> SpellingBuffer; 3602 // NumericLiteralParser wants to overread by one character. Add padding to 3603 // the buffer in case the token is copied to the buffer. If getSpelling() 3604 // returns a StringRef to the memory buffer, it should have a null char at 3605 // the EOF, so it is also safe. 3606 SpellingBuffer.resize(Tok.getLength() + 1); 3607 3608 // Get the spelling of the token, which eliminates trigraphs, etc. 3609 bool Invalid = false; 3610 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3611 if (Invalid) 3612 return ExprError(); 3613 3614 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3615 if (Literal.hadError) 3616 return ExprError(); 3617 3618 if (Literal.hasUDSuffix()) { 3619 // We're building a user-defined literal. 3620 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3621 SourceLocation UDSuffixLoc = 3622 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3623 3624 // Make sure we're allowed user-defined literals here. 3625 if (!UDLScope) 3626 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3627 3628 QualType CookedTy; 3629 if (Literal.isFloatingLiteral()) { 3630 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3631 // long double, the literal is treated as a call of the form 3632 // operator "" X (f L) 3633 CookedTy = Context.LongDoubleTy; 3634 } else { 3635 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3636 // unsigned long long, the literal is treated as a call of the form 3637 // operator "" X (n ULL) 3638 CookedTy = Context.UnsignedLongLongTy; 3639 } 3640 3641 DeclarationName OpName = 3642 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3643 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3644 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3645 3646 SourceLocation TokLoc = Tok.getLocation(); 3647 3648 // Perform literal operator lookup to determine if we're building a raw 3649 // literal or a cooked one. 3650 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3651 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3652 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3653 /*AllowStringTemplate*/ false, 3654 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3655 case LOLR_ErrorNoDiagnostic: 3656 // Lookup failure for imaginary constants isn't fatal, there's still the 3657 // GNU extension producing _Complex types. 3658 break; 3659 case LOLR_Error: 3660 return ExprError(); 3661 case LOLR_Cooked: { 3662 Expr *Lit; 3663 if (Literal.isFloatingLiteral()) { 3664 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3665 } else { 3666 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3667 if (Literal.GetIntegerValue(ResultVal)) 3668 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3669 << /* Unsigned */ 1; 3670 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3671 Tok.getLocation()); 3672 } 3673 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3674 } 3675 3676 case LOLR_Raw: { 3677 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3678 // literal is treated as a call of the form 3679 // operator "" X ("n") 3680 unsigned Length = Literal.getUDSuffixOffset(); 3681 QualType StrTy = Context.getConstantArrayType( 3682 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3683 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3684 Expr *Lit = StringLiteral::Create( 3685 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3686 /*Pascal*/false, StrTy, &TokLoc, 1); 3687 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3688 } 3689 3690 case LOLR_Template: { 3691 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3692 // template), L is treated as a call fo the form 3693 // operator "" X <'c1', 'c2', ... 'ck'>() 3694 // where n is the source character sequence c1 c2 ... ck. 3695 TemplateArgumentListInfo ExplicitArgs; 3696 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3697 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3698 llvm::APSInt Value(CharBits, CharIsUnsigned); 3699 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3700 Value = TokSpelling[I]; 3701 TemplateArgument Arg(Context, Value, Context.CharTy); 3702 TemplateArgumentLocInfo ArgInfo; 3703 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3704 } 3705 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3706 &ExplicitArgs); 3707 } 3708 case LOLR_StringTemplate: 3709 llvm_unreachable("unexpected literal operator lookup result"); 3710 } 3711 } 3712 3713 Expr *Res; 3714 3715 if (Literal.isFixedPointLiteral()) { 3716 QualType Ty; 3717 3718 if (Literal.isAccum) { 3719 if (Literal.isHalf) { 3720 Ty = Context.ShortAccumTy; 3721 } else if (Literal.isLong) { 3722 Ty = Context.LongAccumTy; 3723 } else { 3724 Ty = Context.AccumTy; 3725 } 3726 } else if (Literal.isFract) { 3727 if (Literal.isHalf) { 3728 Ty = Context.ShortFractTy; 3729 } else if (Literal.isLong) { 3730 Ty = Context.LongFractTy; 3731 } else { 3732 Ty = Context.FractTy; 3733 } 3734 } 3735 3736 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3737 3738 bool isSigned = !Literal.isUnsigned; 3739 unsigned scale = Context.getFixedPointScale(Ty); 3740 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3741 3742 llvm::APInt Val(bit_width, 0, isSigned); 3743 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3744 bool ValIsZero = Val.isNullValue() && !Overflowed; 3745 3746 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3747 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3748 // Clause 6.4.4 - The value of a constant shall be in the range of 3749 // representable values for its type, with exception for constants of a 3750 // fract type with a value of exactly 1; such a constant shall denote 3751 // the maximal value for the type. 3752 --Val; 3753 else if (Val.ugt(MaxVal) || Overflowed) 3754 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3755 3756 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3757 Tok.getLocation(), scale); 3758 } else if (Literal.isFloatingLiteral()) { 3759 QualType Ty; 3760 if (Literal.isHalf){ 3761 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3762 Ty = Context.HalfTy; 3763 else { 3764 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3765 return ExprError(); 3766 } 3767 } else if (Literal.isFloat) 3768 Ty = Context.FloatTy; 3769 else if (Literal.isLong) 3770 Ty = Context.LongDoubleTy; 3771 else if (Literal.isFloat16) 3772 Ty = Context.Float16Ty; 3773 else if (Literal.isFloat128) 3774 Ty = Context.Float128Ty; 3775 else 3776 Ty = Context.DoubleTy; 3777 3778 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3779 3780 if (Ty == Context.DoubleTy) { 3781 if (getLangOpts().SinglePrecisionConstants) { 3782 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3783 if (BTy->getKind() != BuiltinType::Float) { 3784 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3785 } 3786 } else if (getLangOpts().OpenCL && 3787 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3788 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3789 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3790 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3791 } 3792 } 3793 } else if (!Literal.isIntegerLiteral()) { 3794 return ExprError(); 3795 } else { 3796 QualType Ty; 3797 3798 // 'long long' is a C99 or C++11 feature. 3799 if (!getLangOpts().C99 && Literal.isLongLong) { 3800 if (getLangOpts().CPlusPlus) 3801 Diag(Tok.getLocation(), 3802 getLangOpts().CPlusPlus11 ? 3803 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3804 else 3805 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3806 } 3807 3808 // Get the value in the widest-possible width. 3809 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3810 llvm::APInt ResultVal(MaxWidth, 0); 3811 3812 if (Literal.GetIntegerValue(ResultVal)) { 3813 // If this value didn't fit into uintmax_t, error and force to ull. 3814 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3815 << /* Unsigned */ 1; 3816 Ty = Context.UnsignedLongLongTy; 3817 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3818 "long long is not intmax_t?"); 3819 } else { 3820 // If this value fits into a ULL, try to figure out what else it fits into 3821 // according to the rules of C99 6.4.4.1p5. 3822 3823 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3824 // be an unsigned int. 3825 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3826 3827 // Check from smallest to largest, picking the smallest type we can. 3828 unsigned Width = 0; 3829 3830 // Microsoft specific integer suffixes are explicitly sized. 3831 if (Literal.MicrosoftInteger) { 3832 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3833 Width = 8; 3834 Ty = Context.CharTy; 3835 } else { 3836 Width = Literal.MicrosoftInteger; 3837 Ty = Context.getIntTypeForBitwidth(Width, 3838 /*Signed=*/!Literal.isUnsigned); 3839 } 3840 } 3841 3842 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3843 // Are int/unsigned possibilities? 3844 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3845 3846 // Does it fit in a unsigned int? 3847 if (ResultVal.isIntN(IntSize)) { 3848 // Does it fit in a signed int? 3849 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3850 Ty = Context.IntTy; 3851 else if (AllowUnsigned) 3852 Ty = Context.UnsignedIntTy; 3853 Width = IntSize; 3854 } 3855 } 3856 3857 // Are long/unsigned long possibilities? 3858 if (Ty.isNull() && !Literal.isLongLong) { 3859 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3860 3861 // Does it fit in a unsigned long? 3862 if (ResultVal.isIntN(LongSize)) { 3863 // Does it fit in a signed long? 3864 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3865 Ty = Context.LongTy; 3866 else if (AllowUnsigned) 3867 Ty = Context.UnsignedLongTy; 3868 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3869 // is compatible. 3870 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3871 const unsigned LongLongSize = 3872 Context.getTargetInfo().getLongLongWidth(); 3873 Diag(Tok.getLocation(), 3874 getLangOpts().CPlusPlus 3875 ? Literal.isLong 3876 ? diag::warn_old_implicitly_unsigned_long_cxx 3877 : /*C++98 UB*/ diag:: 3878 ext_old_implicitly_unsigned_long_cxx 3879 : diag::warn_old_implicitly_unsigned_long) 3880 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3881 : /*will be ill-formed*/ 1); 3882 Ty = Context.UnsignedLongTy; 3883 } 3884 Width = LongSize; 3885 } 3886 } 3887 3888 // Check long long if needed. 3889 if (Ty.isNull()) { 3890 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3891 3892 // Does it fit in a unsigned long long? 3893 if (ResultVal.isIntN(LongLongSize)) { 3894 // Does it fit in a signed long long? 3895 // To be compatible with MSVC, hex integer literals ending with the 3896 // LL or i64 suffix are always signed in Microsoft mode. 3897 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3898 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3899 Ty = Context.LongLongTy; 3900 else if (AllowUnsigned) 3901 Ty = Context.UnsignedLongLongTy; 3902 Width = LongLongSize; 3903 } 3904 } 3905 3906 // If we still couldn't decide a type, we probably have something that 3907 // does not fit in a signed long long, but has no U suffix. 3908 if (Ty.isNull()) { 3909 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3910 Ty = Context.UnsignedLongLongTy; 3911 Width = Context.getTargetInfo().getLongLongWidth(); 3912 } 3913 3914 if (ResultVal.getBitWidth() != Width) 3915 ResultVal = ResultVal.trunc(Width); 3916 } 3917 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3918 } 3919 3920 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3921 if (Literal.isImaginary) { 3922 Res = new (Context) ImaginaryLiteral(Res, 3923 Context.getComplexType(Res->getType())); 3924 3925 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3926 } 3927 return Res; 3928 } 3929 3930 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3931 assert(E && "ActOnParenExpr() missing expr"); 3932 return new (Context) ParenExpr(L, R, E); 3933 } 3934 3935 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3936 SourceLocation Loc, 3937 SourceRange ArgRange) { 3938 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3939 // scalar or vector data type argument..." 3940 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3941 // type (C99 6.2.5p18) or void. 3942 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3943 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3944 << T << ArgRange; 3945 return true; 3946 } 3947 3948 assert((T->isVoidType() || !T->isIncompleteType()) && 3949 "Scalar types should always be complete"); 3950 return false; 3951 } 3952 3953 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3954 SourceLocation Loc, 3955 SourceRange ArgRange, 3956 UnaryExprOrTypeTrait TraitKind) { 3957 // Invalid types must be hard errors for SFINAE in C++. 3958 if (S.LangOpts.CPlusPlus) 3959 return true; 3960 3961 // C99 6.5.3.4p1: 3962 if (T->isFunctionType() && 3963 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3964 TraitKind == UETT_PreferredAlignOf)) { 3965 // sizeof(function)/alignof(function) is allowed as an extension. 3966 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3967 << TraitKind << ArgRange; 3968 return false; 3969 } 3970 3971 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3972 // this is an error (OpenCL v1.1 s6.3.k) 3973 if (T->isVoidType()) { 3974 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3975 : diag::ext_sizeof_alignof_void_type; 3976 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3977 return false; 3978 } 3979 3980 return true; 3981 } 3982 3983 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3984 SourceLocation Loc, 3985 SourceRange ArgRange, 3986 UnaryExprOrTypeTrait TraitKind) { 3987 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3988 // runtime doesn't allow it. 3989 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3990 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3991 << T << (TraitKind == UETT_SizeOf) 3992 << ArgRange; 3993 return true; 3994 } 3995 3996 return false; 3997 } 3998 3999 /// Check whether E is a pointer from a decayed array type (the decayed 4000 /// pointer type is equal to T) and emit a warning if it is. 4001 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4002 Expr *E) { 4003 // Don't warn if the operation changed the type. 4004 if (T != E->getType()) 4005 return; 4006 4007 // Now look for array decays. 4008 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4009 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4010 return; 4011 4012 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4013 << ICE->getType() 4014 << ICE->getSubExpr()->getType(); 4015 } 4016 4017 /// Check the constraints on expression operands to unary type expression 4018 /// and type traits. 4019 /// 4020 /// Completes any types necessary and validates the constraints on the operand 4021 /// expression. The logic mostly mirrors the type-based overload, but may modify 4022 /// the expression as it completes the type for that expression through template 4023 /// instantiation, etc. 4024 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4025 UnaryExprOrTypeTrait ExprKind) { 4026 QualType ExprTy = E->getType(); 4027 assert(!ExprTy->isReferenceType()); 4028 4029 bool IsUnevaluatedOperand = 4030 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4031 ExprKind == UETT_PreferredAlignOf); 4032 if (IsUnevaluatedOperand) { 4033 ExprResult Result = CheckUnevaluatedOperand(E); 4034 if (Result.isInvalid()) 4035 return true; 4036 E = Result.get(); 4037 } 4038 4039 if (ExprKind == UETT_VecStep) 4040 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4041 E->getSourceRange()); 4042 4043 // Whitelist some types as extensions 4044 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4045 E->getSourceRange(), ExprKind)) 4046 return false; 4047 4048 // 'alignof' applied to an expression only requires the base element type of 4049 // the expression to be complete. 'sizeof' requires the expression's type to 4050 // be complete (and will attempt to complete it if it's an array of unknown 4051 // bound). 4052 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4053 if (RequireCompleteSizedType( 4054 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4055 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4056 E->getSourceRange())) 4057 return true; 4058 } else { 4059 if (RequireCompleteSizedExprType( 4060 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4061 E->getSourceRange())) 4062 return true; 4063 } 4064 4065 // Completing the expression's type may have changed it. 4066 ExprTy = E->getType(); 4067 assert(!ExprTy->isReferenceType()); 4068 4069 if (ExprTy->isFunctionType()) { 4070 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4071 << ExprKind << E->getSourceRange(); 4072 return true; 4073 } 4074 4075 // The operand for sizeof and alignof is in an unevaluated expression context, 4076 // so side effects could result in unintended consequences. 4077 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4078 E->HasSideEffects(Context, false)) 4079 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4080 4081 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4082 E->getSourceRange(), ExprKind)) 4083 return true; 4084 4085 if (ExprKind == UETT_SizeOf) { 4086 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4087 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4088 QualType OType = PVD->getOriginalType(); 4089 QualType Type = PVD->getType(); 4090 if (Type->isPointerType() && OType->isArrayType()) { 4091 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4092 << Type << OType; 4093 Diag(PVD->getLocation(), diag::note_declared_at); 4094 } 4095 } 4096 } 4097 4098 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4099 // decays into a pointer and returns an unintended result. This is most 4100 // likely a typo for "sizeof(array) op x". 4101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4102 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4103 BO->getLHS()); 4104 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4105 BO->getRHS()); 4106 } 4107 } 4108 4109 return false; 4110 } 4111 4112 /// Check the constraints on operands to unary expression and type 4113 /// traits. 4114 /// 4115 /// This will complete any types necessary, and validate the various constraints 4116 /// on those operands. 4117 /// 4118 /// The UsualUnaryConversions() function is *not* called by this routine. 4119 /// C99 6.3.2.1p[2-4] all state: 4120 /// Except when it is the operand of the sizeof operator ... 4121 /// 4122 /// C++ [expr.sizeof]p4 4123 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4124 /// standard conversions are not applied to the operand of sizeof. 4125 /// 4126 /// This policy is followed for all of the unary trait expressions. 4127 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4128 SourceLocation OpLoc, 4129 SourceRange ExprRange, 4130 UnaryExprOrTypeTrait ExprKind) { 4131 if (ExprType->isDependentType()) 4132 return false; 4133 4134 // C++ [expr.sizeof]p2: 4135 // When applied to a reference or a reference type, the result 4136 // is the size of the referenced type. 4137 // C++11 [expr.alignof]p3: 4138 // When alignof is applied to a reference type, the result 4139 // shall be the alignment of the referenced type. 4140 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4141 ExprType = Ref->getPointeeType(); 4142 4143 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4144 // When alignof or _Alignof is applied to an array type, the result 4145 // is the alignment of the element type. 4146 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4147 ExprKind == UETT_OpenMPRequiredSimdAlign) 4148 ExprType = Context.getBaseElementType(ExprType); 4149 4150 if (ExprKind == UETT_VecStep) 4151 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4152 4153 // Whitelist some types as extensions 4154 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4155 ExprKind)) 4156 return false; 4157 4158 if (RequireCompleteSizedType( 4159 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4160 ExprKind, ExprRange)) 4161 return true; 4162 4163 if (ExprType->isFunctionType()) { 4164 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4165 << ExprKind << ExprRange; 4166 return true; 4167 } 4168 4169 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4170 ExprKind)) 4171 return true; 4172 4173 return false; 4174 } 4175 4176 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4177 // Cannot know anything else if the expression is dependent. 4178 if (E->isTypeDependent()) 4179 return false; 4180 4181 if (E->getObjectKind() == OK_BitField) { 4182 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4183 << 1 << E->getSourceRange(); 4184 return true; 4185 } 4186 4187 ValueDecl *D = nullptr; 4188 Expr *Inner = E->IgnoreParens(); 4189 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4190 D = DRE->getDecl(); 4191 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4192 D = ME->getMemberDecl(); 4193 } 4194 4195 // If it's a field, require the containing struct to have a 4196 // complete definition so that we can compute the layout. 4197 // 4198 // This can happen in C++11 onwards, either by naming the member 4199 // in a way that is not transformed into a member access expression 4200 // (in an unevaluated operand, for instance), or by naming the member 4201 // in a trailing-return-type. 4202 // 4203 // For the record, since __alignof__ on expressions is a GCC 4204 // extension, GCC seems to permit this but always gives the 4205 // nonsensical answer 0. 4206 // 4207 // We don't really need the layout here --- we could instead just 4208 // directly check for all the appropriate alignment-lowing 4209 // attributes --- but that would require duplicating a lot of 4210 // logic that just isn't worth duplicating for such a marginal 4211 // use-case. 4212 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4213 // Fast path this check, since we at least know the record has a 4214 // definition if we can find a member of it. 4215 if (!FD->getParent()->isCompleteDefinition()) { 4216 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4217 << E->getSourceRange(); 4218 return true; 4219 } 4220 4221 // Otherwise, if it's a field, and the field doesn't have 4222 // reference type, then it must have a complete type (or be a 4223 // flexible array member, which we explicitly want to 4224 // white-list anyway), which makes the following checks trivial. 4225 if (!FD->getType()->isReferenceType()) 4226 return false; 4227 } 4228 4229 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4230 } 4231 4232 bool Sema::CheckVecStepExpr(Expr *E) { 4233 E = E->IgnoreParens(); 4234 4235 // Cannot know anything else if the expression is dependent. 4236 if (E->isTypeDependent()) 4237 return false; 4238 4239 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4240 } 4241 4242 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4243 CapturingScopeInfo *CSI) { 4244 assert(T->isVariablyModifiedType()); 4245 assert(CSI != nullptr); 4246 4247 // We're going to walk down into the type and look for VLA expressions. 4248 do { 4249 const Type *Ty = T.getTypePtr(); 4250 switch (Ty->getTypeClass()) { 4251 #define TYPE(Class, Base) 4252 #define ABSTRACT_TYPE(Class, Base) 4253 #define NON_CANONICAL_TYPE(Class, Base) 4254 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4255 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4256 #include "clang/AST/TypeNodes.inc" 4257 T = QualType(); 4258 break; 4259 // These types are never variably-modified. 4260 case Type::Builtin: 4261 case Type::Complex: 4262 case Type::Vector: 4263 case Type::ExtVector: 4264 case Type::ConstantMatrix: 4265 case Type::Record: 4266 case Type::Enum: 4267 case Type::Elaborated: 4268 case Type::TemplateSpecialization: 4269 case Type::ObjCObject: 4270 case Type::ObjCInterface: 4271 case Type::ObjCObjectPointer: 4272 case Type::ObjCTypeParam: 4273 case Type::Pipe: 4274 case Type::ExtInt: 4275 llvm_unreachable("type class is never variably-modified!"); 4276 case Type::Adjusted: 4277 T = cast<AdjustedType>(Ty)->getOriginalType(); 4278 break; 4279 case Type::Decayed: 4280 T = cast<DecayedType>(Ty)->getPointeeType(); 4281 break; 4282 case Type::Pointer: 4283 T = cast<PointerType>(Ty)->getPointeeType(); 4284 break; 4285 case Type::BlockPointer: 4286 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4287 break; 4288 case Type::LValueReference: 4289 case Type::RValueReference: 4290 T = cast<ReferenceType>(Ty)->getPointeeType(); 4291 break; 4292 case Type::MemberPointer: 4293 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4294 break; 4295 case Type::ConstantArray: 4296 case Type::IncompleteArray: 4297 // Losing element qualification here is fine. 4298 T = cast<ArrayType>(Ty)->getElementType(); 4299 break; 4300 case Type::VariableArray: { 4301 // Losing element qualification here is fine. 4302 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4303 4304 // Unknown size indication requires no size computation. 4305 // Otherwise, evaluate and record it. 4306 auto Size = VAT->getSizeExpr(); 4307 if (Size && !CSI->isVLATypeCaptured(VAT) && 4308 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4309 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4310 4311 T = VAT->getElementType(); 4312 break; 4313 } 4314 case Type::FunctionProto: 4315 case Type::FunctionNoProto: 4316 T = cast<FunctionType>(Ty)->getReturnType(); 4317 break; 4318 case Type::Paren: 4319 case Type::TypeOf: 4320 case Type::UnaryTransform: 4321 case Type::Attributed: 4322 case Type::SubstTemplateTypeParm: 4323 case Type::PackExpansion: 4324 case Type::MacroQualified: 4325 // Keep walking after single level desugaring. 4326 T = T.getSingleStepDesugaredType(Context); 4327 break; 4328 case Type::Typedef: 4329 T = cast<TypedefType>(Ty)->desugar(); 4330 break; 4331 case Type::Decltype: 4332 T = cast<DecltypeType>(Ty)->desugar(); 4333 break; 4334 case Type::Auto: 4335 case Type::DeducedTemplateSpecialization: 4336 T = cast<DeducedType>(Ty)->getDeducedType(); 4337 break; 4338 case Type::TypeOfExpr: 4339 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4340 break; 4341 case Type::Atomic: 4342 T = cast<AtomicType>(Ty)->getValueType(); 4343 break; 4344 } 4345 } while (!T.isNull() && T->isVariablyModifiedType()); 4346 } 4347 4348 /// Build a sizeof or alignof expression given a type operand. 4349 ExprResult 4350 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4351 SourceLocation OpLoc, 4352 UnaryExprOrTypeTrait ExprKind, 4353 SourceRange R) { 4354 if (!TInfo) 4355 return ExprError(); 4356 4357 QualType T = TInfo->getType(); 4358 4359 if (!T->isDependentType() && 4360 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4361 return ExprError(); 4362 4363 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4364 if (auto *TT = T->getAs<TypedefType>()) { 4365 for (auto I = FunctionScopes.rbegin(), 4366 E = std::prev(FunctionScopes.rend()); 4367 I != E; ++I) { 4368 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4369 if (CSI == nullptr) 4370 break; 4371 DeclContext *DC = nullptr; 4372 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4373 DC = LSI->CallOperator; 4374 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4375 DC = CRSI->TheCapturedDecl; 4376 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4377 DC = BSI->TheDecl; 4378 if (DC) { 4379 if (DC->containsDecl(TT->getDecl())) 4380 break; 4381 captureVariablyModifiedType(Context, T, CSI); 4382 } 4383 } 4384 } 4385 } 4386 4387 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4388 return new (Context) UnaryExprOrTypeTraitExpr( 4389 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4390 } 4391 4392 /// Build a sizeof or alignof expression given an expression 4393 /// operand. 4394 ExprResult 4395 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4396 UnaryExprOrTypeTrait ExprKind) { 4397 ExprResult PE = CheckPlaceholderExpr(E); 4398 if (PE.isInvalid()) 4399 return ExprError(); 4400 4401 E = PE.get(); 4402 4403 // Verify that the operand is valid. 4404 bool isInvalid = false; 4405 if (E->isTypeDependent()) { 4406 // Delay type-checking for type-dependent expressions. 4407 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4408 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4409 } else if (ExprKind == UETT_VecStep) { 4410 isInvalid = CheckVecStepExpr(E); 4411 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4412 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4413 isInvalid = true; 4414 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4415 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4416 isInvalid = true; 4417 } else { 4418 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4419 } 4420 4421 if (isInvalid) 4422 return ExprError(); 4423 4424 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4425 PE = TransformToPotentiallyEvaluated(E); 4426 if (PE.isInvalid()) return ExprError(); 4427 E = PE.get(); 4428 } 4429 4430 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4431 return new (Context) UnaryExprOrTypeTraitExpr( 4432 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4433 } 4434 4435 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4436 /// expr and the same for @c alignof and @c __alignof 4437 /// Note that the ArgRange is invalid if isType is false. 4438 ExprResult 4439 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4440 UnaryExprOrTypeTrait ExprKind, bool IsType, 4441 void *TyOrEx, SourceRange ArgRange) { 4442 // If error parsing type, ignore. 4443 if (!TyOrEx) return ExprError(); 4444 4445 if (IsType) { 4446 TypeSourceInfo *TInfo; 4447 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4448 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4449 } 4450 4451 Expr *ArgEx = (Expr *)TyOrEx; 4452 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4453 return Result; 4454 } 4455 4456 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4457 bool IsReal) { 4458 if (V.get()->isTypeDependent()) 4459 return S.Context.DependentTy; 4460 4461 // _Real and _Imag are only l-values for normal l-values. 4462 if (V.get()->getObjectKind() != OK_Ordinary) { 4463 V = S.DefaultLvalueConversion(V.get()); 4464 if (V.isInvalid()) 4465 return QualType(); 4466 } 4467 4468 // These operators return the element type of a complex type. 4469 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4470 return CT->getElementType(); 4471 4472 // Otherwise they pass through real integer and floating point types here. 4473 if (V.get()->getType()->isArithmeticType()) 4474 return V.get()->getType(); 4475 4476 // Test for placeholders. 4477 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4478 if (PR.isInvalid()) return QualType(); 4479 if (PR.get() != V.get()) { 4480 V = PR; 4481 return CheckRealImagOperand(S, V, Loc, IsReal); 4482 } 4483 4484 // Reject anything else. 4485 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4486 << (IsReal ? "__real" : "__imag"); 4487 return QualType(); 4488 } 4489 4490 4491 4492 ExprResult 4493 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4494 tok::TokenKind Kind, Expr *Input) { 4495 UnaryOperatorKind Opc; 4496 switch (Kind) { 4497 default: llvm_unreachable("Unknown unary op!"); 4498 case tok::plusplus: Opc = UO_PostInc; break; 4499 case tok::minusminus: Opc = UO_PostDec; break; 4500 } 4501 4502 // Since this might is a postfix expression, get rid of ParenListExprs. 4503 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4504 if (Result.isInvalid()) return ExprError(); 4505 Input = Result.get(); 4506 4507 return BuildUnaryOp(S, OpLoc, Opc, Input); 4508 } 4509 4510 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4511 /// 4512 /// \return true on error 4513 static bool checkArithmeticOnObjCPointer(Sema &S, 4514 SourceLocation opLoc, 4515 Expr *op) { 4516 assert(op->getType()->isObjCObjectPointerType()); 4517 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4518 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4519 return false; 4520 4521 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4522 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4523 << op->getSourceRange(); 4524 return true; 4525 } 4526 4527 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4528 auto *BaseNoParens = Base->IgnoreParens(); 4529 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4530 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4531 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4532 } 4533 4534 ExprResult 4535 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4536 Expr *idx, SourceLocation rbLoc) { 4537 if (base && !base->getType().isNull() && 4538 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4539 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4540 /*Length=*/nullptr, rbLoc); 4541 4542 // Since this might be a postfix expression, get rid of ParenListExprs. 4543 if (isa<ParenListExpr>(base)) { 4544 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4545 if (result.isInvalid()) return ExprError(); 4546 base = result.get(); 4547 } 4548 4549 // A comma-expression as the index is deprecated in C++2a onwards. 4550 if (getLangOpts().CPlusPlus20 && 4551 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4552 (isa<CXXOperatorCallExpr>(idx) && 4553 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4554 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4555 << SourceRange(base->getBeginLoc(), rbLoc); 4556 } 4557 4558 // Handle any non-overload placeholder types in the base and index 4559 // expressions. We can't handle overloads here because the other 4560 // operand might be an overloadable type, in which case the overload 4561 // resolution for the operator overload should get the first crack 4562 // at the overload. 4563 bool IsMSPropertySubscript = false; 4564 if (base->getType()->isNonOverloadPlaceholderType()) { 4565 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4566 if (!IsMSPropertySubscript) { 4567 ExprResult result = CheckPlaceholderExpr(base); 4568 if (result.isInvalid()) 4569 return ExprError(); 4570 base = result.get(); 4571 } 4572 } 4573 if (idx->getType()->isNonOverloadPlaceholderType()) { 4574 ExprResult result = CheckPlaceholderExpr(idx); 4575 if (result.isInvalid()) return ExprError(); 4576 idx = result.get(); 4577 } 4578 4579 // Build an unanalyzed expression if either operand is type-dependent. 4580 if (getLangOpts().CPlusPlus && 4581 (base->isTypeDependent() || idx->isTypeDependent())) { 4582 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4583 VK_LValue, OK_Ordinary, rbLoc); 4584 } 4585 4586 // MSDN, property (C++) 4587 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4588 // This attribute can also be used in the declaration of an empty array in a 4589 // class or structure definition. For example: 4590 // __declspec(property(get=GetX, put=PutX)) int x[]; 4591 // The above statement indicates that x[] can be used with one or more array 4592 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4593 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4594 if (IsMSPropertySubscript) { 4595 // Build MS property subscript expression if base is MS property reference 4596 // or MS property subscript. 4597 return new (Context) MSPropertySubscriptExpr( 4598 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4599 } 4600 4601 // Use C++ overloaded-operator rules if either operand has record 4602 // type. The spec says to do this if either type is *overloadable*, 4603 // but enum types can't declare subscript operators or conversion 4604 // operators, so there's nothing interesting for overload resolution 4605 // to do if there aren't any record types involved. 4606 // 4607 // ObjC pointers have their own subscripting logic that is not tied 4608 // to overload resolution and so should not take this path. 4609 if (getLangOpts().CPlusPlus && 4610 (base->getType()->isRecordType() || 4611 (!base->getType()->isObjCObjectPointerType() && 4612 idx->getType()->isRecordType()))) { 4613 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4614 } 4615 4616 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4617 4618 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4619 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4620 4621 return Res; 4622 } 4623 4624 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4625 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4626 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4627 4628 // For expressions like `&(*s).b`, the base is recorded and what should be 4629 // checked. 4630 const MemberExpr *Member = nullptr; 4631 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4632 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4633 4634 LastRecord.PossibleDerefs.erase(StrippedExpr); 4635 } 4636 4637 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4638 QualType ResultTy = E->getType(); 4639 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4640 4641 // Bail if the element is an array since it is not memory access. 4642 if (isa<ArrayType>(ResultTy)) 4643 return; 4644 4645 if (ResultTy->hasAttr(attr::NoDeref)) { 4646 LastRecord.PossibleDerefs.insert(E); 4647 return; 4648 } 4649 4650 // Check if the base type is a pointer to a member access of a struct 4651 // marked with noderef. 4652 const Expr *Base = E->getBase(); 4653 QualType BaseTy = Base->getType(); 4654 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4655 // Not a pointer access 4656 return; 4657 4658 const MemberExpr *Member = nullptr; 4659 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4660 Member->isArrow()) 4661 Base = Member->getBase(); 4662 4663 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4664 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4665 LastRecord.PossibleDerefs.insert(E); 4666 } 4667 } 4668 4669 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4670 Expr *LowerBound, 4671 SourceLocation ColonLoc, Expr *Length, 4672 SourceLocation RBLoc) { 4673 if (Base->getType()->isPlaceholderType() && 4674 !Base->getType()->isSpecificPlaceholderType( 4675 BuiltinType::OMPArraySection)) { 4676 ExprResult Result = CheckPlaceholderExpr(Base); 4677 if (Result.isInvalid()) 4678 return ExprError(); 4679 Base = Result.get(); 4680 } 4681 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4682 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4683 if (Result.isInvalid()) 4684 return ExprError(); 4685 Result = DefaultLvalueConversion(Result.get()); 4686 if (Result.isInvalid()) 4687 return ExprError(); 4688 LowerBound = Result.get(); 4689 } 4690 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4691 ExprResult Result = CheckPlaceholderExpr(Length); 4692 if (Result.isInvalid()) 4693 return ExprError(); 4694 Result = DefaultLvalueConversion(Result.get()); 4695 if (Result.isInvalid()) 4696 return ExprError(); 4697 Length = Result.get(); 4698 } 4699 4700 // Build an unanalyzed expression if either operand is type-dependent. 4701 if (Base->isTypeDependent() || 4702 (LowerBound && 4703 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4704 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4705 return new (Context) 4706 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4707 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4708 } 4709 4710 // Perform default conversions. 4711 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4712 QualType ResultTy; 4713 if (OriginalTy->isAnyPointerType()) { 4714 ResultTy = OriginalTy->getPointeeType(); 4715 } else if (OriginalTy->isArrayType()) { 4716 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4717 } else { 4718 return ExprError( 4719 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4720 << Base->getSourceRange()); 4721 } 4722 // C99 6.5.2.1p1 4723 if (LowerBound) { 4724 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4725 LowerBound); 4726 if (Res.isInvalid()) 4727 return ExprError(Diag(LowerBound->getExprLoc(), 4728 diag::err_omp_typecheck_section_not_integer) 4729 << 0 << LowerBound->getSourceRange()); 4730 LowerBound = Res.get(); 4731 4732 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4733 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4734 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4735 << 0 << LowerBound->getSourceRange(); 4736 } 4737 if (Length) { 4738 auto Res = 4739 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4740 if (Res.isInvalid()) 4741 return ExprError(Diag(Length->getExprLoc(), 4742 diag::err_omp_typecheck_section_not_integer) 4743 << 1 << Length->getSourceRange()); 4744 Length = Res.get(); 4745 4746 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4747 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4748 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4749 << 1 << Length->getSourceRange(); 4750 } 4751 4752 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4753 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4754 // type. Note that functions are not objects, and that (in C99 parlance) 4755 // incomplete types are not object types. 4756 if (ResultTy->isFunctionType()) { 4757 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4758 << ResultTy << Base->getSourceRange(); 4759 return ExprError(); 4760 } 4761 4762 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4763 diag::err_omp_section_incomplete_type, Base)) 4764 return ExprError(); 4765 4766 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4767 Expr::EvalResult Result; 4768 if (LowerBound->EvaluateAsInt(Result, Context)) { 4769 // OpenMP 4.5, [2.4 Array Sections] 4770 // The array section must be a subset of the original array. 4771 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4772 if (LowerBoundValue.isNegative()) { 4773 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4774 << LowerBound->getSourceRange(); 4775 return ExprError(); 4776 } 4777 } 4778 } 4779 4780 if (Length) { 4781 Expr::EvalResult Result; 4782 if (Length->EvaluateAsInt(Result, Context)) { 4783 // OpenMP 4.5, [2.4 Array Sections] 4784 // The length must evaluate to non-negative integers. 4785 llvm::APSInt LengthValue = Result.Val.getInt(); 4786 if (LengthValue.isNegative()) { 4787 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4788 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4789 << Length->getSourceRange(); 4790 return ExprError(); 4791 } 4792 } 4793 } else if (ColonLoc.isValid() && 4794 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4795 !OriginalTy->isVariableArrayType()))) { 4796 // OpenMP 4.5, [2.4 Array Sections] 4797 // When the size of the array dimension is not known, the length must be 4798 // specified explicitly. 4799 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4800 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4801 return ExprError(); 4802 } 4803 4804 if (!Base->getType()->isSpecificPlaceholderType( 4805 BuiltinType::OMPArraySection)) { 4806 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4807 if (Result.isInvalid()) 4808 return ExprError(); 4809 Base = Result.get(); 4810 } 4811 return new (Context) 4812 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4813 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4814 } 4815 4816 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4817 SourceLocation RParenLoc, 4818 ArrayRef<Expr *> Dims, 4819 ArrayRef<SourceRange> Brackets) { 4820 if (Base->getType()->isPlaceholderType()) { 4821 ExprResult Result = CheckPlaceholderExpr(Base); 4822 if (Result.isInvalid()) 4823 return ExprError(); 4824 Result = DefaultLvalueConversion(Result.get()); 4825 if (Result.isInvalid()) 4826 return ExprError(); 4827 Base = Result.get(); 4828 } 4829 QualType BaseTy = Base->getType(); 4830 // Delay analysis of the types/expressions if instantiation/specialization is 4831 // required. 4832 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4833 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4834 LParenLoc, RParenLoc, Dims, Brackets); 4835 if (!BaseTy->isPointerType() || 4836 (!Base->isTypeDependent() && 4837 BaseTy->getPointeeType()->isIncompleteType())) 4838 return ExprError(Diag(Base->getExprLoc(), 4839 diag::err_omp_non_pointer_type_array_shaping_base) 4840 << Base->getSourceRange()); 4841 4842 SmallVector<Expr *, 4> NewDims; 4843 bool ErrorFound = false; 4844 for (Expr *Dim : Dims) { 4845 if (Dim->getType()->isPlaceholderType()) { 4846 ExprResult Result = CheckPlaceholderExpr(Dim); 4847 if (Result.isInvalid()) { 4848 ErrorFound = true; 4849 continue; 4850 } 4851 Result = DefaultLvalueConversion(Result.get()); 4852 if (Result.isInvalid()) { 4853 ErrorFound = true; 4854 continue; 4855 } 4856 Dim = Result.get(); 4857 } 4858 if (!Dim->isTypeDependent()) { 4859 ExprResult Result = 4860 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4861 if (Result.isInvalid()) { 4862 ErrorFound = true; 4863 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 4864 << Dim->getSourceRange(); 4865 continue; 4866 } 4867 Dim = Result.get(); 4868 Expr::EvalResult EvResult; 4869 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 4870 // OpenMP 5.0, [2.1.4 Array Shaping] 4871 // Each si is an integral type expression that must evaluate to a 4872 // positive integer. 4873 llvm::APSInt Value = EvResult.Val.getInt(); 4874 if (!Value.isStrictlyPositive()) { 4875 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 4876 << Value.toString(/*Radix=*/10, /*Signed=*/true) 4877 << Dim->getSourceRange(); 4878 ErrorFound = true; 4879 continue; 4880 } 4881 } 4882 } 4883 NewDims.push_back(Dim); 4884 } 4885 if (ErrorFound) 4886 return ExprError(); 4887 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 4888 LParenLoc, RParenLoc, NewDims, Brackets); 4889 } 4890 4891 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 4892 SourceLocation LLoc, SourceLocation RLoc, 4893 ArrayRef<OMPIteratorData> Data) { 4894 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 4895 bool IsCorrect = true; 4896 for (const OMPIteratorData &D : Data) { 4897 TypeSourceInfo *TInfo = nullptr; 4898 SourceLocation StartLoc; 4899 QualType DeclTy; 4900 if (!D.Type.getAsOpaquePtr()) { 4901 // OpenMP 5.0, 2.1.6 Iterators 4902 // In an iterator-specifier, if the iterator-type is not specified then 4903 // the type of that iterator is of int type. 4904 DeclTy = Context.IntTy; 4905 StartLoc = D.DeclIdentLoc; 4906 } else { 4907 DeclTy = GetTypeFromParser(D.Type, &TInfo); 4908 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 4909 } 4910 4911 bool IsDeclTyDependent = DeclTy->isDependentType() || 4912 DeclTy->containsUnexpandedParameterPack() || 4913 DeclTy->isInstantiationDependentType(); 4914 if (!IsDeclTyDependent) { 4915 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 4916 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4917 // The iterator-type must be an integral or pointer type. 4918 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4919 << DeclTy; 4920 IsCorrect = false; 4921 continue; 4922 } 4923 if (DeclTy.isConstant(Context)) { 4924 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 4925 // The iterator-type must not be const qualified. 4926 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 4927 << DeclTy; 4928 IsCorrect = false; 4929 continue; 4930 } 4931 } 4932 4933 // Iterator declaration. 4934 assert(D.DeclIdent && "Identifier expected."); 4935 // Always try to create iterator declarator to avoid extra error messages 4936 // about unknown declarations use. 4937 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 4938 D.DeclIdent, DeclTy, TInfo, SC_None); 4939 VD->setImplicit(); 4940 if (S) { 4941 // Check for conflicting previous declaration. 4942 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 4943 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4944 ForVisibleRedeclaration); 4945 Previous.suppressDiagnostics(); 4946 LookupName(Previous, S); 4947 4948 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 4949 /*AllowInlineNamespace=*/false); 4950 if (!Previous.empty()) { 4951 NamedDecl *Old = Previous.getRepresentativeDecl(); 4952 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 4953 Diag(Old->getLocation(), diag::note_previous_definition); 4954 } else { 4955 PushOnScopeChains(VD, S); 4956 } 4957 } else { 4958 CurContext->addDecl(VD); 4959 } 4960 Expr *Begin = D.Range.Begin; 4961 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 4962 ExprResult BeginRes = 4963 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 4964 Begin = BeginRes.get(); 4965 } 4966 Expr *End = D.Range.End; 4967 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 4968 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 4969 End = EndRes.get(); 4970 } 4971 Expr *Step = D.Range.Step; 4972 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 4973 if (!Step->getType()->isIntegralType(Context)) { 4974 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 4975 << Step << Step->getSourceRange(); 4976 IsCorrect = false; 4977 continue; 4978 } 4979 llvm::APSInt Result; 4980 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 4981 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 4982 // If the step expression of a range-specification equals zero, the 4983 // behavior is unspecified. 4984 if (IsConstant && Result.isNullValue()) { 4985 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 4986 << Step << Step->getSourceRange(); 4987 IsCorrect = false; 4988 continue; 4989 } 4990 } 4991 if (!Begin || !End || !IsCorrect) { 4992 IsCorrect = false; 4993 continue; 4994 } 4995 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 4996 IDElem.IteratorDecl = VD; 4997 IDElem.AssignmentLoc = D.AssignLoc; 4998 IDElem.Range.Begin = Begin; 4999 IDElem.Range.End = End; 5000 IDElem.Range.Step = Step; 5001 IDElem.ColonLoc = D.ColonLoc; 5002 IDElem.SecondColonLoc = D.SecColonLoc; 5003 } 5004 if (!IsCorrect) { 5005 // Invalidate all created iterator declarations if error is found. 5006 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5007 if (Decl *ID = D.IteratorDecl) 5008 ID->setInvalidDecl(); 5009 } 5010 return ExprError(); 5011 } 5012 SmallVector<OMPIteratorHelperData, 4> Helpers; 5013 if (!CurContext->isDependentContext()) { 5014 // Build number of ityeration for each iteration range. 5015 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5016 // ((Begini-Stepi-1-Endi) / -Stepi); 5017 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5018 // (Endi - Begini) 5019 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5020 D.Range.Begin); 5021 if(!Res.isUsable()) { 5022 IsCorrect = false; 5023 continue; 5024 } 5025 ExprResult St, St1; 5026 if (D.Range.Step) { 5027 St = D.Range.Step; 5028 // (Endi - Begini) + Stepi 5029 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5030 if (!Res.isUsable()) { 5031 IsCorrect = false; 5032 continue; 5033 } 5034 // (Endi - Begini) + Stepi - 1 5035 Res = 5036 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5037 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5038 if (!Res.isUsable()) { 5039 IsCorrect = false; 5040 continue; 5041 } 5042 // ((Endi - Begini) + Stepi - 1) / Stepi 5043 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5044 if (!Res.isUsable()) { 5045 IsCorrect = false; 5046 continue; 5047 } 5048 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5049 // (Begini - Endi) 5050 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5051 D.Range.Begin, D.Range.End); 5052 if (!Res1.isUsable()) { 5053 IsCorrect = false; 5054 continue; 5055 } 5056 // (Begini - Endi) - Stepi 5057 Res1 = 5058 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5059 if (!Res1.isUsable()) { 5060 IsCorrect = false; 5061 continue; 5062 } 5063 // (Begini - Endi) - Stepi - 1 5064 Res1 = 5065 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5066 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5067 if (!Res1.isUsable()) { 5068 IsCorrect = false; 5069 continue; 5070 } 5071 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5072 Res1 = 5073 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5074 if (!Res1.isUsable()) { 5075 IsCorrect = false; 5076 continue; 5077 } 5078 // Stepi > 0. 5079 ExprResult CmpRes = 5080 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5081 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5082 if (!CmpRes.isUsable()) { 5083 IsCorrect = false; 5084 continue; 5085 } 5086 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5087 Res.get(), Res1.get()); 5088 if (!Res.isUsable()) { 5089 IsCorrect = false; 5090 continue; 5091 } 5092 } 5093 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5094 if (!Res.isUsable()) { 5095 IsCorrect = false; 5096 continue; 5097 } 5098 5099 // Build counter update. 5100 // Build counter. 5101 auto *CounterVD = 5102 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5103 D.IteratorDecl->getBeginLoc(), nullptr, 5104 Res.get()->getType(), nullptr, SC_None); 5105 CounterVD->setImplicit(); 5106 ExprResult RefRes = 5107 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5108 D.IteratorDecl->getBeginLoc()); 5109 // Build counter update. 5110 // I = Begini + counter * Stepi; 5111 ExprResult UpdateRes; 5112 if (D.Range.Step) { 5113 UpdateRes = CreateBuiltinBinOp( 5114 D.AssignmentLoc, BO_Mul, 5115 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5116 } else { 5117 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5118 } 5119 if (!UpdateRes.isUsable()) { 5120 IsCorrect = false; 5121 continue; 5122 } 5123 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5124 UpdateRes.get()); 5125 if (!UpdateRes.isUsable()) { 5126 IsCorrect = false; 5127 continue; 5128 } 5129 ExprResult VDRes = 5130 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5131 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5132 D.IteratorDecl->getBeginLoc()); 5133 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5134 UpdateRes.get()); 5135 if (!UpdateRes.isUsable()) { 5136 IsCorrect = false; 5137 continue; 5138 } 5139 UpdateRes = 5140 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5141 if (!UpdateRes.isUsable()) { 5142 IsCorrect = false; 5143 continue; 5144 } 5145 ExprResult CounterUpdateRes = 5146 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5147 if (!CounterUpdateRes.isUsable()) { 5148 IsCorrect = false; 5149 continue; 5150 } 5151 CounterUpdateRes = 5152 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5153 if (!CounterUpdateRes.isUsable()) { 5154 IsCorrect = false; 5155 continue; 5156 } 5157 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5158 HD.CounterVD = CounterVD; 5159 HD.Upper = Res.get(); 5160 HD.Update = UpdateRes.get(); 5161 HD.CounterUpdate = CounterUpdateRes.get(); 5162 } 5163 } else { 5164 Helpers.assign(ID.size(), {}); 5165 } 5166 if (!IsCorrect) { 5167 // Invalidate all created iterator declarations if error is found. 5168 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5169 if (Decl *ID = D.IteratorDecl) 5170 ID->setInvalidDecl(); 5171 } 5172 return ExprError(); 5173 } 5174 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5175 LLoc, RLoc, ID, Helpers); 5176 } 5177 5178 ExprResult 5179 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5180 Expr *Idx, SourceLocation RLoc) { 5181 Expr *LHSExp = Base; 5182 Expr *RHSExp = Idx; 5183 5184 ExprValueKind VK = VK_LValue; 5185 ExprObjectKind OK = OK_Ordinary; 5186 5187 // Per C++ core issue 1213, the result is an xvalue if either operand is 5188 // a non-lvalue array, and an lvalue otherwise. 5189 if (getLangOpts().CPlusPlus11) { 5190 for (auto *Op : {LHSExp, RHSExp}) { 5191 Op = Op->IgnoreImplicit(); 5192 if (Op->getType()->isArrayType() && !Op->isLValue()) 5193 VK = VK_XValue; 5194 } 5195 } 5196 5197 // Perform default conversions. 5198 if (!LHSExp->getType()->getAs<VectorType>()) { 5199 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5200 if (Result.isInvalid()) 5201 return ExprError(); 5202 LHSExp = Result.get(); 5203 } 5204 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5205 if (Result.isInvalid()) 5206 return ExprError(); 5207 RHSExp = Result.get(); 5208 5209 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5210 5211 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5212 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5213 // in the subscript position. As a result, we need to derive the array base 5214 // and index from the expression types. 5215 Expr *BaseExpr, *IndexExpr; 5216 QualType ResultType; 5217 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5218 BaseExpr = LHSExp; 5219 IndexExpr = RHSExp; 5220 ResultType = Context.DependentTy; 5221 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5222 BaseExpr = LHSExp; 5223 IndexExpr = RHSExp; 5224 ResultType = PTy->getPointeeType(); 5225 } else if (const ObjCObjectPointerType *PTy = 5226 LHSTy->getAs<ObjCObjectPointerType>()) { 5227 BaseExpr = LHSExp; 5228 IndexExpr = RHSExp; 5229 5230 // Use custom logic if this should be the pseudo-object subscript 5231 // expression. 5232 if (!LangOpts.isSubscriptPointerArithmetic()) 5233 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5234 nullptr); 5235 5236 ResultType = PTy->getPointeeType(); 5237 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5238 // Handle the uncommon case of "123[Ptr]". 5239 BaseExpr = RHSExp; 5240 IndexExpr = LHSExp; 5241 ResultType = PTy->getPointeeType(); 5242 } else if (const ObjCObjectPointerType *PTy = 5243 RHSTy->getAs<ObjCObjectPointerType>()) { 5244 // Handle the uncommon case of "123[Ptr]". 5245 BaseExpr = RHSExp; 5246 IndexExpr = LHSExp; 5247 ResultType = PTy->getPointeeType(); 5248 if (!LangOpts.isSubscriptPointerArithmetic()) { 5249 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5250 << ResultType << BaseExpr->getSourceRange(); 5251 return ExprError(); 5252 } 5253 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5254 BaseExpr = LHSExp; // vectors: V[123] 5255 IndexExpr = RHSExp; 5256 // We apply C++ DR1213 to vector subscripting too. 5257 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5258 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5259 if (Materialized.isInvalid()) 5260 return ExprError(); 5261 LHSExp = Materialized.get(); 5262 } 5263 VK = LHSExp->getValueKind(); 5264 if (VK != VK_RValue) 5265 OK = OK_VectorComponent; 5266 5267 ResultType = VTy->getElementType(); 5268 QualType BaseType = BaseExpr->getType(); 5269 Qualifiers BaseQuals = BaseType.getQualifiers(); 5270 Qualifiers MemberQuals = ResultType.getQualifiers(); 5271 Qualifiers Combined = BaseQuals + MemberQuals; 5272 if (Combined != MemberQuals) 5273 ResultType = Context.getQualifiedType(ResultType, Combined); 5274 } else if (LHSTy->isArrayType()) { 5275 // If we see an array that wasn't promoted by 5276 // DefaultFunctionArrayLvalueConversion, it must be an array that 5277 // wasn't promoted because of the C90 rule that doesn't 5278 // allow promoting non-lvalue arrays. Warn, then 5279 // force the promotion here. 5280 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5281 << LHSExp->getSourceRange(); 5282 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5283 CK_ArrayToPointerDecay).get(); 5284 LHSTy = LHSExp->getType(); 5285 5286 BaseExpr = LHSExp; 5287 IndexExpr = RHSExp; 5288 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5289 } else if (RHSTy->isArrayType()) { 5290 // Same as previous, except for 123[f().a] case 5291 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5292 << RHSExp->getSourceRange(); 5293 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5294 CK_ArrayToPointerDecay).get(); 5295 RHSTy = RHSExp->getType(); 5296 5297 BaseExpr = RHSExp; 5298 IndexExpr = LHSExp; 5299 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5300 } else { 5301 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5302 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5303 } 5304 // C99 6.5.2.1p1 5305 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5306 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5307 << IndexExpr->getSourceRange()); 5308 5309 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5310 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5311 && !IndexExpr->isTypeDependent()) 5312 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5313 5314 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5315 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5316 // type. Note that Functions are not objects, and that (in C99 parlance) 5317 // incomplete types are not object types. 5318 if (ResultType->isFunctionType()) { 5319 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5320 << ResultType << BaseExpr->getSourceRange(); 5321 return ExprError(); 5322 } 5323 5324 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5325 // GNU extension: subscripting on pointer to void 5326 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5327 << BaseExpr->getSourceRange(); 5328 5329 // C forbids expressions of unqualified void type from being l-values. 5330 // See IsCForbiddenLValueType. 5331 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5332 } else if (!ResultType->isDependentType() && 5333 RequireCompleteSizedType( 5334 LLoc, ResultType, 5335 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5336 return ExprError(); 5337 5338 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5339 !ResultType.isCForbiddenLValueType()); 5340 5341 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5342 FunctionScopes.size() > 1) { 5343 if (auto *TT = 5344 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5345 for (auto I = FunctionScopes.rbegin(), 5346 E = std::prev(FunctionScopes.rend()); 5347 I != E; ++I) { 5348 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5349 if (CSI == nullptr) 5350 break; 5351 DeclContext *DC = nullptr; 5352 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5353 DC = LSI->CallOperator; 5354 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5355 DC = CRSI->TheCapturedDecl; 5356 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5357 DC = BSI->TheDecl; 5358 if (DC) { 5359 if (DC->containsDecl(TT->getDecl())) 5360 break; 5361 captureVariablyModifiedType( 5362 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5363 } 5364 } 5365 } 5366 } 5367 5368 return new (Context) 5369 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5370 } 5371 5372 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5373 ParmVarDecl *Param) { 5374 if (Param->hasUnparsedDefaultArg()) { 5375 Diag(CallLoc, 5376 diag::err_use_of_default_argument_to_function_declared_later) << 5377 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5378 Diag(UnparsedDefaultArgLocs[Param], 5379 diag::note_default_argument_declared_here); 5380 return true; 5381 } 5382 5383 if (Param->hasUninstantiatedDefaultArg()) { 5384 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5385 5386 EnterExpressionEvaluationContext EvalContext( 5387 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5388 5389 // Instantiate the expression. 5390 // 5391 // FIXME: Pass in a correct Pattern argument, otherwise 5392 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5393 // 5394 // template<typename T> 5395 // struct A { 5396 // static int FooImpl(); 5397 // 5398 // template<typename Tp> 5399 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5400 // // template argument list [[T], [Tp]], should be [[Tp]]. 5401 // friend A<Tp> Foo(int a); 5402 // }; 5403 // 5404 // template<typename T> 5405 // A<T> Foo(int a = A<T>::FooImpl()); 5406 MultiLevelTemplateArgumentList MutiLevelArgList 5407 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5408 5409 InstantiatingTemplate Inst(*this, CallLoc, Param, 5410 MutiLevelArgList.getInnermost()); 5411 if (Inst.isInvalid()) 5412 return true; 5413 if (Inst.isAlreadyInstantiating()) { 5414 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5415 Param->setInvalidDecl(); 5416 return true; 5417 } 5418 5419 ExprResult Result; 5420 { 5421 // C++ [dcl.fct.default]p5: 5422 // The names in the [default argument] expression are bound, and 5423 // the semantic constraints are checked, at the point where the 5424 // default argument expression appears. 5425 ContextRAII SavedContext(*this, FD); 5426 LocalInstantiationScope Local(*this); 5427 runWithSufficientStackSpace(CallLoc, [&] { 5428 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5429 /*DirectInit*/false); 5430 }); 5431 } 5432 if (Result.isInvalid()) 5433 return true; 5434 5435 // Check the expression as an initializer for the parameter. 5436 InitializedEntity Entity 5437 = InitializedEntity::InitializeParameter(Context, Param); 5438 InitializationKind Kind = InitializationKind::CreateCopy( 5439 Param->getLocation(), 5440 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5441 Expr *ResultE = Result.getAs<Expr>(); 5442 5443 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5444 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5445 if (Result.isInvalid()) 5446 return true; 5447 5448 Result = 5449 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5450 /*DiscardedValue*/ false); 5451 if (Result.isInvalid()) 5452 return true; 5453 5454 // Remember the instantiated default argument. 5455 Param->setDefaultArg(Result.getAs<Expr>()); 5456 if (ASTMutationListener *L = getASTMutationListener()) { 5457 L->DefaultArgumentInstantiated(Param); 5458 } 5459 } 5460 5461 // If the default argument expression is not set yet, we are building it now. 5462 if (!Param->hasInit()) { 5463 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5464 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5465 Param->setInvalidDecl(); 5466 return true; 5467 } 5468 5469 // If the default expression creates temporaries, we need to 5470 // push them to the current stack of expression temporaries so they'll 5471 // be properly destroyed. 5472 // FIXME: We should really be rebuilding the default argument with new 5473 // bound temporaries; see the comment in PR5810. 5474 // We don't need to do that with block decls, though, because 5475 // blocks in default argument expression can never capture anything. 5476 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5477 // Set the "needs cleanups" bit regardless of whether there are 5478 // any explicit objects. 5479 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5480 5481 // Append all the objects to the cleanup list. Right now, this 5482 // should always be a no-op, because blocks in default argument 5483 // expressions should never be able to capture anything. 5484 assert(!Init->getNumObjects() && 5485 "default argument expression has capturing blocks?"); 5486 } 5487 5488 // We already type-checked the argument, so we know it works. 5489 // Just mark all of the declarations in this potentially-evaluated expression 5490 // as being "referenced". 5491 EnterExpressionEvaluationContext EvalContext( 5492 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5493 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5494 /*SkipLocalVariables=*/true); 5495 return false; 5496 } 5497 5498 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5499 FunctionDecl *FD, ParmVarDecl *Param) { 5500 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5501 return ExprError(); 5502 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5503 } 5504 5505 Sema::VariadicCallType 5506 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5507 Expr *Fn) { 5508 if (Proto && Proto->isVariadic()) { 5509 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5510 return VariadicConstructor; 5511 else if (Fn && Fn->getType()->isBlockPointerType()) 5512 return VariadicBlock; 5513 else if (FDecl) { 5514 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5515 if (Method->isInstance()) 5516 return VariadicMethod; 5517 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5518 return VariadicMethod; 5519 return VariadicFunction; 5520 } 5521 return VariadicDoesNotApply; 5522 } 5523 5524 namespace { 5525 class FunctionCallCCC final : public FunctionCallFilterCCC { 5526 public: 5527 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5528 unsigned NumArgs, MemberExpr *ME) 5529 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5530 FunctionName(FuncName) {} 5531 5532 bool ValidateCandidate(const TypoCorrection &candidate) override { 5533 if (!candidate.getCorrectionSpecifier() || 5534 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5535 return false; 5536 } 5537 5538 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5539 } 5540 5541 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5542 return std::make_unique<FunctionCallCCC>(*this); 5543 } 5544 5545 private: 5546 const IdentifierInfo *const FunctionName; 5547 }; 5548 } 5549 5550 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5551 FunctionDecl *FDecl, 5552 ArrayRef<Expr *> Args) { 5553 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5554 DeclarationName FuncName = FDecl->getDeclName(); 5555 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5556 5557 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5558 if (TypoCorrection Corrected = S.CorrectTypo( 5559 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5560 S.getScopeForContext(S.CurContext), nullptr, CCC, 5561 Sema::CTK_ErrorRecovery)) { 5562 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5563 if (Corrected.isOverloaded()) { 5564 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5565 OverloadCandidateSet::iterator Best; 5566 for (NamedDecl *CD : Corrected) { 5567 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5568 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5569 OCS); 5570 } 5571 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5572 case OR_Success: 5573 ND = Best->FoundDecl; 5574 Corrected.setCorrectionDecl(ND); 5575 break; 5576 default: 5577 break; 5578 } 5579 } 5580 ND = ND->getUnderlyingDecl(); 5581 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5582 return Corrected; 5583 } 5584 } 5585 return TypoCorrection(); 5586 } 5587 5588 /// ConvertArgumentsForCall - Converts the arguments specified in 5589 /// Args/NumArgs to the parameter types of the function FDecl with 5590 /// function prototype Proto. Call is the call expression itself, and 5591 /// Fn is the function expression. For a C++ member function, this 5592 /// routine does not attempt to convert the object argument. Returns 5593 /// true if the call is ill-formed. 5594 bool 5595 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5596 FunctionDecl *FDecl, 5597 const FunctionProtoType *Proto, 5598 ArrayRef<Expr *> Args, 5599 SourceLocation RParenLoc, 5600 bool IsExecConfig) { 5601 // Bail out early if calling a builtin with custom typechecking. 5602 if (FDecl) 5603 if (unsigned ID = FDecl->getBuiltinID()) 5604 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5605 return false; 5606 5607 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5608 // assignment, to the types of the corresponding parameter, ... 5609 unsigned NumParams = Proto->getNumParams(); 5610 bool Invalid = false; 5611 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5612 unsigned FnKind = Fn->getType()->isBlockPointerType() 5613 ? 1 /* block */ 5614 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5615 : 0 /* function */); 5616 5617 // If too few arguments are available (and we don't have default 5618 // arguments for the remaining parameters), don't make the call. 5619 if (Args.size() < NumParams) { 5620 if (Args.size() < MinArgs) { 5621 TypoCorrection TC; 5622 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5623 unsigned diag_id = 5624 MinArgs == NumParams && !Proto->isVariadic() 5625 ? diag::err_typecheck_call_too_few_args_suggest 5626 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5627 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5628 << static_cast<unsigned>(Args.size()) 5629 << TC.getCorrectionRange()); 5630 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5631 Diag(RParenLoc, 5632 MinArgs == NumParams && !Proto->isVariadic() 5633 ? diag::err_typecheck_call_too_few_args_one 5634 : diag::err_typecheck_call_too_few_args_at_least_one) 5635 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5636 else 5637 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5638 ? diag::err_typecheck_call_too_few_args 5639 : diag::err_typecheck_call_too_few_args_at_least) 5640 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5641 << Fn->getSourceRange(); 5642 5643 // Emit the location of the prototype. 5644 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5645 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5646 5647 return true; 5648 } 5649 // We reserve space for the default arguments when we create 5650 // the call expression, before calling ConvertArgumentsForCall. 5651 assert((Call->getNumArgs() == NumParams) && 5652 "We should have reserved space for the default arguments before!"); 5653 } 5654 5655 // If too many are passed and not variadic, error on the extras and drop 5656 // them. 5657 if (Args.size() > NumParams) { 5658 if (!Proto->isVariadic()) { 5659 TypoCorrection TC; 5660 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5661 unsigned diag_id = 5662 MinArgs == NumParams && !Proto->isVariadic() 5663 ? diag::err_typecheck_call_too_many_args_suggest 5664 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5665 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5666 << static_cast<unsigned>(Args.size()) 5667 << TC.getCorrectionRange()); 5668 } else if (NumParams == 1 && FDecl && 5669 FDecl->getParamDecl(0)->getDeclName()) 5670 Diag(Args[NumParams]->getBeginLoc(), 5671 MinArgs == NumParams 5672 ? diag::err_typecheck_call_too_many_args_one 5673 : diag::err_typecheck_call_too_many_args_at_most_one) 5674 << FnKind << FDecl->getParamDecl(0) 5675 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5676 << SourceRange(Args[NumParams]->getBeginLoc(), 5677 Args.back()->getEndLoc()); 5678 else 5679 Diag(Args[NumParams]->getBeginLoc(), 5680 MinArgs == NumParams 5681 ? diag::err_typecheck_call_too_many_args 5682 : diag::err_typecheck_call_too_many_args_at_most) 5683 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5684 << Fn->getSourceRange() 5685 << SourceRange(Args[NumParams]->getBeginLoc(), 5686 Args.back()->getEndLoc()); 5687 5688 // Emit the location of the prototype. 5689 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5690 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5691 5692 // This deletes the extra arguments. 5693 Call->shrinkNumArgs(NumParams); 5694 return true; 5695 } 5696 } 5697 SmallVector<Expr *, 8> AllArgs; 5698 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5699 5700 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5701 AllArgs, CallType); 5702 if (Invalid) 5703 return true; 5704 unsigned TotalNumArgs = AllArgs.size(); 5705 for (unsigned i = 0; i < TotalNumArgs; ++i) 5706 Call->setArg(i, AllArgs[i]); 5707 5708 return false; 5709 } 5710 5711 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5712 const FunctionProtoType *Proto, 5713 unsigned FirstParam, ArrayRef<Expr *> Args, 5714 SmallVectorImpl<Expr *> &AllArgs, 5715 VariadicCallType CallType, bool AllowExplicit, 5716 bool IsListInitialization) { 5717 unsigned NumParams = Proto->getNumParams(); 5718 bool Invalid = false; 5719 size_t ArgIx = 0; 5720 // Continue to check argument types (even if we have too few/many args). 5721 for (unsigned i = FirstParam; i < NumParams; i++) { 5722 QualType ProtoArgType = Proto->getParamType(i); 5723 5724 Expr *Arg; 5725 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5726 if (ArgIx < Args.size()) { 5727 Arg = Args[ArgIx++]; 5728 5729 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5730 diag::err_call_incomplete_argument, Arg)) 5731 return true; 5732 5733 // Strip the unbridged-cast placeholder expression off, if applicable. 5734 bool CFAudited = false; 5735 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5736 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5737 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5738 Arg = stripARCUnbridgedCast(Arg); 5739 else if (getLangOpts().ObjCAutoRefCount && 5740 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5741 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5742 CFAudited = true; 5743 5744 if (Proto->getExtParameterInfo(i).isNoEscape()) 5745 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5746 BE->getBlockDecl()->setDoesNotEscape(); 5747 5748 InitializedEntity Entity = 5749 Param ? InitializedEntity::InitializeParameter(Context, Param, 5750 ProtoArgType) 5751 : InitializedEntity::InitializeParameter( 5752 Context, ProtoArgType, Proto->isParamConsumed(i)); 5753 5754 // Remember that parameter belongs to a CF audited API. 5755 if (CFAudited) 5756 Entity.setParameterCFAudited(); 5757 5758 ExprResult ArgE = PerformCopyInitialization( 5759 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5760 if (ArgE.isInvalid()) 5761 return true; 5762 5763 Arg = ArgE.getAs<Expr>(); 5764 } else { 5765 assert(Param && "can't use default arguments without a known callee"); 5766 5767 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5768 if (ArgExpr.isInvalid()) 5769 return true; 5770 5771 Arg = ArgExpr.getAs<Expr>(); 5772 } 5773 5774 // Check for array bounds violations for each argument to the call. This 5775 // check only triggers warnings when the argument isn't a more complex Expr 5776 // with its own checking, such as a BinaryOperator. 5777 CheckArrayAccess(Arg); 5778 5779 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5780 CheckStaticArrayArgument(CallLoc, Param, Arg); 5781 5782 AllArgs.push_back(Arg); 5783 } 5784 5785 // If this is a variadic call, handle args passed through "...". 5786 if (CallType != VariadicDoesNotApply) { 5787 // Assume that extern "C" functions with variadic arguments that 5788 // return __unknown_anytype aren't *really* variadic. 5789 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5790 FDecl->isExternC()) { 5791 for (Expr *A : Args.slice(ArgIx)) { 5792 QualType paramType; // ignored 5793 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5794 Invalid |= arg.isInvalid(); 5795 AllArgs.push_back(arg.get()); 5796 } 5797 5798 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5799 } else { 5800 for (Expr *A : Args.slice(ArgIx)) { 5801 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5802 Invalid |= Arg.isInvalid(); 5803 // Copy blocks to the heap. 5804 if (A->getType()->isBlockPointerType()) 5805 maybeExtendBlockObject(Arg); 5806 AllArgs.push_back(Arg.get()); 5807 } 5808 } 5809 5810 // Check for array bounds violations. 5811 for (Expr *A : Args.slice(ArgIx)) 5812 CheckArrayAccess(A); 5813 } 5814 return Invalid; 5815 } 5816 5817 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5818 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5819 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5820 TL = DTL.getOriginalLoc(); 5821 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5822 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5823 << ATL.getLocalSourceRange(); 5824 } 5825 5826 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5827 /// array parameter, check that it is non-null, and that if it is formed by 5828 /// array-to-pointer decay, the underlying array is sufficiently large. 5829 /// 5830 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5831 /// array type derivation, then for each call to the function, the value of the 5832 /// corresponding actual argument shall provide access to the first element of 5833 /// an array with at least as many elements as specified by the size expression. 5834 void 5835 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5836 ParmVarDecl *Param, 5837 const Expr *ArgExpr) { 5838 // Static array parameters are not supported in C++. 5839 if (!Param || getLangOpts().CPlusPlus) 5840 return; 5841 5842 QualType OrigTy = Param->getOriginalType(); 5843 5844 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5845 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5846 return; 5847 5848 if (ArgExpr->isNullPointerConstant(Context, 5849 Expr::NPC_NeverValueDependent)) { 5850 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5851 DiagnoseCalleeStaticArrayParam(*this, Param); 5852 return; 5853 } 5854 5855 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5856 if (!CAT) 5857 return; 5858 5859 const ConstantArrayType *ArgCAT = 5860 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5861 if (!ArgCAT) 5862 return; 5863 5864 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5865 ArgCAT->getElementType())) { 5866 if (ArgCAT->getSize().ult(CAT->getSize())) { 5867 Diag(CallLoc, diag::warn_static_array_too_small) 5868 << ArgExpr->getSourceRange() 5869 << (unsigned)ArgCAT->getSize().getZExtValue() 5870 << (unsigned)CAT->getSize().getZExtValue() << 0; 5871 DiagnoseCalleeStaticArrayParam(*this, Param); 5872 } 5873 return; 5874 } 5875 5876 Optional<CharUnits> ArgSize = 5877 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5878 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5879 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5880 Diag(CallLoc, diag::warn_static_array_too_small) 5881 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5882 << (unsigned)ParmSize->getQuantity() << 1; 5883 DiagnoseCalleeStaticArrayParam(*this, Param); 5884 } 5885 } 5886 5887 /// Given a function expression of unknown-any type, try to rebuild it 5888 /// to have a function type. 5889 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5890 5891 /// Is the given type a placeholder that we need to lower out 5892 /// immediately during argument processing? 5893 static bool isPlaceholderToRemoveAsArg(QualType type) { 5894 // Placeholders are never sugared. 5895 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5896 if (!placeholder) return false; 5897 5898 switch (placeholder->getKind()) { 5899 // Ignore all the non-placeholder types. 5900 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5901 case BuiltinType::Id: 5902 #include "clang/Basic/OpenCLImageTypes.def" 5903 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5904 case BuiltinType::Id: 5905 #include "clang/Basic/OpenCLExtensionTypes.def" 5906 // In practice we'll never use this, since all SVE types are sugared 5907 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5908 #define SVE_TYPE(Name, Id, SingletonId) \ 5909 case BuiltinType::Id: 5910 #include "clang/Basic/AArch64SVEACLETypes.def" 5911 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5912 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5913 #include "clang/AST/BuiltinTypes.def" 5914 return false; 5915 5916 // We cannot lower out overload sets; they might validly be resolved 5917 // by the call machinery. 5918 case BuiltinType::Overload: 5919 return false; 5920 5921 // Unbridged casts in ARC can be handled in some call positions and 5922 // should be left in place. 5923 case BuiltinType::ARCUnbridgedCast: 5924 return false; 5925 5926 // Pseudo-objects should be converted as soon as possible. 5927 case BuiltinType::PseudoObject: 5928 return true; 5929 5930 // The debugger mode could theoretically but currently does not try 5931 // to resolve unknown-typed arguments based on known parameter types. 5932 case BuiltinType::UnknownAny: 5933 return true; 5934 5935 // These are always invalid as call arguments and should be reported. 5936 case BuiltinType::BoundMember: 5937 case BuiltinType::BuiltinFn: 5938 case BuiltinType::OMPArraySection: 5939 case BuiltinType::OMPArrayShaping: 5940 case BuiltinType::OMPIterator: 5941 return true; 5942 5943 } 5944 llvm_unreachable("bad builtin type kind"); 5945 } 5946 5947 /// Check an argument list for placeholders that we won't try to 5948 /// handle later. 5949 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5950 // Apply this processing to all the arguments at once instead of 5951 // dying at the first failure. 5952 bool hasInvalid = false; 5953 for (size_t i = 0, e = args.size(); i != e; i++) { 5954 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5955 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5956 if (result.isInvalid()) hasInvalid = true; 5957 else args[i] = result.get(); 5958 } else if (hasInvalid) { 5959 (void)S.CorrectDelayedTyposInExpr(args[i]); 5960 } 5961 } 5962 return hasInvalid; 5963 } 5964 5965 /// If a builtin function has a pointer argument with no explicit address 5966 /// space, then it should be able to accept a pointer to any address 5967 /// space as input. In order to do this, we need to replace the 5968 /// standard builtin declaration with one that uses the same address space 5969 /// as the call. 5970 /// 5971 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5972 /// it does not contain any pointer arguments without 5973 /// an address space qualifer. Otherwise the rewritten 5974 /// FunctionDecl is returned. 5975 /// TODO: Handle pointer return types. 5976 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5977 FunctionDecl *FDecl, 5978 MultiExprArg ArgExprs) { 5979 5980 QualType DeclType = FDecl->getType(); 5981 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5982 5983 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5984 ArgExprs.size() < FT->getNumParams()) 5985 return nullptr; 5986 5987 bool NeedsNewDecl = false; 5988 unsigned i = 0; 5989 SmallVector<QualType, 8> OverloadParams; 5990 5991 for (QualType ParamType : FT->param_types()) { 5992 5993 // Convert array arguments to pointer to simplify type lookup. 5994 ExprResult ArgRes = 5995 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5996 if (ArgRes.isInvalid()) 5997 return nullptr; 5998 Expr *Arg = ArgRes.get(); 5999 QualType ArgType = Arg->getType(); 6000 if (!ParamType->isPointerType() || 6001 ParamType.hasAddressSpace() || 6002 !ArgType->isPointerType() || 6003 !ArgType->getPointeeType().hasAddressSpace()) { 6004 OverloadParams.push_back(ParamType); 6005 continue; 6006 } 6007 6008 QualType PointeeType = ParamType->getPointeeType(); 6009 if (PointeeType.hasAddressSpace()) 6010 continue; 6011 6012 NeedsNewDecl = true; 6013 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6014 6015 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6016 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6017 } 6018 6019 if (!NeedsNewDecl) 6020 return nullptr; 6021 6022 FunctionProtoType::ExtProtoInfo EPI; 6023 EPI.Variadic = FT->isVariadic(); 6024 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6025 OverloadParams, EPI); 6026 DeclContext *Parent = FDecl->getParent(); 6027 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6028 FDecl->getLocation(), 6029 FDecl->getLocation(), 6030 FDecl->getIdentifier(), 6031 OverloadTy, 6032 /*TInfo=*/nullptr, 6033 SC_Extern, false, 6034 /*hasPrototype=*/true); 6035 SmallVector<ParmVarDecl*, 16> Params; 6036 FT = cast<FunctionProtoType>(OverloadTy); 6037 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6038 QualType ParamType = FT->getParamType(i); 6039 ParmVarDecl *Parm = 6040 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6041 SourceLocation(), nullptr, ParamType, 6042 /*TInfo=*/nullptr, SC_None, nullptr); 6043 Parm->setScopeInfo(0, i); 6044 Params.push_back(Parm); 6045 } 6046 OverloadDecl->setParams(Params); 6047 return OverloadDecl; 6048 } 6049 6050 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6051 FunctionDecl *Callee, 6052 MultiExprArg ArgExprs) { 6053 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6054 // similar attributes) really don't like it when functions are called with an 6055 // invalid number of args. 6056 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6057 /*PartialOverloading=*/false) && 6058 !Callee->isVariadic()) 6059 return; 6060 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6061 return; 6062 6063 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 6064 S.Diag(Fn->getBeginLoc(), 6065 isa<CXXMethodDecl>(Callee) 6066 ? diag::err_ovl_no_viable_member_function_in_call 6067 : diag::err_ovl_no_viable_function_in_call) 6068 << Callee << Callee->getSourceRange(); 6069 S.Diag(Callee->getLocation(), 6070 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6071 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6072 return; 6073 } 6074 } 6075 6076 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6077 const UnresolvedMemberExpr *const UME, Sema &S) { 6078 6079 const auto GetFunctionLevelDCIfCXXClass = 6080 [](Sema &S) -> const CXXRecordDecl * { 6081 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6082 if (!DC || !DC->getParent()) 6083 return nullptr; 6084 6085 // If the call to some member function was made from within a member 6086 // function body 'M' return return 'M's parent. 6087 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6088 return MD->getParent()->getCanonicalDecl(); 6089 // else the call was made from within a default member initializer of a 6090 // class, so return the class. 6091 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6092 return RD->getCanonicalDecl(); 6093 return nullptr; 6094 }; 6095 // If our DeclContext is neither a member function nor a class (in the 6096 // case of a lambda in a default member initializer), we can't have an 6097 // enclosing 'this'. 6098 6099 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6100 if (!CurParentClass) 6101 return false; 6102 6103 // The naming class for implicit member functions call is the class in which 6104 // name lookup starts. 6105 const CXXRecordDecl *const NamingClass = 6106 UME->getNamingClass()->getCanonicalDecl(); 6107 assert(NamingClass && "Must have naming class even for implicit access"); 6108 6109 // If the unresolved member functions were found in a 'naming class' that is 6110 // related (either the same or derived from) to the class that contains the 6111 // member function that itself contained the implicit member access. 6112 6113 return CurParentClass == NamingClass || 6114 CurParentClass->isDerivedFrom(NamingClass); 6115 } 6116 6117 static void 6118 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6119 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6120 6121 if (!UME) 6122 return; 6123 6124 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6125 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6126 // already been captured, or if this is an implicit member function call (if 6127 // it isn't, an attempt to capture 'this' should already have been made). 6128 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6129 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6130 return; 6131 6132 // Check if the naming class in which the unresolved members were found is 6133 // related (same as or is a base of) to the enclosing class. 6134 6135 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6136 return; 6137 6138 6139 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6140 // If the enclosing function is not dependent, then this lambda is 6141 // capture ready, so if we can capture this, do so. 6142 if (!EnclosingFunctionCtx->isDependentContext()) { 6143 // If the current lambda and all enclosing lambdas can capture 'this' - 6144 // then go ahead and capture 'this' (since our unresolved overload set 6145 // contains at least one non-static member function). 6146 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6147 S.CheckCXXThisCapture(CallLoc); 6148 } else if (S.CurContext->isDependentContext()) { 6149 // ... since this is an implicit member reference, that might potentially 6150 // involve a 'this' capture, mark 'this' for potential capture in 6151 // enclosing lambdas. 6152 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6153 CurLSI->addPotentialThisCapture(CallLoc); 6154 } 6155 } 6156 6157 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6158 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6159 Expr *ExecConfig) { 6160 ExprResult Call = 6161 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6162 if (Call.isInvalid()) 6163 return Call; 6164 6165 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6166 // language modes. 6167 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6168 if (ULE->hasExplicitTemplateArgs() && 6169 ULE->decls_begin() == ULE->decls_end()) { 6170 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6171 ? diag::warn_cxx17_compat_adl_only_template_id 6172 : diag::ext_adl_only_template_id) 6173 << ULE->getName(); 6174 } 6175 } 6176 6177 if (LangOpts.OpenMP) 6178 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6179 ExecConfig); 6180 6181 return Call; 6182 } 6183 6184 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6185 /// This provides the location of the left/right parens and a list of comma 6186 /// locations. 6187 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6188 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6189 Expr *ExecConfig, bool IsExecConfig) { 6190 // Since this might be a postfix expression, get rid of ParenListExprs. 6191 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6192 if (Result.isInvalid()) return ExprError(); 6193 Fn = Result.get(); 6194 6195 if (checkArgsForPlaceholders(*this, ArgExprs)) 6196 return ExprError(); 6197 6198 if (getLangOpts().CPlusPlus) { 6199 // If this is a pseudo-destructor expression, build the call immediately. 6200 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6201 if (!ArgExprs.empty()) { 6202 // Pseudo-destructor calls should not have any arguments. 6203 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6204 << FixItHint::CreateRemoval( 6205 SourceRange(ArgExprs.front()->getBeginLoc(), 6206 ArgExprs.back()->getEndLoc())); 6207 } 6208 6209 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6210 VK_RValue, RParenLoc); 6211 } 6212 if (Fn->getType() == Context.PseudoObjectTy) { 6213 ExprResult result = CheckPlaceholderExpr(Fn); 6214 if (result.isInvalid()) return ExprError(); 6215 Fn = result.get(); 6216 } 6217 6218 // Determine whether this is a dependent call inside a C++ template, 6219 // in which case we won't do any semantic analysis now. 6220 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6221 if (ExecConfig) { 6222 return CUDAKernelCallExpr::Create( 6223 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6224 Context.DependentTy, VK_RValue, RParenLoc); 6225 } else { 6226 6227 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6228 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6229 Fn->getBeginLoc()); 6230 6231 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6232 VK_RValue, RParenLoc); 6233 } 6234 } 6235 6236 // Determine whether this is a call to an object (C++ [over.call.object]). 6237 if (Fn->getType()->isRecordType()) 6238 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6239 RParenLoc); 6240 6241 if (Fn->getType() == Context.UnknownAnyTy) { 6242 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6243 if (result.isInvalid()) return ExprError(); 6244 Fn = result.get(); 6245 } 6246 6247 if (Fn->getType() == Context.BoundMemberTy) { 6248 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6249 RParenLoc); 6250 } 6251 } 6252 6253 // Check for overloaded calls. This can happen even in C due to extensions. 6254 if (Fn->getType() == Context.OverloadTy) { 6255 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6256 6257 // We aren't supposed to apply this logic if there's an '&' involved. 6258 if (!find.HasFormOfMemberPointer) { 6259 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6260 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6261 VK_RValue, RParenLoc); 6262 OverloadExpr *ovl = find.Expression; 6263 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6264 return BuildOverloadedCallExpr( 6265 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6266 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6267 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6268 RParenLoc); 6269 } 6270 } 6271 6272 // If we're directly calling a function, get the appropriate declaration. 6273 if (Fn->getType() == Context.UnknownAnyTy) { 6274 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6275 if (result.isInvalid()) return ExprError(); 6276 Fn = result.get(); 6277 } 6278 6279 Expr *NakedFn = Fn->IgnoreParens(); 6280 6281 bool CallingNDeclIndirectly = false; 6282 NamedDecl *NDecl = nullptr; 6283 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6284 if (UnOp->getOpcode() == UO_AddrOf) { 6285 CallingNDeclIndirectly = true; 6286 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6287 } 6288 } 6289 6290 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6291 NDecl = DRE->getDecl(); 6292 6293 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6294 if (FDecl && FDecl->getBuiltinID()) { 6295 // Rewrite the function decl for this builtin by replacing parameters 6296 // with no explicit address space with the address space of the arguments 6297 // in ArgExprs. 6298 if ((FDecl = 6299 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6300 NDecl = FDecl; 6301 Fn = DeclRefExpr::Create( 6302 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6303 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6304 nullptr, DRE->isNonOdrUse()); 6305 } 6306 } 6307 } else if (isa<MemberExpr>(NakedFn)) 6308 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6309 6310 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6311 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6312 FD, /*Complain=*/true, Fn->getBeginLoc())) 6313 return ExprError(); 6314 6315 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6316 return ExprError(); 6317 6318 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6319 } 6320 6321 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6322 ExecConfig, IsExecConfig); 6323 } 6324 6325 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6326 /// 6327 /// __builtin_astype( value, dst type ) 6328 /// 6329 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6330 SourceLocation BuiltinLoc, 6331 SourceLocation RParenLoc) { 6332 ExprValueKind VK = VK_RValue; 6333 ExprObjectKind OK = OK_Ordinary; 6334 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6335 QualType SrcTy = E->getType(); 6336 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6337 return ExprError(Diag(BuiltinLoc, 6338 diag::err_invalid_astype_of_different_size) 6339 << DstTy 6340 << SrcTy 6341 << E->getSourceRange()); 6342 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6343 } 6344 6345 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6346 /// provided arguments. 6347 /// 6348 /// __builtin_convertvector( value, dst type ) 6349 /// 6350 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6351 SourceLocation BuiltinLoc, 6352 SourceLocation RParenLoc) { 6353 TypeSourceInfo *TInfo; 6354 GetTypeFromParser(ParsedDestTy, &TInfo); 6355 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6356 } 6357 6358 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6359 /// i.e. an expression not of \p OverloadTy. The expression should 6360 /// unary-convert to an expression of function-pointer or 6361 /// block-pointer type. 6362 /// 6363 /// \param NDecl the declaration being called, if available 6364 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6365 SourceLocation LParenLoc, 6366 ArrayRef<Expr *> Args, 6367 SourceLocation RParenLoc, Expr *Config, 6368 bool IsExecConfig, ADLCallKind UsesADL) { 6369 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6370 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6371 6372 // Functions with 'interrupt' attribute cannot be called directly. 6373 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6374 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6375 return ExprError(); 6376 } 6377 6378 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6379 // so there's some risk when calling out to non-interrupt handler functions 6380 // that the callee might not preserve them. This is easy to diagnose here, 6381 // but can be very challenging to debug. 6382 if (auto *Caller = getCurFunctionDecl()) 6383 if (Caller->hasAttr<ARMInterruptAttr>()) { 6384 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6385 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6386 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6387 } 6388 6389 // Promote the function operand. 6390 // We special-case function promotion here because we only allow promoting 6391 // builtin functions to function pointers in the callee of a call. 6392 ExprResult Result; 6393 QualType ResultTy; 6394 if (BuiltinID && 6395 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6396 // Extract the return type from the (builtin) function pointer type. 6397 // FIXME Several builtins still have setType in 6398 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6399 // Builtins.def to ensure they are correct before removing setType calls. 6400 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6401 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6402 ResultTy = FDecl->getCallResultType(); 6403 } else { 6404 Result = CallExprUnaryConversions(Fn); 6405 ResultTy = Context.BoolTy; 6406 } 6407 if (Result.isInvalid()) 6408 return ExprError(); 6409 Fn = Result.get(); 6410 6411 // Check for a valid function type, but only if it is not a builtin which 6412 // requires custom type checking. These will be handled by 6413 // CheckBuiltinFunctionCall below just after creation of the call expression. 6414 const FunctionType *FuncT = nullptr; 6415 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6416 retry: 6417 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6418 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6419 // have type pointer to function". 6420 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6421 if (!FuncT) 6422 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6423 << Fn->getType() << Fn->getSourceRange()); 6424 } else if (const BlockPointerType *BPT = 6425 Fn->getType()->getAs<BlockPointerType>()) { 6426 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6427 } else { 6428 // Handle calls to expressions of unknown-any type. 6429 if (Fn->getType() == Context.UnknownAnyTy) { 6430 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6431 if (rewrite.isInvalid()) 6432 return ExprError(); 6433 Fn = rewrite.get(); 6434 goto retry; 6435 } 6436 6437 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6438 << Fn->getType() << Fn->getSourceRange()); 6439 } 6440 } 6441 6442 // Get the number of parameters in the function prototype, if any. 6443 // We will allocate space for max(Args.size(), NumParams) arguments 6444 // in the call expression. 6445 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6446 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6447 6448 CallExpr *TheCall; 6449 if (Config) { 6450 assert(UsesADL == ADLCallKind::NotADL && 6451 "CUDAKernelCallExpr should not use ADL"); 6452 TheCall = 6453 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6454 ResultTy, VK_RValue, RParenLoc, NumParams); 6455 } else { 6456 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6457 RParenLoc, NumParams, UsesADL); 6458 } 6459 6460 if (!getLangOpts().CPlusPlus) { 6461 // Forget about the nulled arguments since typo correction 6462 // do not handle them well. 6463 TheCall->shrinkNumArgs(Args.size()); 6464 // C cannot always handle TypoExpr nodes in builtin calls and direct 6465 // function calls as their argument checking don't necessarily handle 6466 // dependent types properly, so make sure any TypoExprs have been 6467 // dealt with. 6468 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6469 if (!Result.isUsable()) return ExprError(); 6470 CallExpr *TheOldCall = TheCall; 6471 TheCall = dyn_cast<CallExpr>(Result.get()); 6472 bool CorrectedTypos = TheCall != TheOldCall; 6473 if (!TheCall) return Result; 6474 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6475 6476 // A new call expression node was created if some typos were corrected. 6477 // However it may not have been constructed with enough storage. In this 6478 // case, rebuild the node with enough storage. The waste of space is 6479 // immaterial since this only happens when some typos were corrected. 6480 if (CorrectedTypos && Args.size() < NumParams) { 6481 if (Config) 6482 TheCall = CUDAKernelCallExpr::Create( 6483 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6484 RParenLoc, NumParams); 6485 else 6486 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6487 RParenLoc, NumParams, UsesADL); 6488 } 6489 // We can now handle the nulled arguments for the default arguments. 6490 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6491 } 6492 6493 // Bail out early if calling a builtin with custom type checking. 6494 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6495 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6496 6497 if (getLangOpts().CUDA) { 6498 if (Config) { 6499 // CUDA: Kernel calls must be to global functions 6500 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6501 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6502 << FDecl << Fn->getSourceRange()); 6503 6504 // CUDA: Kernel function must have 'void' return type 6505 if (!FuncT->getReturnType()->isVoidType() && 6506 !FuncT->getReturnType()->getAs<AutoType>() && 6507 !FuncT->getReturnType()->isInstantiationDependentType()) 6508 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6509 << Fn->getType() << Fn->getSourceRange()); 6510 } else { 6511 // CUDA: Calls to global functions must be configured 6512 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6513 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6514 << FDecl << Fn->getSourceRange()); 6515 } 6516 } 6517 6518 // Check for a valid return type 6519 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6520 FDecl)) 6521 return ExprError(); 6522 6523 // We know the result type of the call, set it. 6524 TheCall->setType(FuncT->getCallResultType(Context)); 6525 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6526 6527 if (Proto) { 6528 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6529 IsExecConfig)) 6530 return ExprError(); 6531 } else { 6532 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6533 6534 if (FDecl) { 6535 // Check if we have too few/too many template arguments, based 6536 // on our knowledge of the function definition. 6537 const FunctionDecl *Def = nullptr; 6538 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6539 Proto = Def->getType()->getAs<FunctionProtoType>(); 6540 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6541 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6542 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6543 } 6544 6545 // If the function we're calling isn't a function prototype, but we have 6546 // a function prototype from a prior declaratiom, use that prototype. 6547 if (!FDecl->hasPrototype()) 6548 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6549 } 6550 6551 // Promote the arguments (C99 6.5.2.2p6). 6552 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6553 Expr *Arg = Args[i]; 6554 6555 if (Proto && i < Proto->getNumParams()) { 6556 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6557 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6558 ExprResult ArgE = 6559 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6560 if (ArgE.isInvalid()) 6561 return true; 6562 6563 Arg = ArgE.getAs<Expr>(); 6564 6565 } else { 6566 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6567 6568 if (ArgE.isInvalid()) 6569 return true; 6570 6571 Arg = ArgE.getAs<Expr>(); 6572 } 6573 6574 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6575 diag::err_call_incomplete_argument, Arg)) 6576 return ExprError(); 6577 6578 TheCall->setArg(i, Arg); 6579 } 6580 } 6581 6582 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6583 if (!Method->isStatic()) 6584 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6585 << Fn->getSourceRange()); 6586 6587 // Check for sentinels 6588 if (NDecl) 6589 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6590 6591 // Warn for unions passing across security boundary (CMSE). 6592 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6593 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6594 if (const auto *RT = 6595 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6596 if (RT->getDecl()->isOrContainsUnion()) 6597 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6598 << 0 << i; 6599 } 6600 } 6601 } 6602 6603 // Do special checking on direct calls to functions. 6604 if (FDecl) { 6605 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6606 return ExprError(); 6607 6608 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6609 6610 if (BuiltinID) 6611 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6612 } else if (NDecl) { 6613 if (CheckPointerCall(NDecl, TheCall, Proto)) 6614 return ExprError(); 6615 } else { 6616 if (CheckOtherCall(TheCall, Proto)) 6617 return ExprError(); 6618 } 6619 6620 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6621 } 6622 6623 ExprResult 6624 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6625 SourceLocation RParenLoc, Expr *InitExpr) { 6626 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6627 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6628 6629 TypeSourceInfo *TInfo; 6630 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6631 if (!TInfo) 6632 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6633 6634 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6635 } 6636 6637 ExprResult 6638 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6639 SourceLocation RParenLoc, Expr *LiteralExpr) { 6640 QualType literalType = TInfo->getType(); 6641 6642 if (literalType->isArrayType()) { 6643 if (RequireCompleteSizedType( 6644 LParenLoc, Context.getBaseElementType(literalType), 6645 diag::err_array_incomplete_or_sizeless_type, 6646 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6647 return ExprError(); 6648 if (literalType->isVariableArrayType()) 6649 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6650 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6651 } else if (!literalType->isDependentType() && 6652 RequireCompleteType(LParenLoc, literalType, 6653 diag::err_typecheck_decl_incomplete_type, 6654 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6655 return ExprError(); 6656 6657 InitializedEntity Entity 6658 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6659 InitializationKind Kind 6660 = InitializationKind::CreateCStyleCast(LParenLoc, 6661 SourceRange(LParenLoc, RParenLoc), 6662 /*InitList=*/true); 6663 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6664 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6665 &literalType); 6666 if (Result.isInvalid()) 6667 return ExprError(); 6668 LiteralExpr = Result.get(); 6669 6670 bool isFileScope = !CurContext->isFunctionOrMethod(); 6671 6672 // In C, compound literals are l-values for some reason. 6673 // For GCC compatibility, in C++, file-scope array compound literals with 6674 // constant initializers are also l-values, and compound literals are 6675 // otherwise prvalues. 6676 // 6677 // (GCC also treats C++ list-initialized file-scope array prvalues with 6678 // constant initializers as l-values, but that's non-conforming, so we don't 6679 // follow it there.) 6680 // 6681 // FIXME: It would be better to handle the lvalue cases as materializing and 6682 // lifetime-extending a temporary object, but our materialized temporaries 6683 // representation only supports lifetime extension from a variable, not "out 6684 // of thin air". 6685 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6686 // is bound to the result of applying array-to-pointer decay to the compound 6687 // literal. 6688 // FIXME: GCC supports compound literals of reference type, which should 6689 // obviously have a value kind derived from the kind of reference involved. 6690 ExprValueKind VK = 6691 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6692 ? VK_RValue 6693 : VK_LValue; 6694 6695 if (isFileScope) 6696 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6697 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6698 Expr *Init = ILE->getInit(i); 6699 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6700 } 6701 6702 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6703 VK, LiteralExpr, isFileScope); 6704 if (isFileScope) { 6705 if (!LiteralExpr->isTypeDependent() && 6706 !LiteralExpr->isValueDependent() && 6707 !literalType->isDependentType()) // C99 6.5.2.5p3 6708 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6709 return ExprError(); 6710 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6711 literalType.getAddressSpace() != LangAS::Default) { 6712 // Embedded-C extensions to C99 6.5.2.5: 6713 // "If the compound literal occurs inside the body of a function, the 6714 // type name shall not be qualified by an address-space qualifier." 6715 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6716 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6717 return ExprError(); 6718 } 6719 6720 if (!isFileScope && !getLangOpts().CPlusPlus) { 6721 // Compound literals that have automatic storage duration are destroyed at 6722 // the end of the scope in C; in C++, they're just temporaries. 6723 6724 // Emit diagnostics if it is or contains a C union type that is non-trivial 6725 // to destruct. 6726 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6727 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6728 NTCUC_CompoundLiteral, NTCUK_Destruct); 6729 6730 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6731 if (literalType.isDestructedType()) { 6732 Cleanup.setExprNeedsCleanups(true); 6733 ExprCleanupObjects.push_back(E); 6734 getCurFunction()->setHasBranchProtectedScope(); 6735 } 6736 } 6737 6738 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6739 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6740 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6741 E->getInitializer()->getExprLoc()); 6742 6743 return MaybeBindToTemporary(E); 6744 } 6745 6746 ExprResult 6747 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6748 SourceLocation RBraceLoc) { 6749 // Only produce each kind of designated initialization diagnostic once. 6750 SourceLocation FirstDesignator; 6751 bool DiagnosedArrayDesignator = false; 6752 bool DiagnosedNestedDesignator = false; 6753 bool DiagnosedMixedDesignator = false; 6754 6755 // Check that any designated initializers are syntactically valid in the 6756 // current language mode. 6757 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6758 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6759 if (FirstDesignator.isInvalid()) 6760 FirstDesignator = DIE->getBeginLoc(); 6761 6762 if (!getLangOpts().CPlusPlus) 6763 break; 6764 6765 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6766 DiagnosedNestedDesignator = true; 6767 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6768 << DIE->getDesignatorsSourceRange(); 6769 } 6770 6771 for (auto &Desig : DIE->designators()) { 6772 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6773 DiagnosedArrayDesignator = true; 6774 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6775 << Desig.getSourceRange(); 6776 } 6777 } 6778 6779 if (!DiagnosedMixedDesignator && 6780 !isa<DesignatedInitExpr>(InitArgList[0])) { 6781 DiagnosedMixedDesignator = true; 6782 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6783 << DIE->getSourceRange(); 6784 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6785 << InitArgList[0]->getSourceRange(); 6786 } 6787 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6788 isa<DesignatedInitExpr>(InitArgList[0])) { 6789 DiagnosedMixedDesignator = true; 6790 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6791 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6792 << DIE->getSourceRange(); 6793 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6794 << InitArgList[I]->getSourceRange(); 6795 } 6796 } 6797 6798 if (FirstDesignator.isValid()) { 6799 // Only diagnose designated initiaization as a C++20 extension if we didn't 6800 // already diagnose use of (non-C++20) C99 designator syntax. 6801 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6802 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6803 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6804 ? diag::warn_cxx17_compat_designated_init 6805 : diag::ext_cxx_designated_init); 6806 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6807 Diag(FirstDesignator, diag::ext_designated_init); 6808 } 6809 } 6810 6811 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6812 } 6813 6814 ExprResult 6815 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6816 SourceLocation RBraceLoc) { 6817 // Semantic analysis for initializers is done by ActOnDeclarator() and 6818 // CheckInitializer() - it requires knowledge of the object being initialized. 6819 6820 // Immediately handle non-overload placeholders. Overloads can be 6821 // resolved contextually, but everything else here can't. 6822 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6823 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6824 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6825 6826 // Ignore failures; dropping the entire initializer list because 6827 // of one failure would be terrible for indexing/etc. 6828 if (result.isInvalid()) continue; 6829 6830 InitArgList[I] = result.get(); 6831 } 6832 } 6833 6834 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6835 RBraceLoc); 6836 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6837 return E; 6838 } 6839 6840 /// Do an explicit extend of the given block pointer if we're in ARC. 6841 void Sema::maybeExtendBlockObject(ExprResult &E) { 6842 assert(E.get()->getType()->isBlockPointerType()); 6843 assert(E.get()->isRValue()); 6844 6845 // Only do this in an r-value context. 6846 if (!getLangOpts().ObjCAutoRefCount) return; 6847 6848 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6849 CK_ARCExtendBlockObject, E.get(), 6850 /*base path*/ nullptr, VK_RValue); 6851 Cleanup.setExprNeedsCleanups(true); 6852 } 6853 6854 /// Prepare a conversion of the given expression to an ObjC object 6855 /// pointer type. 6856 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6857 QualType type = E.get()->getType(); 6858 if (type->isObjCObjectPointerType()) { 6859 return CK_BitCast; 6860 } else if (type->isBlockPointerType()) { 6861 maybeExtendBlockObject(E); 6862 return CK_BlockPointerToObjCPointerCast; 6863 } else { 6864 assert(type->isPointerType()); 6865 return CK_CPointerToObjCPointerCast; 6866 } 6867 } 6868 6869 /// Prepares for a scalar cast, performing all the necessary stages 6870 /// except the final cast and returning the kind required. 6871 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6872 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6873 // Also, callers should have filtered out the invalid cases with 6874 // pointers. Everything else should be possible. 6875 6876 QualType SrcTy = Src.get()->getType(); 6877 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6878 return CK_NoOp; 6879 6880 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6881 case Type::STK_MemberPointer: 6882 llvm_unreachable("member pointer type in C"); 6883 6884 case Type::STK_CPointer: 6885 case Type::STK_BlockPointer: 6886 case Type::STK_ObjCObjectPointer: 6887 switch (DestTy->getScalarTypeKind()) { 6888 case Type::STK_CPointer: { 6889 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6890 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6891 if (SrcAS != DestAS) 6892 return CK_AddressSpaceConversion; 6893 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6894 return CK_NoOp; 6895 return CK_BitCast; 6896 } 6897 case Type::STK_BlockPointer: 6898 return (SrcKind == Type::STK_BlockPointer 6899 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6900 case Type::STK_ObjCObjectPointer: 6901 if (SrcKind == Type::STK_ObjCObjectPointer) 6902 return CK_BitCast; 6903 if (SrcKind == Type::STK_CPointer) 6904 return CK_CPointerToObjCPointerCast; 6905 maybeExtendBlockObject(Src); 6906 return CK_BlockPointerToObjCPointerCast; 6907 case Type::STK_Bool: 6908 return CK_PointerToBoolean; 6909 case Type::STK_Integral: 6910 return CK_PointerToIntegral; 6911 case Type::STK_Floating: 6912 case Type::STK_FloatingComplex: 6913 case Type::STK_IntegralComplex: 6914 case Type::STK_MemberPointer: 6915 case Type::STK_FixedPoint: 6916 llvm_unreachable("illegal cast from pointer"); 6917 } 6918 llvm_unreachable("Should have returned before this"); 6919 6920 case Type::STK_FixedPoint: 6921 switch (DestTy->getScalarTypeKind()) { 6922 case Type::STK_FixedPoint: 6923 return CK_FixedPointCast; 6924 case Type::STK_Bool: 6925 return CK_FixedPointToBoolean; 6926 case Type::STK_Integral: 6927 return CK_FixedPointToIntegral; 6928 case Type::STK_Floating: 6929 case Type::STK_IntegralComplex: 6930 case Type::STK_FloatingComplex: 6931 Diag(Src.get()->getExprLoc(), 6932 diag::err_unimplemented_conversion_with_fixed_point_type) 6933 << DestTy; 6934 return CK_IntegralCast; 6935 case Type::STK_CPointer: 6936 case Type::STK_ObjCObjectPointer: 6937 case Type::STK_BlockPointer: 6938 case Type::STK_MemberPointer: 6939 llvm_unreachable("illegal cast to pointer type"); 6940 } 6941 llvm_unreachable("Should have returned before this"); 6942 6943 case Type::STK_Bool: // casting from bool is like casting from an integer 6944 case Type::STK_Integral: 6945 switch (DestTy->getScalarTypeKind()) { 6946 case Type::STK_CPointer: 6947 case Type::STK_ObjCObjectPointer: 6948 case Type::STK_BlockPointer: 6949 if (Src.get()->isNullPointerConstant(Context, 6950 Expr::NPC_ValueDependentIsNull)) 6951 return CK_NullToPointer; 6952 return CK_IntegralToPointer; 6953 case Type::STK_Bool: 6954 return CK_IntegralToBoolean; 6955 case Type::STK_Integral: 6956 return CK_IntegralCast; 6957 case Type::STK_Floating: 6958 return CK_IntegralToFloating; 6959 case Type::STK_IntegralComplex: 6960 Src = ImpCastExprToType(Src.get(), 6961 DestTy->castAs<ComplexType>()->getElementType(), 6962 CK_IntegralCast); 6963 return CK_IntegralRealToComplex; 6964 case Type::STK_FloatingComplex: 6965 Src = ImpCastExprToType(Src.get(), 6966 DestTy->castAs<ComplexType>()->getElementType(), 6967 CK_IntegralToFloating); 6968 return CK_FloatingRealToComplex; 6969 case Type::STK_MemberPointer: 6970 llvm_unreachable("member pointer type in C"); 6971 case Type::STK_FixedPoint: 6972 return CK_IntegralToFixedPoint; 6973 } 6974 llvm_unreachable("Should have returned before this"); 6975 6976 case Type::STK_Floating: 6977 switch (DestTy->getScalarTypeKind()) { 6978 case Type::STK_Floating: 6979 return CK_FloatingCast; 6980 case Type::STK_Bool: 6981 return CK_FloatingToBoolean; 6982 case Type::STK_Integral: 6983 return CK_FloatingToIntegral; 6984 case Type::STK_FloatingComplex: 6985 Src = ImpCastExprToType(Src.get(), 6986 DestTy->castAs<ComplexType>()->getElementType(), 6987 CK_FloatingCast); 6988 return CK_FloatingRealToComplex; 6989 case Type::STK_IntegralComplex: 6990 Src = ImpCastExprToType(Src.get(), 6991 DestTy->castAs<ComplexType>()->getElementType(), 6992 CK_FloatingToIntegral); 6993 return CK_IntegralRealToComplex; 6994 case Type::STK_CPointer: 6995 case Type::STK_ObjCObjectPointer: 6996 case Type::STK_BlockPointer: 6997 llvm_unreachable("valid float->pointer cast?"); 6998 case Type::STK_MemberPointer: 6999 llvm_unreachable("member pointer type in C"); 7000 case Type::STK_FixedPoint: 7001 Diag(Src.get()->getExprLoc(), 7002 diag::err_unimplemented_conversion_with_fixed_point_type) 7003 << SrcTy; 7004 return CK_IntegralCast; 7005 } 7006 llvm_unreachable("Should have returned before this"); 7007 7008 case Type::STK_FloatingComplex: 7009 switch (DestTy->getScalarTypeKind()) { 7010 case Type::STK_FloatingComplex: 7011 return CK_FloatingComplexCast; 7012 case Type::STK_IntegralComplex: 7013 return CK_FloatingComplexToIntegralComplex; 7014 case Type::STK_Floating: { 7015 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7016 if (Context.hasSameType(ET, DestTy)) 7017 return CK_FloatingComplexToReal; 7018 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7019 return CK_FloatingCast; 7020 } 7021 case Type::STK_Bool: 7022 return CK_FloatingComplexToBoolean; 7023 case Type::STK_Integral: 7024 Src = ImpCastExprToType(Src.get(), 7025 SrcTy->castAs<ComplexType>()->getElementType(), 7026 CK_FloatingComplexToReal); 7027 return CK_FloatingToIntegral; 7028 case Type::STK_CPointer: 7029 case Type::STK_ObjCObjectPointer: 7030 case Type::STK_BlockPointer: 7031 llvm_unreachable("valid complex float->pointer cast?"); 7032 case Type::STK_MemberPointer: 7033 llvm_unreachable("member pointer type in C"); 7034 case Type::STK_FixedPoint: 7035 Diag(Src.get()->getExprLoc(), 7036 diag::err_unimplemented_conversion_with_fixed_point_type) 7037 << SrcTy; 7038 return CK_IntegralCast; 7039 } 7040 llvm_unreachable("Should have returned before this"); 7041 7042 case Type::STK_IntegralComplex: 7043 switch (DestTy->getScalarTypeKind()) { 7044 case Type::STK_FloatingComplex: 7045 return CK_IntegralComplexToFloatingComplex; 7046 case Type::STK_IntegralComplex: 7047 return CK_IntegralComplexCast; 7048 case Type::STK_Integral: { 7049 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7050 if (Context.hasSameType(ET, DestTy)) 7051 return CK_IntegralComplexToReal; 7052 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7053 return CK_IntegralCast; 7054 } 7055 case Type::STK_Bool: 7056 return CK_IntegralComplexToBoolean; 7057 case Type::STK_Floating: 7058 Src = ImpCastExprToType(Src.get(), 7059 SrcTy->castAs<ComplexType>()->getElementType(), 7060 CK_IntegralComplexToReal); 7061 return CK_IntegralToFloating; 7062 case Type::STK_CPointer: 7063 case Type::STK_ObjCObjectPointer: 7064 case Type::STK_BlockPointer: 7065 llvm_unreachable("valid complex int->pointer cast?"); 7066 case Type::STK_MemberPointer: 7067 llvm_unreachable("member pointer type in C"); 7068 case Type::STK_FixedPoint: 7069 Diag(Src.get()->getExprLoc(), 7070 diag::err_unimplemented_conversion_with_fixed_point_type) 7071 << SrcTy; 7072 return CK_IntegralCast; 7073 } 7074 llvm_unreachable("Should have returned before this"); 7075 } 7076 7077 llvm_unreachable("Unhandled scalar cast"); 7078 } 7079 7080 static bool breakDownVectorType(QualType type, uint64_t &len, 7081 QualType &eltType) { 7082 // Vectors are simple. 7083 if (const VectorType *vecType = type->getAs<VectorType>()) { 7084 len = vecType->getNumElements(); 7085 eltType = vecType->getElementType(); 7086 assert(eltType->isScalarType()); 7087 return true; 7088 } 7089 7090 // We allow lax conversion to and from non-vector types, but only if 7091 // they're real types (i.e. non-complex, non-pointer scalar types). 7092 if (!type->isRealType()) return false; 7093 7094 len = 1; 7095 eltType = type; 7096 return true; 7097 } 7098 7099 /// Are the two types lax-compatible vector types? That is, given 7100 /// that one of them is a vector, do they have equal storage sizes, 7101 /// where the storage size is the number of elements times the element 7102 /// size? 7103 /// 7104 /// This will also return false if either of the types is neither a 7105 /// vector nor a real type. 7106 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7107 assert(destTy->isVectorType() || srcTy->isVectorType()); 7108 7109 // Disallow lax conversions between scalars and ExtVectors (these 7110 // conversions are allowed for other vector types because common headers 7111 // depend on them). Most scalar OP ExtVector cases are handled by the 7112 // splat path anyway, which does what we want (convert, not bitcast). 7113 // What this rules out for ExtVectors is crazy things like char4*float. 7114 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7115 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7116 7117 uint64_t srcLen, destLen; 7118 QualType srcEltTy, destEltTy; 7119 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7120 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7121 7122 // ASTContext::getTypeSize will return the size rounded up to a 7123 // power of 2, so instead of using that, we need to use the raw 7124 // element size multiplied by the element count. 7125 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7126 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7127 7128 return (srcLen * srcEltSize == destLen * destEltSize); 7129 } 7130 7131 /// Is this a legal conversion between two types, one of which is 7132 /// known to be a vector type? 7133 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7134 assert(destTy->isVectorType() || srcTy->isVectorType()); 7135 7136 switch (Context.getLangOpts().getLaxVectorConversions()) { 7137 case LangOptions::LaxVectorConversionKind::None: 7138 return false; 7139 7140 case LangOptions::LaxVectorConversionKind::Integer: 7141 if (!srcTy->isIntegralOrEnumerationType()) { 7142 auto *Vec = srcTy->getAs<VectorType>(); 7143 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7144 return false; 7145 } 7146 if (!destTy->isIntegralOrEnumerationType()) { 7147 auto *Vec = destTy->getAs<VectorType>(); 7148 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7149 return false; 7150 } 7151 // OK, integer (vector) -> integer (vector) bitcast. 7152 break; 7153 7154 case LangOptions::LaxVectorConversionKind::All: 7155 break; 7156 } 7157 7158 return areLaxCompatibleVectorTypes(srcTy, destTy); 7159 } 7160 7161 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7162 CastKind &Kind) { 7163 assert(VectorTy->isVectorType() && "Not a vector type!"); 7164 7165 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7166 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7167 return Diag(R.getBegin(), 7168 Ty->isVectorType() ? 7169 diag::err_invalid_conversion_between_vectors : 7170 diag::err_invalid_conversion_between_vector_and_integer) 7171 << VectorTy << Ty << R; 7172 } else 7173 return Diag(R.getBegin(), 7174 diag::err_invalid_conversion_between_vector_and_scalar) 7175 << VectorTy << Ty << R; 7176 7177 Kind = CK_BitCast; 7178 return false; 7179 } 7180 7181 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7182 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7183 7184 if (DestElemTy == SplattedExpr->getType()) 7185 return SplattedExpr; 7186 7187 assert(DestElemTy->isFloatingType() || 7188 DestElemTy->isIntegralOrEnumerationType()); 7189 7190 CastKind CK; 7191 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7192 // OpenCL requires that we convert `true` boolean expressions to -1, but 7193 // only when splatting vectors. 7194 if (DestElemTy->isFloatingType()) { 7195 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7196 // in two steps: boolean to signed integral, then to floating. 7197 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7198 CK_BooleanToSignedIntegral); 7199 SplattedExpr = CastExprRes.get(); 7200 CK = CK_IntegralToFloating; 7201 } else { 7202 CK = CK_BooleanToSignedIntegral; 7203 } 7204 } else { 7205 ExprResult CastExprRes = SplattedExpr; 7206 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7207 if (CastExprRes.isInvalid()) 7208 return ExprError(); 7209 SplattedExpr = CastExprRes.get(); 7210 } 7211 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7212 } 7213 7214 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7215 Expr *CastExpr, CastKind &Kind) { 7216 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7217 7218 QualType SrcTy = CastExpr->getType(); 7219 7220 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7221 // an ExtVectorType. 7222 // In OpenCL, casts between vectors of different types are not allowed. 7223 // (See OpenCL 6.2). 7224 if (SrcTy->isVectorType()) { 7225 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7226 (getLangOpts().OpenCL && 7227 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7228 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7229 << DestTy << SrcTy << R; 7230 return ExprError(); 7231 } 7232 Kind = CK_BitCast; 7233 return CastExpr; 7234 } 7235 7236 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7237 // conversion will take place first from scalar to elt type, and then 7238 // splat from elt type to vector. 7239 if (SrcTy->isPointerType()) 7240 return Diag(R.getBegin(), 7241 diag::err_invalid_conversion_between_vector_and_scalar) 7242 << DestTy << SrcTy << R; 7243 7244 Kind = CK_VectorSplat; 7245 return prepareVectorSplat(DestTy, CastExpr); 7246 } 7247 7248 ExprResult 7249 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7250 Declarator &D, ParsedType &Ty, 7251 SourceLocation RParenLoc, Expr *CastExpr) { 7252 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7253 "ActOnCastExpr(): missing type or expr"); 7254 7255 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7256 if (D.isInvalidType()) 7257 return ExprError(); 7258 7259 if (getLangOpts().CPlusPlus) { 7260 // Check that there are no default arguments (C++ only). 7261 CheckExtraCXXDefaultArguments(D); 7262 } else { 7263 // Make sure any TypoExprs have been dealt with. 7264 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7265 if (!Res.isUsable()) 7266 return ExprError(); 7267 CastExpr = Res.get(); 7268 } 7269 7270 checkUnusedDeclAttributes(D); 7271 7272 QualType castType = castTInfo->getType(); 7273 Ty = CreateParsedType(castType, castTInfo); 7274 7275 bool isVectorLiteral = false; 7276 7277 // Check for an altivec or OpenCL literal, 7278 // i.e. all the elements are integer constants. 7279 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7280 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7281 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7282 && castType->isVectorType() && (PE || PLE)) { 7283 if (PLE && PLE->getNumExprs() == 0) { 7284 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7285 return ExprError(); 7286 } 7287 if (PE || PLE->getNumExprs() == 1) { 7288 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7289 if (!E->getType()->isVectorType()) 7290 isVectorLiteral = true; 7291 } 7292 else 7293 isVectorLiteral = true; 7294 } 7295 7296 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7297 // then handle it as such. 7298 if (isVectorLiteral) 7299 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7300 7301 // If the Expr being casted is a ParenListExpr, handle it specially. 7302 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7303 // sequence of BinOp comma operators. 7304 if (isa<ParenListExpr>(CastExpr)) { 7305 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7306 if (Result.isInvalid()) return ExprError(); 7307 CastExpr = Result.get(); 7308 } 7309 7310 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7311 !getSourceManager().isInSystemMacro(LParenLoc)) 7312 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7313 7314 CheckTollFreeBridgeCast(castType, CastExpr); 7315 7316 CheckObjCBridgeRelatedCast(castType, CastExpr); 7317 7318 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7319 7320 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7321 } 7322 7323 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7324 SourceLocation RParenLoc, Expr *E, 7325 TypeSourceInfo *TInfo) { 7326 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7327 "Expected paren or paren list expression"); 7328 7329 Expr **exprs; 7330 unsigned numExprs; 7331 Expr *subExpr; 7332 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7333 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7334 LiteralLParenLoc = PE->getLParenLoc(); 7335 LiteralRParenLoc = PE->getRParenLoc(); 7336 exprs = PE->getExprs(); 7337 numExprs = PE->getNumExprs(); 7338 } else { // isa<ParenExpr> by assertion at function entrance 7339 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7340 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7341 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7342 exprs = &subExpr; 7343 numExprs = 1; 7344 } 7345 7346 QualType Ty = TInfo->getType(); 7347 assert(Ty->isVectorType() && "Expected vector type"); 7348 7349 SmallVector<Expr *, 8> initExprs; 7350 const VectorType *VTy = Ty->castAs<VectorType>(); 7351 unsigned numElems = VTy->getNumElements(); 7352 7353 // '(...)' form of vector initialization in AltiVec: the number of 7354 // initializers must be one or must match the size of the vector. 7355 // If a single value is specified in the initializer then it will be 7356 // replicated to all the components of the vector 7357 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7358 // The number of initializers must be one or must match the size of the 7359 // vector. If a single value is specified in the initializer then it will 7360 // be replicated to all the components of the vector 7361 if (numExprs == 1) { 7362 QualType ElemTy = VTy->getElementType(); 7363 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7364 if (Literal.isInvalid()) 7365 return ExprError(); 7366 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7367 PrepareScalarCast(Literal, ElemTy)); 7368 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7369 } 7370 else if (numExprs < numElems) { 7371 Diag(E->getExprLoc(), 7372 diag::err_incorrect_number_of_vector_initializers); 7373 return ExprError(); 7374 } 7375 else 7376 initExprs.append(exprs, exprs + numExprs); 7377 } 7378 else { 7379 // For OpenCL, when the number of initializers is a single value, 7380 // it will be replicated to all components of the vector. 7381 if (getLangOpts().OpenCL && 7382 VTy->getVectorKind() == VectorType::GenericVector && 7383 numExprs == 1) { 7384 QualType ElemTy = VTy->getElementType(); 7385 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7386 if (Literal.isInvalid()) 7387 return ExprError(); 7388 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7389 PrepareScalarCast(Literal, ElemTy)); 7390 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7391 } 7392 7393 initExprs.append(exprs, exprs + numExprs); 7394 } 7395 // FIXME: This means that pretty-printing the final AST will produce curly 7396 // braces instead of the original commas. 7397 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7398 initExprs, LiteralRParenLoc); 7399 initE->setType(Ty); 7400 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7401 } 7402 7403 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7404 /// the ParenListExpr into a sequence of comma binary operators. 7405 ExprResult 7406 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7407 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7408 if (!E) 7409 return OrigExpr; 7410 7411 ExprResult Result(E->getExpr(0)); 7412 7413 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7414 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7415 E->getExpr(i)); 7416 7417 if (Result.isInvalid()) return ExprError(); 7418 7419 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7420 } 7421 7422 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7423 SourceLocation R, 7424 MultiExprArg Val) { 7425 return ParenListExpr::Create(Context, L, Val, R); 7426 } 7427 7428 /// Emit a specialized diagnostic when one expression is a null pointer 7429 /// constant and the other is not a pointer. Returns true if a diagnostic is 7430 /// emitted. 7431 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7432 SourceLocation QuestionLoc) { 7433 Expr *NullExpr = LHSExpr; 7434 Expr *NonPointerExpr = RHSExpr; 7435 Expr::NullPointerConstantKind NullKind = 7436 NullExpr->isNullPointerConstant(Context, 7437 Expr::NPC_ValueDependentIsNotNull); 7438 7439 if (NullKind == Expr::NPCK_NotNull) { 7440 NullExpr = RHSExpr; 7441 NonPointerExpr = LHSExpr; 7442 NullKind = 7443 NullExpr->isNullPointerConstant(Context, 7444 Expr::NPC_ValueDependentIsNotNull); 7445 } 7446 7447 if (NullKind == Expr::NPCK_NotNull) 7448 return false; 7449 7450 if (NullKind == Expr::NPCK_ZeroExpression) 7451 return false; 7452 7453 if (NullKind == Expr::NPCK_ZeroLiteral) { 7454 // In this case, check to make sure that we got here from a "NULL" 7455 // string in the source code. 7456 NullExpr = NullExpr->IgnoreParenImpCasts(); 7457 SourceLocation loc = NullExpr->getExprLoc(); 7458 if (!findMacroSpelling(loc, "NULL")) 7459 return false; 7460 } 7461 7462 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7463 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7464 << NonPointerExpr->getType() << DiagType 7465 << NonPointerExpr->getSourceRange(); 7466 return true; 7467 } 7468 7469 /// Return false if the condition expression is valid, true otherwise. 7470 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7471 QualType CondTy = Cond->getType(); 7472 7473 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7474 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7475 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7476 << CondTy << Cond->getSourceRange(); 7477 return true; 7478 } 7479 7480 // C99 6.5.15p2 7481 if (CondTy->isScalarType()) return false; 7482 7483 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7484 << CondTy << Cond->getSourceRange(); 7485 return true; 7486 } 7487 7488 /// Handle when one or both operands are void type. 7489 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7490 ExprResult &RHS) { 7491 Expr *LHSExpr = LHS.get(); 7492 Expr *RHSExpr = RHS.get(); 7493 7494 if (!LHSExpr->getType()->isVoidType()) 7495 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7496 << RHSExpr->getSourceRange(); 7497 if (!RHSExpr->getType()->isVoidType()) 7498 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7499 << LHSExpr->getSourceRange(); 7500 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7501 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7502 return S.Context.VoidTy; 7503 } 7504 7505 /// Return false if the NullExpr can be promoted to PointerTy, 7506 /// true otherwise. 7507 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7508 QualType PointerTy) { 7509 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7510 !NullExpr.get()->isNullPointerConstant(S.Context, 7511 Expr::NPC_ValueDependentIsNull)) 7512 return true; 7513 7514 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7515 return false; 7516 } 7517 7518 /// Checks compatibility between two pointers and return the resulting 7519 /// type. 7520 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7521 ExprResult &RHS, 7522 SourceLocation Loc) { 7523 QualType LHSTy = LHS.get()->getType(); 7524 QualType RHSTy = RHS.get()->getType(); 7525 7526 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7527 // Two identical pointers types are always compatible. 7528 return LHSTy; 7529 } 7530 7531 QualType lhptee, rhptee; 7532 7533 // Get the pointee types. 7534 bool IsBlockPointer = false; 7535 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7536 lhptee = LHSBTy->getPointeeType(); 7537 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7538 IsBlockPointer = true; 7539 } else { 7540 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7541 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7542 } 7543 7544 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7545 // differently qualified versions of compatible types, the result type is 7546 // a pointer to an appropriately qualified version of the composite 7547 // type. 7548 7549 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7550 // clause doesn't make sense for our extensions. E.g. address space 2 should 7551 // be incompatible with address space 3: they may live on different devices or 7552 // anything. 7553 Qualifiers lhQual = lhptee.getQualifiers(); 7554 Qualifiers rhQual = rhptee.getQualifiers(); 7555 7556 LangAS ResultAddrSpace = LangAS::Default; 7557 LangAS LAddrSpace = lhQual.getAddressSpace(); 7558 LangAS RAddrSpace = rhQual.getAddressSpace(); 7559 7560 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7561 // spaces is disallowed. 7562 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7563 ResultAddrSpace = LAddrSpace; 7564 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7565 ResultAddrSpace = RAddrSpace; 7566 else { 7567 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7568 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7569 << RHS.get()->getSourceRange(); 7570 return QualType(); 7571 } 7572 7573 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7574 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7575 lhQual.removeCVRQualifiers(); 7576 rhQual.removeCVRQualifiers(); 7577 7578 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7579 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7580 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7581 // qual types are compatible iff 7582 // * corresponded types are compatible 7583 // * CVR qualifiers are equal 7584 // * address spaces are equal 7585 // Thus for conditional operator we merge CVR and address space unqualified 7586 // pointees and if there is a composite type we return a pointer to it with 7587 // merged qualifiers. 7588 LHSCastKind = 7589 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7590 RHSCastKind = 7591 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7592 lhQual.removeAddressSpace(); 7593 rhQual.removeAddressSpace(); 7594 7595 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7596 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7597 7598 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7599 7600 if (CompositeTy.isNull()) { 7601 // In this situation, we assume void* type. No especially good 7602 // reason, but this is what gcc does, and we do have to pick 7603 // to get a consistent AST. 7604 QualType incompatTy; 7605 incompatTy = S.Context.getPointerType( 7606 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7607 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7608 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7609 7610 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7611 // for casts between types with incompatible address space qualifiers. 7612 // For the following code the compiler produces casts between global and 7613 // local address spaces of the corresponded innermost pointees: 7614 // local int *global *a; 7615 // global int *global *b; 7616 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7617 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7618 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7619 << RHS.get()->getSourceRange(); 7620 7621 return incompatTy; 7622 } 7623 7624 // The pointer types are compatible. 7625 // In case of OpenCL ResultTy should have the address space qualifier 7626 // which is a superset of address spaces of both the 2nd and the 3rd 7627 // operands of the conditional operator. 7628 QualType ResultTy = [&, ResultAddrSpace]() { 7629 if (S.getLangOpts().OpenCL) { 7630 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7631 CompositeQuals.setAddressSpace(ResultAddrSpace); 7632 return S.Context 7633 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7634 .withCVRQualifiers(MergedCVRQual); 7635 } 7636 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7637 }(); 7638 if (IsBlockPointer) 7639 ResultTy = S.Context.getBlockPointerType(ResultTy); 7640 else 7641 ResultTy = S.Context.getPointerType(ResultTy); 7642 7643 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7644 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7645 return ResultTy; 7646 } 7647 7648 /// Return the resulting type when the operands are both block pointers. 7649 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7650 ExprResult &LHS, 7651 ExprResult &RHS, 7652 SourceLocation Loc) { 7653 QualType LHSTy = LHS.get()->getType(); 7654 QualType RHSTy = RHS.get()->getType(); 7655 7656 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7657 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7658 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7659 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7660 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7661 return destType; 7662 } 7663 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7664 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7665 << RHS.get()->getSourceRange(); 7666 return QualType(); 7667 } 7668 7669 // We have 2 block pointer types. 7670 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7671 } 7672 7673 /// Return the resulting type when the operands are both pointers. 7674 static QualType 7675 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7676 ExprResult &RHS, 7677 SourceLocation Loc) { 7678 // get the pointer types 7679 QualType LHSTy = LHS.get()->getType(); 7680 QualType RHSTy = RHS.get()->getType(); 7681 7682 // get the "pointed to" types 7683 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7684 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7685 7686 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7687 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7688 // Figure out necessary qualifiers (C99 6.5.15p6) 7689 QualType destPointee 7690 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7691 QualType destType = S.Context.getPointerType(destPointee); 7692 // Add qualifiers if necessary. 7693 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7694 // Promote to void*. 7695 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7696 return destType; 7697 } 7698 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7699 QualType destPointee 7700 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7701 QualType destType = S.Context.getPointerType(destPointee); 7702 // Add qualifiers if necessary. 7703 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7704 // Promote to void*. 7705 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7706 return destType; 7707 } 7708 7709 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7710 } 7711 7712 /// Return false if the first expression is not an integer and the second 7713 /// expression is not a pointer, true otherwise. 7714 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7715 Expr* PointerExpr, SourceLocation Loc, 7716 bool IsIntFirstExpr) { 7717 if (!PointerExpr->getType()->isPointerType() || 7718 !Int.get()->getType()->isIntegerType()) 7719 return false; 7720 7721 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7722 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7723 7724 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7725 << Expr1->getType() << Expr2->getType() 7726 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7727 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7728 CK_IntegralToPointer); 7729 return true; 7730 } 7731 7732 /// Simple conversion between integer and floating point types. 7733 /// 7734 /// Used when handling the OpenCL conditional operator where the 7735 /// condition is a vector while the other operands are scalar. 7736 /// 7737 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7738 /// types are either integer or floating type. Between the two 7739 /// operands, the type with the higher rank is defined as the "result 7740 /// type". The other operand needs to be promoted to the same type. No 7741 /// other type promotion is allowed. We cannot use 7742 /// UsualArithmeticConversions() for this purpose, since it always 7743 /// promotes promotable types. 7744 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7745 ExprResult &RHS, 7746 SourceLocation QuestionLoc) { 7747 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7748 if (LHS.isInvalid()) 7749 return QualType(); 7750 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7751 if (RHS.isInvalid()) 7752 return QualType(); 7753 7754 // For conversion purposes, we ignore any qualifiers. 7755 // For example, "const float" and "float" are equivalent. 7756 QualType LHSType = 7757 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7758 QualType RHSType = 7759 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7760 7761 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7762 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7763 << LHSType << LHS.get()->getSourceRange(); 7764 return QualType(); 7765 } 7766 7767 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7768 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7769 << RHSType << RHS.get()->getSourceRange(); 7770 return QualType(); 7771 } 7772 7773 // If both types are identical, no conversion is needed. 7774 if (LHSType == RHSType) 7775 return LHSType; 7776 7777 // Now handle "real" floating types (i.e. float, double, long double). 7778 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7779 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7780 /*IsCompAssign = */ false); 7781 7782 // Finally, we have two differing integer types. 7783 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7784 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7785 } 7786 7787 /// Convert scalar operands to a vector that matches the 7788 /// condition in length. 7789 /// 7790 /// Used when handling the OpenCL conditional operator where the 7791 /// condition is a vector while the other operands are scalar. 7792 /// 7793 /// We first compute the "result type" for the scalar operands 7794 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7795 /// into a vector of that type where the length matches the condition 7796 /// vector type. s6.11.6 requires that the element types of the result 7797 /// and the condition must have the same number of bits. 7798 static QualType 7799 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7800 QualType CondTy, SourceLocation QuestionLoc) { 7801 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7802 if (ResTy.isNull()) return QualType(); 7803 7804 const VectorType *CV = CondTy->getAs<VectorType>(); 7805 assert(CV); 7806 7807 // Determine the vector result type 7808 unsigned NumElements = CV->getNumElements(); 7809 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7810 7811 // Ensure that all types have the same number of bits 7812 if (S.Context.getTypeSize(CV->getElementType()) 7813 != S.Context.getTypeSize(ResTy)) { 7814 // Since VectorTy is created internally, it does not pretty print 7815 // with an OpenCL name. Instead, we just print a description. 7816 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7817 SmallString<64> Str; 7818 llvm::raw_svector_ostream OS(Str); 7819 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7820 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7821 << CondTy << OS.str(); 7822 return QualType(); 7823 } 7824 7825 // Convert operands to the vector result type 7826 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7827 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7828 7829 return VectorTy; 7830 } 7831 7832 /// Return false if this is a valid OpenCL condition vector 7833 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7834 SourceLocation QuestionLoc) { 7835 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7836 // integral type. 7837 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7838 assert(CondTy); 7839 QualType EleTy = CondTy->getElementType(); 7840 if (EleTy->isIntegerType()) return false; 7841 7842 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7843 << Cond->getType() << Cond->getSourceRange(); 7844 return true; 7845 } 7846 7847 /// Return false if the vector condition type and the vector 7848 /// result type are compatible. 7849 /// 7850 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7851 /// number of elements, and their element types have the same number 7852 /// of bits. 7853 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7854 SourceLocation QuestionLoc) { 7855 const VectorType *CV = CondTy->getAs<VectorType>(); 7856 const VectorType *RV = VecResTy->getAs<VectorType>(); 7857 assert(CV && RV); 7858 7859 if (CV->getNumElements() != RV->getNumElements()) { 7860 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7861 << CondTy << VecResTy; 7862 return true; 7863 } 7864 7865 QualType CVE = CV->getElementType(); 7866 QualType RVE = RV->getElementType(); 7867 7868 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7869 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7870 << CondTy << VecResTy; 7871 return true; 7872 } 7873 7874 return false; 7875 } 7876 7877 /// Return the resulting type for the conditional operator in 7878 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7879 /// s6.3.i) when the condition is a vector type. 7880 static QualType 7881 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7882 ExprResult &LHS, ExprResult &RHS, 7883 SourceLocation QuestionLoc) { 7884 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7885 if (Cond.isInvalid()) 7886 return QualType(); 7887 QualType CondTy = Cond.get()->getType(); 7888 7889 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7890 return QualType(); 7891 7892 // If either operand is a vector then find the vector type of the 7893 // result as specified in OpenCL v1.1 s6.3.i. 7894 if (LHS.get()->getType()->isVectorType() || 7895 RHS.get()->getType()->isVectorType()) { 7896 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7897 /*isCompAssign*/false, 7898 /*AllowBothBool*/true, 7899 /*AllowBoolConversions*/false); 7900 if (VecResTy.isNull()) return QualType(); 7901 // The result type must match the condition type as specified in 7902 // OpenCL v1.1 s6.11.6. 7903 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7904 return QualType(); 7905 return VecResTy; 7906 } 7907 7908 // Both operands are scalar. 7909 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7910 } 7911 7912 /// Return true if the Expr is block type 7913 static bool checkBlockType(Sema &S, const Expr *E) { 7914 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7915 QualType Ty = CE->getCallee()->getType(); 7916 if (Ty->isBlockPointerType()) { 7917 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7918 return true; 7919 } 7920 } 7921 return false; 7922 } 7923 7924 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7925 /// In that case, LHS = cond. 7926 /// C99 6.5.15 7927 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7928 ExprResult &RHS, ExprValueKind &VK, 7929 ExprObjectKind &OK, 7930 SourceLocation QuestionLoc) { 7931 7932 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7933 if (!LHSResult.isUsable()) return QualType(); 7934 LHS = LHSResult; 7935 7936 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7937 if (!RHSResult.isUsable()) return QualType(); 7938 RHS = RHSResult; 7939 7940 // C++ is sufficiently different to merit its own checker. 7941 if (getLangOpts().CPlusPlus) 7942 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7943 7944 VK = VK_RValue; 7945 OK = OK_Ordinary; 7946 7947 // The OpenCL operator with a vector condition is sufficiently 7948 // different to merit its own checker. 7949 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7950 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7951 7952 // First, check the condition. 7953 Cond = UsualUnaryConversions(Cond.get()); 7954 if (Cond.isInvalid()) 7955 return QualType(); 7956 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7957 return QualType(); 7958 7959 // Now check the two expressions. 7960 if (LHS.get()->getType()->isVectorType() || 7961 RHS.get()->getType()->isVectorType()) 7962 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7963 /*AllowBothBool*/true, 7964 /*AllowBoolConversions*/false); 7965 7966 QualType ResTy = 7967 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7968 if (LHS.isInvalid() || RHS.isInvalid()) 7969 return QualType(); 7970 7971 QualType LHSTy = LHS.get()->getType(); 7972 QualType RHSTy = RHS.get()->getType(); 7973 7974 // Diagnose attempts to convert between __float128 and long double where 7975 // such conversions currently can't be handled. 7976 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7977 Diag(QuestionLoc, 7978 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7979 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7980 return QualType(); 7981 } 7982 7983 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7984 // selection operator (?:). 7985 if (getLangOpts().OpenCL && 7986 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7987 return QualType(); 7988 } 7989 7990 // If both operands have arithmetic type, do the usual arithmetic conversions 7991 // to find a common type: C99 6.5.15p3,5. 7992 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7993 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7994 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7995 7996 return ResTy; 7997 } 7998 7999 // If both operands are the same structure or union type, the result is that 8000 // type. 8001 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8002 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8003 if (LHSRT->getDecl() == RHSRT->getDecl()) 8004 // "If both the operands have structure or union type, the result has 8005 // that type." This implies that CV qualifiers are dropped. 8006 return LHSTy.getUnqualifiedType(); 8007 // FIXME: Type of conditional expression must be complete in C mode. 8008 } 8009 8010 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8011 // The following || allows only one side to be void (a GCC-ism). 8012 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8013 return checkConditionalVoidType(*this, LHS, RHS); 8014 } 8015 8016 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8017 // the type of the other operand." 8018 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8019 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8020 8021 // All objective-c pointer type analysis is done here. 8022 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8023 QuestionLoc); 8024 if (LHS.isInvalid() || RHS.isInvalid()) 8025 return QualType(); 8026 if (!compositeType.isNull()) 8027 return compositeType; 8028 8029 8030 // Handle block pointer types. 8031 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8032 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8033 QuestionLoc); 8034 8035 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8036 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8037 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8038 QuestionLoc); 8039 8040 // GCC compatibility: soften pointer/integer mismatch. Note that 8041 // null pointers have been filtered out by this point. 8042 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8043 /*IsIntFirstExpr=*/true)) 8044 return RHSTy; 8045 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8046 /*IsIntFirstExpr=*/false)) 8047 return LHSTy; 8048 8049 // Allow ?: operations in which both operands have the same 8050 // built-in sizeless type. 8051 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8052 return LHSTy; 8053 8054 // Emit a better diagnostic if one of the expressions is a null pointer 8055 // constant and the other is not a pointer type. In this case, the user most 8056 // likely forgot to take the address of the other expression. 8057 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8058 return QualType(); 8059 8060 // Otherwise, the operands are not compatible. 8061 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8062 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8063 << RHS.get()->getSourceRange(); 8064 return QualType(); 8065 } 8066 8067 /// FindCompositeObjCPointerType - Helper method to find composite type of 8068 /// two objective-c pointer types of the two input expressions. 8069 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8070 SourceLocation QuestionLoc) { 8071 QualType LHSTy = LHS.get()->getType(); 8072 QualType RHSTy = RHS.get()->getType(); 8073 8074 // Handle things like Class and struct objc_class*. Here we case the result 8075 // to the pseudo-builtin, because that will be implicitly cast back to the 8076 // redefinition type if an attempt is made to access its fields. 8077 if (LHSTy->isObjCClassType() && 8078 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8079 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8080 return LHSTy; 8081 } 8082 if (RHSTy->isObjCClassType() && 8083 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8084 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8085 return RHSTy; 8086 } 8087 // And the same for struct objc_object* / id 8088 if (LHSTy->isObjCIdType() && 8089 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8090 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8091 return LHSTy; 8092 } 8093 if (RHSTy->isObjCIdType() && 8094 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8095 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8096 return RHSTy; 8097 } 8098 // And the same for struct objc_selector* / SEL 8099 if (Context.isObjCSelType(LHSTy) && 8100 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8101 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8102 return LHSTy; 8103 } 8104 if (Context.isObjCSelType(RHSTy) && 8105 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8106 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8107 return RHSTy; 8108 } 8109 // Check constraints for Objective-C object pointers types. 8110 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8111 8112 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8113 // Two identical object pointer types are always compatible. 8114 return LHSTy; 8115 } 8116 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8117 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8118 QualType compositeType = LHSTy; 8119 8120 // If both operands are interfaces and either operand can be 8121 // assigned to the other, use that type as the composite 8122 // type. This allows 8123 // xxx ? (A*) a : (B*) b 8124 // where B is a subclass of A. 8125 // 8126 // Additionally, as for assignment, if either type is 'id' 8127 // allow silent coercion. Finally, if the types are 8128 // incompatible then make sure to use 'id' as the composite 8129 // type so the result is acceptable for sending messages to. 8130 8131 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8132 // It could return the composite type. 8133 if (!(compositeType = 8134 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8135 // Nothing more to do. 8136 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8137 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8138 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8139 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8140 } else if ((LHSOPT->isObjCQualifiedIdType() || 8141 RHSOPT->isObjCQualifiedIdType()) && 8142 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8143 true)) { 8144 // Need to handle "id<xx>" explicitly. 8145 // GCC allows qualified id and any Objective-C type to devolve to 8146 // id. Currently localizing to here until clear this should be 8147 // part of ObjCQualifiedIdTypesAreCompatible. 8148 compositeType = Context.getObjCIdType(); 8149 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8150 compositeType = Context.getObjCIdType(); 8151 } else { 8152 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8153 << LHSTy << RHSTy 8154 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8155 QualType incompatTy = Context.getObjCIdType(); 8156 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8157 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8158 return incompatTy; 8159 } 8160 // The object pointer types are compatible. 8161 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8162 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8163 return compositeType; 8164 } 8165 // Check Objective-C object pointer types and 'void *' 8166 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8167 if (getLangOpts().ObjCAutoRefCount) { 8168 // ARC forbids the implicit conversion of object pointers to 'void *', 8169 // so these types are not compatible. 8170 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8172 LHS = RHS = true; 8173 return QualType(); 8174 } 8175 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8176 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8177 QualType destPointee 8178 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8179 QualType destType = Context.getPointerType(destPointee); 8180 // Add qualifiers if necessary. 8181 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8182 // Promote to void*. 8183 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8184 return destType; 8185 } 8186 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8187 if (getLangOpts().ObjCAutoRefCount) { 8188 // ARC forbids the implicit conversion of object pointers to 'void *', 8189 // so these types are not compatible. 8190 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8191 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8192 LHS = RHS = true; 8193 return QualType(); 8194 } 8195 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8196 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8197 QualType destPointee 8198 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8199 QualType destType = Context.getPointerType(destPointee); 8200 // Add qualifiers if necessary. 8201 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8202 // Promote to void*. 8203 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8204 return destType; 8205 } 8206 return QualType(); 8207 } 8208 8209 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8210 /// ParenRange in parentheses. 8211 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8212 const PartialDiagnostic &Note, 8213 SourceRange ParenRange) { 8214 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8215 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8216 EndLoc.isValid()) { 8217 Self.Diag(Loc, Note) 8218 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8219 << FixItHint::CreateInsertion(EndLoc, ")"); 8220 } else { 8221 // We can't display the parentheses, so just show the bare note. 8222 Self.Diag(Loc, Note) << ParenRange; 8223 } 8224 } 8225 8226 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8227 return BinaryOperator::isAdditiveOp(Opc) || 8228 BinaryOperator::isMultiplicativeOp(Opc) || 8229 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8230 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8231 // not any of the logical operators. Bitwise-xor is commonly used as a 8232 // logical-xor because there is no logical-xor operator. The logical 8233 // operators, including uses of xor, have a high false positive rate for 8234 // precedence warnings. 8235 } 8236 8237 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8238 /// expression, either using a built-in or overloaded operator, 8239 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8240 /// expression. 8241 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8242 Expr **RHSExprs) { 8243 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8244 E = E->IgnoreImpCasts(); 8245 E = E->IgnoreConversionOperator(); 8246 E = E->IgnoreImpCasts(); 8247 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8248 E = MTE->getSubExpr(); 8249 E = E->IgnoreImpCasts(); 8250 } 8251 8252 // Built-in binary operator. 8253 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8254 if (IsArithmeticOp(OP->getOpcode())) { 8255 *Opcode = OP->getOpcode(); 8256 *RHSExprs = OP->getRHS(); 8257 return true; 8258 } 8259 } 8260 8261 // Overloaded operator. 8262 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8263 if (Call->getNumArgs() != 2) 8264 return false; 8265 8266 // Make sure this is really a binary operator that is safe to pass into 8267 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8268 OverloadedOperatorKind OO = Call->getOperator(); 8269 if (OO < OO_Plus || OO > OO_Arrow || 8270 OO == OO_PlusPlus || OO == OO_MinusMinus) 8271 return false; 8272 8273 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8274 if (IsArithmeticOp(OpKind)) { 8275 *Opcode = OpKind; 8276 *RHSExprs = Call->getArg(1); 8277 return true; 8278 } 8279 } 8280 8281 return false; 8282 } 8283 8284 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8285 /// or is a logical expression such as (x==y) which has int type, but is 8286 /// commonly interpreted as boolean. 8287 static bool ExprLooksBoolean(Expr *E) { 8288 E = E->IgnoreParenImpCasts(); 8289 8290 if (E->getType()->isBooleanType()) 8291 return true; 8292 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8293 return OP->isComparisonOp() || OP->isLogicalOp(); 8294 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8295 return OP->getOpcode() == UO_LNot; 8296 if (E->getType()->isPointerType()) 8297 return true; 8298 // FIXME: What about overloaded operator calls returning "unspecified boolean 8299 // type"s (commonly pointer-to-members)? 8300 8301 return false; 8302 } 8303 8304 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8305 /// and binary operator are mixed in a way that suggests the programmer assumed 8306 /// the conditional operator has higher precedence, for example: 8307 /// "int x = a + someBinaryCondition ? 1 : 2". 8308 static void DiagnoseConditionalPrecedence(Sema &Self, 8309 SourceLocation OpLoc, 8310 Expr *Condition, 8311 Expr *LHSExpr, 8312 Expr *RHSExpr) { 8313 BinaryOperatorKind CondOpcode; 8314 Expr *CondRHS; 8315 8316 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8317 return; 8318 if (!ExprLooksBoolean(CondRHS)) 8319 return; 8320 8321 // The condition is an arithmetic binary expression, with a right- 8322 // hand side that looks boolean, so warn. 8323 8324 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8325 ? diag::warn_precedence_bitwise_conditional 8326 : diag::warn_precedence_conditional; 8327 8328 Self.Diag(OpLoc, DiagID) 8329 << Condition->getSourceRange() 8330 << BinaryOperator::getOpcodeStr(CondOpcode); 8331 8332 SuggestParentheses( 8333 Self, OpLoc, 8334 Self.PDiag(diag::note_precedence_silence) 8335 << BinaryOperator::getOpcodeStr(CondOpcode), 8336 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8337 8338 SuggestParentheses(Self, OpLoc, 8339 Self.PDiag(diag::note_precedence_conditional_first), 8340 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8341 } 8342 8343 /// Compute the nullability of a conditional expression. 8344 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8345 QualType LHSTy, QualType RHSTy, 8346 ASTContext &Ctx) { 8347 if (!ResTy->isAnyPointerType()) 8348 return ResTy; 8349 8350 auto GetNullability = [&Ctx](QualType Ty) { 8351 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8352 if (Kind) 8353 return *Kind; 8354 return NullabilityKind::Unspecified; 8355 }; 8356 8357 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8358 NullabilityKind MergedKind; 8359 8360 // Compute nullability of a binary conditional expression. 8361 if (IsBin) { 8362 if (LHSKind == NullabilityKind::NonNull) 8363 MergedKind = NullabilityKind::NonNull; 8364 else 8365 MergedKind = RHSKind; 8366 // Compute nullability of a normal conditional expression. 8367 } else { 8368 if (LHSKind == NullabilityKind::Nullable || 8369 RHSKind == NullabilityKind::Nullable) 8370 MergedKind = NullabilityKind::Nullable; 8371 else if (LHSKind == NullabilityKind::NonNull) 8372 MergedKind = RHSKind; 8373 else if (RHSKind == NullabilityKind::NonNull) 8374 MergedKind = LHSKind; 8375 else 8376 MergedKind = NullabilityKind::Unspecified; 8377 } 8378 8379 // Return if ResTy already has the correct nullability. 8380 if (GetNullability(ResTy) == MergedKind) 8381 return ResTy; 8382 8383 // Strip all nullability from ResTy. 8384 while (ResTy->getNullability(Ctx)) 8385 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8386 8387 // Create a new AttributedType with the new nullability kind. 8388 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8389 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8390 } 8391 8392 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8393 /// in the case of a the GNU conditional expr extension. 8394 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8395 SourceLocation ColonLoc, 8396 Expr *CondExpr, Expr *LHSExpr, 8397 Expr *RHSExpr) { 8398 if (!getLangOpts().CPlusPlus) { 8399 // C cannot handle TypoExpr nodes in the condition because it 8400 // doesn't handle dependent types properly, so make sure any TypoExprs have 8401 // been dealt with before checking the operands. 8402 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8403 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8404 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8405 8406 if (!CondResult.isUsable()) 8407 return ExprError(); 8408 8409 if (LHSExpr) { 8410 if (!LHSResult.isUsable()) 8411 return ExprError(); 8412 } 8413 8414 if (!RHSResult.isUsable()) 8415 return ExprError(); 8416 8417 CondExpr = CondResult.get(); 8418 LHSExpr = LHSResult.get(); 8419 RHSExpr = RHSResult.get(); 8420 } 8421 8422 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8423 // was the condition. 8424 OpaqueValueExpr *opaqueValue = nullptr; 8425 Expr *commonExpr = nullptr; 8426 if (!LHSExpr) { 8427 commonExpr = CondExpr; 8428 // Lower out placeholder types first. This is important so that we don't 8429 // try to capture a placeholder. This happens in few cases in C++; such 8430 // as Objective-C++'s dictionary subscripting syntax. 8431 if (commonExpr->hasPlaceholderType()) { 8432 ExprResult result = CheckPlaceholderExpr(commonExpr); 8433 if (!result.isUsable()) return ExprError(); 8434 commonExpr = result.get(); 8435 } 8436 // We usually want to apply unary conversions *before* saving, except 8437 // in the special case of a C++ l-value conditional. 8438 if (!(getLangOpts().CPlusPlus 8439 && !commonExpr->isTypeDependent() 8440 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8441 && commonExpr->isGLValue() 8442 && commonExpr->isOrdinaryOrBitFieldObject() 8443 && RHSExpr->isOrdinaryOrBitFieldObject() 8444 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8445 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8446 if (commonRes.isInvalid()) 8447 return ExprError(); 8448 commonExpr = commonRes.get(); 8449 } 8450 8451 // If the common expression is a class or array prvalue, materialize it 8452 // so that we can safely refer to it multiple times. 8453 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8454 commonExpr->getType()->isArrayType())) { 8455 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8456 if (MatExpr.isInvalid()) 8457 return ExprError(); 8458 commonExpr = MatExpr.get(); 8459 } 8460 8461 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8462 commonExpr->getType(), 8463 commonExpr->getValueKind(), 8464 commonExpr->getObjectKind(), 8465 commonExpr); 8466 LHSExpr = CondExpr = opaqueValue; 8467 } 8468 8469 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8470 ExprValueKind VK = VK_RValue; 8471 ExprObjectKind OK = OK_Ordinary; 8472 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8473 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8474 VK, OK, QuestionLoc); 8475 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8476 RHS.isInvalid()) 8477 return ExprError(); 8478 8479 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8480 RHS.get()); 8481 8482 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8483 8484 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8485 Context); 8486 8487 if (!commonExpr) 8488 return new (Context) 8489 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8490 RHS.get(), result, VK, OK); 8491 8492 return new (Context) BinaryConditionalOperator( 8493 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8494 ColonLoc, result, VK, OK); 8495 } 8496 8497 // Check if we have a conversion between incompatible cmse function pointer 8498 // types, that is, a conversion between a function pointer with the 8499 // cmse_nonsecure_call attribute and one without. 8500 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8501 QualType ToType) { 8502 if (const auto *ToFn = 8503 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8504 if (const auto *FromFn = 8505 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8506 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8507 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8508 8509 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8510 } 8511 } 8512 return false; 8513 } 8514 8515 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8516 // being closely modeled after the C99 spec:-). The odd characteristic of this 8517 // routine is it effectively iqnores the qualifiers on the top level pointee. 8518 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8519 // FIXME: add a couple examples in this comment. 8520 static Sema::AssignConvertType 8521 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8522 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8523 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8524 8525 // get the "pointed to" type (ignoring qualifiers at the top level) 8526 const Type *lhptee, *rhptee; 8527 Qualifiers lhq, rhq; 8528 std::tie(lhptee, lhq) = 8529 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8530 std::tie(rhptee, rhq) = 8531 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8532 8533 Sema::AssignConvertType ConvTy = Sema::Compatible; 8534 8535 // C99 6.5.16.1p1: This following citation is common to constraints 8536 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8537 // qualifiers of the type *pointed to* by the right; 8538 8539 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8540 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8541 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8542 // Ignore lifetime for further calculation. 8543 lhq.removeObjCLifetime(); 8544 rhq.removeObjCLifetime(); 8545 } 8546 8547 if (!lhq.compatiblyIncludes(rhq)) { 8548 // Treat address-space mismatches as fatal. 8549 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8550 return Sema::IncompatiblePointerDiscardsQualifiers; 8551 8552 // It's okay to add or remove GC or lifetime qualifiers when converting to 8553 // and from void*. 8554 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8555 .compatiblyIncludes( 8556 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8557 && (lhptee->isVoidType() || rhptee->isVoidType())) 8558 ; // keep old 8559 8560 // Treat lifetime mismatches as fatal. 8561 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8562 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8563 8564 // For GCC/MS compatibility, other qualifier mismatches are treated 8565 // as still compatible in C. 8566 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8567 } 8568 8569 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8570 // incomplete type and the other is a pointer to a qualified or unqualified 8571 // version of void... 8572 if (lhptee->isVoidType()) { 8573 if (rhptee->isIncompleteOrObjectType()) 8574 return ConvTy; 8575 8576 // As an extension, we allow cast to/from void* to function pointer. 8577 assert(rhptee->isFunctionType()); 8578 return Sema::FunctionVoidPointer; 8579 } 8580 8581 if (rhptee->isVoidType()) { 8582 if (lhptee->isIncompleteOrObjectType()) 8583 return ConvTy; 8584 8585 // As an extension, we allow cast to/from void* to function pointer. 8586 assert(lhptee->isFunctionType()); 8587 return Sema::FunctionVoidPointer; 8588 } 8589 8590 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8591 // unqualified versions of compatible types, ... 8592 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8593 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8594 // Check if the pointee types are compatible ignoring the sign. 8595 // We explicitly check for char so that we catch "char" vs 8596 // "unsigned char" on systems where "char" is unsigned. 8597 if (lhptee->isCharType()) 8598 ltrans = S.Context.UnsignedCharTy; 8599 else if (lhptee->hasSignedIntegerRepresentation()) 8600 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8601 8602 if (rhptee->isCharType()) 8603 rtrans = S.Context.UnsignedCharTy; 8604 else if (rhptee->hasSignedIntegerRepresentation()) 8605 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8606 8607 if (ltrans == rtrans) { 8608 // Types are compatible ignoring the sign. Qualifier incompatibility 8609 // takes priority over sign incompatibility because the sign 8610 // warning can be disabled. 8611 if (ConvTy != Sema::Compatible) 8612 return ConvTy; 8613 8614 return Sema::IncompatiblePointerSign; 8615 } 8616 8617 // If we are a multi-level pointer, it's possible that our issue is simply 8618 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8619 // the eventual target type is the same and the pointers have the same 8620 // level of indirection, this must be the issue. 8621 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8622 do { 8623 std::tie(lhptee, lhq) = 8624 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8625 std::tie(rhptee, rhq) = 8626 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8627 8628 // Inconsistent address spaces at this point is invalid, even if the 8629 // address spaces would be compatible. 8630 // FIXME: This doesn't catch address space mismatches for pointers of 8631 // different nesting levels, like: 8632 // __local int *** a; 8633 // int ** b = a; 8634 // It's not clear how to actually determine when such pointers are 8635 // invalidly incompatible. 8636 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8637 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8638 8639 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8640 8641 if (lhptee == rhptee) 8642 return Sema::IncompatibleNestedPointerQualifiers; 8643 } 8644 8645 // General pointer incompatibility takes priority over qualifiers. 8646 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8647 return Sema::IncompatibleFunctionPointer; 8648 return Sema::IncompatiblePointer; 8649 } 8650 if (!S.getLangOpts().CPlusPlus && 8651 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8652 return Sema::IncompatibleFunctionPointer; 8653 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8654 return Sema::IncompatibleFunctionPointer; 8655 return ConvTy; 8656 } 8657 8658 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8659 /// block pointer types are compatible or whether a block and normal pointer 8660 /// are compatible. It is more restrict than comparing two function pointer 8661 // types. 8662 static Sema::AssignConvertType 8663 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8664 QualType RHSType) { 8665 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8666 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8667 8668 QualType lhptee, rhptee; 8669 8670 // get the "pointed to" type (ignoring qualifiers at the top level) 8671 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8672 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8673 8674 // In C++, the types have to match exactly. 8675 if (S.getLangOpts().CPlusPlus) 8676 return Sema::IncompatibleBlockPointer; 8677 8678 Sema::AssignConvertType ConvTy = Sema::Compatible; 8679 8680 // For blocks we enforce that qualifiers are identical. 8681 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8682 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8683 if (S.getLangOpts().OpenCL) { 8684 LQuals.removeAddressSpace(); 8685 RQuals.removeAddressSpace(); 8686 } 8687 if (LQuals != RQuals) 8688 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8689 8690 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8691 // assignment. 8692 // The current behavior is similar to C++ lambdas. A block might be 8693 // assigned to a variable iff its return type and parameters are compatible 8694 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8695 // an assignment. Presumably it should behave in way that a function pointer 8696 // assignment does in C, so for each parameter and return type: 8697 // * CVR and address space of LHS should be a superset of CVR and address 8698 // space of RHS. 8699 // * unqualified types should be compatible. 8700 if (S.getLangOpts().OpenCL) { 8701 if (!S.Context.typesAreBlockPointerCompatible( 8702 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8703 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8704 return Sema::IncompatibleBlockPointer; 8705 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8706 return Sema::IncompatibleBlockPointer; 8707 8708 return ConvTy; 8709 } 8710 8711 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8712 /// for assignment compatibility. 8713 static Sema::AssignConvertType 8714 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8715 QualType RHSType) { 8716 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8717 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8718 8719 if (LHSType->isObjCBuiltinType()) { 8720 // Class is not compatible with ObjC object pointers. 8721 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8722 !RHSType->isObjCQualifiedClassType()) 8723 return Sema::IncompatiblePointer; 8724 return Sema::Compatible; 8725 } 8726 if (RHSType->isObjCBuiltinType()) { 8727 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8728 !LHSType->isObjCQualifiedClassType()) 8729 return Sema::IncompatiblePointer; 8730 return Sema::Compatible; 8731 } 8732 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8733 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8734 8735 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8736 // make an exception for id<P> 8737 !LHSType->isObjCQualifiedIdType()) 8738 return Sema::CompatiblePointerDiscardsQualifiers; 8739 8740 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8741 return Sema::Compatible; 8742 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8743 return Sema::IncompatibleObjCQualifiedId; 8744 return Sema::IncompatiblePointer; 8745 } 8746 8747 Sema::AssignConvertType 8748 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8749 QualType LHSType, QualType RHSType) { 8750 // Fake up an opaque expression. We don't actually care about what 8751 // cast operations are required, so if CheckAssignmentConstraints 8752 // adds casts to this they'll be wasted, but fortunately that doesn't 8753 // usually happen on valid code. 8754 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8755 ExprResult RHSPtr = &RHSExpr; 8756 CastKind K; 8757 8758 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8759 } 8760 8761 /// This helper function returns true if QT is a vector type that has element 8762 /// type ElementType. 8763 static bool isVector(QualType QT, QualType ElementType) { 8764 if (const VectorType *VT = QT->getAs<VectorType>()) 8765 return VT->getElementType().getCanonicalType() == ElementType; 8766 return false; 8767 } 8768 8769 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8770 /// has code to accommodate several GCC extensions when type checking 8771 /// pointers. Here are some objectionable examples that GCC considers warnings: 8772 /// 8773 /// int a, *pint; 8774 /// short *pshort; 8775 /// struct foo *pfoo; 8776 /// 8777 /// pint = pshort; // warning: assignment from incompatible pointer type 8778 /// a = pint; // warning: assignment makes integer from pointer without a cast 8779 /// pint = a; // warning: assignment makes pointer from integer without a cast 8780 /// pint = pfoo; // warning: assignment from incompatible pointer type 8781 /// 8782 /// As a result, the code for dealing with pointers is more complex than the 8783 /// C99 spec dictates. 8784 /// 8785 /// Sets 'Kind' for any result kind except Incompatible. 8786 Sema::AssignConvertType 8787 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8788 CastKind &Kind, bool ConvertRHS) { 8789 QualType RHSType = RHS.get()->getType(); 8790 QualType OrigLHSType = LHSType; 8791 8792 // Get canonical types. We're not formatting these types, just comparing 8793 // them. 8794 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8795 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8796 8797 // Common case: no conversion required. 8798 if (LHSType == RHSType) { 8799 Kind = CK_NoOp; 8800 return Compatible; 8801 } 8802 8803 // If we have an atomic type, try a non-atomic assignment, then just add an 8804 // atomic qualification step. 8805 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8806 Sema::AssignConvertType result = 8807 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8808 if (result != Compatible) 8809 return result; 8810 if (Kind != CK_NoOp && ConvertRHS) 8811 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8812 Kind = CK_NonAtomicToAtomic; 8813 return Compatible; 8814 } 8815 8816 // If the left-hand side is a reference type, then we are in a 8817 // (rare!) case where we've allowed the use of references in C, 8818 // e.g., as a parameter type in a built-in function. In this case, 8819 // just make sure that the type referenced is compatible with the 8820 // right-hand side type. The caller is responsible for adjusting 8821 // LHSType so that the resulting expression does not have reference 8822 // type. 8823 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8824 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8825 Kind = CK_LValueBitCast; 8826 return Compatible; 8827 } 8828 return Incompatible; 8829 } 8830 8831 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8832 // to the same ExtVector type. 8833 if (LHSType->isExtVectorType()) { 8834 if (RHSType->isExtVectorType()) 8835 return Incompatible; 8836 if (RHSType->isArithmeticType()) { 8837 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8838 if (ConvertRHS) 8839 RHS = prepareVectorSplat(LHSType, RHS.get()); 8840 Kind = CK_VectorSplat; 8841 return Compatible; 8842 } 8843 } 8844 8845 // Conversions to or from vector type. 8846 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8847 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8848 // Allow assignments of an AltiVec vector type to an equivalent GCC 8849 // vector type and vice versa 8850 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8851 Kind = CK_BitCast; 8852 return Compatible; 8853 } 8854 8855 // If we are allowing lax vector conversions, and LHS and RHS are both 8856 // vectors, the total size only needs to be the same. This is a bitcast; 8857 // no bits are changed but the result type is different. 8858 if (isLaxVectorConversion(RHSType, LHSType)) { 8859 Kind = CK_BitCast; 8860 return IncompatibleVectors; 8861 } 8862 } 8863 8864 // When the RHS comes from another lax conversion (e.g. binops between 8865 // scalars and vectors) the result is canonicalized as a vector. When the 8866 // LHS is also a vector, the lax is allowed by the condition above. Handle 8867 // the case where LHS is a scalar. 8868 if (LHSType->isScalarType()) { 8869 const VectorType *VecType = RHSType->getAs<VectorType>(); 8870 if (VecType && VecType->getNumElements() == 1 && 8871 isLaxVectorConversion(RHSType, LHSType)) { 8872 ExprResult *VecExpr = &RHS; 8873 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8874 Kind = CK_BitCast; 8875 return Compatible; 8876 } 8877 } 8878 8879 return Incompatible; 8880 } 8881 8882 // Diagnose attempts to convert between __float128 and long double where 8883 // such conversions currently can't be handled. 8884 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8885 return Incompatible; 8886 8887 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8888 // discards the imaginary part. 8889 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8890 !LHSType->getAs<ComplexType>()) 8891 return Incompatible; 8892 8893 // Arithmetic conversions. 8894 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8895 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8896 if (ConvertRHS) 8897 Kind = PrepareScalarCast(RHS, LHSType); 8898 return Compatible; 8899 } 8900 8901 // Conversions to normal pointers. 8902 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8903 // U* -> T* 8904 if (isa<PointerType>(RHSType)) { 8905 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8906 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8907 if (AddrSpaceL != AddrSpaceR) 8908 Kind = CK_AddressSpaceConversion; 8909 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8910 Kind = CK_NoOp; 8911 else 8912 Kind = CK_BitCast; 8913 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8914 } 8915 8916 // int -> T* 8917 if (RHSType->isIntegerType()) { 8918 Kind = CK_IntegralToPointer; // FIXME: null? 8919 return IntToPointer; 8920 } 8921 8922 // C pointers are not compatible with ObjC object pointers, 8923 // with two exceptions: 8924 if (isa<ObjCObjectPointerType>(RHSType)) { 8925 // - conversions to void* 8926 if (LHSPointer->getPointeeType()->isVoidType()) { 8927 Kind = CK_BitCast; 8928 return Compatible; 8929 } 8930 8931 // - conversions from 'Class' to the redefinition type 8932 if (RHSType->isObjCClassType() && 8933 Context.hasSameType(LHSType, 8934 Context.getObjCClassRedefinitionType())) { 8935 Kind = CK_BitCast; 8936 return Compatible; 8937 } 8938 8939 Kind = CK_BitCast; 8940 return IncompatiblePointer; 8941 } 8942 8943 // U^ -> void* 8944 if (RHSType->getAs<BlockPointerType>()) { 8945 if (LHSPointer->getPointeeType()->isVoidType()) { 8946 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8947 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8948 ->getPointeeType() 8949 .getAddressSpace(); 8950 Kind = 8951 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8952 return Compatible; 8953 } 8954 } 8955 8956 return Incompatible; 8957 } 8958 8959 // Conversions to block pointers. 8960 if (isa<BlockPointerType>(LHSType)) { 8961 // U^ -> T^ 8962 if (RHSType->isBlockPointerType()) { 8963 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8964 ->getPointeeType() 8965 .getAddressSpace(); 8966 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8967 ->getPointeeType() 8968 .getAddressSpace(); 8969 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8970 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8971 } 8972 8973 // int or null -> T^ 8974 if (RHSType->isIntegerType()) { 8975 Kind = CK_IntegralToPointer; // FIXME: null 8976 return IntToBlockPointer; 8977 } 8978 8979 // id -> T^ 8980 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8981 Kind = CK_AnyPointerToBlockPointerCast; 8982 return Compatible; 8983 } 8984 8985 // void* -> T^ 8986 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8987 if (RHSPT->getPointeeType()->isVoidType()) { 8988 Kind = CK_AnyPointerToBlockPointerCast; 8989 return Compatible; 8990 } 8991 8992 return Incompatible; 8993 } 8994 8995 // Conversions to Objective-C pointers. 8996 if (isa<ObjCObjectPointerType>(LHSType)) { 8997 // A* -> B* 8998 if (RHSType->isObjCObjectPointerType()) { 8999 Kind = CK_BitCast; 9000 Sema::AssignConvertType result = 9001 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9002 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9003 result == Compatible && 9004 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9005 result = IncompatibleObjCWeakRef; 9006 return result; 9007 } 9008 9009 // int or null -> A* 9010 if (RHSType->isIntegerType()) { 9011 Kind = CK_IntegralToPointer; // FIXME: null 9012 return IntToPointer; 9013 } 9014 9015 // In general, C pointers are not compatible with ObjC object pointers, 9016 // with two exceptions: 9017 if (isa<PointerType>(RHSType)) { 9018 Kind = CK_CPointerToObjCPointerCast; 9019 9020 // - conversions from 'void*' 9021 if (RHSType->isVoidPointerType()) { 9022 return Compatible; 9023 } 9024 9025 // - conversions to 'Class' from its redefinition type 9026 if (LHSType->isObjCClassType() && 9027 Context.hasSameType(RHSType, 9028 Context.getObjCClassRedefinitionType())) { 9029 return Compatible; 9030 } 9031 9032 return IncompatiblePointer; 9033 } 9034 9035 // Only under strict condition T^ is compatible with an Objective-C pointer. 9036 if (RHSType->isBlockPointerType() && 9037 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9038 if (ConvertRHS) 9039 maybeExtendBlockObject(RHS); 9040 Kind = CK_BlockPointerToObjCPointerCast; 9041 return Compatible; 9042 } 9043 9044 return Incompatible; 9045 } 9046 9047 // Conversions from pointers that are not covered by the above. 9048 if (isa<PointerType>(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 // Conversions from Objective-C pointers that are not covered by the above. 9065 if (isa<ObjCObjectPointerType>(RHSType)) { 9066 // T* -> _Bool 9067 if (LHSType == Context.BoolTy) { 9068 Kind = CK_PointerToBoolean; 9069 return Compatible; 9070 } 9071 9072 // T* -> int 9073 if (LHSType->isIntegerType()) { 9074 Kind = CK_PointerToIntegral; 9075 return PointerToInt; 9076 } 9077 9078 return Incompatible; 9079 } 9080 9081 // struct A -> struct B 9082 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9083 if (Context.typesAreCompatible(LHSType, RHSType)) { 9084 Kind = CK_NoOp; 9085 return Compatible; 9086 } 9087 } 9088 9089 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9090 Kind = CK_IntToOCLSampler; 9091 return Compatible; 9092 } 9093 9094 return Incompatible; 9095 } 9096 9097 /// Constructs a transparent union from an expression that is 9098 /// used to initialize the transparent union. 9099 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9100 ExprResult &EResult, QualType UnionType, 9101 FieldDecl *Field) { 9102 // Build an initializer list that designates the appropriate member 9103 // of the transparent union. 9104 Expr *E = EResult.get(); 9105 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9106 E, SourceLocation()); 9107 Initializer->setType(UnionType); 9108 Initializer->setInitializedFieldInUnion(Field); 9109 9110 // Build a compound literal constructing a value of the transparent 9111 // union type from this initializer list. 9112 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9113 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9114 VK_RValue, Initializer, false); 9115 } 9116 9117 Sema::AssignConvertType 9118 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9119 ExprResult &RHS) { 9120 QualType RHSType = RHS.get()->getType(); 9121 9122 // If the ArgType is a Union type, we want to handle a potential 9123 // transparent_union GCC extension. 9124 const RecordType *UT = ArgType->getAsUnionType(); 9125 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9126 return Incompatible; 9127 9128 // The field to initialize within the transparent union. 9129 RecordDecl *UD = UT->getDecl(); 9130 FieldDecl *InitField = nullptr; 9131 // It's compatible if the expression matches any of the fields. 9132 for (auto *it : UD->fields()) { 9133 if (it->getType()->isPointerType()) { 9134 // If the transparent union contains a pointer type, we allow: 9135 // 1) void pointer 9136 // 2) null pointer constant 9137 if (RHSType->isPointerType()) 9138 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9139 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9140 InitField = it; 9141 break; 9142 } 9143 9144 if (RHS.get()->isNullPointerConstant(Context, 9145 Expr::NPC_ValueDependentIsNull)) { 9146 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9147 CK_NullToPointer); 9148 InitField = it; 9149 break; 9150 } 9151 } 9152 9153 CastKind Kind; 9154 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9155 == Compatible) { 9156 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9157 InitField = it; 9158 break; 9159 } 9160 } 9161 9162 if (!InitField) 9163 return Incompatible; 9164 9165 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9166 return Compatible; 9167 } 9168 9169 Sema::AssignConvertType 9170 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9171 bool Diagnose, 9172 bool DiagnoseCFAudited, 9173 bool ConvertRHS) { 9174 // We need to be able to tell the caller whether we diagnosed a problem, if 9175 // they ask us to issue diagnostics. 9176 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9177 9178 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9179 // we can't avoid *all* modifications at the moment, so we need some somewhere 9180 // to put the updated value. 9181 ExprResult LocalRHS = CallerRHS; 9182 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9183 9184 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9185 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9186 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9187 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9188 Diag(RHS.get()->getExprLoc(), 9189 diag::warn_noderef_to_dereferenceable_pointer) 9190 << RHS.get()->getSourceRange(); 9191 } 9192 } 9193 } 9194 9195 if (getLangOpts().CPlusPlus) { 9196 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9197 // C++ 5.17p3: If the left operand is not of class type, the 9198 // expression is implicitly converted (C++ 4) to the 9199 // cv-unqualified type of the left operand. 9200 QualType RHSType = RHS.get()->getType(); 9201 if (Diagnose) { 9202 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9203 AA_Assigning); 9204 } else { 9205 ImplicitConversionSequence ICS = 9206 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9207 /*SuppressUserConversions=*/false, 9208 AllowedExplicit::None, 9209 /*InOverloadResolution=*/false, 9210 /*CStyle=*/false, 9211 /*AllowObjCWritebackConversion=*/false); 9212 if (ICS.isFailure()) 9213 return Incompatible; 9214 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9215 ICS, AA_Assigning); 9216 } 9217 if (RHS.isInvalid()) 9218 return Incompatible; 9219 Sema::AssignConvertType result = Compatible; 9220 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9221 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9222 result = IncompatibleObjCWeakRef; 9223 return result; 9224 } 9225 9226 // FIXME: Currently, we fall through and treat C++ classes like C 9227 // structures. 9228 // FIXME: We also fall through for atomics; not sure what should 9229 // happen there, though. 9230 } else if (RHS.get()->getType() == Context.OverloadTy) { 9231 // As a set of extensions to C, we support overloading on functions. These 9232 // functions need to be resolved here. 9233 DeclAccessPair DAP; 9234 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9235 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9236 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9237 else 9238 return Incompatible; 9239 } 9240 9241 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9242 // a null pointer constant. 9243 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9244 LHSType->isBlockPointerType()) && 9245 RHS.get()->isNullPointerConstant(Context, 9246 Expr::NPC_ValueDependentIsNull)) { 9247 if (Diagnose || ConvertRHS) { 9248 CastKind Kind; 9249 CXXCastPath Path; 9250 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9251 /*IgnoreBaseAccess=*/false, Diagnose); 9252 if (ConvertRHS) 9253 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9254 } 9255 return Compatible; 9256 } 9257 9258 // OpenCL queue_t type assignment. 9259 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9260 Context, Expr::NPC_ValueDependentIsNull)) { 9261 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9262 return Compatible; 9263 } 9264 9265 // This check seems unnatural, however it is necessary to ensure the proper 9266 // conversion of functions/arrays. If the conversion were done for all 9267 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9268 // expressions that suppress this implicit conversion (&, sizeof). 9269 // 9270 // Suppress this for references: C++ 8.5.3p5. 9271 if (!LHSType->isReferenceType()) { 9272 // FIXME: We potentially allocate here even if ConvertRHS is false. 9273 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9274 if (RHS.isInvalid()) 9275 return Incompatible; 9276 } 9277 CastKind Kind; 9278 Sema::AssignConvertType result = 9279 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9280 9281 // C99 6.5.16.1p2: The value of the right operand is converted to the 9282 // type of the assignment expression. 9283 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9284 // so that we can use references in built-in functions even in C. 9285 // The getNonReferenceType() call makes sure that the resulting expression 9286 // does not have reference type. 9287 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9288 QualType Ty = LHSType.getNonLValueExprType(Context); 9289 Expr *E = RHS.get(); 9290 9291 // Check for various Objective-C errors. If we are not reporting 9292 // diagnostics and just checking for errors, e.g., during overload 9293 // resolution, return Incompatible to indicate the failure. 9294 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9295 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9296 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9297 if (!Diagnose) 9298 return Incompatible; 9299 } 9300 if (getLangOpts().ObjC && 9301 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9302 E->getType(), E, Diagnose) || 9303 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9304 if (!Diagnose) 9305 return Incompatible; 9306 // Replace the expression with a corrected version and continue so we 9307 // can find further errors. 9308 RHS = E; 9309 return Compatible; 9310 } 9311 9312 if (ConvertRHS) 9313 RHS = ImpCastExprToType(E, Ty, Kind); 9314 } 9315 9316 return result; 9317 } 9318 9319 namespace { 9320 /// The original operand to an operator, prior to the application of the usual 9321 /// arithmetic conversions and converting the arguments of a builtin operator 9322 /// candidate. 9323 struct OriginalOperand { 9324 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9325 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9326 Op = MTE->getSubExpr(); 9327 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9328 Op = BTE->getSubExpr(); 9329 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9330 Orig = ICE->getSubExprAsWritten(); 9331 Conversion = ICE->getConversionFunction(); 9332 } 9333 } 9334 9335 QualType getType() const { return Orig->getType(); } 9336 9337 Expr *Orig; 9338 NamedDecl *Conversion; 9339 }; 9340 } 9341 9342 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9343 ExprResult &RHS) { 9344 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9345 9346 Diag(Loc, diag::err_typecheck_invalid_operands) 9347 << OrigLHS.getType() << OrigRHS.getType() 9348 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9349 9350 // If a user-defined conversion was applied to either of the operands prior 9351 // to applying the built-in operator rules, tell the user about it. 9352 if (OrigLHS.Conversion) { 9353 Diag(OrigLHS.Conversion->getLocation(), 9354 diag::note_typecheck_invalid_operands_converted) 9355 << 0 << LHS.get()->getType(); 9356 } 9357 if (OrigRHS.Conversion) { 9358 Diag(OrigRHS.Conversion->getLocation(), 9359 diag::note_typecheck_invalid_operands_converted) 9360 << 1 << RHS.get()->getType(); 9361 } 9362 9363 return QualType(); 9364 } 9365 9366 // Diagnose cases where a scalar was implicitly converted to a vector and 9367 // diagnose the underlying types. Otherwise, diagnose the error 9368 // as invalid vector logical operands for non-C++ cases. 9369 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9370 ExprResult &RHS) { 9371 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9372 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9373 9374 bool LHSNatVec = LHSType->isVectorType(); 9375 bool RHSNatVec = RHSType->isVectorType(); 9376 9377 if (!(LHSNatVec && RHSNatVec)) { 9378 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9379 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9380 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9381 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9382 << Vector->getSourceRange(); 9383 return QualType(); 9384 } 9385 9386 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9387 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9388 << RHS.get()->getSourceRange(); 9389 9390 return QualType(); 9391 } 9392 9393 /// Try to convert a value of non-vector type to a vector type by converting 9394 /// the type to the element type of the vector and then performing a splat. 9395 /// If the language is OpenCL, we only use conversions that promote scalar 9396 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9397 /// for float->int. 9398 /// 9399 /// OpenCL V2.0 6.2.6.p2: 9400 /// An error shall occur if any scalar operand type has greater rank 9401 /// than the type of the vector element. 9402 /// 9403 /// \param scalar - if non-null, actually perform the conversions 9404 /// \return true if the operation fails (but without diagnosing the failure) 9405 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9406 QualType scalarTy, 9407 QualType vectorEltTy, 9408 QualType vectorTy, 9409 unsigned &DiagID) { 9410 // The conversion to apply to the scalar before splatting it, 9411 // if necessary. 9412 CastKind scalarCast = CK_NoOp; 9413 9414 if (vectorEltTy->isIntegralType(S.Context)) { 9415 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9416 (scalarTy->isIntegerType() && 9417 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9418 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9419 return true; 9420 } 9421 if (!scalarTy->isIntegralType(S.Context)) 9422 return true; 9423 scalarCast = CK_IntegralCast; 9424 } else if (vectorEltTy->isRealFloatingType()) { 9425 if (scalarTy->isRealFloatingType()) { 9426 if (S.getLangOpts().OpenCL && 9427 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9428 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9429 return true; 9430 } 9431 scalarCast = CK_FloatingCast; 9432 } 9433 else if (scalarTy->isIntegralType(S.Context)) 9434 scalarCast = CK_IntegralToFloating; 9435 else 9436 return true; 9437 } else { 9438 return true; 9439 } 9440 9441 // Adjust scalar if desired. 9442 if (scalar) { 9443 if (scalarCast != CK_NoOp) 9444 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9445 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9446 } 9447 return false; 9448 } 9449 9450 /// Convert vector E to a vector with the same number of elements but different 9451 /// element type. 9452 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9453 const auto *VecTy = E->getType()->getAs<VectorType>(); 9454 assert(VecTy && "Expression E must be a vector"); 9455 QualType NewVecTy = S.Context.getVectorType(ElementType, 9456 VecTy->getNumElements(), 9457 VecTy->getVectorKind()); 9458 9459 // Look through the implicit cast. Return the subexpression if its type is 9460 // NewVecTy. 9461 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9462 if (ICE->getSubExpr()->getType() == NewVecTy) 9463 return ICE->getSubExpr(); 9464 9465 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9466 return S.ImpCastExprToType(E, NewVecTy, Cast); 9467 } 9468 9469 /// Test if a (constant) integer Int can be casted to another integer type 9470 /// IntTy without losing precision. 9471 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9472 QualType OtherIntTy) { 9473 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9474 9475 // Reject cases where the value of the Int is unknown as that would 9476 // possibly cause truncation, but accept cases where the scalar can be 9477 // demoted without loss of precision. 9478 Expr::EvalResult EVResult; 9479 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9480 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9481 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9482 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9483 9484 if (CstInt) { 9485 // If the scalar is constant and is of a higher order and has more active 9486 // bits that the vector element type, reject it. 9487 llvm::APSInt Result = EVResult.Val.getInt(); 9488 unsigned NumBits = IntSigned 9489 ? (Result.isNegative() ? Result.getMinSignedBits() 9490 : Result.getActiveBits()) 9491 : Result.getActiveBits(); 9492 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9493 return true; 9494 9495 // If the signedness of the scalar type and the vector element type 9496 // differs and the number of bits is greater than that of the vector 9497 // element reject it. 9498 return (IntSigned != OtherIntSigned && 9499 NumBits > S.Context.getIntWidth(OtherIntTy)); 9500 } 9501 9502 // Reject cases where the value of the scalar is not constant and it's 9503 // order is greater than that of the vector element type. 9504 return (Order < 0); 9505 } 9506 9507 /// Test if a (constant) integer Int can be casted to floating point type 9508 /// FloatTy without losing precision. 9509 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9510 QualType FloatTy) { 9511 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9512 9513 // Determine if the integer constant can be expressed as a floating point 9514 // number of the appropriate type. 9515 Expr::EvalResult EVResult; 9516 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9517 9518 uint64_t Bits = 0; 9519 if (CstInt) { 9520 // Reject constants that would be truncated if they were converted to 9521 // the floating point type. Test by simple to/from conversion. 9522 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9523 // could be avoided if there was a convertFromAPInt method 9524 // which could signal back if implicit truncation occurred. 9525 llvm::APSInt Result = EVResult.Val.getInt(); 9526 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9527 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9528 llvm::APFloat::rmTowardZero); 9529 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9530 !IntTy->hasSignedIntegerRepresentation()); 9531 bool Ignored = false; 9532 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9533 &Ignored); 9534 if (Result != ConvertBack) 9535 return true; 9536 } else { 9537 // Reject types that cannot be fully encoded into the mantissa of 9538 // the float. 9539 Bits = S.Context.getTypeSize(IntTy); 9540 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9541 S.Context.getFloatTypeSemantics(FloatTy)); 9542 if (Bits > FloatPrec) 9543 return true; 9544 } 9545 9546 return false; 9547 } 9548 9549 /// Attempt to convert and splat Scalar into a vector whose types matches 9550 /// Vector following GCC conversion rules. The rule is that implicit 9551 /// conversion can occur when Scalar can be casted to match Vector's element 9552 /// type without causing truncation of Scalar. 9553 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9554 ExprResult *Vector) { 9555 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9556 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9557 const VectorType *VT = VectorTy->getAs<VectorType>(); 9558 9559 assert(!isa<ExtVectorType>(VT) && 9560 "ExtVectorTypes should not be handled here!"); 9561 9562 QualType VectorEltTy = VT->getElementType(); 9563 9564 // Reject cases where the vector element type or the scalar element type are 9565 // not integral or floating point types. 9566 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9567 return true; 9568 9569 // The conversion to apply to the scalar before splatting it, 9570 // if necessary. 9571 CastKind ScalarCast = CK_NoOp; 9572 9573 // Accept cases where the vector elements are integers and the scalar is 9574 // an integer. 9575 // FIXME: Notionally if the scalar was a floating point value with a precise 9576 // integral representation, we could cast it to an appropriate integer 9577 // type and then perform the rest of the checks here. GCC will perform 9578 // this conversion in some cases as determined by the input language. 9579 // We should accept it on a language independent basis. 9580 if (VectorEltTy->isIntegralType(S.Context) && 9581 ScalarTy->isIntegralType(S.Context) && 9582 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9583 9584 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9585 return true; 9586 9587 ScalarCast = CK_IntegralCast; 9588 } else if (VectorEltTy->isIntegralType(S.Context) && 9589 ScalarTy->isRealFloatingType()) { 9590 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9591 ScalarCast = CK_FloatingToIntegral; 9592 else 9593 return true; 9594 } else if (VectorEltTy->isRealFloatingType()) { 9595 if (ScalarTy->isRealFloatingType()) { 9596 9597 // Reject cases where the scalar type is not a constant and has a higher 9598 // Order than the vector element type. 9599 llvm::APFloat Result(0.0); 9600 9601 // Determine whether this is a constant scalar. In the event that the 9602 // value is dependent (and thus cannot be evaluated by the constant 9603 // evaluator), skip the evaluation. This will then diagnose once the 9604 // expression is instantiated. 9605 bool CstScalar = Scalar->get()->isValueDependent() || 9606 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9607 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9608 if (!CstScalar && Order < 0) 9609 return true; 9610 9611 // If the scalar cannot be safely casted to the vector element type, 9612 // reject it. 9613 if (CstScalar) { 9614 bool Truncated = false; 9615 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9616 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9617 if (Truncated) 9618 return true; 9619 } 9620 9621 ScalarCast = CK_FloatingCast; 9622 } else if (ScalarTy->isIntegralType(S.Context)) { 9623 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9624 return true; 9625 9626 ScalarCast = CK_IntegralToFloating; 9627 } else 9628 return true; 9629 } else if (ScalarTy->isEnumeralType()) 9630 return true; 9631 9632 // Adjust scalar if desired. 9633 if (Scalar) { 9634 if (ScalarCast != CK_NoOp) 9635 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9636 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9637 } 9638 return false; 9639 } 9640 9641 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9642 SourceLocation Loc, bool IsCompAssign, 9643 bool AllowBothBool, 9644 bool AllowBoolConversions) { 9645 if (!IsCompAssign) { 9646 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9647 if (LHS.isInvalid()) 9648 return QualType(); 9649 } 9650 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9651 if (RHS.isInvalid()) 9652 return QualType(); 9653 9654 // For conversion purposes, we ignore any qualifiers. 9655 // For example, "const float" and "float" are equivalent. 9656 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9657 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9658 9659 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9660 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9661 assert(LHSVecType || RHSVecType); 9662 9663 // AltiVec-style "vector bool op vector bool" combinations are allowed 9664 // for some operators but not others. 9665 if (!AllowBothBool && 9666 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9667 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9668 return InvalidOperands(Loc, LHS, RHS); 9669 9670 // If the vector types are identical, return. 9671 if (Context.hasSameType(LHSType, RHSType)) 9672 return LHSType; 9673 9674 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9675 if (LHSVecType && RHSVecType && 9676 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9677 if (isa<ExtVectorType>(LHSVecType)) { 9678 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9679 return LHSType; 9680 } 9681 9682 if (!IsCompAssign) 9683 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9684 return RHSType; 9685 } 9686 9687 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9688 // can be mixed, with the result being the non-bool type. The non-bool 9689 // operand must have integer element type. 9690 if (AllowBoolConversions && LHSVecType && RHSVecType && 9691 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9692 (Context.getTypeSize(LHSVecType->getElementType()) == 9693 Context.getTypeSize(RHSVecType->getElementType()))) { 9694 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9695 LHSVecType->getElementType()->isIntegerType() && 9696 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9697 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9698 return LHSType; 9699 } 9700 if (!IsCompAssign && 9701 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9702 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9703 RHSVecType->getElementType()->isIntegerType()) { 9704 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9705 return RHSType; 9706 } 9707 } 9708 9709 // If there's a vector type and a scalar, try to convert the scalar to 9710 // the vector element type and splat. 9711 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9712 if (!RHSVecType) { 9713 if (isa<ExtVectorType>(LHSVecType)) { 9714 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9715 LHSVecType->getElementType(), LHSType, 9716 DiagID)) 9717 return LHSType; 9718 } else { 9719 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9720 return LHSType; 9721 } 9722 } 9723 if (!LHSVecType) { 9724 if (isa<ExtVectorType>(RHSVecType)) { 9725 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9726 LHSType, RHSVecType->getElementType(), 9727 RHSType, DiagID)) 9728 return RHSType; 9729 } else { 9730 if (LHS.get()->getValueKind() == VK_LValue || 9731 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9732 return RHSType; 9733 } 9734 } 9735 9736 // FIXME: The code below also handles conversion between vectors and 9737 // non-scalars, we should break this down into fine grained specific checks 9738 // and emit proper diagnostics. 9739 QualType VecType = LHSVecType ? LHSType : RHSType; 9740 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9741 QualType OtherType = LHSVecType ? RHSType : LHSType; 9742 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9743 if (isLaxVectorConversion(OtherType, VecType)) { 9744 // If we're allowing lax vector conversions, only the total (data) size 9745 // needs to be the same. For non compound assignment, if one of the types is 9746 // scalar, the result is always the vector type. 9747 if (!IsCompAssign) { 9748 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9749 return VecType; 9750 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9751 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9752 // type. Note that this is already done by non-compound assignments in 9753 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9754 // <1 x T> -> T. The result is also a vector type. 9755 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9756 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9757 ExprResult *RHSExpr = &RHS; 9758 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9759 return VecType; 9760 } 9761 } 9762 9763 // Okay, the expression is invalid. 9764 9765 // If there's a non-vector, non-real operand, diagnose that. 9766 if ((!RHSVecType && !RHSType->isRealType()) || 9767 (!LHSVecType && !LHSType->isRealType())) { 9768 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9769 << LHSType << RHSType 9770 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9771 return QualType(); 9772 } 9773 9774 // OpenCL V1.1 6.2.6.p1: 9775 // If the operands are of more than one vector type, then an error shall 9776 // occur. Implicit conversions between vector types are not permitted, per 9777 // section 6.2.1. 9778 if (getLangOpts().OpenCL && 9779 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9780 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9781 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9782 << RHSType; 9783 return QualType(); 9784 } 9785 9786 9787 // If there is a vector type that is not a ExtVector and a scalar, we reach 9788 // this point if scalar could not be converted to the vector's element type 9789 // without truncation. 9790 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9791 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9792 QualType Scalar = LHSVecType ? RHSType : LHSType; 9793 QualType Vector = LHSVecType ? LHSType : RHSType; 9794 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9795 Diag(Loc, 9796 diag::err_typecheck_vector_not_convertable_implict_truncation) 9797 << ScalarOrVector << Scalar << Vector; 9798 9799 return QualType(); 9800 } 9801 9802 // Otherwise, use the generic diagnostic. 9803 Diag(Loc, DiagID) 9804 << LHSType << RHSType 9805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9806 return QualType(); 9807 } 9808 9809 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9810 // expression. These are mainly cases where the null pointer is used as an 9811 // integer instead of a pointer. 9812 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9813 SourceLocation Loc, bool IsCompare) { 9814 // The canonical way to check for a GNU null is with isNullPointerConstant, 9815 // but we use a bit of a hack here for speed; this is a relatively 9816 // hot path, and isNullPointerConstant is slow. 9817 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9818 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9819 9820 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9821 9822 // Avoid analyzing cases where the result will either be invalid (and 9823 // diagnosed as such) or entirely valid and not something to warn about. 9824 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9825 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9826 return; 9827 9828 // Comparison operations would not make sense with a null pointer no matter 9829 // what the other expression is. 9830 if (!IsCompare) { 9831 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9832 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9833 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9834 return; 9835 } 9836 9837 // The rest of the operations only make sense with a null pointer 9838 // if the other expression is a pointer. 9839 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9840 NonNullType->canDecayToPointerType()) 9841 return; 9842 9843 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9844 << LHSNull /* LHS is NULL */ << NonNullType 9845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9846 } 9847 9848 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9849 SourceLocation Loc) { 9850 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9851 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9852 if (!LUE || !RUE) 9853 return; 9854 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9855 RUE->getKind() != UETT_SizeOf) 9856 return; 9857 9858 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9859 QualType LHSTy = LHSArg->getType(); 9860 QualType RHSTy; 9861 9862 if (RUE->isArgumentType()) 9863 RHSTy = RUE->getArgumentType(); 9864 else 9865 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9866 9867 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9868 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9869 return; 9870 9871 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9872 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9873 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9874 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9875 << LHSArgDecl; 9876 } 9877 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9878 QualType ArrayElemTy = ArrayTy->getElementType(); 9879 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9880 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9881 ArrayElemTy->isCharType() || 9882 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9883 return; 9884 S.Diag(Loc, diag::warn_division_sizeof_array) 9885 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9886 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9887 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9888 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9889 << LHSArgDecl; 9890 } 9891 9892 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9893 } 9894 } 9895 9896 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9897 ExprResult &RHS, 9898 SourceLocation Loc, bool IsDiv) { 9899 // Check for division/remainder by zero. 9900 Expr::EvalResult RHSValue; 9901 if (!RHS.get()->isValueDependent() && 9902 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9903 RHSValue.Val.getInt() == 0) 9904 S.DiagRuntimeBehavior(Loc, RHS.get(), 9905 S.PDiag(diag::warn_remainder_division_by_zero) 9906 << IsDiv << RHS.get()->getSourceRange()); 9907 } 9908 9909 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9910 SourceLocation Loc, 9911 bool IsCompAssign, bool IsDiv) { 9912 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9913 9914 if (LHS.get()->getType()->isVectorType() || 9915 RHS.get()->getType()->isVectorType()) 9916 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9917 /*AllowBothBool*/getLangOpts().AltiVec, 9918 /*AllowBoolConversions*/false); 9919 9920 QualType compType = UsualArithmeticConversions( 9921 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9922 if (LHS.isInvalid() || RHS.isInvalid()) 9923 return QualType(); 9924 9925 9926 if (compType.isNull() || !compType->isArithmeticType()) 9927 return InvalidOperands(Loc, LHS, RHS); 9928 if (IsDiv) { 9929 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9930 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9931 } 9932 return compType; 9933 } 9934 9935 QualType Sema::CheckRemainderOperands( 9936 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9937 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9938 9939 if (LHS.get()->getType()->isVectorType() || 9940 RHS.get()->getType()->isVectorType()) { 9941 if (LHS.get()->getType()->hasIntegerRepresentation() && 9942 RHS.get()->getType()->hasIntegerRepresentation()) 9943 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9944 /*AllowBothBool*/getLangOpts().AltiVec, 9945 /*AllowBoolConversions*/false); 9946 return InvalidOperands(Loc, LHS, RHS); 9947 } 9948 9949 QualType compType = UsualArithmeticConversions( 9950 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9951 if (LHS.isInvalid() || RHS.isInvalid()) 9952 return QualType(); 9953 9954 if (compType.isNull() || !compType->isIntegerType()) 9955 return InvalidOperands(Loc, LHS, RHS); 9956 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9957 return compType; 9958 } 9959 9960 /// Diagnose invalid arithmetic on two void pointers. 9961 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9962 Expr *LHSExpr, Expr *RHSExpr) { 9963 S.Diag(Loc, S.getLangOpts().CPlusPlus 9964 ? diag::err_typecheck_pointer_arith_void_type 9965 : diag::ext_gnu_void_ptr) 9966 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9967 << RHSExpr->getSourceRange(); 9968 } 9969 9970 /// Diagnose invalid arithmetic on a void pointer. 9971 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9972 Expr *Pointer) { 9973 S.Diag(Loc, S.getLangOpts().CPlusPlus 9974 ? diag::err_typecheck_pointer_arith_void_type 9975 : diag::ext_gnu_void_ptr) 9976 << 0 /* one pointer */ << Pointer->getSourceRange(); 9977 } 9978 9979 /// Diagnose invalid arithmetic on a null pointer. 9980 /// 9981 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9982 /// idiom, which we recognize as a GNU extension. 9983 /// 9984 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9985 Expr *Pointer, bool IsGNUIdiom) { 9986 if (IsGNUIdiom) 9987 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9988 << Pointer->getSourceRange(); 9989 else 9990 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9991 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9992 } 9993 9994 /// Diagnose invalid arithmetic on two function pointers. 9995 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9996 Expr *LHS, Expr *RHS) { 9997 assert(LHS->getType()->isAnyPointerType()); 9998 assert(RHS->getType()->isAnyPointerType()); 9999 S.Diag(Loc, S.getLangOpts().CPlusPlus 10000 ? diag::err_typecheck_pointer_arith_function_type 10001 : diag::ext_gnu_ptr_func_arith) 10002 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10003 // We only show the second type if it differs from the first. 10004 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10005 RHS->getType()) 10006 << RHS->getType()->getPointeeType() 10007 << LHS->getSourceRange() << RHS->getSourceRange(); 10008 } 10009 10010 /// Diagnose invalid arithmetic on a function pointer. 10011 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10012 Expr *Pointer) { 10013 assert(Pointer->getType()->isAnyPointerType()); 10014 S.Diag(Loc, S.getLangOpts().CPlusPlus 10015 ? diag::err_typecheck_pointer_arith_function_type 10016 : diag::ext_gnu_ptr_func_arith) 10017 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10018 << 0 /* one pointer, so only one type */ 10019 << Pointer->getSourceRange(); 10020 } 10021 10022 /// Emit error if Operand is incomplete pointer type 10023 /// 10024 /// \returns True if pointer has incomplete type 10025 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10026 Expr *Operand) { 10027 QualType ResType = Operand->getType(); 10028 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10029 ResType = ResAtomicType->getValueType(); 10030 10031 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10032 QualType PointeeTy = ResType->getPointeeType(); 10033 return S.RequireCompleteSizedType( 10034 Loc, PointeeTy, 10035 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10036 Operand->getSourceRange()); 10037 } 10038 10039 /// Check the validity of an arithmetic pointer operand. 10040 /// 10041 /// If the operand has pointer type, this code will check for pointer types 10042 /// which are invalid in arithmetic operations. These will be diagnosed 10043 /// appropriately, including whether or not the use is supported as an 10044 /// extension. 10045 /// 10046 /// \returns True when the operand is valid to use (even if as an extension). 10047 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10048 Expr *Operand) { 10049 QualType ResType = Operand->getType(); 10050 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10051 ResType = ResAtomicType->getValueType(); 10052 10053 if (!ResType->isAnyPointerType()) return true; 10054 10055 QualType PointeeTy = ResType->getPointeeType(); 10056 if (PointeeTy->isVoidType()) { 10057 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10058 return !S.getLangOpts().CPlusPlus; 10059 } 10060 if (PointeeTy->isFunctionType()) { 10061 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10062 return !S.getLangOpts().CPlusPlus; 10063 } 10064 10065 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10066 10067 return true; 10068 } 10069 10070 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10071 /// operands. 10072 /// 10073 /// This routine will diagnose any invalid arithmetic on pointer operands much 10074 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10075 /// for emitting a single diagnostic even for operations where both LHS and RHS 10076 /// are (potentially problematic) pointers. 10077 /// 10078 /// \returns True when the operand is valid to use (even if as an extension). 10079 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10080 Expr *LHSExpr, Expr *RHSExpr) { 10081 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10082 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10083 if (!isLHSPointer && !isRHSPointer) return true; 10084 10085 QualType LHSPointeeTy, RHSPointeeTy; 10086 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10087 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10088 10089 // if both are pointers check if operation is valid wrt address spaces 10090 if (isLHSPointer && isRHSPointer) { 10091 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10092 S.Diag(Loc, 10093 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10094 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10095 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10096 return false; 10097 } 10098 } 10099 10100 // Check for arithmetic on pointers to incomplete types. 10101 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10102 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10103 if (isLHSVoidPtr || isRHSVoidPtr) { 10104 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10105 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10106 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10107 10108 return !S.getLangOpts().CPlusPlus; 10109 } 10110 10111 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10112 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10113 if (isLHSFuncPtr || isRHSFuncPtr) { 10114 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10115 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10116 RHSExpr); 10117 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10118 10119 return !S.getLangOpts().CPlusPlus; 10120 } 10121 10122 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10123 return false; 10124 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10125 return false; 10126 10127 return true; 10128 } 10129 10130 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10131 /// literal. 10132 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10133 Expr *LHSExpr, Expr *RHSExpr) { 10134 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10135 Expr* IndexExpr = RHSExpr; 10136 if (!StrExpr) { 10137 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10138 IndexExpr = LHSExpr; 10139 } 10140 10141 bool IsStringPlusInt = StrExpr && 10142 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10143 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10144 return; 10145 10146 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10147 Self.Diag(OpLoc, diag::warn_string_plus_int) 10148 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10149 10150 // Only print a fixit for "str" + int, not for int + "str". 10151 if (IndexExpr == RHSExpr) { 10152 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10153 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10154 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10155 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10156 << FixItHint::CreateInsertion(EndLoc, "]"); 10157 } else 10158 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10159 } 10160 10161 /// Emit a warning when adding a char literal to a string. 10162 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10163 Expr *LHSExpr, Expr *RHSExpr) { 10164 const Expr *StringRefExpr = LHSExpr; 10165 const CharacterLiteral *CharExpr = 10166 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10167 10168 if (!CharExpr) { 10169 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10170 StringRefExpr = RHSExpr; 10171 } 10172 10173 if (!CharExpr || !StringRefExpr) 10174 return; 10175 10176 const QualType StringType = StringRefExpr->getType(); 10177 10178 // Return if not a PointerType. 10179 if (!StringType->isAnyPointerType()) 10180 return; 10181 10182 // Return if not a CharacterType. 10183 if (!StringType->getPointeeType()->isAnyCharacterType()) 10184 return; 10185 10186 ASTContext &Ctx = Self.getASTContext(); 10187 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10188 10189 const QualType CharType = CharExpr->getType(); 10190 if (!CharType->isAnyCharacterType() && 10191 CharType->isIntegerType() && 10192 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10193 Self.Diag(OpLoc, diag::warn_string_plus_char) 10194 << DiagRange << Ctx.CharTy; 10195 } else { 10196 Self.Diag(OpLoc, diag::warn_string_plus_char) 10197 << DiagRange << CharExpr->getType(); 10198 } 10199 10200 // Only print a fixit for str + char, not for char + str. 10201 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10202 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10203 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10204 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10205 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10206 << FixItHint::CreateInsertion(EndLoc, "]"); 10207 } else { 10208 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10209 } 10210 } 10211 10212 /// Emit error when two pointers are incompatible. 10213 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10214 Expr *LHSExpr, Expr *RHSExpr) { 10215 assert(LHSExpr->getType()->isAnyPointerType()); 10216 assert(RHSExpr->getType()->isAnyPointerType()); 10217 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10218 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10219 << RHSExpr->getSourceRange(); 10220 } 10221 10222 // C99 6.5.6 10223 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10224 SourceLocation Loc, BinaryOperatorKind Opc, 10225 QualType* CompLHSTy) { 10226 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10227 10228 if (LHS.get()->getType()->isVectorType() || 10229 RHS.get()->getType()->isVectorType()) { 10230 QualType compType = CheckVectorOperands( 10231 LHS, RHS, Loc, CompLHSTy, 10232 /*AllowBothBool*/getLangOpts().AltiVec, 10233 /*AllowBoolConversions*/getLangOpts().ZVector); 10234 if (CompLHSTy) *CompLHSTy = compType; 10235 return compType; 10236 } 10237 10238 QualType compType = UsualArithmeticConversions( 10239 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10240 if (LHS.isInvalid() || RHS.isInvalid()) 10241 return QualType(); 10242 10243 // Diagnose "string literal" '+' int and string '+' "char literal". 10244 if (Opc == BO_Add) { 10245 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10246 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10247 } 10248 10249 // handle the common case first (both operands are arithmetic). 10250 if (!compType.isNull() && compType->isArithmeticType()) { 10251 if (CompLHSTy) *CompLHSTy = compType; 10252 return compType; 10253 } 10254 10255 // Type-checking. Ultimately the pointer's going to be in PExp; 10256 // note that we bias towards the LHS being the pointer. 10257 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10258 10259 bool isObjCPointer; 10260 if (PExp->getType()->isPointerType()) { 10261 isObjCPointer = false; 10262 } else if (PExp->getType()->isObjCObjectPointerType()) { 10263 isObjCPointer = true; 10264 } else { 10265 std::swap(PExp, IExp); 10266 if (PExp->getType()->isPointerType()) { 10267 isObjCPointer = false; 10268 } else if (PExp->getType()->isObjCObjectPointerType()) { 10269 isObjCPointer = true; 10270 } else { 10271 return InvalidOperands(Loc, LHS, RHS); 10272 } 10273 } 10274 assert(PExp->getType()->isAnyPointerType()); 10275 10276 if (!IExp->getType()->isIntegerType()) 10277 return InvalidOperands(Loc, LHS, RHS); 10278 10279 // Adding to a null pointer results in undefined behavior. 10280 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10281 Context, Expr::NPC_ValueDependentIsNotNull)) { 10282 // In C++ adding zero to a null pointer is defined. 10283 Expr::EvalResult KnownVal; 10284 if (!getLangOpts().CPlusPlus || 10285 (!IExp->isValueDependent() && 10286 (!IExp->EvaluateAsInt(KnownVal, Context) || 10287 KnownVal.Val.getInt() != 0))) { 10288 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10289 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10290 Context, BO_Add, PExp, IExp); 10291 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10292 } 10293 } 10294 10295 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10296 return QualType(); 10297 10298 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10299 return QualType(); 10300 10301 // Check array bounds for pointer arithemtic 10302 CheckArrayAccess(PExp, IExp); 10303 10304 if (CompLHSTy) { 10305 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10306 if (LHSTy.isNull()) { 10307 LHSTy = LHS.get()->getType(); 10308 if (LHSTy->isPromotableIntegerType()) 10309 LHSTy = Context.getPromotedIntegerType(LHSTy); 10310 } 10311 *CompLHSTy = LHSTy; 10312 } 10313 10314 return PExp->getType(); 10315 } 10316 10317 // C99 6.5.6 10318 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10319 SourceLocation Loc, 10320 QualType* CompLHSTy) { 10321 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10322 10323 if (LHS.get()->getType()->isVectorType() || 10324 RHS.get()->getType()->isVectorType()) { 10325 QualType compType = CheckVectorOperands( 10326 LHS, RHS, Loc, CompLHSTy, 10327 /*AllowBothBool*/getLangOpts().AltiVec, 10328 /*AllowBoolConversions*/getLangOpts().ZVector); 10329 if (CompLHSTy) *CompLHSTy = compType; 10330 return compType; 10331 } 10332 10333 QualType compType = UsualArithmeticConversions( 10334 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10335 if (LHS.isInvalid() || RHS.isInvalid()) 10336 return QualType(); 10337 10338 // Enforce type constraints: C99 6.5.6p3. 10339 10340 // Handle the common case first (both operands are arithmetic). 10341 if (!compType.isNull() && compType->isArithmeticType()) { 10342 if (CompLHSTy) *CompLHSTy = compType; 10343 return compType; 10344 } 10345 10346 // Either ptr - int or ptr - ptr. 10347 if (LHS.get()->getType()->isAnyPointerType()) { 10348 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10349 10350 // Diagnose bad cases where we step over interface counts. 10351 if (LHS.get()->getType()->isObjCObjectPointerType() && 10352 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10353 return QualType(); 10354 10355 // The result type of a pointer-int computation is the pointer type. 10356 if (RHS.get()->getType()->isIntegerType()) { 10357 // Subtracting from a null pointer should produce a warning. 10358 // The last argument to the diagnose call says this doesn't match the 10359 // GNU int-to-pointer idiom. 10360 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10361 Expr::NPC_ValueDependentIsNotNull)) { 10362 // In C++ adding zero to a null pointer is defined. 10363 Expr::EvalResult KnownVal; 10364 if (!getLangOpts().CPlusPlus || 10365 (!RHS.get()->isValueDependent() && 10366 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10367 KnownVal.Val.getInt() != 0))) { 10368 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10369 } 10370 } 10371 10372 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10373 return QualType(); 10374 10375 // Check array bounds for pointer arithemtic 10376 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10377 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10378 10379 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10380 return LHS.get()->getType(); 10381 } 10382 10383 // Handle pointer-pointer subtractions. 10384 if (const PointerType *RHSPTy 10385 = RHS.get()->getType()->getAs<PointerType>()) { 10386 QualType rpointee = RHSPTy->getPointeeType(); 10387 10388 if (getLangOpts().CPlusPlus) { 10389 // Pointee types must be the same: C++ [expr.add] 10390 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10391 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10392 } 10393 } else { 10394 // Pointee types must be compatible C99 6.5.6p3 10395 if (!Context.typesAreCompatible( 10396 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10397 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10398 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10399 return QualType(); 10400 } 10401 } 10402 10403 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10404 LHS.get(), RHS.get())) 10405 return QualType(); 10406 10407 // FIXME: Add warnings for nullptr - ptr. 10408 10409 // The pointee type may have zero size. As an extension, a structure or 10410 // union may have zero size or an array may have zero length. In this 10411 // case subtraction does not make sense. 10412 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10413 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10414 if (ElementSize.isZero()) { 10415 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10416 << rpointee.getUnqualifiedType() 10417 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10418 } 10419 } 10420 10421 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10422 return Context.getPointerDiffType(); 10423 } 10424 } 10425 10426 return InvalidOperands(Loc, LHS, RHS); 10427 } 10428 10429 static bool isScopedEnumerationType(QualType T) { 10430 if (const EnumType *ET = T->getAs<EnumType>()) 10431 return ET->getDecl()->isScoped(); 10432 return false; 10433 } 10434 10435 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10436 SourceLocation Loc, BinaryOperatorKind Opc, 10437 QualType LHSType) { 10438 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10439 // so skip remaining warnings as we don't want to modify values within Sema. 10440 if (S.getLangOpts().OpenCL) 10441 return; 10442 10443 // Check right/shifter operand 10444 Expr::EvalResult RHSResult; 10445 if (RHS.get()->isValueDependent() || 10446 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10447 return; 10448 llvm::APSInt Right = RHSResult.Val.getInt(); 10449 10450 if (Right.isNegative()) { 10451 S.DiagRuntimeBehavior(Loc, RHS.get(), 10452 S.PDiag(diag::warn_shift_negative) 10453 << RHS.get()->getSourceRange()); 10454 return; 10455 } 10456 10457 QualType LHSExprType = LHS.get()->getType(); 10458 uint64_t LeftSize = LHSExprType->isExtIntType() 10459 ? S.Context.getIntWidth(LHSExprType) 10460 : S.Context.getTypeSize(LHSExprType); 10461 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10462 if (Right.uge(LeftBits)) { 10463 S.DiagRuntimeBehavior(Loc, RHS.get(), 10464 S.PDiag(diag::warn_shift_gt_typewidth) 10465 << RHS.get()->getSourceRange()); 10466 return; 10467 } 10468 10469 if (Opc != BO_Shl) 10470 return; 10471 10472 // When left shifting an ICE which is signed, we can check for overflow which 10473 // according to C++ standards prior to C++2a has undefined behavior 10474 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10475 // more than the maximum value representable in the result type, so never 10476 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10477 // expression is still probably a bug.) 10478 Expr::EvalResult LHSResult; 10479 if (LHS.get()->isValueDependent() || 10480 LHSType->hasUnsignedIntegerRepresentation() || 10481 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10482 return; 10483 llvm::APSInt Left = LHSResult.Val.getInt(); 10484 10485 // If LHS does not have a signed type and non-negative value 10486 // then, the behavior is undefined before C++2a. Warn about it. 10487 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10488 !S.getLangOpts().CPlusPlus20) { 10489 S.DiagRuntimeBehavior(Loc, LHS.get(), 10490 S.PDiag(diag::warn_shift_lhs_negative) 10491 << LHS.get()->getSourceRange()); 10492 return; 10493 } 10494 10495 llvm::APInt ResultBits = 10496 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10497 if (LeftBits.uge(ResultBits)) 10498 return; 10499 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10500 Result = Result.shl(Right); 10501 10502 // Print the bit representation of the signed integer as an unsigned 10503 // hexadecimal number. 10504 SmallString<40> HexResult; 10505 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10506 10507 // If we are only missing a sign bit, this is less likely to result in actual 10508 // bugs -- if the result is cast back to an unsigned type, it will have the 10509 // expected value. Thus we place this behind a different warning that can be 10510 // turned off separately if needed. 10511 if (LeftBits == ResultBits - 1) { 10512 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10513 << HexResult << LHSType 10514 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10515 return; 10516 } 10517 10518 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10519 << HexResult.str() << Result.getMinSignedBits() << LHSType 10520 << Left.getBitWidth() << LHS.get()->getSourceRange() 10521 << RHS.get()->getSourceRange(); 10522 } 10523 10524 /// Return the resulting type when a vector is shifted 10525 /// by a scalar or vector shift amount. 10526 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10527 SourceLocation Loc, bool IsCompAssign) { 10528 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10529 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10530 !LHS.get()->getType()->isVectorType()) { 10531 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10532 << RHS.get()->getType() << LHS.get()->getType() 10533 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10534 return QualType(); 10535 } 10536 10537 if (!IsCompAssign) { 10538 LHS = S.UsualUnaryConversions(LHS.get()); 10539 if (LHS.isInvalid()) return QualType(); 10540 } 10541 10542 RHS = S.UsualUnaryConversions(RHS.get()); 10543 if (RHS.isInvalid()) return QualType(); 10544 10545 QualType LHSType = LHS.get()->getType(); 10546 // Note that LHS might be a scalar because the routine calls not only in 10547 // OpenCL case. 10548 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10549 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10550 10551 // Note that RHS might not be a vector. 10552 QualType RHSType = RHS.get()->getType(); 10553 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10554 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10555 10556 // The operands need to be integers. 10557 if (!LHSEleType->isIntegerType()) { 10558 S.Diag(Loc, diag::err_typecheck_expect_int) 10559 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10560 return QualType(); 10561 } 10562 10563 if (!RHSEleType->isIntegerType()) { 10564 S.Diag(Loc, diag::err_typecheck_expect_int) 10565 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10566 return QualType(); 10567 } 10568 10569 if (!LHSVecTy) { 10570 assert(RHSVecTy); 10571 if (IsCompAssign) 10572 return RHSType; 10573 if (LHSEleType != RHSEleType) { 10574 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10575 LHSEleType = RHSEleType; 10576 } 10577 QualType VecTy = 10578 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10579 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10580 LHSType = VecTy; 10581 } else if (RHSVecTy) { 10582 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10583 // are applied component-wise. So if RHS is a vector, then ensure 10584 // that the number of elements is the same as LHS... 10585 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10586 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10587 << LHS.get()->getType() << RHS.get()->getType() 10588 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10589 return QualType(); 10590 } 10591 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10592 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10593 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10594 if (LHSBT != RHSBT && 10595 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10596 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10597 << LHS.get()->getType() << RHS.get()->getType() 10598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10599 } 10600 } 10601 } else { 10602 // ...else expand RHS to match the number of elements in LHS. 10603 QualType VecTy = 10604 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10605 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10606 } 10607 10608 return LHSType; 10609 } 10610 10611 // C99 6.5.7 10612 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10613 SourceLocation Loc, BinaryOperatorKind Opc, 10614 bool IsCompAssign) { 10615 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10616 10617 // Vector shifts promote their scalar inputs to vector type. 10618 if (LHS.get()->getType()->isVectorType() || 10619 RHS.get()->getType()->isVectorType()) { 10620 if (LangOpts.ZVector) { 10621 // The shift operators for the z vector extensions work basically 10622 // like general shifts, except that neither the LHS nor the RHS is 10623 // allowed to be a "vector bool". 10624 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10625 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10626 return InvalidOperands(Loc, LHS, RHS); 10627 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10628 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10629 return InvalidOperands(Loc, LHS, RHS); 10630 } 10631 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10632 } 10633 10634 // Shifts don't perform usual arithmetic conversions, they just do integer 10635 // promotions on each operand. C99 6.5.7p3 10636 10637 // For the LHS, do usual unary conversions, but then reset them away 10638 // if this is a compound assignment. 10639 ExprResult OldLHS = LHS; 10640 LHS = UsualUnaryConversions(LHS.get()); 10641 if (LHS.isInvalid()) 10642 return QualType(); 10643 QualType LHSType = LHS.get()->getType(); 10644 if (IsCompAssign) LHS = OldLHS; 10645 10646 // The RHS is simpler. 10647 RHS = UsualUnaryConversions(RHS.get()); 10648 if (RHS.isInvalid()) 10649 return QualType(); 10650 QualType RHSType = RHS.get()->getType(); 10651 10652 // C99 6.5.7p2: Each of the operands shall have integer type. 10653 if (!LHSType->hasIntegerRepresentation() || 10654 !RHSType->hasIntegerRepresentation()) 10655 return InvalidOperands(Loc, LHS, RHS); 10656 10657 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10658 // hasIntegerRepresentation() above instead of this. 10659 if (isScopedEnumerationType(LHSType) || 10660 isScopedEnumerationType(RHSType)) { 10661 return InvalidOperands(Loc, LHS, RHS); 10662 } 10663 // Sanity-check shift operands 10664 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10665 10666 // "The type of the result is that of the promoted left operand." 10667 return LHSType; 10668 } 10669 10670 /// Diagnose bad pointer comparisons. 10671 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10672 ExprResult &LHS, ExprResult &RHS, 10673 bool IsError) { 10674 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10675 : diag::ext_typecheck_comparison_of_distinct_pointers) 10676 << LHS.get()->getType() << RHS.get()->getType() 10677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10678 } 10679 10680 /// Returns false if the pointers are converted to a composite type, 10681 /// true otherwise. 10682 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10683 ExprResult &LHS, ExprResult &RHS) { 10684 // C++ [expr.rel]p2: 10685 // [...] Pointer conversions (4.10) and qualification 10686 // conversions (4.4) are performed on pointer operands (or on 10687 // a pointer operand and a null pointer constant) to bring 10688 // them to their composite pointer type. [...] 10689 // 10690 // C++ [expr.eq]p1 uses the same notion for (in)equality 10691 // comparisons of pointers. 10692 10693 QualType LHSType = LHS.get()->getType(); 10694 QualType RHSType = RHS.get()->getType(); 10695 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10696 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10697 10698 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10699 if (T.isNull()) { 10700 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10701 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10702 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10703 else 10704 S.InvalidOperands(Loc, LHS, RHS); 10705 return true; 10706 } 10707 10708 return false; 10709 } 10710 10711 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10712 ExprResult &LHS, 10713 ExprResult &RHS, 10714 bool IsError) { 10715 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10716 : diag::ext_typecheck_comparison_of_fptr_to_void) 10717 << LHS.get()->getType() << RHS.get()->getType() 10718 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10719 } 10720 10721 static bool isObjCObjectLiteral(ExprResult &E) { 10722 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10723 case Stmt::ObjCArrayLiteralClass: 10724 case Stmt::ObjCDictionaryLiteralClass: 10725 case Stmt::ObjCStringLiteralClass: 10726 case Stmt::ObjCBoxedExprClass: 10727 return true; 10728 default: 10729 // Note that ObjCBoolLiteral is NOT an object literal! 10730 return false; 10731 } 10732 } 10733 10734 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10735 const ObjCObjectPointerType *Type = 10736 LHS->getType()->getAs<ObjCObjectPointerType>(); 10737 10738 // If this is not actually an Objective-C object, bail out. 10739 if (!Type) 10740 return false; 10741 10742 // Get the LHS object's interface type. 10743 QualType InterfaceType = Type->getPointeeType(); 10744 10745 // If the RHS isn't an Objective-C object, bail out. 10746 if (!RHS->getType()->isObjCObjectPointerType()) 10747 return false; 10748 10749 // Try to find the -isEqual: method. 10750 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10751 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10752 InterfaceType, 10753 /*IsInstance=*/true); 10754 if (!Method) { 10755 if (Type->isObjCIdType()) { 10756 // For 'id', just check the global pool. 10757 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10758 /*receiverId=*/true); 10759 } else { 10760 // Check protocols. 10761 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10762 /*IsInstance=*/true); 10763 } 10764 } 10765 10766 if (!Method) 10767 return false; 10768 10769 QualType T = Method->parameters()[0]->getType(); 10770 if (!T->isObjCObjectPointerType()) 10771 return false; 10772 10773 QualType R = Method->getReturnType(); 10774 if (!R->isScalarType()) 10775 return false; 10776 10777 return true; 10778 } 10779 10780 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10781 FromE = FromE->IgnoreParenImpCasts(); 10782 switch (FromE->getStmtClass()) { 10783 default: 10784 break; 10785 case Stmt::ObjCStringLiteralClass: 10786 // "string literal" 10787 return LK_String; 10788 case Stmt::ObjCArrayLiteralClass: 10789 // "array literal" 10790 return LK_Array; 10791 case Stmt::ObjCDictionaryLiteralClass: 10792 // "dictionary literal" 10793 return LK_Dictionary; 10794 case Stmt::BlockExprClass: 10795 return LK_Block; 10796 case Stmt::ObjCBoxedExprClass: { 10797 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10798 switch (Inner->getStmtClass()) { 10799 case Stmt::IntegerLiteralClass: 10800 case Stmt::FloatingLiteralClass: 10801 case Stmt::CharacterLiteralClass: 10802 case Stmt::ObjCBoolLiteralExprClass: 10803 case Stmt::CXXBoolLiteralExprClass: 10804 // "numeric literal" 10805 return LK_Numeric; 10806 case Stmt::ImplicitCastExprClass: { 10807 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10808 // Boolean literals can be represented by implicit casts. 10809 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10810 return LK_Numeric; 10811 break; 10812 } 10813 default: 10814 break; 10815 } 10816 return LK_Boxed; 10817 } 10818 } 10819 return LK_None; 10820 } 10821 10822 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10823 ExprResult &LHS, ExprResult &RHS, 10824 BinaryOperator::Opcode Opc){ 10825 Expr *Literal; 10826 Expr *Other; 10827 if (isObjCObjectLiteral(LHS)) { 10828 Literal = LHS.get(); 10829 Other = RHS.get(); 10830 } else { 10831 Literal = RHS.get(); 10832 Other = LHS.get(); 10833 } 10834 10835 // Don't warn on comparisons against nil. 10836 Other = Other->IgnoreParenCasts(); 10837 if (Other->isNullPointerConstant(S.getASTContext(), 10838 Expr::NPC_ValueDependentIsNotNull)) 10839 return; 10840 10841 // This should be kept in sync with warn_objc_literal_comparison. 10842 // LK_String should always be after the other literals, since it has its own 10843 // warning flag. 10844 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10845 assert(LiteralKind != Sema::LK_Block); 10846 if (LiteralKind == Sema::LK_None) { 10847 llvm_unreachable("Unknown Objective-C object literal kind"); 10848 } 10849 10850 if (LiteralKind == Sema::LK_String) 10851 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10852 << Literal->getSourceRange(); 10853 else 10854 S.Diag(Loc, diag::warn_objc_literal_comparison) 10855 << LiteralKind << Literal->getSourceRange(); 10856 10857 if (BinaryOperator::isEqualityOp(Opc) && 10858 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10859 SourceLocation Start = LHS.get()->getBeginLoc(); 10860 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10861 CharSourceRange OpRange = 10862 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10863 10864 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10865 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10866 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10867 << FixItHint::CreateInsertion(End, "]"); 10868 } 10869 } 10870 10871 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10872 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10873 ExprResult &RHS, SourceLocation Loc, 10874 BinaryOperatorKind Opc) { 10875 // Check that left hand side is !something. 10876 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10877 if (!UO || UO->getOpcode() != UO_LNot) return; 10878 10879 // Only check if the right hand side is non-bool arithmetic type. 10880 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10881 10882 // Make sure that the something in !something is not bool. 10883 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10884 if (SubExpr->isKnownToHaveBooleanValue()) return; 10885 10886 // Emit warning. 10887 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10888 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10889 << Loc << IsBitwiseOp; 10890 10891 // First note suggest !(x < y) 10892 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10893 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10894 FirstClose = S.getLocForEndOfToken(FirstClose); 10895 if (FirstClose.isInvalid()) 10896 FirstOpen = SourceLocation(); 10897 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10898 << IsBitwiseOp 10899 << FixItHint::CreateInsertion(FirstOpen, "(") 10900 << FixItHint::CreateInsertion(FirstClose, ")"); 10901 10902 // Second note suggests (!x) < y 10903 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10904 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10905 SecondClose = S.getLocForEndOfToken(SecondClose); 10906 if (SecondClose.isInvalid()) 10907 SecondOpen = SourceLocation(); 10908 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10909 << FixItHint::CreateInsertion(SecondOpen, "(") 10910 << FixItHint::CreateInsertion(SecondClose, ")"); 10911 } 10912 10913 // Returns true if E refers to a non-weak array. 10914 static bool checkForArray(const Expr *E) { 10915 const ValueDecl *D = nullptr; 10916 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10917 D = DR->getDecl(); 10918 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10919 if (Mem->isImplicitAccess()) 10920 D = Mem->getMemberDecl(); 10921 } 10922 if (!D) 10923 return false; 10924 return D->getType()->isArrayType() && !D->isWeak(); 10925 } 10926 10927 /// Diagnose some forms of syntactically-obvious tautological comparison. 10928 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10929 Expr *LHS, Expr *RHS, 10930 BinaryOperatorKind Opc) { 10931 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10932 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10933 10934 QualType LHSType = LHS->getType(); 10935 QualType RHSType = RHS->getType(); 10936 if (LHSType->hasFloatingRepresentation() || 10937 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10938 S.inTemplateInstantiation()) 10939 return; 10940 10941 // Comparisons between two array types are ill-formed for operator<=>, so 10942 // we shouldn't emit any additional warnings about it. 10943 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10944 return; 10945 10946 // For non-floating point types, check for self-comparisons of the form 10947 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10948 // often indicate logic errors in the program. 10949 // 10950 // NOTE: Don't warn about comparison expressions resulting from macro 10951 // expansion. Also don't warn about comparisons which are only self 10952 // comparisons within a template instantiation. The warnings should catch 10953 // obvious cases in the definition of the template anyways. The idea is to 10954 // warn when the typed comparison operator will always evaluate to the same 10955 // result. 10956 10957 // Used for indexing into %select in warn_comparison_always 10958 enum { 10959 AlwaysConstant, 10960 AlwaysTrue, 10961 AlwaysFalse, 10962 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10963 }; 10964 10965 // C++2a [depr.array.comp]: 10966 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10967 // operands of array type are deprecated. 10968 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 10969 RHSStripped->getType()->isArrayType()) { 10970 S.Diag(Loc, diag::warn_depr_array_comparison) 10971 << LHS->getSourceRange() << RHS->getSourceRange() 10972 << LHSStripped->getType() << RHSStripped->getType(); 10973 // Carry on to produce the tautological comparison warning, if this 10974 // expression is potentially-evaluated, we can resolve the array to a 10975 // non-weak declaration, and so on. 10976 } 10977 10978 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10979 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10980 unsigned Result; 10981 switch (Opc) { 10982 case BO_EQ: 10983 case BO_LE: 10984 case BO_GE: 10985 Result = AlwaysTrue; 10986 break; 10987 case BO_NE: 10988 case BO_LT: 10989 case BO_GT: 10990 Result = AlwaysFalse; 10991 break; 10992 case BO_Cmp: 10993 Result = AlwaysEqual; 10994 break; 10995 default: 10996 Result = AlwaysConstant; 10997 break; 10998 } 10999 S.DiagRuntimeBehavior(Loc, nullptr, 11000 S.PDiag(diag::warn_comparison_always) 11001 << 0 /*self-comparison*/ 11002 << Result); 11003 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11004 // What is it always going to evaluate to? 11005 unsigned Result; 11006 switch (Opc) { 11007 case BO_EQ: // e.g. array1 == array2 11008 Result = AlwaysFalse; 11009 break; 11010 case BO_NE: // e.g. array1 != array2 11011 Result = AlwaysTrue; 11012 break; 11013 default: // e.g. array1 <= array2 11014 // The best we can say is 'a constant' 11015 Result = AlwaysConstant; 11016 break; 11017 } 11018 S.DiagRuntimeBehavior(Loc, nullptr, 11019 S.PDiag(diag::warn_comparison_always) 11020 << 1 /*array comparison*/ 11021 << Result); 11022 } 11023 } 11024 11025 if (isa<CastExpr>(LHSStripped)) 11026 LHSStripped = LHSStripped->IgnoreParenCasts(); 11027 if (isa<CastExpr>(RHSStripped)) 11028 RHSStripped = RHSStripped->IgnoreParenCasts(); 11029 11030 // Warn about comparisons against a string constant (unless the other 11031 // operand is null); the user probably wants string comparison function. 11032 Expr *LiteralString = nullptr; 11033 Expr *LiteralStringStripped = nullptr; 11034 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11035 !RHSStripped->isNullPointerConstant(S.Context, 11036 Expr::NPC_ValueDependentIsNull)) { 11037 LiteralString = LHS; 11038 LiteralStringStripped = LHSStripped; 11039 } else if ((isa<StringLiteral>(RHSStripped) || 11040 isa<ObjCEncodeExpr>(RHSStripped)) && 11041 !LHSStripped->isNullPointerConstant(S.Context, 11042 Expr::NPC_ValueDependentIsNull)) { 11043 LiteralString = RHS; 11044 LiteralStringStripped = RHSStripped; 11045 } 11046 11047 if (LiteralString) { 11048 S.DiagRuntimeBehavior(Loc, nullptr, 11049 S.PDiag(diag::warn_stringcompare) 11050 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11051 << LiteralString->getSourceRange()); 11052 } 11053 } 11054 11055 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11056 switch (CK) { 11057 default: { 11058 #ifndef NDEBUG 11059 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11060 << "\n"; 11061 #endif 11062 llvm_unreachable("unhandled cast kind"); 11063 } 11064 case CK_UserDefinedConversion: 11065 return ICK_Identity; 11066 case CK_LValueToRValue: 11067 return ICK_Lvalue_To_Rvalue; 11068 case CK_ArrayToPointerDecay: 11069 return ICK_Array_To_Pointer; 11070 case CK_FunctionToPointerDecay: 11071 return ICK_Function_To_Pointer; 11072 case CK_IntegralCast: 11073 return ICK_Integral_Conversion; 11074 case CK_FloatingCast: 11075 return ICK_Floating_Conversion; 11076 case CK_IntegralToFloating: 11077 case CK_FloatingToIntegral: 11078 return ICK_Floating_Integral; 11079 case CK_IntegralComplexCast: 11080 case CK_FloatingComplexCast: 11081 case CK_FloatingComplexToIntegralComplex: 11082 case CK_IntegralComplexToFloatingComplex: 11083 return ICK_Complex_Conversion; 11084 case CK_FloatingComplexToReal: 11085 case CK_FloatingRealToComplex: 11086 case CK_IntegralComplexToReal: 11087 case CK_IntegralRealToComplex: 11088 return ICK_Complex_Real; 11089 } 11090 } 11091 11092 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11093 QualType FromType, 11094 SourceLocation Loc) { 11095 // Check for a narrowing implicit conversion. 11096 StandardConversionSequence SCS; 11097 SCS.setAsIdentityConversion(); 11098 SCS.setToType(0, FromType); 11099 SCS.setToType(1, ToType); 11100 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11101 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11102 11103 APValue PreNarrowingValue; 11104 QualType PreNarrowingType; 11105 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11106 PreNarrowingType, 11107 /*IgnoreFloatToIntegralConversion*/ true)) { 11108 case NK_Dependent_Narrowing: 11109 // Implicit conversion to a narrower type, but the expression is 11110 // value-dependent so we can't tell whether it's actually narrowing. 11111 case NK_Not_Narrowing: 11112 return false; 11113 11114 case NK_Constant_Narrowing: 11115 // Implicit conversion to a narrower type, and the value is not a constant 11116 // expression. 11117 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11118 << /*Constant*/ 1 11119 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11120 return true; 11121 11122 case NK_Variable_Narrowing: 11123 // Implicit conversion to a narrower type, and the value is not a constant 11124 // expression. 11125 case NK_Type_Narrowing: 11126 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11127 << /*Constant*/ 0 << FromType << ToType; 11128 // TODO: It's not a constant expression, but what if the user intended it 11129 // to be? Can we produce notes to help them figure out why it isn't? 11130 return true; 11131 } 11132 llvm_unreachable("unhandled case in switch"); 11133 } 11134 11135 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11136 ExprResult &LHS, 11137 ExprResult &RHS, 11138 SourceLocation Loc) { 11139 QualType LHSType = LHS.get()->getType(); 11140 QualType RHSType = RHS.get()->getType(); 11141 // Dig out the original argument type and expression before implicit casts 11142 // were applied. These are the types/expressions we need to check the 11143 // [expr.spaceship] requirements against. 11144 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11145 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11146 QualType LHSStrippedType = LHSStripped.get()->getType(); 11147 QualType RHSStrippedType = RHSStripped.get()->getType(); 11148 11149 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11150 // other is not, the program is ill-formed. 11151 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11152 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11153 return QualType(); 11154 } 11155 11156 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11157 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11158 RHSStrippedType->isEnumeralType(); 11159 if (NumEnumArgs == 1) { 11160 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11161 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11162 if (OtherTy->hasFloatingRepresentation()) { 11163 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11164 return QualType(); 11165 } 11166 } 11167 if (NumEnumArgs == 2) { 11168 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11169 // type E, the operator yields the result of converting the operands 11170 // to the underlying type of E and applying <=> to the converted operands. 11171 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11172 S.InvalidOperands(Loc, LHS, RHS); 11173 return QualType(); 11174 } 11175 QualType IntType = 11176 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11177 assert(IntType->isArithmeticType()); 11178 11179 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11180 // promote the boolean type, and all other promotable integer types, to 11181 // avoid this. 11182 if (IntType->isPromotableIntegerType()) 11183 IntType = S.Context.getPromotedIntegerType(IntType); 11184 11185 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11186 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11187 LHSType = RHSType = IntType; 11188 } 11189 11190 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11191 // usual arithmetic conversions are applied to the operands. 11192 QualType Type = 11193 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11194 if (LHS.isInvalid() || RHS.isInvalid()) 11195 return QualType(); 11196 if (Type.isNull()) 11197 return S.InvalidOperands(Loc, LHS, RHS); 11198 11199 Optional<ComparisonCategoryType> CCT = 11200 getComparisonCategoryForBuiltinCmp(Type); 11201 if (!CCT) 11202 return S.InvalidOperands(Loc, LHS, RHS); 11203 11204 bool HasNarrowing = checkThreeWayNarrowingConversion( 11205 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11206 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11207 RHS.get()->getBeginLoc()); 11208 if (HasNarrowing) 11209 return QualType(); 11210 11211 assert(!Type.isNull() && "composite type for <=> has not been set"); 11212 11213 return S.CheckComparisonCategoryType( 11214 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11215 } 11216 11217 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11218 ExprResult &RHS, 11219 SourceLocation Loc, 11220 BinaryOperatorKind Opc) { 11221 if (Opc == BO_Cmp) 11222 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11223 11224 // C99 6.5.8p3 / C99 6.5.9p4 11225 QualType Type = 11226 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11227 if (LHS.isInvalid() || RHS.isInvalid()) 11228 return QualType(); 11229 if (Type.isNull()) 11230 return S.InvalidOperands(Loc, LHS, RHS); 11231 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11232 11233 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11234 return S.InvalidOperands(Loc, LHS, RHS); 11235 11236 // Check for comparisons of floating point operands using != and ==. 11237 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11238 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11239 11240 // The result of comparisons is 'bool' in C++, 'int' in C. 11241 return S.Context.getLogicalOperationType(); 11242 } 11243 11244 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11245 if (!NullE.get()->getType()->isAnyPointerType()) 11246 return; 11247 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11248 if (!E.get()->getType()->isAnyPointerType() && 11249 E.get()->isNullPointerConstant(Context, 11250 Expr::NPC_ValueDependentIsNotNull) == 11251 Expr::NPCK_ZeroExpression) { 11252 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11253 if (CL->getValue() == 0) 11254 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11255 << NullValue 11256 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11257 NullValue ? "NULL" : "(void *)0"); 11258 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11259 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11260 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11261 if (T == Context.CharTy) 11262 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11263 << NullValue 11264 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11265 NullValue ? "NULL" : "(void *)0"); 11266 } 11267 } 11268 } 11269 11270 // C99 6.5.8, C++ [expr.rel] 11271 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11272 SourceLocation Loc, 11273 BinaryOperatorKind Opc) { 11274 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11275 bool IsThreeWay = Opc == BO_Cmp; 11276 bool IsOrdered = IsRelational || IsThreeWay; 11277 auto IsAnyPointerType = [](ExprResult E) { 11278 QualType Ty = E.get()->getType(); 11279 return Ty->isPointerType() || Ty->isMemberPointerType(); 11280 }; 11281 11282 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11283 // type, array-to-pointer, ..., conversions are performed on both operands to 11284 // bring them to their composite type. 11285 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11286 // any type-related checks. 11287 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11288 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11289 if (LHS.isInvalid()) 11290 return QualType(); 11291 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11292 if (RHS.isInvalid()) 11293 return QualType(); 11294 } else { 11295 LHS = DefaultLvalueConversion(LHS.get()); 11296 if (LHS.isInvalid()) 11297 return QualType(); 11298 RHS = DefaultLvalueConversion(RHS.get()); 11299 if (RHS.isInvalid()) 11300 return QualType(); 11301 } 11302 11303 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11304 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11305 CheckPtrComparisonWithNullChar(LHS, RHS); 11306 CheckPtrComparisonWithNullChar(RHS, LHS); 11307 } 11308 11309 // Handle vector comparisons separately. 11310 if (LHS.get()->getType()->isVectorType() || 11311 RHS.get()->getType()->isVectorType()) 11312 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11313 11314 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11315 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11316 11317 QualType LHSType = LHS.get()->getType(); 11318 QualType RHSType = RHS.get()->getType(); 11319 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11320 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11321 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11322 11323 const Expr::NullPointerConstantKind LHSNullKind = 11324 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11325 const Expr::NullPointerConstantKind RHSNullKind = 11326 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11327 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11328 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11329 11330 auto computeResultTy = [&]() { 11331 if (Opc != BO_Cmp) 11332 return Context.getLogicalOperationType(); 11333 assert(getLangOpts().CPlusPlus); 11334 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11335 11336 QualType CompositeTy = LHS.get()->getType(); 11337 assert(!CompositeTy->isReferenceType()); 11338 11339 Optional<ComparisonCategoryType> CCT = 11340 getComparisonCategoryForBuiltinCmp(CompositeTy); 11341 if (!CCT) 11342 return InvalidOperands(Loc, LHS, RHS); 11343 11344 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11345 // P0946R0: Comparisons between a null pointer constant and an object 11346 // pointer result in std::strong_equality, which is ill-formed under 11347 // P1959R0. 11348 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11349 << (LHSIsNull ? LHS.get()->getSourceRange() 11350 : RHS.get()->getSourceRange()); 11351 return QualType(); 11352 } 11353 11354 return CheckComparisonCategoryType( 11355 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11356 }; 11357 11358 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11359 bool IsEquality = Opc == BO_EQ; 11360 if (RHSIsNull) 11361 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11362 RHS.get()->getSourceRange()); 11363 else 11364 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11365 LHS.get()->getSourceRange()); 11366 } 11367 11368 if ((LHSType->isIntegerType() && !LHSIsNull) || 11369 (RHSType->isIntegerType() && !RHSIsNull)) { 11370 // Skip normal pointer conversion checks in this case; we have better 11371 // diagnostics for this below. 11372 } else if (getLangOpts().CPlusPlus) { 11373 // Equality comparison of a function pointer to a void pointer is invalid, 11374 // but we allow it as an extension. 11375 // FIXME: If we really want to allow this, should it be part of composite 11376 // pointer type computation so it works in conditionals too? 11377 if (!IsOrdered && 11378 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11379 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11380 // This is a gcc extension compatibility comparison. 11381 // In a SFINAE context, we treat this as a hard error to maintain 11382 // conformance with the C++ standard. 11383 diagnoseFunctionPointerToVoidComparison( 11384 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11385 11386 if (isSFINAEContext()) 11387 return QualType(); 11388 11389 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11390 return computeResultTy(); 11391 } 11392 11393 // C++ [expr.eq]p2: 11394 // If at least one operand is a pointer [...] bring them to their 11395 // composite pointer type. 11396 // C++ [expr.spaceship]p6 11397 // If at least one of the operands is of pointer type, [...] bring them 11398 // to their composite pointer type. 11399 // C++ [expr.rel]p2: 11400 // If both operands are pointers, [...] bring them to their composite 11401 // pointer type. 11402 // For <=>, the only valid non-pointer types are arrays and functions, and 11403 // we already decayed those, so this is really the same as the relational 11404 // comparison rule. 11405 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11406 (IsOrdered ? 2 : 1) && 11407 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11408 RHSType->isObjCObjectPointerType()))) { 11409 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11410 return QualType(); 11411 return computeResultTy(); 11412 } 11413 } else if (LHSType->isPointerType() && 11414 RHSType->isPointerType()) { // C99 6.5.8p2 11415 // All of the following pointer-related warnings are GCC extensions, except 11416 // when handling null pointer constants. 11417 QualType LCanPointeeTy = 11418 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11419 QualType RCanPointeeTy = 11420 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11421 11422 // C99 6.5.9p2 and C99 6.5.8p2 11423 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11424 RCanPointeeTy.getUnqualifiedType())) { 11425 // Valid unless a relational comparison of function pointers 11426 if (IsRelational && LCanPointeeTy->isFunctionType()) { 11427 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11428 << LHSType << RHSType << LHS.get()->getSourceRange() 11429 << RHS.get()->getSourceRange(); 11430 } 11431 } else if (!IsRelational && 11432 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11433 // Valid unless comparison between non-null pointer and function pointer 11434 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11435 && !LHSIsNull && !RHSIsNull) 11436 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11437 /*isError*/false); 11438 } else { 11439 // Invalid 11440 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11441 } 11442 if (LCanPointeeTy != RCanPointeeTy) { 11443 // Treat NULL constant as a special case in OpenCL. 11444 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11445 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11446 Diag(Loc, 11447 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11448 << LHSType << RHSType << 0 /* comparison */ 11449 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11450 } 11451 } 11452 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11453 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11454 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11455 : CK_BitCast; 11456 if (LHSIsNull && !RHSIsNull) 11457 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11458 else 11459 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11460 } 11461 return computeResultTy(); 11462 } 11463 11464 if (getLangOpts().CPlusPlus) { 11465 // C++ [expr.eq]p4: 11466 // Two operands of type std::nullptr_t or one operand of type 11467 // std::nullptr_t and the other a null pointer constant compare equal. 11468 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11469 if (LHSType->isNullPtrType()) { 11470 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11471 return computeResultTy(); 11472 } 11473 if (RHSType->isNullPtrType()) { 11474 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11475 return computeResultTy(); 11476 } 11477 } 11478 11479 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11480 // These aren't covered by the composite pointer type rules. 11481 if (!IsOrdered && RHSType->isNullPtrType() && 11482 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11483 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11484 return computeResultTy(); 11485 } 11486 if (!IsOrdered && LHSType->isNullPtrType() && 11487 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11488 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11489 return computeResultTy(); 11490 } 11491 11492 if (IsRelational && 11493 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11494 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11495 // HACK: Relational comparison of nullptr_t against a pointer type is 11496 // invalid per DR583, but we allow it within std::less<> and friends, 11497 // since otherwise common uses of it break. 11498 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11499 // friends to have std::nullptr_t overload candidates. 11500 DeclContext *DC = CurContext; 11501 if (isa<FunctionDecl>(DC)) 11502 DC = DC->getParent(); 11503 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11504 if (CTSD->isInStdNamespace() && 11505 llvm::StringSwitch<bool>(CTSD->getName()) 11506 .Cases("less", "less_equal", "greater", "greater_equal", true) 11507 .Default(false)) { 11508 if (RHSType->isNullPtrType()) 11509 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11510 else 11511 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11512 return computeResultTy(); 11513 } 11514 } 11515 } 11516 11517 // C++ [expr.eq]p2: 11518 // If at least one operand is a pointer to member, [...] bring them to 11519 // their composite pointer type. 11520 if (!IsOrdered && 11521 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11522 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11523 return QualType(); 11524 else 11525 return computeResultTy(); 11526 } 11527 } 11528 11529 // Handle block pointer types. 11530 if (!IsOrdered && LHSType->isBlockPointerType() && 11531 RHSType->isBlockPointerType()) { 11532 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11533 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11534 11535 if (!LHSIsNull && !RHSIsNull && 11536 !Context.typesAreCompatible(lpointee, rpointee)) { 11537 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11538 << LHSType << RHSType << LHS.get()->getSourceRange() 11539 << RHS.get()->getSourceRange(); 11540 } 11541 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11542 return computeResultTy(); 11543 } 11544 11545 // Allow block pointers to be compared with null pointer constants. 11546 if (!IsOrdered 11547 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11548 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11549 if (!LHSIsNull && !RHSIsNull) { 11550 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11551 ->getPointeeType()->isVoidType()) 11552 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11553 ->getPointeeType()->isVoidType()))) 11554 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11555 << LHSType << RHSType << LHS.get()->getSourceRange() 11556 << RHS.get()->getSourceRange(); 11557 } 11558 if (LHSIsNull && !RHSIsNull) 11559 LHS = ImpCastExprToType(LHS.get(), RHSType, 11560 RHSType->isPointerType() ? CK_BitCast 11561 : CK_AnyPointerToBlockPointerCast); 11562 else 11563 RHS = ImpCastExprToType(RHS.get(), LHSType, 11564 LHSType->isPointerType() ? CK_BitCast 11565 : CK_AnyPointerToBlockPointerCast); 11566 return computeResultTy(); 11567 } 11568 11569 if (LHSType->isObjCObjectPointerType() || 11570 RHSType->isObjCObjectPointerType()) { 11571 const PointerType *LPT = LHSType->getAs<PointerType>(); 11572 const PointerType *RPT = RHSType->getAs<PointerType>(); 11573 if (LPT || RPT) { 11574 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11575 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11576 11577 if (!LPtrToVoid && !RPtrToVoid && 11578 !Context.typesAreCompatible(LHSType, RHSType)) { 11579 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11580 /*isError*/false); 11581 } 11582 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11583 // the RHS, but we have test coverage for this behavior. 11584 // FIXME: Consider using convertPointersToCompositeType in C++. 11585 if (LHSIsNull && !RHSIsNull) { 11586 Expr *E = LHS.get(); 11587 if (getLangOpts().ObjCAutoRefCount) 11588 CheckObjCConversion(SourceRange(), RHSType, E, 11589 CCK_ImplicitConversion); 11590 LHS = ImpCastExprToType(E, RHSType, 11591 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11592 } 11593 else { 11594 Expr *E = RHS.get(); 11595 if (getLangOpts().ObjCAutoRefCount) 11596 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11597 /*Diagnose=*/true, 11598 /*DiagnoseCFAudited=*/false, Opc); 11599 RHS = ImpCastExprToType(E, LHSType, 11600 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11601 } 11602 return computeResultTy(); 11603 } 11604 if (LHSType->isObjCObjectPointerType() && 11605 RHSType->isObjCObjectPointerType()) { 11606 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11607 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11608 /*isError*/false); 11609 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11610 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11611 11612 if (LHSIsNull && !RHSIsNull) 11613 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11614 else 11615 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11616 return computeResultTy(); 11617 } 11618 11619 if (!IsOrdered && LHSType->isBlockPointerType() && 11620 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11621 LHS = ImpCastExprToType(LHS.get(), RHSType, 11622 CK_BlockPointerToObjCPointerCast); 11623 return computeResultTy(); 11624 } else if (!IsOrdered && 11625 LHSType->isBlockCompatibleObjCPointerType(Context) && 11626 RHSType->isBlockPointerType()) { 11627 RHS = ImpCastExprToType(RHS.get(), LHSType, 11628 CK_BlockPointerToObjCPointerCast); 11629 return computeResultTy(); 11630 } 11631 } 11632 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11633 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11634 unsigned DiagID = 0; 11635 bool isError = false; 11636 if (LangOpts.DebuggerSupport) { 11637 // Under a debugger, allow the comparison of pointers to integers, 11638 // since users tend to want to compare addresses. 11639 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11640 (RHSIsNull && RHSType->isIntegerType())) { 11641 if (IsOrdered) { 11642 isError = getLangOpts().CPlusPlus; 11643 DiagID = 11644 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11645 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11646 } 11647 } else if (getLangOpts().CPlusPlus) { 11648 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11649 isError = true; 11650 } else if (IsOrdered) 11651 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11652 else 11653 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11654 11655 if (DiagID) { 11656 Diag(Loc, DiagID) 11657 << LHSType << RHSType << LHS.get()->getSourceRange() 11658 << RHS.get()->getSourceRange(); 11659 if (isError) 11660 return QualType(); 11661 } 11662 11663 if (LHSType->isIntegerType()) 11664 LHS = ImpCastExprToType(LHS.get(), RHSType, 11665 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11666 else 11667 RHS = ImpCastExprToType(RHS.get(), LHSType, 11668 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11669 return computeResultTy(); 11670 } 11671 11672 // Handle block pointers. 11673 if (!IsOrdered && RHSIsNull 11674 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11675 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11676 return computeResultTy(); 11677 } 11678 if (!IsOrdered && LHSIsNull 11679 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11680 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11681 return computeResultTy(); 11682 } 11683 11684 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11685 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11686 return computeResultTy(); 11687 } 11688 11689 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11690 return computeResultTy(); 11691 } 11692 11693 if (LHSIsNull && RHSType->isQueueT()) { 11694 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11695 return computeResultTy(); 11696 } 11697 11698 if (LHSType->isQueueT() && RHSIsNull) { 11699 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11700 return computeResultTy(); 11701 } 11702 } 11703 11704 return InvalidOperands(Loc, LHS, RHS); 11705 } 11706 11707 // Return a signed ext_vector_type that is of identical size and number of 11708 // elements. For floating point vectors, return an integer type of identical 11709 // size and number of elements. In the non ext_vector_type case, search from 11710 // the largest type to the smallest type to avoid cases where long long == long, 11711 // where long gets picked over long long. 11712 QualType Sema::GetSignedVectorType(QualType V) { 11713 const VectorType *VTy = V->castAs<VectorType>(); 11714 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11715 11716 if (isa<ExtVectorType>(VTy)) { 11717 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11718 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11719 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11720 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11721 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11722 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11723 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11724 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11725 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11726 "Unhandled vector element size in vector compare"); 11727 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11728 } 11729 11730 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11731 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11732 VectorType::GenericVector); 11733 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11734 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11735 VectorType::GenericVector); 11736 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11737 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11738 VectorType::GenericVector); 11739 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11740 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11741 VectorType::GenericVector); 11742 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11743 "Unhandled vector element size in vector compare"); 11744 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11745 VectorType::GenericVector); 11746 } 11747 11748 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11749 /// operates on extended vector types. Instead of producing an IntTy result, 11750 /// like a scalar comparison, a vector comparison produces a vector of integer 11751 /// types. 11752 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11753 SourceLocation Loc, 11754 BinaryOperatorKind Opc) { 11755 if (Opc == BO_Cmp) { 11756 Diag(Loc, diag::err_three_way_vector_comparison); 11757 return QualType(); 11758 } 11759 11760 // Check to make sure we're operating on vectors of the same type and width, 11761 // Allowing one side to be a scalar of element type. 11762 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11763 /*AllowBothBool*/true, 11764 /*AllowBoolConversions*/getLangOpts().ZVector); 11765 if (vType.isNull()) 11766 return vType; 11767 11768 QualType LHSType = LHS.get()->getType(); 11769 11770 // If AltiVec, the comparison results in a numeric type, i.e. 11771 // bool for C++, int for C 11772 if (getLangOpts().AltiVec && 11773 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11774 return Context.getLogicalOperationType(); 11775 11776 // For non-floating point types, check for self-comparisons of the form 11777 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11778 // often indicate logic errors in the program. 11779 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11780 11781 // Check for comparisons of floating point operands using != and ==. 11782 if (BinaryOperator::isEqualityOp(Opc) && 11783 LHSType->hasFloatingRepresentation()) { 11784 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11785 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11786 } 11787 11788 // Return a signed type for the vector. 11789 return GetSignedVectorType(vType); 11790 } 11791 11792 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11793 const ExprResult &XorRHS, 11794 const SourceLocation Loc) { 11795 // Do not diagnose macros. 11796 if (Loc.isMacroID()) 11797 return; 11798 11799 bool Negative = false; 11800 bool ExplicitPlus = false; 11801 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11802 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11803 11804 if (!LHSInt) 11805 return; 11806 if (!RHSInt) { 11807 // Check negative literals. 11808 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11809 UnaryOperatorKind Opc = UO->getOpcode(); 11810 if (Opc != UO_Minus && Opc != UO_Plus) 11811 return; 11812 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11813 if (!RHSInt) 11814 return; 11815 Negative = (Opc == UO_Minus); 11816 ExplicitPlus = !Negative; 11817 } else { 11818 return; 11819 } 11820 } 11821 11822 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11823 llvm::APInt RightSideValue = RHSInt->getValue(); 11824 if (LeftSideValue != 2 && LeftSideValue != 10) 11825 return; 11826 11827 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11828 return; 11829 11830 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11831 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11832 llvm::StringRef ExprStr = 11833 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11834 11835 CharSourceRange XorRange = 11836 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11837 llvm::StringRef XorStr = 11838 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11839 // Do not diagnose if xor keyword/macro is used. 11840 if (XorStr == "xor") 11841 return; 11842 11843 std::string LHSStr = std::string(Lexer::getSourceText( 11844 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11845 S.getSourceManager(), S.getLangOpts())); 11846 std::string RHSStr = std::string(Lexer::getSourceText( 11847 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11848 S.getSourceManager(), S.getLangOpts())); 11849 11850 if (Negative) { 11851 RightSideValue = -RightSideValue; 11852 RHSStr = "-" + RHSStr; 11853 } else if (ExplicitPlus) { 11854 RHSStr = "+" + RHSStr; 11855 } 11856 11857 StringRef LHSStrRef = LHSStr; 11858 StringRef RHSStrRef = RHSStr; 11859 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11860 // literals. 11861 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11862 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11863 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11864 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11865 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11866 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11867 LHSStrRef.find('\'') != StringRef::npos || 11868 RHSStrRef.find('\'') != StringRef::npos) 11869 return; 11870 11871 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11872 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11873 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11874 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11875 std::string SuggestedExpr = "1 << " + RHSStr; 11876 bool Overflow = false; 11877 llvm::APInt One = (LeftSideValue - 1); 11878 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11879 if (Overflow) { 11880 if (RightSideIntValue < 64) 11881 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11882 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11883 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11884 else if (RightSideIntValue == 64) 11885 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11886 else 11887 return; 11888 } else { 11889 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11890 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11891 << PowValue.toString(10, true) 11892 << FixItHint::CreateReplacement( 11893 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11894 } 11895 11896 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11897 } else if (LeftSideValue == 10) { 11898 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11899 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11900 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11901 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11902 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11903 } 11904 } 11905 11906 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11907 SourceLocation Loc) { 11908 // Ensure that either both operands are of the same vector type, or 11909 // one operand is of a vector type and the other is of its element type. 11910 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11911 /*AllowBothBool*/true, 11912 /*AllowBoolConversions*/false); 11913 if (vType.isNull()) 11914 return InvalidOperands(Loc, LHS, RHS); 11915 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11916 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11917 return InvalidOperands(Loc, LHS, RHS); 11918 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11919 // usage of the logical operators && and || with vectors in C. This 11920 // check could be notionally dropped. 11921 if (!getLangOpts().CPlusPlus && 11922 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11923 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11924 11925 return GetSignedVectorType(LHS.get()->getType()); 11926 } 11927 11928 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11929 SourceLocation Loc, 11930 BinaryOperatorKind Opc) { 11931 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11932 11933 bool IsCompAssign = 11934 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11935 11936 if (LHS.get()->getType()->isVectorType() || 11937 RHS.get()->getType()->isVectorType()) { 11938 if (LHS.get()->getType()->hasIntegerRepresentation() && 11939 RHS.get()->getType()->hasIntegerRepresentation()) 11940 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11941 /*AllowBothBool*/true, 11942 /*AllowBoolConversions*/getLangOpts().ZVector); 11943 return InvalidOperands(Loc, LHS, RHS); 11944 } 11945 11946 if (Opc == BO_And) 11947 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11948 11949 if (LHS.get()->getType()->hasFloatingRepresentation() || 11950 RHS.get()->getType()->hasFloatingRepresentation()) 11951 return InvalidOperands(Loc, LHS, RHS); 11952 11953 ExprResult LHSResult = LHS, RHSResult = RHS; 11954 QualType compType = UsualArithmeticConversions( 11955 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11956 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11957 return QualType(); 11958 LHS = LHSResult.get(); 11959 RHS = RHSResult.get(); 11960 11961 if (Opc == BO_Xor) 11962 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11963 11964 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11965 return compType; 11966 return InvalidOperands(Loc, LHS, RHS); 11967 } 11968 11969 // C99 6.5.[13,14] 11970 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11971 SourceLocation Loc, 11972 BinaryOperatorKind Opc) { 11973 // Check vector operands differently. 11974 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11975 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11976 11977 bool EnumConstantInBoolContext = false; 11978 for (const ExprResult &HS : {LHS, RHS}) { 11979 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11980 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11981 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11982 EnumConstantInBoolContext = true; 11983 } 11984 } 11985 11986 if (EnumConstantInBoolContext) 11987 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11988 11989 // Diagnose cases where the user write a logical and/or but probably meant a 11990 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11991 // is a constant. 11992 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11993 !LHS.get()->getType()->isBooleanType() && 11994 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11995 // Don't warn in macros or template instantiations. 11996 !Loc.isMacroID() && !inTemplateInstantiation()) { 11997 // If the RHS can be constant folded, and if it constant folds to something 11998 // that isn't 0 or 1 (which indicate a potential logical operation that 11999 // happened to fold to true/false) then warn. 12000 // Parens on the RHS are ignored. 12001 Expr::EvalResult EVResult; 12002 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12003 llvm::APSInt Result = EVResult.Val.getInt(); 12004 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12005 !RHS.get()->getExprLoc().isMacroID()) || 12006 (Result != 0 && Result != 1)) { 12007 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12008 << RHS.get()->getSourceRange() 12009 << (Opc == BO_LAnd ? "&&" : "||"); 12010 // Suggest replacing the logical operator with the bitwise version 12011 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12012 << (Opc == BO_LAnd ? "&" : "|") 12013 << FixItHint::CreateReplacement(SourceRange( 12014 Loc, getLocForEndOfToken(Loc)), 12015 Opc == BO_LAnd ? "&" : "|"); 12016 if (Opc == BO_LAnd) 12017 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12018 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12019 << FixItHint::CreateRemoval( 12020 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12021 RHS.get()->getEndLoc())); 12022 } 12023 } 12024 } 12025 12026 if (!Context.getLangOpts().CPlusPlus) { 12027 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12028 // not operate on the built-in scalar and vector float types. 12029 if (Context.getLangOpts().OpenCL && 12030 Context.getLangOpts().OpenCLVersion < 120) { 12031 if (LHS.get()->getType()->isFloatingType() || 12032 RHS.get()->getType()->isFloatingType()) 12033 return InvalidOperands(Loc, LHS, RHS); 12034 } 12035 12036 LHS = UsualUnaryConversions(LHS.get()); 12037 if (LHS.isInvalid()) 12038 return QualType(); 12039 12040 RHS = UsualUnaryConversions(RHS.get()); 12041 if (RHS.isInvalid()) 12042 return QualType(); 12043 12044 if (!LHS.get()->getType()->isScalarType() || 12045 !RHS.get()->getType()->isScalarType()) 12046 return InvalidOperands(Loc, LHS, RHS); 12047 12048 return Context.IntTy; 12049 } 12050 12051 // The following is safe because we only use this method for 12052 // non-overloadable operands. 12053 12054 // C++ [expr.log.and]p1 12055 // C++ [expr.log.or]p1 12056 // The operands are both contextually converted to type bool. 12057 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12058 if (LHSRes.isInvalid()) 12059 return InvalidOperands(Loc, LHS, RHS); 12060 LHS = LHSRes; 12061 12062 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12063 if (RHSRes.isInvalid()) 12064 return InvalidOperands(Loc, LHS, RHS); 12065 RHS = RHSRes; 12066 12067 // C++ [expr.log.and]p2 12068 // C++ [expr.log.or]p2 12069 // The result is a bool. 12070 return Context.BoolTy; 12071 } 12072 12073 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12074 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12075 if (!ME) return false; 12076 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12077 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12078 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12079 if (!Base) return false; 12080 return Base->getMethodDecl() != nullptr; 12081 } 12082 12083 /// Is the given expression (which must be 'const') a reference to a 12084 /// variable which was originally non-const, but which has become 12085 /// 'const' due to being captured within a block? 12086 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12087 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12088 assert(E->isLValue() && E->getType().isConstQualified()); 12089 E = E->IgnoreParens(); 12090 12091 // Must be a reference to a declaration from an enclosing scope. 12092 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12093 if (!DRE) return NCCK_None; 12094 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12095 12096 // The declaration must be a variable which is not declared 'const'. 12097 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12098 if (!var) return NCCK_None; 12099 if (var->getType().isConstQualified()) return NCCK_None; 12100 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12101 12102 // Decide whether the first capture was for a block or a lambda. 12103 DeclContext *DC = S.CurContext, *Prev = nullptr; 12104 // Decide whether the first capture was for a block or a lambda. 12105 while (DC) { 12106 // For init-capture, it is possible that the variable belongs to the 12107 // template pattern of the current context. 12108 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12109 if (var->isInitCapture() && 12110 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12111 break; 12112 if (DC == var->getDeclContext()) 12113 break; 12114 Prev = DC; 12115 DC = DC->getParent(); 12116 } 12117 // Unless we have an init-capture, we've gone one step too far. 12118 if (!var->isInitCapture()) 12119 DC = Prev; 12120 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12121 } 12122 12123 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12124 Ty = Ty.getNonReferenceType(); 12125 if (IsDereference && Ty->isPointerType()) 12126 Ty = Ty->getPointeeType(); 12127 return !Ty.isConstQualified(); 12128 } 12129 12130 // Update err_typecheck_assign_const and note_typecheck_assign_const 12131 // when this enum is changed. 12132 enum { 12133 ConstFunction, 12134 ConstVariable, 12135 ConstMember, 12136 ConstMethod, 12137 NestedConstMember, 12138 ConstUnknown, // Keep as last element 12139 }; 12140 12141 /// Emit the "read-only variable not assignable" error and print notes to give 12142 /// more information about why the variable is not assignable, such as pointing 12143 /// to the declaration of a const variable, showing that a method is const, or 12144 /// that the function is returning a const reference. 12145 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12146 SourceLocation Loc) { 12147 SourceRange ExprRange = E->getSourceRange(); 12148 12149 // Only emit one error on the first const found. All other consts will emit 12150 // a note to the error. 12151 bool DiagnosticEmitted = false; 12152 12153 // Track if the current expression is the result of a dereference, and if the 12154 // next checked expression is the result of a dereference. 12155 bool IsDereference = false; 12156 bool NextIsDereference = false; 12157 12158 // Loop to process MemberExpr chains. 12159 while (true) { 12160 IsDereference = NextIsDereference; 12161 12162 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12163 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12164 NextIsDereference = ME->isArrow(); 12165 const ValueDecl *VD = ME->getMemberDecl(); 12166 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12167 // Mutable fields can be modified even if the class is const. 12168 if (Field->isMutable()) { 12169 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12170 break; 12171 } 12172 12173 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12174 if (!DiagnosticEmitted) { 12175 S.Diag(Loc, diag::err_typecheck_assign_const) 12176 << ExprRange << ConstMember << false /*static*/ << Field 12177 << Field->getType(); 12178 DiagnosticEmitted = true; 12179 } 12180 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12181 << ConstMember << false /*static*/ << Field << Field->getType() 12182 << Field->getSourceRange(); 12183 } 12184 E = ME->getBase(); 12185 continue; 12186 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12187 if (VDecl->getType().isConstQualified()) { 12188 if (!DiagnosticEmitted) { 12189 S.Diag(Loc, diag::err_typecheck_assign_const) 12190 << ExprRange << ConstMember << true /*static*/ << VDecl 12191 << VDecl->getType(); 12192 DiagnosticEmitted = true; 12193 } 12194 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12195 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12196 << VDecl->getSourceRange(); 12197 } 12198 // Static fields do not inherit constness from parents. 12199 break; 12200 } 12201 break; // End MemberExpr 12202 } else if (const ArraySubscriptExpr *ASE = 12203 dyn_cast<ArraySubscriptExpr>(E)) { 12204 E = ASE->getBase()->IgnoreParenImpCasts(); 12205 continue; 12206 } else if (const ExtVectorElementExpr *EVE = 12207 dyn_cast<ExtVectorElementExpr>(E)) { 12208 E = EVE->getBase()->IgnoreParenImpCasts(); 12209 continue; 12210 } 12211 break; 12212 } 12213 12214 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12215 // Function calls 12216 const FunctionDecl *FD = CE->getDirectCallee(); 12217 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12218 if (!DiagnosticEmitted) { 12219 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12220 << ConstFunction << FD; 12221 DiagnosticEmitted = true; 12222 } 12223 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12224 diag::note_typecheck_assign_const) 12225 << ConstFunction << FD << FD->getReturnType() 12226 << FD->getReturnTypeSourceRange(); 12227 } 12228 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12229 // Point to variable declaration. 12230 if (const ValueDecl *VD = DRE->getDecl()) { 12231 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12232 if (!DiagnosticEmitted) { 12233 S.Diag(Loc, diag::err_typecheck_assign_const) 12234 << ExprRange << ConstVariable << VD << VD->getType(); 12235 DiagnosticEmitted = true; 12236 } 12237 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12238 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12239 } 12240 } 12241 } else if (isa<CXXThisExpr>(E)) { 12242 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12243 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12244 if (MD->isConst()) { 12245 if (!DiagnosticEmitted) { 12246 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12247 << ConstMethod << MD; 12248 DiagnosticEmitted = true; 12249 } 12250 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12251 << ConstMethod << MD << MD->getSourceRange(); 12252 } 12253 } 12254 } 12255 } 12256 12257 if (DiagnosticEmitted) 12258 return; 12259 12260 // Can't determine a more specific message, so display the generic error. 12261 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12262 } 12263 12264 enum OriginalExprKind { 12265 OEK_Variable, 12266 OEK_Member, 12267 OEK_LValue 12268 }; 12269 12270 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12271 const RecordType *Ty, 12272 SourceLocation Loc, SourceRange Range, 12273 OriginalExprKind OEK, 12274 bool &DiagnosticEmitted) { 12275 std::vector<const RecordType *> RecordTypeList; 12276 RecordTypeList.push_back(Ty); 12277 unsigned NextToCheckIndex = 0; 12278 // We walk the record hierarchy breadth-first to ensure that we print 12279 // diagnostics in field nesting order. 12280 while (RecordTypeList.size() > NextToCheckIndex) { 12281 bool IsNested = NextToCheckIndex > 0; 12282 for (const FieldDecl *Field : 12283 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12284 // First, check every field for constness. 12285 QualType FieldTy = Field->getType(); 12286 if (FieldTy.isConstQualified()) { 12287 if (!DiagnosticEmitted) { 12288 S.Diag(Loc, diag::err_typecheck_assign_const) 12289 << Range << NestedConstMember << OEK << VD 12290 << IsNested << Field; 12291 DiagnosticEmitted = true; 12292 } 12293 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12294 << NestedConstMember << IsNested << Field 12295 << FieldTy << Field->getSourceRange(); 12296 } 12297 12298 // Then we append it to the list to check next in order. 12299 FieldTy = FieldTy.getCanonicalType(); 12300 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12301 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12302 RecordTypeList.push_back(FieldRecTy); 12303 } 12304 } 12305 ++NextToCheckIndex; 12306 } 12307 } 12308 12309 /// Emit an error for the case where a record we are trying to assign to has a 12310 /// const-qualified field somewhere in its hierarchy. 12311 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12312 SourceLocation Loc) { 12313 QualType Ty = E->getType(); 12314 assert(Ty->isRecordType() && "lvalue was not record?"); 12315 SourceRange Range = E->getSourceRange(); 12316 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12317 bool DiagEmitted = false; 12318 12319 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12320 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12321 Range, OEK_Member, DiagEmitted); 12322 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12323 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12324 Range, OEK_Variable, DiagEmitted); 12325 else 12326 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12327 Range, OEK_LValue, DiagEmitted); 12328 if (!DiagEmitted) 12329 DiagnoseConstAssignment(S, E, Loc); 12330 } 12331 12332 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12333 /// emit an error and return true. If so, return false. 12334 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12335 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12336 12337 S.CheckShadowingDeclModification(E, Loc); 12338 12339 SourceLocation OrigLoc = Loc; 12340 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12341 &Loc); 12342 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12343 IsLV = Expr::MLV_InvalidMessageExpression; 12344 if (IsLV == Expr::MLV_Valid) 12345 return false; 12346 12347 unsigned DiagID = 0; 12348 bool NeedType = false; 12349 switch (IsLV) { // C99 6.5.16p2 12350 case Expr::MLV_ConstQualified: 12351 // Use a specialized diagnostic when we're assigning to an object 12352 // from an enclosing function or block. 12353 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12354 if (NCCK == NCCK_Block) 12355 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12356 else 12357 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12358 break; 12359 } 12360 12361 // In ARC, use some specialized diagnostics for occasions where we 12362 // infer 'const'. These are always pseudo-strong variables. 12363 if (S.getLangOpts().ObjCAutoRefCount) { 12364 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12365 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12366 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12367 12368 // Use the normal diagnostic if it's pseudo-__strong but the 12369 // user actually wrote 'const'. 12370 if (var->isARCPseudoStrong() && 12371 (!var->getTypeSourceInfo() || 12372 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12373 // There are three pseudo-strong cases: 12374 // - self 12375 ObjCMethodDecl *method = S.getCurMethodDecl(); 12376 if (method && var == method->getSelfDecl()) { 12377 DiagID = method->isClassMethod() 12378 ? diag::err_typecheck_arc_assign_self_class_method 12379 : diag::err_typecheck_arc_assign_self; 12380 12381 // - Objective-C externally_retained attribute. 12382 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12383 isa<ParmVarDecl>(var)) { 12384 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12385 12386 // - fast enumeration variables 12387 } else { 12388 DiagID = diag::err_typecheck_arr_assign_enumeration; 12389 } 12390 12391 SourceRange Assign; 12392 if (Loc != OrigLoc) 12393 Assign = SourceRange(OrigLoc, OrigLoc); 12394 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12395 // We need to preserve the AST regardless, so migration tool 12396 // can do its job. 12397 return false; 12398 } 12399 } 12400 } 12401 12402 // If none of the special cases above are triggered, then this is a 12403 // simple const assignment. 12404 if (DiagID == 0) { 12405 DiagnoseConstAssignment(S, E, Loc); 12406 return true; 12407 } 12408 12409 break; 12410 case Expr::MLV_ConstAddrSpace: 12411 DiagnoseConstAssignment(S, E, Loc); 12412 return true; 12413 case Expr::MLV_ConstQualifiedField: 12414 DiagnoseRecursiveConstFields(S, E, Loc); 12415 return true; 12416 case Expr::MLV_ArrayType: 12417 case Expr::MLV_ArrayTemporary: 12418 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12419 NeedType = true; 12420 break; 12421 case Expr::MLV_NotObjectType: 12422 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12423 NeedType = true; 12424 break; 12425 case Expr::MLV_LValueCast: 12426 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12427 break; 12428 case Expr::MLV_Valid: 12429 llvm_unreachable("did not take early return for MLV_Valid"); 12430 case Expr::MLV_InvalidExpression: 12431 case Expr::MLV_MemberFunction: 12432 case Expr::MLV_ClassTemporary: 12433 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12434 break; 12435 case Expr::MLV_IncompleteType: 12436 case Expr::MLV_IncompleteVoidType: 12437 return S.RequireCompleteType(Loc, E->getType(), 12438 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12439 case Expr::MLV_DuplicateVectorComponents: 12440 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12441 break; 12442 case Expr::MLV_NoSetterProperty: 12443 llvm_unreachable("readonly properties should be processed differently"); 12444 case Expr::MLV_InvalidMessageExpression: 12445 DiagID = diag::err_readonly_message_assignment; 12446 break; 12447 case Expr::MLV_SubObjCPropertySetting: 12448 DiagID = diag::err_no_subobject_property_setting; 12449 break; 12450 } 12451 12452 SourceRange Assign; 12453 if (Loc != OrigLoc) 12454 Assign = SourceRange(OrigLoc, OrigLoc); 12455 if (NeedType) 12456 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12457 else 12458 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12459 return true; 12460 } 12461 12462 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12463 SourceLocation Loc, 12464 Sema &Sema) { 12465 if (Sema.inTemplateInstantiation()) 12466 return; 12467 if (Sema.isUnevaluatedContext()) 12468 return; 12469 if (Loc.isInvalid() || Loc.isMacroID()) 12470 return; 12471 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12472 return; 12473 12474 // C / C++ fields 12475 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12476 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12477 if (ML && MR) { 12478 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12479 return; 12480 const ValueDecl *LHSDecl = 12481 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12482 const ValueDecl *RHSDecl = 12483 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12484 if (LHSDecl != RHSDecl) 12485 return; 12486 if (LHSDecl->getType().isVolatileQualified()) 12487 return; 12488 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12489 if (RefTy->getPointeeType().isVolatileQualified()) 12490 return; 12491 12492 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12493 } 12494 12495 // Objective-C instance variables 12496 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12497 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12498 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12499 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12500 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12501 if (RL && RR && RL->getDecl() == RR->getDecl()) 12502 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12503 } 12504 } 12505 12506 // C99 6.5.16.1 12507 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12508 SourceLocation Loc, 12509 QualType CompoundType) { 12510 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12511 12512 // Verify that LHS is a modifiable lvalue, and emit error if not. 12513 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12514 return QualType(); 12515 12516 QualType LHSType = LHSExpr->getType(); 12517 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12518 CompoundType; 12519 // OpenCL v1.2 s6.1.1.1 p2: 12520 // The half data type can only be used to declare a pointer to a buffer that 12521 // contains half values 12522 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12523 LHSType->isHalfType()) { 12524 Diag(Loc, diag::err_opencl_half_load_store) << 1 12525 << LHSType.getUnqualifiedType(); 12526 return QualType(); 12527 } 12528 12529 AssignConvertType ConvTy; 12530 if (CompoundType.isNull()) { 12531 Expr *RHSCheck = RHS.get(); 12532 12533 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12534 12535 QualType LHSTy(LHSType); 12536 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12537 if (RHS.isInvalid()) 12538 return QualType(); 12539 // Special case of NSObject attributes on c-style pointer types. 12540 if (ConvTy == IncompatiblePointer && 12541 ((Context.isObjCNSObjectType(LHSType) && 12542 RHSType->isObjCObjectPointerType()) || 12543 (Context.isObjCNSObjectType(RHSType) && 12544 LHSType->isObjCObjectPointerType()))) 12545 ConvTy = Compatible; 12546 12547 if (ConvTy == Compatible && 12548 LHSType->isObjCObjectType()) 12549 Diag(Loc, diag::err_objc_object_assignment) 12550 << LHSType; 12551 12552 // If the RHS is a unary plus or minus, check to see if they = and + are 12553 // right next to each other. If so, the user may have typo'd "x =+ 4" 12554 // instead of "x += 4". 12555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12556 RHSCheck = ICE->getSubExpr(); 12557 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12558 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12559 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12560 // Only if the two operators are exactly adjacent. 12561 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12562 // And there is a space or other character before the subexpr of the 12563 // unary +/-. We don't want to warn on "x=-1". 12564 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12565 UO->getSubExpr()->getBeginLoc().isFileID()) { 12566 Diag(Loc, diag::warn_not_compound_assign) 12567 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12568 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12569 } 12570 } 12571 12572 if (ConvTy == Compatible) { 12573 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12574 // Warn about retain cycles where a block captures the LHS, but 12575 // not if the LHS is a simple variable into which the block is 12576 // being stored...unless that variable can be captured by reference! 12577 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12578 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12579 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12580 checkRetainCycles(LHSExpr, RHS.get()); 12581 } 12582 12583 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12584 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12585 // It is safe to assign a weak reference into a strong variable. 12586 // Although this code can still have problems: 12587 // id x = self.weakProp; 12588 // id y = self.weakProp; 12589 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12590 // paths through the function. This should be revisited if 12591 // -Wrepeated-use-of-weak is made flow-sensitive. 12592 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12593 // variable, which will be valid for the current autorelease scope. 12594 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12595 RHS.get()->getBeginLoc())) 12596 getCurFunction()->markSafeWeakUse(RHS.get()); 12597 12598 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12599 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12600 } 12601 } 12602 } else { 12603 // Compound assignment "x += y" 12604 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12605 } 12606 12607 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12608 RHS.get(), AA_Assigning)) 12609 return QualType(); 12610 12611 CheckForNullPointerDereference(*this, LHSExpr); 12612 12613 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12614 if (CompoundType.isNull()) { 12615 // C++2a [expr.ass]p5: 12616 // A simple-assignment whose left operand is of a volatile-qualified 12617 // type is deprecated unless the assignment is either a discarded-value 12618 // expression or an unevaluated operand 12619 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12620 } else { 12621 // C++2a [expr.ass]p6: 12622 // [Compound-assignment] expressions are deprecated if E1 has 12623 // volatile-qualified type 12624 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12625 } 12626 } 12627 12628 // C99 6.5.16p3: The type of an assignment expression is the type of the 12629 // left operand unless the left operand has qualified type, in which case 12630 // it is the unqualified version of the type of the left operand. 12631 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12632 // is converted to the type of the assignment expression (above). 12633 // C++ 5.17p1: the type of the assignment expression is that of its left 12634 // operand. 12635 return (getLangOpts().CPlusPlus 12636 ? LHSType : LHSType.getUnqualifiedType()); 12637 } 12638 12639 // Only ignore explicit casts to void. 12640 static bool IgnoreCommaOperand(const Expr *E) { 12641 E = E->IgnoreParens(); 12642 12643 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12644 if (CE->getCastKind() == CK_ToVoid) { 12645 return true; 12646 } 12647 12648 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12649 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12650 CE->getSubExpr()->getType()->isDependentType()) { 12651 return true; 12652 } 12653 } 12654 12655 return false; 12656 } 12657 12658 // Look for instances where it is likely the comma operator is confused with 12659 // another operator. There is a whitelist of acceptable expressions for the 12660 // left hand side of the comma operator, otherwise emit a warning. 12661 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12662 // No warnings in macros 12663 if (Loc.isMacroID()) 12664 return; 12665 12666 // Don't warn in template instantiations. 12667 if (inTemplateInstantiation()) 12668 return; 12669 12670 // Scope isn't fine-grained enough to whitelist the specific cases, so 12671 // instead, skip more than needed, then call back into here with the 12672 // CommaVisitor in SemaStmt.cpp. 12673 // The whitelisted locations are the initialization and increment portions 12674 // of a for loop. The additional checks are on the condition of 12675 // if statements, do/while loops, and for loops. 12676 // Differences in scope flags for C89 mode requires the extra logic. 12677 const unsigned ForIncrementFlags = 12678 getLangOpts().C99 || getLangOpts().CPlusPlus 12679 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12680 : Scope::ContinueScope | Scope::BreakScope; 12681 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12682 const unsigned ScopeFlags = getCurScope()->getFlags(); 12683 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12684 (ScopeFlags & ForInitFlags) == ForInitFlags) 12685 return; 12686 12687 // If there are multiple comma operators used together, get the RHS of the 12688 // of the comma operator as the LHS. 12689 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12690 if (BO->getOpcode() != BO_Comma) 12691 break; 12692 LHS = BO->getRHS(); 12693 } 12694 12695 // Only allow some expressions on LHS to not warn. 12696 if (IgnoreCommaOperand(LHS)) 12697 return; 12698 12699 Diag(Loc, diag::warn_comma_operator); 12700 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12701 << LHS->getSourceRange() 12702 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12703 LangOpts.CPlusPlus ? "static_cast<void>(" 12704 : "(void)(") 12705 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12706 ")"); 12707 } 12708 12709 // C99 6.5.17 12710 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12711 SourceLocation Loc) { 12712 LHS = S.CheckPlaceholderExpr(LHS.get()); 12713 RHS = S.CheckPlaceholderExpr(RHS.get()); 12714 if (LHS.isInvalid() || RHS.isInvalid()) 12715 return QualType(); 12716 12717 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12718 // operands, but not unary promotions. 12719 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12720 12721 // So we treat the LHS as a ignored value, and in C++ we allow the 12722 // containing site to determine what should be done with the RHS. 12723 LHS = S.IgnoredValueConversions(LHS.get()); 12724 if (LHS.isInvalid()) 12725 return QualType(); 12726 12727 S.DiagnoseUnusedExprResult(LHS.get()); 12728 12729 if (!S.getLangOpts().CPlusPlus) { 12730 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12731 if (RHS.isInvalid()) 12732 return QualType(); 12733 if (!RHS.get()->getType()->isVoidType()) 12734 S.RequireCompleteType(Loc, RHS.get()->getType(), 12735 diag::err_incomplete_type); 12736 } 12737 12738 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12739 S.DiagnoseCommaOperator(LHS.get(), Loc); 12740 12741 return RHS.get()->getType(); 12742 } 12743 12744 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12745 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12746 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12747 ExprValueKind &VK, 12748 ExprObjectKind &OK, 12749 SourceLocation OpLoc, 12750 bool IsInc, bool IsPrefix) { 12751 if (Op->isTypeDependent()) 12752 return S.Context.DependentTy; 12753 12754 QualType ResType = Op->getType(); 12755 // Atomic types can be used for increment / decrement where the non-atomic 12756 // versions can, so ignore the _Atomic() specifier for the purpose of 12757 // checking. 12758 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12759 ResType = ResAtomicType->getValueType(); 12760 12761 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12762 12763 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12764 // Decrement of bool is not allowed. 12765 if (!IsInc) { 12766 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12767 return QualType(); 12768 } 12769 // Increment of bool sets it to true, but is deprecated. 12770 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12771 : diag::warn_increment_bool) 12772 << Op->getSourceRange(); 12773 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12774 // Error on enum increments and decrements in C++ mode 12775 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12776 return QualType(); 12777 } else if (ResType->isRealType()) { 12778 // OK! 12779 } else if (ResType->isPointerType()) { 12780 // C99 6.5.2.4p2, 6.5.6p2 12781 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12782 return QualType(); 12783 } else if (ResType->isObjCObjectPointerType()) { 12784 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12785 // Otherwise, we just need a complete type. 12786 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12787 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12788 return QualType(); 12789 } else if (ResType->isAnyComplexType()) { 12790 // C99 does not support ++/-- on complex types, we allow as an extension. 12791 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12792 << ResType << Op->getSourceRange(); 12793 } else if (ResType->isPlaceholderType()) { 12794 ExprResult PR = S.CheckPlaceholderExpr(Op); 12795 if (PR.isInvalid()) return QualType(); 12796 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12797 IsInc, IsPrefix); 12798 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12799 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12800 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12801 (ResType->castAs<VectorType>()->getVectorKind() != 12802 VectorType::AltiVecBool)) { 12803 // The z vector extensions allow ++ and -- for non-bool vectors. 12804 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12805 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12806 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12807 } else { 12808 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12809 << ResType << int(IsInc) << Op->getSourceRange(); 12810 return QualType(); 12811 } 12812 // At this point, we know we have a real, complex or pointer type. 12813 // Now make sure the operand is a modifiable lvalue. 12814 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12815 return QualType(); 12816 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 12817 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12818 // An operand with volatile-qualified type is deprecated 12819 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12820 << IsInc << ResType; 12821 } 12822 // In C++, a prefix increment is the same type as the operand. Otherwise 12823 // (in C or with postfix), the increment is the unqualified type of the 12824 // operand. 12825 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12826 VK = VK_LValue; 12827 OK = Op->getObjectKind(); 12828 return ResType; 12829 } else { 12830 VK = VK_RValue; 12831 return ResType.getUnqualifiedType(); 12832 } 12833 } 12834 12835 12836 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12837 /// This routine allows us to typecheck complex/recursive expressions 12838 /// where the declaration is needed for type checking. We only need to 12839 /// handle cases when the expression references a function designator 12840 /// or is an lvalue. Here are some examples: 12841 /// - &(x) => x 12842 /// - &*****f => f for f a function designator. 12843 /// - &s.xx => s 12844 /// - &s.zz[1].yy -> s, if zz is an array 12845 /// - *(x + 1) -> x, if x is an array 12846 /// - &"123"[2] -> 0 12847 /// - & __real__ x -> x 12848 /// 12849 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 12850 /// members. 12851 static ValueDecl *getPrimaryDecl(Expr *E) { 12852 switch (E->getStmtClass()) { 12853 case Stmt::DeclRefExprClass: 12854 return cast<DeclRefExpr>(E)->getDecl(); 12855 case Stmt::MemberExprClass: 12856 // If this is an arrow operator, the address is an offset from 12857 // the base's value, so the object the base refers to is 12858 // irrelevant. 12859 if (cast<MemberExpr>(E)->isArrow()) 12860 return nullptr; 12861 // Otherwise, the expression refers to a part of the base 12862 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12863 case Stmt::ArraySubscriptExprClass: { 12864 // FIXME: This code shouldn't be necessary! We should catch the implicit 12865 // promotion of register arrays earlier. 12866 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12867 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12868 if (ICE->getSubExpr()->getType()->isArrayType()) 12869 return getPrimaryDecl(ICE->getSubExpr()); 12870 } 12871 return nullptr; 12872 } 12873 case Stmt::UnaryOperatorClass: { 12874 UnaryOperator *UO = cast<UnaryOperator>(E); 12875 12876 switch(UO->getOpcode()) { 12877 case UO_Real: 12878 case UO_Imag: 12879 case UO_Extension: 12880 return getPrimaryDecl(UO->getSubExpr()); 12881 default: 12882 return nullptr; 12883 } 12884 } 12885 case Stmt::ParenExprClass: 12886 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12887 case Stmt::ImplicitCastExprClass: 12888 // If the result of an implicit cast is an l-value, we care about 12889 // the sub-expression; otherwise, the result here doesn't matter. 12890 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12891 case Stmt::CXXUuidofExprClass: 12892 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 12893 default: 12894 return nullptr; 12895 } 12896 } 12897 12898 namespace { 12899 enum { 12900 AO_Bit_Field = 0, 12901 AO_Vector_Element = 1, 12902 AO_Property_Expansion = 2, 12903 AO_Register_Variable = 3, 12904 AO_No_Error = 4 12905 }; 12906 } 12907 /// Diagnose invalid operand for address of operations. 12908 /// 12909 /// \param Type The type of operand which cannot have its address taken. 12910 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12911 Expr *E, unsigned Type) { 12912 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12913 } 12914 12915 /// CheckAddressOfOperand - The operand of & must be either a function 12916 /// designator or an lvalue designating an object. If it is an lvalue, the 12917 /// object cannot be declared with storage class register or be a bit field. 12918 /// Note: The usual conversions are *not* applied to the operand of the & 12919 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12920 /// In C++, the operand might be an overloaded function name, in which case 12921 /// we allow the '&' but retain the overloaded-function type. 12922 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12923 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12924 if (PTy->getKind() == BuiltinType::Overload) { 12925 Expr *E = OrigOp.get()->IgnoreParens(); 12926 if (!isa<OverloadExpr>(E)) { 12927 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12928 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12929 << OrigOp.get()->getSourceRange(); 12930 return QualType(); 12931 } 12932 12933 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12934 if (isa<UnresolvedMemberExpr>(Ovl)) 12935 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12936 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12937 << OrigOp.get()->getSourceRange(); 12938 return QualType(); 12939 } 12940 12941 return Context.OverloadTy; 12942 } 12943 12944 if (PTy->getKind() == BuiltinType::UnknownAny) 12945 return Context.UnknownAnyTy; 12946 12947 if (PTy->getKind() == BuiltinType::BoundMember) { 12948 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12949 << OrigOp.get()->getSourceRange(); 12950 return QualType(); 12951 } 12952 12953 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12954 if (OrigOp.isInvalid()) return QualType(); 12955 } 12956 12957 if (OrigOp.get()->isTypeDependent()) 12958 return Context.DependentTy; 12959 12960 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12961 12962 // Make sure to ignore parentheses in subsequent checks 12963 Expr *op = OrigOp.get()->IgnoreParens(); 12964 12965 // In OpenCL captures for blocks called as lambda functions 12966 // are located in the private address space. Blocks used in 12967 // enqueue_kernel can be located in a different address space 12968 // depending on a vendor implementation. Thus preventing 12969 // taking an address of the capture to avoid invalid AS casts. 12970 if (LangOpts.OpenCL) { 12971 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12972 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12973 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12974 return QualType(); 12975 } 12976 } 12977 12978 if (getLangOpts().C99) { 12979 // Implement C99-only parts of addressof rules. 12980 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12981 if (uOp->getOpcode() == UO_Deref) 12982 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12983 // (assuming the deref expression is valid). 12984 return uOp->getSubExpr()->getType(); 12985 } 12986 // Technically, there should be a check for array subscript 12987 // expressions here, but the result of one is always an lvalue anyway. 12988 } 12989 ValueDecl *dcl = getPrimaryDecl(op); 12990 12991 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12992 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12993 op->getBeginLoc())) 12994 return QualType(); 12995 12996 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12997 unsigned AddressOfError = AO_No_Error; 12998 12999 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13000 bool sfinae = (bool)isSFINAEContext(); 13001 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13002 : diag::ext_typecheck_addrof_temporary) 13003 << op->getType() << op->getSourceRange(); 13004 if (sfinae) 13005 return QualType(); 13006 // Materialize the temporary as an lvalue so that we can take its address. 13007 OrigOp = op = 13008 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13009 } else if (isa<ObjCSelectorExpr>(op)) { 13010 return Context.getPointerType(op->getType()); 13011 } else if (lval == Expr::LV_MemberFunction) { 13012 // If it's an instance method, make a member pointer. 13013 // The expression must have exactly the form &A::foo. 13014 13015 // If the underlying expression isn't a decl ref, give up. 13016 if (!isa<DeclRefExpr>(op)) { 13017 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13018 << OrigOp.get()->getSourceRange(); 13019 return QualType(); 13020 } 13021 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13022 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13023 13024 // The id-expression was parenthesized. 13025 if (OrigOp.get() != DRE) { 13026 Diag(OpLoc, diag::err_parens_pointer_member_function) 13027 << OrigOp.get()->getSourceRange(); 13028 13029 // The method was named without a qualifier. 13030 } else if (!DRE->getQualifier()) { 13031 if (MD->getParent()->getName().empty()) 13032 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13033 << op->getSourceRange(); 13034 else { 13035 SmallString<32> Str; 13036 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13037 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13038 << op->getSourceRange() 13039 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13040 } 13041 } 13042 13043 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13044 if (isa<CXXDestructorDecl>(MD)) 13045 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13046 13047 QualType MPTy = Context.getMemberPointerType( 13048 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13049 // Under the MS ABI, lock down the inheritance model now. 13050 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13051 (void)isCompleteType(OpLoc, MPTy); 13052 return MPTy; 13053 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13054 // C99 6.5.3.2p1 13055 // The operand must be either an l-value or a function designator 13056 if (!op->getType()->isFunctionType()) { 13057 // Use a special diagnostic for loads from property references. 13058 if (isa<PseudoObjectExpr>(op)) { 13059 AddressOfError = AO_Property_Expansion; 13060 } else { 13061 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13062 << op->getType() << op->getSourceRange(); 13063 return QualType(); 13064 } 13065 } 13066 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13067 // The operand cannot be a bit-field 13068 AddressOfError = AO_Bit_Field; 13069 } else if (op->getObjectKind() == OK_VectorComponent) { 13070 // The operand cannot be an element of a vector 13071 AddressOfError = AO_Vector_Element; 13072 } else if (dcl) { // C99 6.5.3.2p1 13073 // We have an lvalue with a decl. Make sure the decl is not declared 13074 // with the register storage-class specifier. 13075 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13076 // in C++ it is not error to take address of a register 13077 // variable (c++03 7.1.1P3) 13078 if (vd->getStorageClass() == SC_Register && 13079 !getLangOpts().CPlusPlus) { 13080 AddressOfError = AO_Register_Variable; 13081 } 13082 } else if (isa<MSPropertyDecl>(dcl)) { 13083 AddressOfError = AO_Property_Expansion; 13084 } else if (isa<FunctionTemplateDecl>(dcl)) { 13085 return Context.OverloadTy; 13086 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13087 // Okay: we can take the address of a field. 13088 // Could be a pointer to member, though, if there is an explicit 13089 // scope qualifier for the class. 13090 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13091 DeclContext *Ctx = dcl->getDeclContext(); 13092 if (Ctx && Ctx->isRecord()) { 13093 if (dcl->getType()->isReferenceType()) { 13094 Diag(OpLoc, 13095 diag::err_cannot_form_pointer_to_member_of_reference_type) 13096 << dcl->getDeclName() << dcl->getType(); 13097 return QualType(); 13098 } 13099 13100 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13101 Ctx = Ctx->getParent(); 13102 13103 QualType MPTy = Context.getMemberPointerType( 13104 op->getType(), 13105 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13106 // Under the MS ABI, lock down the inheritance model now. 13107 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13108 (void)isCompleteType(OpLoc, MPTy); 13109 return MPTy; 13110 } 13111 } 13112 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13113 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13114 llvm_unreachable("Unknown/unexpected decl type"); 13115 } 13116 13117 if (AddressOfError != AO_No_Error) { 13118 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13119 return QualType(); 13120 } 13121 13122 if (lval == Expr::LV_IncompleteVoidType) { 13123 // Taking the address of a void variable is technically illegal, but we 13124 // allow it in cases which are otherwise valid. 13125 // Example: "extern void x; void* y = &x;". 13126 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13127 } 13128 13129 // If the operand has type "type", the result has type "pointer to type". 13130 if (op->getType()->isObjCObjectType()) 13131 return Context.getObjCObjectPointerType(op->getType()); 13132 13133 CheckAddressOfPackedMember(op); 13134 13135 return Context.getPointerType(op->getType()); 13136 } 13137 13138 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13139 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13140 if (!DRE) 13141 return; 13142 const Decl *D = DRE->getDecl(); 13143 if (!D) 13144 return; 13145 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13146 if (!Param) 13147 return; 13148 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13149 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13150 return; 13151 if (FunctionScopeInfo *FD = S.getCurFunction()) 13152 if (!FD->ModifiedNonNullParams.count(Param)) 13153 FD->ModifiedNonNullParams.insert(Param); 13154 } 13155 13156 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13157 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13158 SourceLocation OpLoc) { 13159 if (Op->isTypeDependent()) 13160 return S.Context.DependentTy; 13161 13162 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13163 if (ConvResult.isInvalid()) 13164 return QualType(); 13165 Op = ConvResult.get(); 13166 QualType OpTy = Op->getType(); 13167 QualType Result; 13168 13169 if (isa<CXXReinterpretCastExpr>(Op)) { 13170 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13171 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13172 Op->getSourceRange()); 13173 } 13174 13175 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13176 { 13177 Result = PT->getPointeeType(); 13178 } 13179 else if (const ObjCObjectPointerType *OPT = 13180 OpTy->getAs<ObjCObjectPointerType>()) 13181 Result = OPT->getPointeeType(); 13182 else { 13183 ExprResult PR = S.CheckPlaceholderExpr(Op); 13184 if (PR.isInvalid()) return QualType(); 13185 if (PR.get() != Op) 13186 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13187 } 13188 13189 if (Result.isNull()) { 13190 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13191 << OpTy << Op->getSourceRange(); 13192 return QualType(); 13193 } 13194 13195 // Note that per both C89 and C99, indirection is always legal, even if Result 13196 // is an incomplete type or void. It would be possible to warn about 13197 // dereferencing a void pointer, but it's completely well-defined, and such a 13198 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13199 // for pointers to 'void' but is fine for any other pointer type: 13200 // 13201 // C++ [expr.unary.op]p1: 13202 // [...] the expression to which [the unary * operator] is applied shall 13203 // be a pointer to an object type, or a pointer to a function type 13204 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13205 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13206 << OpTy << Op->getSourceRange(); 13207 13208 // Dereferences are usually l-values... 13209 VK = VK_LValue; 13210 13211 // ...except that certain expressions are never l-values in C. 13212 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13213 VK = VK_RValue; 13214 13215 return Result; 13216 } 13217 13218 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13219 BinaryOperatorKind Opc; 13220 switch (Kind) { 13221 default: llvm_unreachable("Unknown binop!"); 13222 case tok::periodstar: Opc = BO_PtrMemD; break; 13223 case tok::arrowstar: Opc = BO_PtrMemI; break; 13224 case tok::star: Opc = BO_Mul; break; 13225 case tok::slash: Opc = BO_Div; break; 13226 case tok::percent: Opc = BO_Rem; break; 13227 case tok::plus: Opc = BO_Add; break; 13228 case tok::minus: Opc = BO_Sub; break; 13229 case tok::lessless: Opc = BO_Shl; break; 13230 case tok::greatergreater: Opc = BO_Shr; break; 13231 case tok::lessequal: Opc = BO_LE; break; 13232 case tok::less: Opc = BO_LT; break; 13233 case tok::greaterequal: Opc = BO_GE; break; 13234 case tok::greater: Opc = BO_GT; break; 13235 case tok::exclaimequal: Opc = BO_NE; break; 13236 case tok::equalequal: Opc = BO_EQ; break; 13237 case tok::spaceship: Opc = BO_Cmp; break; 13238 case tok::amp: Opc = BO_And; break; 13239 case tok::caret: Opc = BO_Xor; break; 13240 case tok::pipe: Opc = BO_Or; break; 13241 case tok::ampamp: Opc = BO_LAnd; break; 13242 case tok::pipepipe: Opc = BO_LOr; break; 13243 case tok::equal: Opc = BO_Assign; break; 13244 case tok::starequal: Opc = BO_MulAssign; break; 13245 case tok::slashequal: Opc = BO_DivAssign; break; 13246 case tok::percentequal: Opc = BO_RemAssign; break; 13247 case tok::plusequal: Opc = BO_AddAssign; break; 13248 case tok::minusequal: Opc = BO_SubAssign; break; 13249 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13250 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13251 case tok::ampequal: Opc = BO_AndAssign; break; 13252 case tok::caretequal: Opc = BO_XorAssign; break; 13253 case tok::pipeequal: Opc = BO_OrAssign; break; 13254 case tok::comma: Opc = BO_Comma; break; 13255 } 13256 return Opc; 13257 } 13258 13259 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13260 tok::TokenKind Kind) { 13261 UnaryOperatorKind Opc; 13262 switch (Kind) { 13263 default: llvm_unreachable("Unknown unary op!"); 13264 case tok::plusplus: Opc = UO_PreInc; break; 13265 case tok::minusminus: Opc = UO_PreDec; break; 13266 case tok::amp: Opc = UO_AddrOf; break; 13267 case tok::star: Opc = UO_Deref; break; 13268 case tok::plus: Opc = UO_Plus; break; 13269 case tok::minus: Opc = UO_Minus; break; 13270 case tok::tilde: Opc = UO_Not; break; 13271 case tok::exclaim: Opc = UO_LNot; break; 13272 case tok::kw___real: Opc = UO_Real; break; 13273 case tok::kw___imag: Opc = UO_Imag; break; 13274 case tok::kw___extension__: Opc = UO_Extension; break; 13275 } 13276 return Opc; 13277 } 13278 13279 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13280 /// This warning suppressed in the event of macro expansions. 13281 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13282 SourceLocation OpLoc, bool IsBuiltin) { 13283 if (S.inTemplateInstantiation()) 13284 return; 13285 if (S.isUnevaluatedContext()) 13286 return; 13287 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13288 return; 13289 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13290 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13291 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13292 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13293 if (!LHSDeclRef || !RHSDeclRef || 13294 LHSDeclRef->getLocation().isMacroID() || 13295 RHSDeclRef->getLocation().isMacroID()) 13296 return; 13297 const ValueDecl *LHSDecl = 13298 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13299 const ValueDecl *RHSDecl = 13300 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13301 if (LHSDecl != RHSDecl) 13302 return; 13303 if (LHSDecl->getType().isVolatileQualified()) 13304 return; 13305 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13306 if (RefTy->getPointeeType().isVolatileQualified()) 13307 return; 13308 13309 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13310 : diag::warn_self_assignment_overloaded) 13311 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13312 << RHSExpr->getSourceRange(); 13313 } 13314 13315 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13316 /// is usually indicative of introspection within the Objective-C pointer. 13317 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13318 SourceLocation OpLoc) { 13319 if (!S.getLangOpts().ObjC) 13320 return; 13321 13322 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13323 const Expr *LHS = L.get(); 13324 const Expr *RHS = R.get(); 13325 13326 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13327 ObjCPointerExpr = LHS; 13328 OtherExpr = RHS; 13329 } 13330 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13331 ObjCPointerExpr = RHS; 13332 OtherExpr = LHS; 13333 } 13334 13335 // This warning is deliberately made very specific to reduce false 13336 // positives with logic that uses '&' for hashing. This logic mainly 13337 // looks for code trying to introspect into tagged pointers, which 13338 // code should generally never do. 13339 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13340 unsigned Diag = diag::warn_objc_pointer_masking; 13341 // Determine if we are introspecting the result of performSelectorXXX. 13342 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13343 // Special case messages to -performSelector and friends, which 13344 // can return non-pointer values boxed in a pointer value. 13345 // Some clients may wish to silence warnings in this subcase. 13346 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13347 Selector S = ME->getSelector(); 13348 StringRef SelArg0 = S.getNameForSlot(0); 13349 if (SelArg0.startswith("performSelector")) 13350 Diag = diag::warn_objc_pointer_masking_performSelector; 13351 } 13352 13353 S.Diag(OpLoc, Diag) 13354 << ObjCPointerExpr->getSourceRange(); 13355 } 13356 } 13357 13358 static NamedDecl *getDeclFromExpr(Expr *E) { 13359 if (!E) 13360 return nullptr; 13361 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13362 return DRE->getDecl(); 13363 if (auto *ME = dyn_cast<MemberExpr>(E)) 13364 return ME->getMemberDecl(); 13365 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13366 return IRE->getDecl(); 13367 return nullptr; 13368 } 13369 13370 // This helper function promotes a binary operator's operands (which are of a 13371 // half vector type) to a vector of floats and then truncates the result to 13372 // a vector of either half or short. 13373 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13374 BinaryOperatorKind Opc, QualType ResultTy, 13375 ExprValueKind VK, ExprObjectKind OK, 13376 bool IsCompAssign, SourceLocation OpLoc, 13377 FPOptions FPFeatures) { 13378 auto &Context = S.getASTContext(); 13379 assert((isVector(ResultTy, Context.HalfTy) || 13380 isVector(ResultTy, Context.ShortTy)) && 13381 "Result must be a vector of half or short"); 13382 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13383 isVector(RHS.get()->getType(), Context.HalfTy) && 13384 "both operands expected to be a half vector"); 13385 13386 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13387 QualType BinOpResTy = RHS.get()->getType(); 13388 13389 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13390 // change BinOpResTy to a vector of ints. 13391 if (isVector(ResultTy, Context.ShortTy)) 13392 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13393 13394 if (IsCompAssign) 13395 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13396 ResultTy, VK, OK, OpLoc, FPFeatures, 13397 BinOpResTy, BinOpResTy); 13398 13399 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13400 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13401 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13402 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13403 } 13404 13405 static std::pair<ExprResult, ExprResult> 13406 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13407 Expr *RHSExpr) { 13408 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13409 if (!S.getLangOpts().CPlusPlus) { 13410 // C cannot handle TypoExpr nodes on either side of a binop because it 13411 // doesn't handle dependent types properly, so make sure any TypoExprs have 13412 // been dealt with before checking the operands. 13413 LHS = S.CorrectDelayedTyposInExpr(LHS); 13414 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 13415 if (Opc != BO_Assign) 13416 return ExprResult(E); 13417 // Avoid correcting the RHS to the same Expr as the LHS. 13418 Decl *D = getDeclFromExpr(E); 13419 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13420 }); 13421 } 13422 return std::make_pair(LHS, RHS); 13423 } 13424 13425 /// Returns true if conversion between vectors of halfs and vectors of floats 13426 /// is needed. 13427 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13428 Expr *E0, Expr *E1 = nullptr) { 13429 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13430 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13431 return false; 13432 13433 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13434 QualType Ty = E->IgnoreImplicit()->getType(); 13435 13436 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13437 // to vectors of floats. Although the element type of the vectors is __fp16, 13438 // the vectors shouldn't be treated as storage-only types. See the 13439 // discussion here: https://reviews.llvm.org/rG825235c140e7 13440 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13441 if (VT->getVectorKind() == VectorType::NeonVector) 13442 return false; 13443 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13444 } 13445 return false; 13446 }; 13447 13448 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13449 } 13450 13451 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13452 /// operator @p Opc at location @c TokLoc. This routine only supports 13453 /// built-in operations; ActOnBinOp handles overloaded operators. 13454 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13455 BinaryOperatorKind Opc, 13456 Expr *LHSExpr, Expr *RHSExpr) { 13457 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13458 // The syntax only allows initializer lists on the RHS of assignment, 13459 // so we don't need to worry about accepting invalid code for 13460 // non-assignment operators. 13461 // C++11 5.17p9: 13462 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13463 // of x = {} is x = T(). 13464 InitializationKind Kind = InitializationKind::CreateDirectList( 13465 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13466 InitializedEntity Entity = 13467 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13468 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13469 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13470 if (Init.isInvalid()) 13471 return Init; 13472 RHSExpr = Init.get(); 13473 } 13474 13475 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13476 QualType ResultTy; // Result type of the binary operator. 13477 // The following two variables are used for compound assignment operators 13478 QualType CompLHSTy; // Type of LHS after promotions for computation 13479 QualType CompResultTy; // Type of computation result 13480 ExprValueKind VK = VK_RValue; 13481 ExprObjectKind OK = OK_Ordinary; 13482 bool ConvertHalfVec = false; 13483 13484 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13485 if (!LHS.isUsable() || !RHS.isUsable()) 13486 return ExprError(); 13487 13488 if (getLangOpts().OpenCL) { 13489 QualType LHSTy = LHSExpr->getType(); 13490 QualType RHSTy = RHSExpr->getType(); 13491 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13492 // the ATOMIC_VAR_INIT macro. 13493 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13494 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13495 if (BO_Assign == Opc) 13496 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13497 else 13498 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13499 return ExprError(); 13500 } 13501 13502 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13503 // only with a builtin functions and therefore should be disallowed here. 13504 if (LHSTy->isImageType() || RHSTy->isImageType() || 13505 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13506 LHSTy->isPipeType() || RHSTy->isPipeType() || 13507 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13508 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13509 return ExprError(); 13510 } 13511 } 13512 13513 // Diagnose operations on the unsupported types for OpenMP device compilation. 13514 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13515 if (Opc != BO_Assign && Opc != BO_Comma) { 13516 checkOpenMPDeviceExpr(LHSExpr); 13517 checkOpenMPDeviceExpr(RHSExpr); 13518 } 13519 } 13520 13521 switch (Opc) { 13522 case BO_Assign: 13523 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13524 if (getLangOpts().CPlusPlus && 13525 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13526 VK = LHS.get()->getValueKind(); 13527 OK = LHS.get()->getObjectKind(); 13528 } 13529 if (!ResultTy.isNull()) { 13530 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13531 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13532 13533 // Avoid copying a block to the heap if the block is assigned to a local 13534 // auto variable that is declared in the same scope as the block. This 13535 // optimization is unsafe if the local variable is declared in an outer 13536 // scope. For example: 13537 // 13538 // BlockTy b; 13539 // { 13540 // b = ^{...}; 13541 // } 13542 // // It is unsafe to invoke the block here if it wasn't copied to the 13543 // // heap. 13544 // b(); 13545 13546 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13547 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13548 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13549 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13550 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13551 13552 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13553 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13554 NTCUC_Assignment, NTCUK_Copy); 13555 } 13556 RecordModifiableNonNullParam(*this, LHS.get()); 13557 break; 13558 case BO_PtrMemD: 13559 case BO_PtrMemI: 13560 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13561 Opc == BO_PtrMemI); 13562 break; 13563 case BO_Mul: 13564 case BO_Div: 13565 ConvertHalfVec = true; 13566 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13567 Opc == BO_Div); 13568 break; 13569 case BO_Rem: 13570 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13571 break; 13572 case BO_Add: 13573 ConvertHalfVec = true; 13574 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13575 break; 13576 case BO_Sub: 13577 ConvertHalfVec = true; 13578 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13579 break; 13580 case BO_Shl: 13581 case BO_Shr: 13582 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13583 break; 13584 case BO_LE: 13585 case BO_LT: 13586 case BO_GE: 13587 case BO_GT: 13588 ConvertHalfVec = true; 13589 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13590 break; 13591 case BO_EQ: 13592 case BO_NE: 13593 ConvertHalfVec = true; 13594 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13595 break; 13596 case BO_Cmp: 13597 ConvertHalfVec = true; 13598 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13599 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13600 break; 13601 case BO_And: 13602 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13603 LLVM_FALLTHROUGH; 13604 case BO_Xor: 13605 case BO_Or: 13606 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13607 break; 13608 case BO_LAnd: 13609 case BO_LOr: 13610 ConvertHalfVec = true; 13611 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13612 break; 13613 case BO_MulAssign: 13614 case BO_DivAssign: 13615 ConvertHalfVec = true; 13616 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13617 Opc == BO_DivAssign); 13618 CompLHSTy = CompResultTy; 13619 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13620 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13621 break; 13622 case BO_RemAssign: 13623 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13624 CompLHSTy = CompResultTy; 13625 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13626 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13627 break; 13628 case BO_AddAssign: 13629 ConvertHalfVec = true; 13630 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13631 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13632 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13633 break; 13634 case BO_SubAssign: 13635 ConvertHalfVec = true; 13636 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13637 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13638 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13639 break; 13640 case BO_ShlAssign: 13641 case BO_ShrAssign: 13642 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13643 CompLHSTy = CompResultTy; 13644 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13645 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13646 break; 13647 case BO_AndAssign: 13648 case BO_OrAssign: // fallthrough 13649 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13650 LLVM_FALLTHROUGH; 13651 case BO_XorAssign: 13652 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13653 CompLHSTy = CompResultTy; 13654 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13655 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13656 break; 13657 case BO_Comma: 13658 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13659 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13660 VK = RHS.get()->getValueKind(); 13661 OK = RHS.get()->getObjectKind(); 13662 } 13663 break; 13664 } 13665 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13666 return ExprError(); 13667 13668 // Some of the binary operations require promoting operands of half vector to 13669 // float vectors and truncating the result back to half vector. For now, we do 13670 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13671 // arm64). 13672 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13673 isVector(LHS.get()->getType(), Context.HalfTy) && 13674 "both sides are half vectors or neither sides are"); 13675 ConvertHalfVec = 13676 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13677 13678 // Check for array bounds violations for both sides of the BinaryOperator 13679 CheckArrayAccess(LHS.get()); 13680 CheckArrayAccess(RHS.get()); 13681 13682 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13683 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13684 &Context.Idents.get("object_setClass"), 13685 SourceLocation(), LookupOrdinaryName); 13686 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13687 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13688 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13689 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13690 "object_setClass(") 13691 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13692 ",") 13693 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13694 } 13695 else 13696 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13697 } 13698 else if (const ObjCIvarRefExpr *OIRE = 13699 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13700 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13701 13702 // Opc is not a compound assignment if CompResultTy is null. 13703 if (CompResultTy.isNull()) { 13704 if (ConvertHalfVec) 13705 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13706 OpLoc, CurFPFeatures); 13707 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13708 VK, OK, OpLoc, CurFPFeatures); 13709 } 13710 13711 // Handle compound assignments. 13712 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13713 OK_ObjCProperty) { 13714 VK = VK_LValue; 13715 OK = LHS.get()->getObjectKind(); 13716 } 13717 13718 // The LHS is not converted to the result type for fixed-point compound 13719 // assignment as the common type is computed on demand. Reset the CompLHSTy 13720 // to the LHS type we would have gotten after unary conversions. 13721 if (CompResultTy->isFixedPointType()) 13722 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13723 13724 if (ConvertHalfVec) 13725 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13726 OpLoc, CurFPFeatures); 13727 13728 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13729 ResultTy, VK, OK, OpLoc, CurFPFeatures, 13730 CompLHSTy, CompResultTy); 13731 } 13732 13733 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13734 /// operators are mixed in a way that suggests that the programmer forgot that 13735 /// comparison operators have higher precedence. The most typical example of 13736 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13737 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13738 SourceLocation OpLoc, Expr *LHSExpr, 13739 Expr *RHSExpr) { 13740 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13741 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13742 13743 // Check that one of the sides is a comparison operator and the other isn't. 13744 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13745 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13746 if (isLeftComp == isRightComp) 13747 return; 13748 13749 // Bitwise operations are sometimes used as eager logical ops. 13750 // Don't diagnose this. 13751 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13752 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13753 if (isLeftBitwise || isRightBitwise) 13754 return; 13755 13756 SourceRange DiagRange = isLeftComp 13757 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13758 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13759 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13760 SourceRange ParensRange = 13761 isLeftComp 13762 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13763 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13764 13765 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13766 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13767 SuggestParentheses(Self, OpLoc, 13768 Self.PDiag(diag::note_precedence_silence) << OpStr, 13769 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13770 SuggestParentheses(Self, OpLoc, 13771 Self.PDiag(diag::note_precedence_bitwise_first) 13772 << BinaryOperator::getOpcodeStr(Opc), 13773 ParensRange); 13774 } 13775 13776 /// It accepts a '&&' expr that is inside a '||' one. 13777 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13778 /// in parentheses. 13779 static void 13780 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13781 BinaryOperator *Bop) { 13782 assert(Bop->getOpcode() == BO_LAnd); 13783 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13784 << Bop->getSourceRange() << OpLoc; 13785 SuggestParentheses(Self, Bop->getOperatorLoc(), 13786 Self.PDiag(diag::note_precedence_silence) 13787 << Bop->getOpcodeStr(), 13788 Bop->getSourceRange()); 13789 } 13790 13791 /// Returns true if the given expression can be evaluated as a constant 13792 /// 'true'. 13793 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13794 bool Res; 13795 return !E->isValueDependent() && 13796 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13797 } 13798 13799 /// Returns true if the given expression can be evaluated as a constant 13800 /// 'false'. 13801 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13802 bool Res; 13803 return !E->isValueDependent() && 13804 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13805 } 13806 13807 /// Look for '&&' in the left hand of a '||' expr. 13808 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13809 Expr *LHSExpr, Expr *RHSExpr) { 13810 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13811 if (Bop->getOpcode() == BO_LAnd) { 13812 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13813 if (EvaluatesAsFalse(S, RHSExpr)) 13814 return; 13815 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13816 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13817 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13818 } else if (Bop->getOpcode() == BO_LOr) { 13819 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13820 // If it's "a || b && 1 || c" we didn't warn earlier for 13821 // "a || b && 1", but warn now. 13822 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13823 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13824 } 13825 } 13826 } 13827 } 13828 13829 /// Look for '&&' in the right hand of a '||' expr. 13830 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13831 Expr *LHSExpr, Expr *RHSExpr) { 13832 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13833 if (Bop->getOpcode() == BO_LAnd) { 13834 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13835 if (EvaluatesAsFalse(S, LHSExpr)) 13836 return; 13837 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13838 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13839 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13840 } 13841 } 13842 } 13843 13844 /// Look for bitwise op in the left or right hand of a bitwise op with 13845 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13846 /// the '&' expression in parentheses. 13847 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13848 SourceLocation OpLoc, Expr *SubExpr) { 13849 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13850 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13851 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13852 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13853 << Bop->getSourceRange() << OpLoc; 13854 SuggestParentheses(S, Bop->getOperatorLoc(), 13855 S.PDiag(diag::note_precedence_silence) 13856 << Bop->getOpcodeStr(), 13857 Bop->getSourceRange()); 13858 } 13859 } 13860 } 13861 13862 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13863 Expr *SubExpr, StringRef Shift) { 13864 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13865 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13866 StringRef Op = Bop->getOpcodeStr(); 13867 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13868 << Bop->getSourceRange() << OpLoc << Shift << Op; 13869 SuggestParentheses(S, Bop->getOperatorLoc(), 13870 S.PDiag(diag::note_precedence_silence) << Op, 13871 Bop->getSourceRange()); 13872 } 13873 } 13874 } 13875 13876 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13877 Expr *LHSExpr, Expr *RHSExpr) { 13878 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13879 if (!OCE) 13880 return; 13881 13882 FunctionDecl *FD = OCE->getDirectCallee(); 13883 if (!FD || !FD->isOverloadedOperator()) 13884 return; 13885 13886 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13887 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13888 return; 13889 13890 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13891 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13892 << (Kind == OO_LessLess); 13893 SuggestParentheses(S, OCE->getOperatorLoc(), 13894 S.PDiag(diag::note_precedence_silence) 13895 << (Kind == OO_LessLess ? "<<" : ">>"), 13896 OCE->getSourceRange()); 13897 SuggestParentheses( 13898 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13899 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13900 } 13901 13902 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13903 /// precedence. 13904 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13905 SourceLocation OpLoc, Expr *LHSExpr, 13906 Expr *RHSExpr){ 13907 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13908 if (BinaryOperator::isBitwiseOp(Opc)) 13909 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13910 13911 // Diagnose "arg1 & arg2 | arg3" 13912 if ((Opc == BO_Or || Opc == BO_Xor) && 13913 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13914 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13915 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13916 } 13917 13918 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13919 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13920 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13921 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13922 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13923 } 13924 13925 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13926 || Opc == BO_Shr) { 13927 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13928 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13929 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13930 } 13931 13932 // Warn on overloaded shift operators and comparisons, such as: 13933 // cout << 5 == 4; 13934 if (BinaryOperator::isComparisonOp(Opc)) 13935 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13936 } 13937 13938 // Binary Operators. 'Tok' is the token for the operator. 13939 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13940 tok::TokenKind Kind, 13941 Expr *LHSExpr, Expr *RHSExpr) { 13942 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13943 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13944 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13945 13946 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13947 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13948 13949 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13950 } 13951 13952 /// Build an overloaded binary operator expression in the given scope. 13953 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13954 BinaryOperatorKind Opc, 13955 Expr *LHS, Expr *RHS) { 13956 switch (Opc) { 13957 case BO_Assign: 13958 case BO_DivAssign: 13959 case BO_RemAssign: 13960 case BO_SubAssign: 13961 case BO_AndAssign: 13962 case BO_OrAssign: 13963 case BO_XorAssign: 13964 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13965 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13966 break; 13967 default: 13968 break; 13969 } 13970 13971 // Find all of the overloaded operators visible from this 13972 // point. We perform both an operator-name lookup from the local 13973 // scope and an argument-dependent lookup based on the types of 13974 // the arguments. 13975 UnresolvedSet<16> Functions; 13976 OverloadedOperatorKind OverOp 13977 = BinaryOperator::getOverloadedOperator(Opc); 13978 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13979 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13980 RHS->getType(), Functions); 13981 13982 // In C++20 onwards, we may have a second operator to look up. 13983 if (S.getLangOpts().CPlusPlus20) { 13984 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13985 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13986 RHS->getType(), Functions); 13987 } 13988 13989 // Build the (potentially-overloaded, potentially-dependent) 13990 // binary operation. 13991 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13992 } 13993 13994 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13995 BinaryOperatorKind Opc, 13996 Expr *LHSExpr, Expr *RHSExpr) { 13997 ExprResult LHS, RHS; 13998 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13999 if (!LHS.isUsable() || !RHS.isUsable()) 14000 return ExprError(); 14001 LHSExpr = LHS.get(); 14002 RHSExpr = RHS.get(); 14003 14004 // We want to end up calling one of checkPseudoObjectAssignment 14005 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14006 // both expressions are overloadable or either is type-dependent), 14007 // or CreateBuiltinBinOp (in any other case). We also want to get 14008 // any placeholder types out of the way. 14009 14010 // Handle pseudo-objects in the LHS. 14011 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14012 // Assignments with a pseudo-object l-value need special analysis. 14013 if (pty->getKind() == BuiltinType::PseudoObject && 14014 BinaryOperator::isAssignmentOp(Opc)) 14015 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14016 14017 // Don't resolve overloads if the other type is overloadable. 14018 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14019 // We can't actually test that if we still have a placeholder, 14020 // though. Fortunately, none of the exceptions we see in that 14021 // code below are valid when the LHS is an overload set. Note 14022 // that an overload set can be dependently-typed, but it never 14023 // instantiates to having an overloadable type. 14024 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14025 if (resolvedRHS.isInvalid()) return ExprError(); 14026 RHSExpr = resolvedRHS.get(); 14027 14028 if (RHSExpr->isTypeDependent() || 14029 RHSExpr->getType()->isOverloadableType()) 14030 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14031 } 14032 14033 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14034 // template, diagnose the missing 'template' keyword instead of diagnosing 14035 // an invalid use of a bound member function. 14036 // 14037 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14038 // to C++1z [over.over]/1.4, but we already checked for that case above. 14039 if (Opc == BO_LT && inTemplateInstantiation() && 14040 (pty->getKind() == BuiltinType::BoundMember || 14041 pty->getKind() == BuiltinType::Overload)) { 14042 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14043 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14044 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14045 return isa<FunctionTemplateDecl>(ND); 14046 })) { 14047 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14048 : OE->getNameLoc(), 14049 diag::err_template_kw_missing) 14050 << OE->getName().getAsString() << ""; 14051 return ExprError(); 14052 } 14053 } 14054 14055 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14056 if (LHS.isInvalid()) return ExprError(); 14057 LHSExpr = LHS.get(); 14058 } 14059 14060 // Handle pseudo-objects in the RHS. 14061 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14062 // An overload in the RHS can potentially be resolved by the type 14063 // being assigned to. 14064 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14065 if (getLangOpts().CPlusPlus && 14066 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14067 LHSExpr->getType()->isOverloadableType())) 14068 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14069 14070 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14071 } 14072 14073 // Don't resolve overloads if the other type is overloadable. 14074 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14075 LHSExpr->getType()->isOverloadableType()) 14076 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14077 14078 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14079 if (!resolvedRHS.isUsable()) return ExprError(); 14080 RHSExpr = resolvedRHS.get(); 14081 } 14082 14083 if (getLangOpts().CPlusPlus) { 14084 // If either expression is type-dependent, always build an 14085 // overloaded op. 14086 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14087 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14088 14089 // Otherwise, build an overloaded op if either expression has an 14090 // overloadable type. 14091 if (LHSExpr->getType()->isOverloadableType() || 14092 RHSExpr->getType()->isOverloadableType()) 14093 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14094 } 14095 14096 // Build a built-in binary operation. 14097 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14098 } 14099 14100 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14101 if (T.isNull() || T->isDependentType()) 14102 return false; 14103 14104 if (!T->isPromotableIntegerType()) 14105 return true; 14106 14107 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14108 } 14109 14110 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14111 UnaryOperatorKind Opc, 14112 Expr *InputExpr) { 14113 ExprResult Input = InputExpr; 14114 ExprValueKind VK = VK_RValue; 14115 ExprObjectKind OK = OK_Ordinary; 14116 QualType resultType; 14117 bool CanOverflow = false; 14118 14119 bool ConvertHalfVec = false; 14120 if (getLangOpts().OpenCL) { 14121 QualType Ty = InputExpr->getType(); 14122 // The only legal unary operation for atomics is '&'. 14123 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14124 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14125 // only with a builtin functions and therefore should be disallowed here. 14126 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14127 || Ty->isBlockPointerType())) { 14128 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14129 << InputExpr->getType() 14130 << Input.get()->getSourceRange()); 14131 } 14132 } 14133 // Diagnose operations on the unsupported types for OpenMP device compilation. 14134 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 14135 if (UnaryOperator::isIncrementDecrementOp(Opc) || 14136 UnaryOperator::isArithmeticOp(Opc)) 14137 checkOpenMPDeviceExpr(InputExpr); 14138 } 14139 14140 switch (Opc) { 14141 case UO_PreInc: 14142 case UO_PreDec: 14143 case UO_PostInc: 14144 case UO_PostDec: 14145 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14146 OpLoc, 14147 Opc == UO_PreInc || 14148 Opc == UO_PostInc, 14149 Opc == UO_PreInc || 14150 Opc == UO_PreDec); 14151 CanOverflow = isOverflowingIntegerType(Context, resultType); 14152 break; 14153 case UO_AddrOf: 14154 resultType = CheckAddressOfOperand(Input, OpLoc); 14155 CheckAddressOfNoDeref(InputExpr); 14156 RecordModifiableNonNullParam(*this, InputExpr); 14157 break; 14158 case UO_Deref: { 14159 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14160 if (Input.isInvalid()) return ExprError(); 14161 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14162 break; 14163 } 14164 case UO_Plus: 14165 case UO_Minus: 14166 CanOverflow = Opc == UO_Minus && 14167 isOverflowingIntegerType(Context, Input.get()->getType()); 14168 Input = UsualUnaryConversions(Input.get()); 14169 if (Input.isInvalid()) return ExprError(); 14170 // Unary plus and minus require promoting an operand of half vector to a 14171 // float vector and truncating the result back to a half vector. For now, we 14172 // do this only when HalfArgsAndReturns is set (that is, when the target is 14173 // arm or arm64). 14174 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14175 14176 // If the operand is a half vector, promote it to a float vector. 14177 if (ConvertHalfVec) 14178 Input = convertVector(Input.get(), Context.FloatTy, *this); 14179 resultType = Input.get()->getType(); 14180 if (resultType->isDependentType()) 14181 break; 14182 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14183 break; 14184 else if (resultType->isVectorType() && 14185 // The z vector extensions don't allow + or - with bool vectors. 14186 (!Context.getLangOpts().ZVector || 14187 resultType->castAs<VectorType>()->getVectorKind() != 14188 VectorType::AltiVecBool)) 14189 break; 14190 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14191 Opc == UO_Plus && 14192 resultType->isPointerType()) 14193 break; 14194 14195 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14196 << resultType << Input.get()->getSourceRange()); 14197 14198 case UO_Not: // bitwise complement 14199 Input = UsualUnaryConversions(Input.get()); 14200 if (Input.isInvalid()) 14201 return ExprError(); 14202 resultType = Input.get()->getType(); 14203 if (resultType->isDependentType()) 14204 break; 14205 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14206 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14207 // C99 does not support '~' for complex conjugation. 14208 Diag(OpLoc, diag::ext_integer_complement_complex) 14209 << resultType << Input.get()->getSourceRange(); 14210 else if (resultType->hasIntegerRepresentation()) 14211 break; 14212 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14213 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14214 // on vector float types. 14215 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14216 if (!T->isIntegerType()) 14217 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14218 << resultType << Input.get()->getSourceRange()); 14219 } else { 14220 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14221 << resultType << Input.get()->getSourceRange()); 14222 } 14223 break; 14224 14225 case UO_LNot: // logical negation 14226 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14227 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14228 if (Input.isInvalid()) return ExprError(); 14229 resultType = Input.get()->getType(); 14230 14231 // Though we still have to promote half FP to float... 14232 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14233 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14234 resultType = Context.FloatTy; 14235 } 14236 14237 if (resultType->isDependentType()) 14238 break; 14239 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14240 // C99 6.5.3.3p1: ok, fallthrough; 14241 if (Context.getLangOpts().CPlusPlus) { 14242 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14243 // operand contextually converted to bool. 14244 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14245 ScalarTypeToBooleanCastKind(resultType)); 14246 } else if (Context.getLangOpts().OpenCL && 14247 Context.getLangOpts().OpenCLVersion < 120) { 14248 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14249 // operate on scalar float types. 14250 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14251 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14252 << resultType << Input.get()->getSourceRange()); 14253 } 14254 } else if (resultType->isExtVectorType()) { 14255 if (Context.getLangOpts().OpenCL && 14256 Context.getLangOpts().OpenCLVersion < 120 && 14257 !Context.getLangOpts().OpenCLCPlusPlus) { 14258 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14259 // operate on vector float types. 14260 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14261 if (!T->isIntegerType()) 14262 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14263 << resultType << Input.get()->getSourceRange()); 14264 } 14265 // Vector logical not returns the signed variant of the operand type. 14266 resultType = GetSignedVectorType(resultType); 14267 break; 14268 } else { 14269 // FIXME: GCC's vector extension permits the usage of '!' with a vector 14270 // type in C++. We should allow that here too. 14271 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14272 << resultType << Input.get()->getSourceRange()); 14273 } 14274 14275 // LNot always has type int. C99 6.5.3.3p5. 14276 // In C++, it's bool. C++ 5.3.1p8 14277 resultType = Context.getLogicalOperationType(); 14278 break; 14279 case UO_Real: 14280 case UO_Imag: 14281 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14282 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14283 // complex l-values to ordinary l-values and all other values to r-values. 14284 if (Input.isInvalid()) return ExprError(); 14285 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14286 if (Input.get()->getValueKind() != VK_RValue && 14287 Input.get()->getObjectKind() == OK_Ordinary) 14288 VK = Input.get()->getValueKind(); 14289 } else if (!getLangOpts().CPlusPlus) { 14290 // In C, a volatile scalar is read by __imag. In C++, it is not. 14291 Input = DefaultLvalueConversion(Input.get()); 14292 } 14293 break; 14294 case UO_Extension: 14295 resultType = Input.get()->getType(); 14296 VK = Input.get()->getValueKind(); 14297 OK = Input.get()->getObjectKind(); 14298 break; 14299 case UO_Coawait: 14300 // It's unnecessary to represent the pass-through operator co_await in the 14301 // AST; just return the input expression instead. 14302 assert(!Input.get()->getType()->isDependentType() && 14303 "the co_await expression must be non-dependant before " 14304 "building operator co_await"); 14305 return Input; 14306 } 14307 if (resultType.isNull() || Input.isInvalid()) 14308 return ExprError(); 14309 14310 // Check for array bounds violations in the operand of the UnaryOperator, 14311 // except for the '*' and '&' operators that have to be handled specially 14312 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14313 // that are explicitly defined as valid by the standard). 14314 if (Opc != UO_AddrOf && Opc != UO_Deref) 14315 CheckArrayAccess(Input.get()); 14316 14317 auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, 14318 OK, OpLoc, CanOverflow, CurFPFeatures); 14319 14320 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14321 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14322 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14323 14324 // Convert the result back to a half vector. 14325 if (ConvertHalfVec) 14326 return convertVector(UO, Context.HalfTy, *this); 14327 return UO; 14328 } 14329 14330 /// Determine whether the given expression is a qualified member 14331 /// access expression, of a form that could be turned into a pointer to member 14332 /// with the address-of operator. 14333 bool Sema::isQualifiedMemberAccess(Expr *E) { 14334 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14335 if (!DRE->getQualifier()) 14336 return false; 14337 14338 ValueDecl *VD = DRE->getDecl(); 14339 if (!VD->isCXXClassMember()) 14340 return false; 14341 14342 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14343 return true; 14344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14345 return Method->isInstance(); 14346 14347 return false; 14348 } 14349 14350 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14351 if (!ULE->getQualifier()) 14352 return false; 14353 14354 for (NamedDecl *D : ULE->decls()) { 14355 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14356 if (Method->isInstance()) 14357 return true; 14358 } else { 14359 // Overload set does not contain methods. 14360 break; 14361 } 14362 } 14363 14364 return false; 14365 } 14366 14367 return false; 14368 } 14369 14370 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14371 UnaryOperatorKind Opc, Expr *Input) { 14372 // First things first: handle placeholders so that the 14373 // overloaded-operator check considers the right type. 14374 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14375 // Increment and decrement of pseudo-object references. 14376 if (pty->getKind() == BuiltinType::PseudoObject && 14377 UnaryOperator::isIncrementDecrementOp(Opc)) 14378 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14379 14380 // extension is always a builtin operator. 14381 if (Opc == UO_Extension) 14382 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14383 14384 // & gets special logic for several kinds of placeholder. 14385 // The builtin code knows what to do. 14386 if (Opc == UO_AddrOf && 14387 (pty->getKind() == BuiltinType::Overload || 14388 pty->getKind() == BuiltinType::UnknownAny || 14389 pty->getKind() == BuiltinType::BoundMember)) 14390 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14391 14392 // Anything else needs to be handled now. 14393 ExprResult Result = CheckPlaceholderExpr(Input); 14394 if (Result.isInvalid()) return ExprError(); 14395 Input = Result.get(); 14396 } 14397 14398 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14399 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14400 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14401 // Find all of the overloaded operators visible from this 14402 // point. We perform both an operator-name lookup from the local 14403 // scope and an argument-dependent lookup based on the types of 14404 // the arguments. 14405 UnresolvedSet<16> Functions; 14406 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14407 if (S && OverOp != OO_None) 14408 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14409 Functions); 14410 14411 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14412 } 14413 14414 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14415 } 14416 14417 // Unary Operators. 'Tok' is the token for the operator. 14418 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14419 tok::TokenKind Op, Expr *Input) { 14420 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14421 } 14422 14423 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14424 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14425 LabelDecl *TheDecl) { 14426 TheDecl->markUsed(Context); 14427 // Create the AST node. The address of a label always has type 'void*'. 14428 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14429 Context.getPointerType(Context.VoidTy)); 14430 } 14431 14432 void Sema::ActOnStartStmtExpr() { 14433 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14434 } 14435 14436 void Sema::ActOnStmtExprError() { 14437 // Note that function is also called by TreeTransform when leaving a 14438 // StmtExpr scope without rebuilding anything. 14439 14440 DiscardCleanupsInEvaluationContext(); 14441 PopExpressionEvaluationContext(); 14442 } 14443 14444 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14445 SourceLocation RPLoc) { 14446 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14447 } 14448 14449 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14450 SourceLocation RPLoc, unsigned TemplateDepth) { 14451 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14452 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14453 14454 if (hasAnyUnrecoverableErrorsInThisFunction()) 14455 DiscardCleanupsInEvaluationContext(); 14456 assert(!Cleanup.exprNeedsCleanups() && 14457 "cleanups within StmtExpr not correctly bound!"); 14458 PopExpressionEvaluationContext(); 14459 14460 // FIXME: there are a variety of strange constraints to enforce here, for 14461 // example, it is not possible to goto into a stmt expression apparently. 14462 // More semantic analysis is needed. 14463 14464 // If there are sub-stmts in the compound stmt, take the type of the last one 14465 // as the type of the stmtexpr. 14466 QualType Ty = Context.VoidTy; 14467 bool StmtExprMayBindToTemp = false; 14468 if (!Compound->body_empty()) { 14469 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14470 if (const auto *LastStmt = 14471 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14472 if (const Expr *Value = LastStmt->getExprStmt()) { 14473 StmtExprMayBindToTemp = true; 14474 Ty = Value->getType(); 14475 } 14476 } 14477 } 14478 14479 // FIXME: Check that expression type is complete/non-abstract; statement 14480 // expressions are not lvalues. 14481 Expr *ResStmtExpr = 14482 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14483 if (StmtExprMayBindToTemp) 14484 return MaybeBindToTemporary(ResStmtExpr); 14485 return ResStmtExpr; 14486 } 14487 14488 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14489 if (ER.isInvalid()) 14490 return ExprError(); 14491 14492 // Do function/array conversion on the last expression, but not 14493 // lvalue-to-rvalue. However, initialize an unqualified type. 14494 ER = DefaultFunctionArrayConversion(ER.get()); 14495 if (ER.isInvalid()) 14496 return ExprError(); 14497 Expr *E = ER.get(); 14498 14499 if (E->isTypeDependent()) 14500 return E; 14501 14502 // In ARC, if the final expression ends in a consume, splice 14503 // the consume out and bind it later. In the alternate case 14504 // (when dealing with a retainable type), the result 14505 // initialization will create a produce. In both cases the 14506 // result will be +1, and we'll need to balance that out with 14507 // a bind. 14508 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14509 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14510 return Cast->getSubExpr(); 14511 14512 // FIXME: Provide a better location for the initialization. 14513 return PerformCopyInitialization( 14514 InitializedEntity::InitializeStmtExprResult( 14515 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14516 SourceLocation(), E); 14517 } 14518 14519 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14520 TypeSourceInfo *TInfo, 14521 ArrayRef<OffsetOfComponent> Components, 14522 SourceLocation RParenLoc) { 14523 QualType ArgTy = TInfo->getType(); 14524 bool Dependent = ArgTy->isDependentType(); 14525 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14526 14527 // We must have at least one component that refers to the type, and the first 14528 // one is known to be a field designator. Verify that the ArgTy represents 14529 // a struct/union/class. 14530 if (!Dependent && !ArgTy->isRecordType()) 14531 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14532 << ArgTy << TypeRange); 14533 14534 // Type must be complete per C99 7.17p3 because a declaring a variable 14535 // with an incomplete type would be ill-formed. 14536 if (!Dependent 14537 && RequireCompleteType(BuiltinLoc, ArgTy, 14538 diag::err_offsetof_incomplete_type, TypeRange)) 14539 return ExprError(); 14540 14541 bool DidWarnAboutNonPOD = false; 14542 QualType CurrentType = ArgTy; 14543 SmallVector<OffsetOfNode, 4> Comps; 14544 SmallVector<Expr*, 4> Exprs; 14545 for (const OffsetOfComponent &OC : Components) { 14546 if (OC.isBrackets) { 14547 // Offset of an array sub-field. TODO: Should we allow vector elements? 14548 if (!CurrentType->isDependentType()) { 14549 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14550 if(!AT) 14551 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14552 << CurrentType); 14553 CurrentType = AT->getElementType(); 14554 } else 14555 CurrentType = Context.DependentTy; 14556 14557 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14558 if (IdxRval.isInvalid()) 14559 return ExprError(); 14560 Expr *Idx = IdxRval.get(); 14561 14562 // The expression must be an integral expression. 14563 // FIXME: An integral constant expression? 14564 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14565 !Idx->getType()->isIntegerType()) 14566 return ExprError( 14567 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14568 << Idx->getSourceRange()); 14569 14570 // Record this array index. 14571 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14572 Exprs.push_back(Idx); 14573 continue; 14574 } 14575 14576 // Offset of a field. 14577 if (CurrentType->isDependentType()) { 14578 // We have the offset of a field, but we can't look into the dependent 14579 // type. Just record the identifier of the field. 14580 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14581 CurrentType = Context.DependentTy; 14582 continue; 14583 } 14584 14585 // We need to have a complete type to look into. 14586 if (RequireCompleteType(OC.LocStart, CurrentType, 14587 diag::err_offsetof_incomplete_type)) 14588 return ExprError(); 14589 14590 // Look for the designated field. 14591 const RecordType *RC = CurrentType->getAs<RecordType>(); 14592 if (!RC) 14593 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14594 << CurrentType); 14595 RecordDecl *RD = RC->getDecl(); 14596 14597 // C++ [lib.support.types]p5: 14598 // The macro offsetof accepts a restricted set of type arguments in this 14599 // International Standard. type shall be a POD structure or a POD union 14600 // (clause 9). 14601 // C++11 [support.types]p4: 14602 // If type is not a standard-layout class (Clause 9), the results are 14603 // undefined. 14604 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14605 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14606 unsigned DiagID = 14607 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14608 : diag::ext_offsetof_non_pod_type; 14609 14610 if (!IsSafe && !DidWarnAboutNonPOD && 14611 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14612 PDiag(DiagID) 14613 << SourceRange(Components[0].LocStart, OC.LocEnd) 14614 << CurrentType)) 14615 DidWarnAboutNonPOD = true; 14616 } 14617 14618 // Look for the field. 14619 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14620 LookupQualifiedName(R, RD); 14621 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14622 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14623 if (!MemberDecl) { 14624 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14625 MemberDecl = IndirectMemberDecl->getAnonField(); 14626 } 14627 14628 if (!MemberDecl) 14629 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14630 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14631 OC.LocEnd)); 14632 14633 // C99 7.17p3: 14634 // (If the specified member is a bit-field, the behavior is undefined.) 14635 // 14636 // We diagnose this as an error. 14637 if (MemberDecl->isBitField()) { 14638 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14639 << MemberDecl->getDeclName() 14640 << SourceRange(BuiltinLoc, RParenLoc); 14641 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14642 return ExprError(); 14643 } 14644 14645 RecordDecl *Parent = MemberDecl->getParent(); 14646 if (IndirectMemberDecl) 14647 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14648 14649 // If the member was found in a base class, introduce OffsetOfNodes for 14650 // the base class indirections. 14651 CXXBasePaths Paths; 14652 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14653 Paths)) { 14654 if (Paths.getDetectedVirtual()) { 14655 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14656 << MemberDecl->getDeclName() 14657 << SourceRange(BuiltinLoc, RParenLoc); 14658 return ExprError(); 14659 } 14660 14661 CXXBasePath &Path = Paths.front(); 14662 for (const CXXBasePathElement &B : Path) 14663 Comps.push_back(OffsetOfNode(B.Base)); 14664 } 14665 14666 if (IndirectMemberDecl) { 14667 for (auto *FI : IndirectMemberDecl->chain()) { 14668 assert(isa<FieldDecl>(FI)); 14669 Comps.push_back(OffsetOfNode(OC.LocStart, 14670 cast<FieldDecl>(FI), OC.LocEnd)); 14671 } 14672 } else 14673 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14674 14675 CurrentType = MemberDecl->getType().getNonReferenceType(); 14676 } 14677 14678 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14679 Comps, Exprs, RParenLoc); 14680 } 14681 14682 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14683 SourceLocation BuiltinLoc, 14684 SourceLocation TypeLoc, 14685 ParsedType ParsedArgTy, 14686 ArrayRef<OffsetOfComponent> Components, 14687 SourceLocation RParenLoc) { 14688 14689 TypeSourceInfo *ArgTInfo; 14690 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14691 if (ArgTy.isNull()) 14692 return ExprError(); 14693 14694 if (!ArgTInfo) 14695 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14696 14697 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14698 } 14699 14700 14701 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14702 Expr *CondExpr, 14703 Expr *LHSExpr, Expr *RHSExpr, 14704 SourceLocation RPLoc) { 14705 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14706 14707 ExprValueKind VK = VK_RValue; 14708 ExprObjectKind OK = OK_Ordinary; 14709 QualType resType; 14710 bool CondIsTrue = false; 14711 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14712 resType = Context.DependentTy; 14713 } else { 14714 // The conditional expression is required to be a constant expression. 14715 llvm::APSInt condEval(32); 14716 ExprResult CondICE 14717 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14718 diag::err_typecheck_choose_expr_requires_constant, false); 14719 if (CondICE.isInvalid()) 14720 return ExprError(); 14721 CondExpr = CondICE.get(); 14722 CondIsTrue = condEval.getZExtValue(); 14723 14724 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14725 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14726 14727 resType = ActiveExpr->getType(); 14728 VK = ActiveExpr->getValueKind(); 14729 OK = ActiveExpr->getObjectKind(); 14730 } 14731 14732 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14733 resType, VK, OK, RPLoc, CondIsTrue); 14734 } 14735 14736 //===----------------------------------------------------------------------===// 14737 // Clang Extensions. 14738 //===----------------------------------------------------------------------===// 14739 14740 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14741 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14742 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14743 14744 if (LangOpts.CPlusPlus) { 14745 MangleNumberingContext *MCtx; 14746 Decl *ManglingContextDecl; 14747 std::tie(MCtx, ManglingContextDecl) = 14748 getCurrentMangleNumberContext(Block->getDeclContext()); 14749 if (MCtx) { 14750 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14751 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14752 } 14753 } 14754 14755 PushBlockScope(CurScope, Block); 14756 CurContext->addDecl(Block); 14757 if (CurScope) 14758 PushDeclContext(CurScope, Block); 14759 else 14760 CurContext = Block; 14761 14762 getCurBlock()->HasImplicitReturnType = true; 14763 14764 // Enter a new evaluation context to insulate the block from any 14765 // cleanups from the enclosing full-expression. 14766 PushExpressionEvaluationContext( 14767 ExpressionEvaluationContext::PotentiallyEvaluated); 14768 } 14769 14770 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14771 Scope *CurScope) { 14772 assert(ParamInfo.getIdentifier() == nullptr && 14773 "block-id should have no identifier!"); 14774 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14775 BlockScopeInfo *CurBlock = getCurBlock(); 14776 14777 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14778 QualType T = Sig->getType(); 14779 14780 // FIXME: We should allow unexpanded parameter packs here, but that would, 14781 // in turn, make the block expression contain unexpanded parameter packs. 14782 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14783 // Drop the parameters. 14784 FunctionProtoType::ExtProtoInfo EPI; 14785 EPI.HasTrailingReturn = false; 14786 EPI.TypeQuals.addConst(); 14787 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14788 Sig = Context.getTrivialTypeSourceInfo(T); 14789 } 14790 14791 // GetTypeForDeclarator always produces a function type for a block 14792 // literal signature. Furthermore, it is always a FunctionProtoType 14793 // unless the function was written with a typedef. 14794 assert(T->isFunctionType() && 14795 "GetTypeForDeclarator made a non-function block signature"); 14796 14797 // Look for an explicit signature in that function type. 14798 FunctionProtoTypeLoc ExplicitSignature; 14799 14800 if ((ExplicitSignature = Sig->getTypeLoc() 14801 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14802 14803 // Check whether that explicit signature was synthesized by 14804 // GetTypeForDeclarator. If so, don't save that as part of the 14805 // written signature. 14806 if (ExplicitSignature.getLocalRangeBegin() == 14807 ExplicitSignature.getLocalRangeEnd()) { 14808 // This would be much cheaper if we stored TypeLocs instead of 14809 // TypeSourceInfos. 14810 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14811 unsigned Size = Result.getFullDataSize(); 14812 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14813 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14814 14815 ExplicitSignature = FunctionProtoTypeLoc(); 14816 } 14817 } 14818 14819 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14820 CurBlock->FunctionType = T; 14821 14822 const FunctionType *Fn = T->getAs<FunctionType>(); 14823 QualType RetTy = Fn->getReturnType(); 14824 bool isVariadic = 14825 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14826 14827 CurBlock->TheDecl->setIsVariadic(isVariadic); 14828 14829 // Context.DependentTy is used as a placeholder for a missing block 14830 // return type. TODO: what should we do with declarators like: 14831 // ^ * { ... } 14832 // If the answer is "apply template argument deduction".... 14833 if (RetTy != Context.DependentTy) { 14834 CurBlock->ReturnType = RetTy; 14835 CurBlock->TheDecl->setBlockMissingReturnType(false); 14836 CurBlock->HasImplicitReturnType = false; 14837 } 14838 14839 // Push block parameters from the declarator if we had them. 14840 SmallVector<ParmVarDecl*, 8> Params; 14841 if (ExplicitSignature) { 14842 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14843 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14844 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 14845 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 14846 // Diagnose this as an extension in C17 and earlier. 14847 if (!getLangOpts().C2x) 14848 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14849 } 14850 Params.push_back(Param); 14851 } 14852 14853 // Fake up parameter variables if we have a typedef, like 14854 // ^ fntype { ... } 14855 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14856 for (const auto &I : Fn->param_types()) { 14857 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14858 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14859 Params.push_back(Param); 14860 } 14861 } 14862 14863 // Set the parameters on the block decl. 14864 if (!Params.empty()) { 14865 CurBlock->TheDecl->setParams(Params); 14866 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14867 /*CheckParameterNames=*/false); 14868 } 14869 14870 // Finally we can process decl attributes. 14871 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14872 14873 // Put the parameter variables in scope. 14874 for (auto AI : CurBlock->TheDecl->parameters()) { 14875 AI->setOwningFunction(CurBlock->TheDecl); 14876 14877 // If this has an identifier, add it to the scope stack. 14878 if (AI->getIdentifier()) { 14879 CheckShadow(CurBlock->TheScope, AI); 14880 14881 PushOnScopeChains(AI, CurBlock->TheScope); 14882 } 14883 } 14884 } 14885 14886 /// ActOnBlockError - If there is an error parsing a block, this callback 14887 /// is invoked to pop the information about the block from the action impl. 14888 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14889 // Leave the expression-evaluation context. 14890 DiscardCleanupsInEvaluationContext(); 14891 PopExpressionEvaluationContext(); 14892 14893 // Pop off CurBlock, handle nested blocks. 14894 PopDeclContext(); 14895 PopFunctionScopeInfo(); 14896 } 14897 14898 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14899 /// literal was successfully completed. ^(int x){...} 14900 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14901 Stmt *Body, Scope *CurScope) { 14902 // If blocks are disabled, emit an error. 14903 if (!LangOpts.Blocks) 14904 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14905 14906 // Leave the expression-evaluation context. 14907 if (hasAnyUnrecoverableErrorsInThisFunction()) 14908 DiscardCleanupsInEvaluationContext(); 14909 assert(!Cleanup.exprNeedsCleanups() && 14910 "cleanups within block not correctly bound!"); 14911 PopExpressionEvaluationContext(); 14912 14913 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14914 BlockDecl *BD = BSI->TheDecl; 14915 14916 if (BSI->HasImplicitReturnType) 14917 deduceClosureReturnType(*BSI); 14918 14919 QualType RetTy = Context.VoidTy; 14920 if (!BSI->ReturnType.isNull()) 14921 RetTy = BSI->ReturnType; 14922 14923 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14924 QualType BlockTy; 14925 14926 // If the user wrote a function type in some form, try to use that. 14927 if (!BSI->FunctionType.isNull()) { 14928 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14929 14930 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14931 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14932 14933 // Turn protoless block types into nullary block types. 14934 if (isa<FunctionNoProtoType>(FTy)) { 14935 FunctionProtoType::ExtProtoInfo EPI; 14936 EPI.ExtInfo = Ext; 14937 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14938 14939 // Otherwise, if we don't need to change anything about the function type, 14940 // preserve its sugar structure. 14941 } else if (FTy->getReturnType() == RetTy && 14942 (!NoReturn || FTy->getNoReturnAttr())) { 14943 BlockTy = BSI->FunctionType; 14944 14945 // Otherwise, make the minimal modifications to the function type. 14946 } else { 14947 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14948 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14949 EPI.TypeQuals = Qualifiers(); 14950 EPI.ExtInfo = Ext; 14951 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14952 } 14953 14954 // If we don't have a function type, just build one from nothing. 14955 } else { 14956 FunctionProtoType::ExtProtoInfo EPI; 14957 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14958 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14959 } 14960 14961 DiagnoseUnusedParameters(BD->parameters()); 14962 BlockTy = Context.getBlockPointerType(BlockTy); 14963 14964 // If needed, diagnose invalid gotos and switches in the block. 14965 if (getCurFunction()->NeedsScopeChecking() && 14966 !PP.isCodeCompletionEnabled()) 14967 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14968 14969 BD->setBody(cast<CompoundStmt>(Body)); 14970 14971 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14972 DiagnoseUnguardedAvailabilityViolations(BD); 14973 14974 // Try to apply the named return value optimization. We have to check again 14975 // if we can do this, though, because blocks keep return statements around 14976 // to deduce an implicit return type. 14977 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14978 !BD->isDependentContext()) 14979 computeNRVO(Body, BSI); 14980 14981 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14982 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14983 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14984 NTCUK_Destruct|NTCUK_Copy); 14985 14986 PopDeclContext(); 14987 14988 // Pop the block scope now but keep it alive to the end of this function. 14989 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14990 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14991 14992 // Set the captured variables on the block. 14993 SmallVector<BlockDecl::Capture, 4> Captures; 14994 for (Capture &Cap : BSI->Captures) { 14995 if (Cap.isInvalid() || Cap.isThisCapture()) 14996 continue; 14997 14998 VarDecl *Var = Cap.getVariable(); 14999 Expr *CopyExpr = nullptr; 15000 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15001 if (const RecordType *Record = 15002 Cap.getCaptureType()->getAs<RecordType>()) { 15003 // The capture logic needs the destructor, so make sure we mark it. 15004 // Usually this is unnecessary because most local variables have 15005 // their destructors marked at declaration time, but parameters are 15006 // an exception because it's technically only the call site that 15007 // actually requires the destructor. 15008 if (isa<ParmVarDecl>(Var)) 15009 FinalizeVarWithDestructor(Var, Record); 15010 15011 // Enter a separate potentially-evaluated context while building block 15012 // initializers to isolate their cleanups from those of the block 15013 // itself. 15014 // FIXME: Is this appropriate even when the block itself occurs in an 15015 // unevaluated operand? 15016 EnterExpressionEvaluationContext EvalContext( 15017 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15018 15019 SourceLocation Loc = Cap.getLocation(); 15020 15021 ExprResult Result = BuildDeclarationNameExpr( 15022 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15023 15024 // According to the blocks spec, the capture of a variable from 15025 // the stack requires a const copy constructor. This is not true 15026 // of the copy/move done to move a __block variable to the heap. 15027 if (!Result.isInvalid() && 15028 !Result.get()->getType().isConstQualified()) { 15029 Result = ImpCastExprToType(Result.get(), 15030 Result.get()->getType().withConst(), 15031 CK_NoOp, VK_LValue); 15032 } 15033 15034 if (!Result.isInvalid()) { 15035 Result = PerformCopyInitialization( 15036 InitializedEntity::InitializeBlock(Var->getLocation(), 15037 Cap.getCaptureType(), false), 15038 Loc, Result.get()); 15039 } 15040 15041 // Build a full-expression copy expression if initialization 15042 // succeeded and used a non-trivial constructor. Recover from 15043 // errors by pretending that the copy isn't necessary. 15044 if (!Result.isInvalid() && 15045 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15046 ->isTrivial()) { 15047 Result = MaybeCreateExprWithCleanups(Result); 15048 CopyExpr = Result.get(); 15049 } 15050 } 15051 } 15052 15053 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15054 CopyExpr); 15055 Captures.push_back(NewCap); 15056 } 15057 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15058 15059 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15060 15061 // If the block isn't obviously global, i.e. it captures anything at 15062 // all, then we need to do a few things in the surrounding context: 15063 if (Result->getBlockDecl()->hasCaptures()) { 15064 // First, this expression has a new cleanup object. 15065 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15066 Cleanup.setExprNeedsCleanups(true); 15067 15068 // It also gets a branch-protected scope if any of the captured 15069 // variables needs destruction. 15070 for (const auto &CI : Result->getBlockDecl()->captures()) { 15071 const VarDecl *var = CI.getVariable(); 15072 if (var->getType().isDestructedType() != QualType::DK_none) { 15073 setFunctionHasBranchProtectedScope(); 15074 break; 15075 } 15076 } 15077 } 15078 15079 if (getCurFunction()) 15080 getCurFunction()->addBlock(BD); 15081 15082 return Result; 15083 } 15084 15085 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15086 SourceLocation RPLoc) { 15087 TypeSourceInfo *TInfo; 15088 GetTypeFromParser(Ty, &TInfo); 15089 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15090 } 15091 15092 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15093 Expr *E, TypeSourceInfo *TInfo, 15094 SourceLocation RPLoc) { 15095 Expr *OrigExpr = E; 15096 bool IsMS = false; 15097 15098 // CUDA device code does not support varargs. 15099 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15100 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15101 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15102 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15103 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15104 } 15105 } 15106 15107 // NVPTX does not support va_arg expression. 15108 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15109 Context.getTargetInfo().getTriple().isNVPTX()) 15110 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15111 15112 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15113 // as Microsoft ABI on an actual Microsoft platform, where 15114 // __builtin_ms_va_list and __builtin_va_list are the same.) 15115 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15116 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15117 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15118 if (Context.hasSameType(MSVaListType, E->getType())) { 15119 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15120 return ExprError(); 15121 IsMS = true; 15122 } 15123 } 15124 15125 // Get the va_list type 15126 QualType VaListType = Context.getBuiltinVaListType(); 15127 if (!IsMS) { 15128 if (VaListType->isArrayType()) { 15129 // Deal with implicit array decay; for example, on x86-64, 15130 // va_list is an array, but it's supposed to decay to 15131 // a pointer for va_arg. 15132 VaListType = Context.getArrayDecayedType(VaListType); 15133 // Make sure the input expression also decays appropriately. 15134 ExprResult Result = UsualUnaryConversions(E); 15135 if (Result.isInvalid()) 15136 return ExprError(); 15137 E = Result.get(); 15138 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15139 // If va_list is a record type and we are compiling in C++ mode, 15140 // check the argument using reference binding. 15141 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15142 Context, Context.getLValueReferenceType(VaListType), false); 15143 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15144 if (Init.isInvalid()) 15145 return ExprError(); 15146 E = Init.getAs<Expr>(); 15147 } else { 15148 // Otherwise, the va_list argument must be an l-value because 15149 // it is modified by va_arg. 15150 if (!E->isTypeDependent() && 15151 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15152 return ExprError(); 15153 } 15154 } 15155 15156 if (!IsMS && !E->isTypeDependent() && 15157 !Context.hasSameType(VaListType, E->getType())) 15158 return ExprError( 15159 Diag(E->getBeginLoc(), 15160 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15161 << OrigExpr->getType() << E->getSourceRange()); 15162 15163 if (!TInfo->getType()->isDependentType()) { 15164 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15165 diag::err_second_parameter_to_va_arg_incomplete, 15166 TInfo->getTypeLoc())) 15167 return ExprError(); 15168 15169 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15170 TInfo->getType(), 15171 diag::err_second_parameter_to_va_arg_abstract, 15172 TInfo->getTypeLoc())) 15173 return ExprError(); 15174 15175 if (!TInfo->getType().isPODType(Context)) { 15176 Diag(TInfo->getTypeLoc().getBeginLoc(), 15177 TInfo->getType()->isObjCLifetimeType() 15178 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15179 : diag::warn_second_parameter_to_va_arg_not_pod) 15180 << TInfo->getType() 15181 << TInfo->getTypeLoc().getSourceRange(); 15182 } 15183 15184 // Check for va_arg where arguments of the given type will be promoted 15185 // (i.e. this va_arg is guaranteed to have undefined behavior). 15186 QualType PromoteType; 15187 if (TInfo->getType()->isPromotableIntegerType()) { 15188 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15189 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15190 PromoteType = QualType(); 15191 } 15192 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15193 PromoteType = Context.DoubleTy; 15194 if (!PromoteType.isNull()) 15195 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15196 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15197 << TInfo->getType() 15198 << PromoteType 15199 << TInfo->getTypeLoc().getSourceRange()); 15200 } 15201 15202 QualType T = TInfo->getType().getNonLValueExprType(Context); 15203 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15204 } 15205 15206 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15207 // The type of __null will be int or long, depending on the size of 15208 // pointers on the target. 15209 QualType Ty; 15210 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15211 if (pw == Context.getTargetInfo().getIntWidth()) 15212 Ty = Context.IntTy; 15213 else if (pw == Context.getTargetInfo().getLongWidth()) 15214 Ty = Context.LongTy; 15215 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15216 Ty = Context.LongLongTy; 15217 else { 15218 llvm_unreachable("I don't know size of pointer!"); 15219 } 15220 15221 return new (Context) GNUNullExpr(Ty, TokenLoc); 15222 } 15223 15224 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15225 SourceLocation BuiltinLoc, 15226 SourceLocation RPLoc) { 15227 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15228 } 15229 15230 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15231 SourceLocation BuiltinLoc, 15232 SourceLocation RPLoc, 15233 DeclContext *ParentContext) { 15234 return new (Context) 15235 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15236 } 15237 15238 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15239 bool Diagnose) { 15240 if (!getLangOpts().ObjC) 15241 return false; 15242 15243 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15244 if (!PT) 15245 return false; 15246 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15247 15248 // Ignore any parens, implicit casts (should only be 15249 // array-to-pointer decays), and not-so-opaque values. The last is 15250 // important for making this trigger for property assignments. 15251 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15252 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15253 if (OV->getSourceExpr()) 15254 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15255 15256 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15257 if (!PT->isObjCIdType() && 15258 !(ID && ID->getIdentifier()->isStr("NSString"))) 15259 return false; 15260 if (!SL->isAscii()) 15261 return false; 15262 15263 if (Diagnose) { 15264 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15265 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15266 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15267 } 15268 return true; 15269 } 15270 15271 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15272 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15273 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15274 !SrcExpr->isNullPointerConstant( 15275 getASTContext(), Expr::NPC_NeverValueDependent)) { 15276 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15277 return false; 15278 if (Diagnose) { 15279 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15280 << /*number*/1 15281 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15282 Expr *NumLit = 15283 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15284 if (NumLit) 15285 Exp = NumLit; 15286 } 15287 return true; 15288 } 15289 15290 return false; 15291 } 15292 15293 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15294 const Expr *SrcExpr) { 15295 if (!DstType->isFunctionPointerType() || 15296 !SrcExpr->getType()->isFunctionType()) 15297 return false; 15298 15299 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15300 if (!DRE) 15301 return false; 15302 15303 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15304 if (!FD) 15305 return false; 15306 15307 return !S.checkAddressOfFunctionIsAvailable(FD, 15308 /*Complain=*/true, 15309 SrcExpr->getBeginLoc()); 15310 } 15311 15312 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15313 SourceLocation Loc, 15314 QualType DstType, QualType SrcType, 15315 Expr *SrcExpr, AssignmentAction Action, 15316 bool *Complained) { 15317 if (Complained) 15318 *Complained = false; 15319 15320 // Decode the result (notice that AST's are still created for extensions). 15321 bool CheckInferredResultType = false; 15322 bool isInvalid = false; 15323 unsigned DiagKind = 0; 15324 FixItHint Hint; 15325 ConversionFixItGenerator ConvHints; 15326 bool MayHaveConvFixit = false; 15327 bool MayHaveFunctionDiff = false; 15328 const ObjCInterfaceDecl *IFace = nullptr; 15329 const ObjCProtocolDecl *PDecl = nullptr; 15330 15331 switch (ConvTy) { 15332 case Compatible: 15333 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15334 return false; 15335 15336 case PointerToInt: 15337 if (getLangOpts().CPlusPlus) { 15338 DiagKind = diag::err_typecheck_convert_pointer_int; 15339 isInvalid = true; 15340 } else { 15341 DiagKind = diag::ext_typecheck_convert_pointer_int; 15342 } 15343 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15344 MayHaveConvFixit = true; 15345 break; 15346 case IntToPointer: 15347 if (getLangOpts().CPlusPlus) { 15348 DiagKind = diag::err_typecheck_convert_int_pointer; 15349 isInvalid = true; 15350 } else { 15351 DiagKind = diag::ext_typecheck_convert_int_pointer; 15352 } 15353 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15354 MayHaveConvFixit = true; 15355 break; 15356 case IncompatibleFunctionPointer: 15357 if (getLangOpts().CPlusPlus) { 15358 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15359 isInvalid = true; 15360 } else { 15361 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15362 } 15363 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15364 MayHaveConvFixit = true; 15365 break; 15366 case IncompatiblePointer: 15367 if (Action == AA_Passing_CFAudited) { 15368 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15369 } else if (getLangOpts().CPlusPlus) { 15370 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15371 isInvalid = true; 15372 } else { 15373 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15374 } 15375 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15376 SrcType->isObjCObjectPointerType(); 15377 if (Hint.isNull() && !CheckInferredResultType) { 15378 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15379 } 15380 else if (CheckInferredResultType) { 15381 SrcType = SrcType.getUnqualifiedType(); 15382 DstType = DstType.getUnqualifiedType(); 15383 } 15384 MayHaveConvFixit = true; 15385 break; 15386 case IncompatiblePointerSign: 15387 if (getLangOpts().CPlusPlus) { 15388 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15389 isInvalid = true; 15390 } else { 15391 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15392 } 15393 break; 15394 case FunctionVoidPointer: 15395 if (getLangOpts().CPlusPlus) { 15396 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15397 isInvalid = true; 15398 } else { 15399 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15400 } 15401 break; 15402 case IncompatiblePointerDiscardsQualifiers: { 15403 // Perform array-to-pointer decay if necessary. 15404 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15405 15406 isInvalid = true; 15407 15408 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15409 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15410 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15411 DiagKind = diag::err_typecheck_incompatible_address_space; 15412 break; 15413 15414 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15415 DiagKind = diag::err_typecheck_incompatible_ownership; 15416 break; 15417 } 15418 15419 llvm_unreachable("unknown error case for discarding qualifiers!"); 15420 // fallthrough 15421 } 15422 case CompatiblePointerDiscardsQualifiers: 15423 // If the qualifiers lost were because we were applying the 15424 // (deprecated) C++ conversion from a string literal to a char* 15425 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15426 // Ideally, this check would be performed in 15427 // checkPointerTypesForAssignment. However, that would require a 15428 // bit of refactoring (so that the second argument is an 15429 // expression, rather than a type), which should be done as part 15430 // of a larger effort to fix checkPointerTypesForAssignment for 15431 // C++ semantics. 15432 if (getLangOpts().CPlusPlus && 15433 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15434 return false; 15435 if (getLangOpts().CPlusPlus) { 15436 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15437 isInvalid = true; 15438 } else { 15439 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15440 } 15441 15442 break; 15443 case IncompatibleNestedPointerQualifiers: 15444 if (getLangOpts().CPlusPlus) { 15445 isInvalid = true; 15446 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15447 } else { 15448 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15449 } 15450 break; 15451 case IncompatibleNestedPointerAddressSpaceMismatch: 15452 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15453 isInvalid = true; 15454 break; 15455 case IntToBlockPointer: 15456 DiagKind = diag::err_int_to_block_pointer; 15457 isInvalid = true; 15458 break; 15459 case IncompatibleBlockPointer: 15460 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15461 isInvalid = true; 15462 break; 15463 case IncompatibleObjCQualifiedId: { 15464 if (SrcType->isObjCQualifiedIdType()) { 15465 const ObjCObjectPointerType *srcOPT = 15466 SrcType->castAs<ObjCObjectPointerType>(); 15467 for (auto *srcProto : srcOPT->quals()) { 15468 PDecl = srcProto; 15469 break; 15470 } 15471 if (const ObjCInterfaceType *IFaceT = 15472 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15473 IFace = IFaceT->getDecl(); 15474 } 15475 else if (DstType->isObjCQualifiedIdType()) { 15476 const ObjCObjectPointerType *dstOPT = 15477 DstType->castAs<ObjCObjectPointerType>(); 15478 for (auto *dstProto : dstOPT->quals()) { 15479 PDecl = dstProto; 15480 break; 15481 } 15482 if (const ObjCInterfaceType *IFaceT = 15483 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15484 IFace = IFaceT->getDecl(); 15485 } 15486 if (getLangOpts().CPlusPlus) { 15487 DiagKind = diag::err_incompatible_qualified_id; 15488 isInvalid = true; 15489 } else { 15490 DiagKind = diag::warn_incompatible_qualified_id; 15491 } 15492 break; 15493 } 15494 case IncompatibleVectors: 15495 if (getLangOpts().CPlusPlus) { 15496 DiagKind = diag::err_incompatible_vectors; 15497 isInvalid = true; 15498 } else { 15499 DiagKind = diag::warn_incompatible_vectors; 15500 } 15501 break; 15502 case IncompatibleObjCWeakRef: 15503 DiagKind = diag::err_arc_weak_unavailable_assign; 15504 isInvalid = true; 15505 break; 15506 case Incompatible: 15507 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15508 if (Complained) 15509 *Complained = true; 15510 return true; 15511 } 15512 15513 DiagKind = diag::err_typecheck_convert_incompatible; 15514 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15515 MayHaveConvFixit = true; 15516 isInvalid = true; 15517 MayHaveFunctionDiff = true; 15518 break; 15519 } 15520 15521 QualType FirstType, SecondType; 15522 switch (Action) { 15523 case AA_Assigning: 15524 case AA_Initializing: 15525 // The destination type comes first. 15526 FirstType = DstType; 15527 SecondType = SrcType; 15528 break; 15529 15530 case AA_Returning: 15531 case AA_Passing: 15532 case AA_Passing_CFAudited: 15533 case AA_Converting: 15534 case AA_Sending: 15535 case AA_Casting: 15536 // The source type comes first. 15537 FirstType = SrcType; 15538 SecondType = DstType; 15539 break; 15540 } 15541 15542 PartialDiagnostic FDiag = PDiag(DiagKind); 15543 if (Action == AA_Passing_CFAudited) 15544 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15545 else 15546 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15547 15548 // If we can fix the conversion, suggest the FixIts. 15549 assert(ConvHints.isNull() || Hint.isNull()); 15550 if (!ConvHints.isNull()) { 15551 for (FixItHint &H : ConvHints.Hints) 15552 FDiag << H; 15553 } else { 15554 FDiag << Hint; 15555 } 15556 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15557 15558 if (MayHaveFunctionDiff) 15559 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15560 15561 Diag(Loc, FDiag); 15562 if ((DiagKind == diag::warn_incompatible_qualified_id || 15563 DiagKind == diag::err_incompatible_qualified_id) && 15564 PDecl && IFace && !IFace->hasDefinition()) 15565 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15566 << IFace << PDecl; 15567 15568 if (SecondType == Context.OverloadTy) 15569 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15570 FirstType, /*TakingAddress=*/true); 15571 15572 if (CheckInferredResultType) 15573 EmitRelatedResultTypeNote(SrcExpr); 15574 15575 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15576 EmitRelatedResultTypeNoteForReturn(DstType); 15577 15578 if (Complained) 15579 *Complained = true; 15580 return isInvalid; 15581 } 15582 15583 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15584 llvm::APSInt *Result) { 15585 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15586 public: 15587 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15588 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15589 } 15590 } Diagnoser; 15591 15592 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15593 } 15594 15595 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15596 llvm::APSInt *Result, 15597 unsigned DiagID, 15598 bool AllowFold) { 15599 class IDDiagnoser : public VerifyICEDiagnoser { 15600 unsigned DiagID; 15601 15602 public: 15603 IDDiagnoser(unsigned DiagID) 15604 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15605 15606 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15607 S.Diag(Loc, DiagID) << SR; 15608 } 15609 } Diagnoser(DiagID); 15610 15611 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15612 } 15613 15614 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15615 SourceRange SR) { 15616 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15617 } 15618 15619 ExprResult 15620 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15621 VerifyICEDiagnoser &Diagnoser, 15622 bool AllowFold) { 15623 SourceLocation DiagLoc = E->getBeginLoc(); 15624 15625 if (getLangOpts().CPlusPlus11) { 15626 // C++11 [expr.const]p5: 15627 // If an expression of literal class type is used in a context where an 15628 // integral constant expression is required, then that class type shall 15629 // have a single non-explicit conversion function to an integral or 15630 // unscoped enumeration type 15631 ExprResult Converted; 15632 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15633 public: 15634 CXX11ConvertDiagnoser(bool Silent) 15635 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15636 Silent, true) {} 15637 15638 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15639 QualType T) override { 15640 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15641 } 15642 15643 SemaDiagnosticBuilder diagnoseIncomplete( 15644 Sema &S, SourceLocation Loc, QualType T) override { 15645 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15646 } 15647 15648 SemaDiagnosticBuilder diagnoseExplicitConv( 15649 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15650 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15651 } 15652 15653 SemaDiagnosticBuilder noteExplicitConv( 15654 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15655 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15656 << ConvTy->isEnumeralType() << ConvTy; 15657 } 15658 15659 SemaDiagnosticBuilder diagnoseAmbiguous( 15660 Sema &S, SourceLocation Loc, QualType T) override { 15661 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15662 } 15663 15664 SemaDiagnosticBuilder noteAmbiguous( 15665 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15666 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15667 << ConvTy->isEnumeralType() << ConvTy; 15668 } 15669 15670 SemaDiagnosticBuilder diagnoseConversion( 15671 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15672 llvm_unreachable("conversion functions are permitted"); 15673 } 15674 } ConvertDiagnoser(Diagnoser.Suppress); 15675 15676 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15677 ConvertDiagnoser); 15678 if (Converted.isInvalid()) 15679 return Converted; 15680 E = Converted.get(); 15681 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15682 return ExprError(); 15683 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15684 // An ICE must be of integral or unscoped enumeration type. 15685 if (!Diagnoser.Suppress) 15686 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15687 return ExprError(); 15688 } 15689 15690 ExprResult RValueExpr = DefaultLvalueConversion(E); 15691 if (RValueExpr.isInvalid()) 15692 return ExprError(); 15693 15694 E = RValueExpr.get(); 15695 15696 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15697 // in the non-ICE case. 15698 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15699 if (Result) 15700 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15701 if (!isa<ConstantExpr>(E)) 15702 E = ConstantExpr::Create(Context, E); 15703 return E; 15704 } 15705 15706 Expr::EvalResult EvalResult; 15707 SmallVector<PartialDiagnosticAt, 8> Notes; 15708 EvalResult.Diag = &Notes; 15709 15710 // Try to evaluate the expression, and produce diagnostics explaining why it's 15711 // not a constant expression as a side-effect. 15712 bool Folded = 15713 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15714 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15715 15716 if (!isa<ConstantExpr>(E)) 15717 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15718 15719 // In C++11, we can rely on diagnostics being produced for any expression 15720 // which is not a constant expression. If no diagnostics were produced, then 15721 // this is a constant expression. 15722 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15723 if (Result) 15724 *Result = EvalResult.Val.getInt(); 15725 return E; 15726 } 15727 15728 // If our only note is the usual "invalid subexpression" note, just point 15729 // the caret at its location rather than producing an essentially 15730 // redundant note. 15731 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15732 diag::note_invalid_subexpr_in_const_expr) { 15733 DiagLoc = Notes[0].first; 15734 Notes.clear(); 15735 } 15736 15737 if (!Folded || !AllowFold) { 15738 if (!Diagnoser.Suppress) { 15739 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15740 for (const PartialDiagnosticAt &Note : Notes) 15741 Diag(Note.first, Note.second); 15742 } 15743 15744 return ExprError(); 15745 } 15746 15747 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15748 for (const PartialDiagnosticAt &Note : Notes) 15749 Diag(Note.first, Note.second); 15750 15751 if (Result) 15752 *Result = EvalResult.Val.getInt(); 15753 return E; 15754 } 15755 15756 namespace { 15757 // Handle the case where we conclude a expression which we speculatively 15758 // considered to be unevaluated is actually evaluated. 15759 class TransformToPE : public TreeTransform<TransformToPE> { 15760 typedef TreeTransform<TransformToPE> BaseTransform; 15761 15762 public: 15763 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15764 15765 // Make sure we redo semantic analysis 15766 bool AlwaysRebuild() { return true; } 15767 bool ReplacingOriginal() { return true; } 15768 15769 // We need to special-case DeclRefExprs referring to FieldDecls which 15770 // are not part of a member pointer formation; normal TreeTransforming 15771 // doesn't catch this case because of the way we represent them in the AST. 15772 // FIXME: This is a bit ugly; is it really the best way to handle this 15773 // case? 15774 // 15775 // Error on DeclRefExprs referring to FieldDecls. 15776 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15777 if (isa<FieldDecl>(E->getDecl()) && 15778 !SemaRef.isUnevaluatedContext()) 15779 return SemaRef.Diag(E->getLocation(), 15780 diag::err_invalid_non_static_member_use) 15781 << E->getDecl() << E->getSourceRange(); 15782 15783 return BaseTransform::TransformDeclRefExpr(E); 15784 } 15785 15786 // Exception: filter out member pointer formation 15787 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15788 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15789 return E; 15790 15791 return BaseTransform::TransformUnaryOperator(E); 15792 } 15793 15794 // The body of a lambda-expression is in a separate expression evaluation 15795 // context so never needs to be transformed. 15796 // FIXME: Ideally we wouldn't transform the closure type either, and would 15797 // just recreate the capture expressions and lambda expression. 15798 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15799 return SkipLambdaBody(E, Body); 15800 } 15801 }; 15802 } 15803 15804 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15805 assert(isUnevaluatedContext() && 15806 "Should only transform unevaluated expressions"); 15807 ExprEvalContexts.back().Context = 15808 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15809 if (isUnevaluatedContext()) 15810 return E; 15811 return TransformToPE(*this).TransformExpr(E); 15812 } 15813 15814 void 15815 Sema::PushExpressionEvaluationContext( 15816 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15817 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15818 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15819 LambdaContextDecl, ExprContext); 15820 Cleanup.reset(); 15821 if (!MaybeODRUseExprs.empty()) 15822 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15823 } 15824 15825 void 15826 Sema::PushExpressionEvaluationContext( 15827 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15828 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15829 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15830 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15831 } 15832 15833 namespace { 15834 15835 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15836 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15837 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15838 if (E->getOpcode() == UO_Deref) 15839 return CheckPossibleDeref(S, E->getSubExpr()); 15840 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15841 return CheckPossibleDeref(S, E->getBase()); 15842 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15843 return CheckPossibleDeref(S, E->getBase()); 15844 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15845 QualType Inner; 15846 QualType Ty = E->getType(); 15847 if (const auto *Ptr = Ty->getAs<PointerType>()) 15848 Inner = Ptr->getPointeeType(); 15849 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15850 Inner = Arr->getElementType(); 15851 else 15852 return nullptr; 15853 15854 if (Inner->hasAttr(attr::NoDeref)) 15855 return E; 15856 } 15857 return nullptr; 15858 } 15859 15860 } // namespace 15861 15862 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15863 for (const Expr *E : Rec.PossibleDerefs) { 15864 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15865 if (DeclRef) { 15866 const ValueDecl *Decl = DeclRef->getDecl(); 15867 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15868 << Decl->getName() << E->getSourceRange(); 15869 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15870 } else { 15871 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15872 << E->getSourceRange(); 15873 } 15874 } 15875 Rec.PossibleDerefs.clear(); 15876 } 15877 15878 /// Check whether E, which is either a discarded-value expression or an 15879 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15880 /// and if so, remove it from the list of volatile-qualified assignments that 15881 /// we are going to warn are deprecated. 15882 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15883 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 15884 return; 15885 15886 // Note: ignoring parens here is not justified by the standard rules, but 15887 // ignoring parentheses seems like a more reasonable approach, and this only 15888 // drives a deprecation warning so doesn't affect conformance. 15889 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15890 if (BO->getOpcode() == BO_Assign) { 15891 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15892 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15893 LHSs.end()); 15894 } 15895 } 15896 } 15897 15898 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15899 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15900 RebuildingImmediateInvocation) 15901 return E; 15902 15903 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15904 /// It's OK if this fails; we'll also remove this in 15905 /// HandleImmediateInvocations, but catching it here allows us to avoid 15906 /// walking the AST looking for it in simple cases. 15907 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15908 if (auto *DeclRef = 15909 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15910 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15911 15912 E = MaybeCreateExprWithCleanups(E); 15913 15914 ConstantExpr *Res = ConstantExpr::Create( 15915 getASTContext(), E.get(), 15916 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15917 getASTContext()), 15918 /*IsImmediateInvocation*/ true); 15919 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15920 return Res; 15921 } 15922 15923 static void EvaluateAndDiagnoseImmediateInvocation( 15924 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15925 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15926 Expr::EvalResult Eval; 15927 Eval.Diag = &Notes; 15928 ConstantExpr *CE = Candidate.getPointer(); 15929 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15930 SemaRef.getASTContext(), true); 15931 if (!Result || !Notes.empty()) { 15932 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15933 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 15934 InnerExpr = FunctionalCast->getSubExpr(); 15935 FunctionDecl *FD = nullptr; 15936 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15937 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15938 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15939 FD = Call->getConstructor(); 15940 else 15941 llvm_unreachable("unhandled decl kind"); 15942 assert(FD->isConsteval()); 15943 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15944 for (auto &Note : Notes) 15945 SemaRef.Diag(Note.first, Note.second); 15946 return; 15947 } 15948 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15949 } 15950 15951 static void RemoveNestedImmediateInvocation( 15952 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15953 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15954 struct ComplexRemove : TreeTransform<ComplexRemove> { 15955 using Base = TreeTransform<ComplexRemove>; 15956 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15957 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15958 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15959 CurrentII; 15960 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15961 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15962 SmallVector<Sema::ImmediateInvocationCandidate, 15963 4>::reverse_iterator Current) 15964 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15965 void RemoveImmediateInvocation(ConstantExpr* E) { 15966 auto It = std::find_if(CurrentII, IISet.rend(), 15967 [E](Sema::ImmediateInvocationCandidate Elem) { 15968 return Elem.getPointer() == E; 15969 }); 15970 assert(It != IISet.rend() && 15971 "ConstantExpr marked IsImmediateInvocation should " 15972 "be present"); 15973 It->setInt(1); // Mark as deleted 15974 } 15975 ExprResult TransformConstantExpr(ConstantExpr *E) { 15976 if (!E->isImmediateInvocation()) 15977 return Base::TransformConstantExpr(E); 15978 RemoveImmediateInvocation(E); 15979 return Base::TransformExpr(E->getSubExpr()); 15980 } 15981 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15982 /// we need to remove its DeclRefExpr from the DRSet. 15983 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15984 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15985 return Base::TransformCXXOperatorCallExpr(E); 15986 } 15987 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15988 /// here. 15989 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15990 if (!Init) 15991 return Init; 15992 /// ConstantExpr are the first layer of implicit node to be removed so if 15993 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15994 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 15995 if (CE->isImmediateInvocation()) 15996 RemoveImmediateInvocation(CE); 15997 return Base::TransformInitializer(Init, NotCopyInit); 15998 } 15999 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16000 DRSet.erase(E); 16001 return E; 16002 } 16003 bool AlwaysRebuild() { return false; } 16004 bool ReplacingOriginal() { return true; } 16005 bool AllowSkippingCXXConstructExpr() { 16006 bool Res = AllowSkippingFirstCXXConstructExpr; 16007 AllowSkippingFirstCXXConstructExpr = true; 16008 return Res; 16009 } 16010 bool AllowSkippingFirstCXXConstructExpr = true; 16011 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16012 Rec.ImmediateInvocationCandidates, It); 16013 16014 /// CXXConstructExpr with a single argument are getting skipped by 16015 /// TreeTransform in some situtation because they could be implicit. This 16016 /// can only occur for the top-level CXXConstructExpr because it is used 16017 /// nowhere in the expression being transformed therefore will not be rebuilt. 16018 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16019 /// skipping the first CXXConstructExpr. 16020 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16021 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16022 16023 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16024 assert(Res.isUsable()); 16025 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16026 It->getPointer()->setSubExpr(Res.get()); 16027 } 16028 16029 static void 16030 HandleImmediateInvocations(Sema &SemaRef, 16031 Sema::ExpressionEvaluationContextRecord &Rec) { 16032 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16033 Rec.ReferenceToConsteval.size() == 0) || 16034 SemaRef.RebuildingImmediateInvocation) 16035 return; 16036 16037 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16038 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16039 /// need to remove ReferenceToConsteval in the immediate invocation. 16040 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16041 16042 /// Prevent sema calls during the tree transform from adding pointers that 16043 /// are already in the sets. 16044 llvm::SaveAndRestore<bool> DisableIITracking( 16045 SemaRef.RebuildingImmediateInvocation, true); 16046 16047 /// Prevent diagnostic during tree transfrom as they are duplicates 16048 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16049 16050 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16051 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16052 if (!It->getInt()) 16053 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16054 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16055 Rec.ReferenceToConsteval.size()) { 16056 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16057 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16058 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16059 bool VisitDeclRefExpr(DeclRefExpr *E) { 16060 DRSet.erase(E); 16061 return DRSet.size(); 16062 } 16063 } Visitor(Rec.ReferenceToConsteval); 16064 Visitor.TraverseStmt( 16065 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16066 } 16067 for (auto CE : Rec.ImmediateInvocationCandidates) 16068 if (!CE.getInt()) 16069 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16070 for (auto DR : Rec.ReferenceToConsteval) { 16071 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16072 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16073 << FD; 16074 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16075 } 16076 } 16077 16078 void Sema::PopExpressionEvaluationContext() { 16079 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16080 unsigned NumTypos = Rec.NumTypos; 16081 16082 if (!Rec.Lambdas.empty()) { 16083 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16084 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16085 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16086 unsigned D; 16087 if (Rec.isUnevaluated()) { 16088 // C++11 [expr.prim.lambda]p2: 16089 // A lambda-expression shall not appear in an unevaluated operand 16090 // (Clause 5). 16091 D = diag::err_lambda_unevaluated_operand; 16092 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16093 // C++1y [expr.const]p2: 16094 // A conditional-expression e is a core constant expression unless the 16095 // evaluation of e, following the rules of the abstract machine, would 16096 // evaluate [...] a lambda-expression. 16097 D = diag::err_lambda_in_constant_expression; 16098 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16099 // C++17 [expr.prim.lamda]p2: 16100 // A lambda-expression shall not appear [...] in a template-argument. 16101 D = diag::err_lambda_in_invalid_context; 16102 } else 16103 llvm_unreachable("Couldn't infer lambda error message."); 16104 16105 for (const auto *L : Rec.Lambdas) 16106 Diag(L->getBeginLoc(), D); 16107 } 16108 } 16109 16110 WarnOnPendingNoDerefs(Rec); 16111 HandleImmediateInvocations(*this, Rec); 16112 16113 // Warn on any volatile-qualified simple-assignments that are not discarded- 16114 // value expressions nor unevaluated operands (those cases get removed from 16115 // this list by CheckUnusedVolatileAssignment). 16116 for (auto *BO : Rec.VolatileAssignmentLHSs) 16117 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16118 << BO->getType(); 16119 16120 // When are coming out of an unevaluated context, clear out any 16121 // temporaries that we may have created as part of the evaluation of 16122 // the expression in that context: they aren't relevant because they 16123 // will never be constructed. 16124 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16125 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16126 ExprCleanupObjects.end()); 16127 Cleanup = Rec.ParentCleanup; 16128 CleanupVarDeclMarking(); 16129 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16130 // Otherwise, merge the contexts together. 16131 } else { 16132 Cleanup.mergeFrom(Rec.ParentCleanup); 16133 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16134 Rec.SavedMaybeODRUseExprs.end()); 16135 } 16136 16137 // Pop the current expression evaluation context off the stack. 16138 ExprEvalContexts.pop_back(); 16139 16140 // The global expression evaluation context record is never popped. 16141 ExprEvalContexts.back().NumTypos += NumTypos; 16142 } 16143 16144 void Sema::DiscardCleanupsInEvaluationContext() { 16145 ExprCleanupObjects.erase( 16146 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16147 ExprCleanupObjects.end()); 16148 Cleanup.reset(); 16149 MaybeODRUseExprs.clear(); 16150 } 16151 16152 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16153 ExprResult Result = CheckPlaceholderExpr(E); 16154 if (Result.isInvalid()) 16155 return ExprError(); 16156 E = Result.get(); 16157 if (!E->getType()->isVariablyModifiedType()) 16158 return E; 16159 return TransformToPotentiallyEvaluated(E); 16160 } 16161 16162 /// Are we in a context that is potentially constant evaluated per C++20 16163 /// [expr.const]p12? 16164 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16165 /// C++2a [expr.const]p12: 16166 // An expression or conversion is potentially constant evaluated if it is 16167 switch (SemaRef.ExprEvalContexts.back().Context) { 16168 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16169 // -- a manifestly constant-evaluated expression, 16170 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16171 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16172 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16173 // -- a potentially-evaluated expression, 16174 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16175 // -- an immediate subexpression of a braced-init-list, 16176 16177 // -- [FIXME] an expression of the form & cast-expression that occurs 16178 // within a templated entity 16179 // -- a subexpression of one of the above that is not a subexpression of 16180 // a nested unevaluated operand. 16181 return true; 16182 16183 case Sema::ExpressionEvaluationContext::Unevaluated: 16184 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16185 // Expressions in this context are never evaluated. 16186 return false; 16187 } 16188 llvm_unreachable("Invalid context"); 16189 } 16190 16191 /// Return true if this function has a calling convention that requires mangling 16192 /// in the size of the parameter pack. 16193 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16194 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16195 // we don't need parameter type sizes. 16196 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16197 if (!TT.isOSWindows() || !TT.isX86()) 16198 return false; 16199 16200 // If this is C++ and this isn't an extern "C" function, parameters do not 16201 // need to be complete. In this case, C++ mangling will apply, which doesn't 16202 // use the size of the parameters. 16203 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16204 return false; 16205 16206 // Stdcall, fastcall, and vectorcall need this special treatment. 16207 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16208 switch (CC) { 16209 case CC_X86StdCall: 16210 case CC_X86FastCall: 16211 case CC_X86VectorCall: 16212 return true; 16213 default: 16214 break; 16215 } 16216 return false; 16217 } 16218 16219 /// Require that all of the parameter types of function be complete. Normally, 16220 /// parameter types are only required to be complete when a function is called 16221 /// or defined, but to mangle functions with certain calling conventions, the 16222 /// mangler needs to know the size of the parameter list. In this situation, 16223 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16224 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16225 /// result in a linker error. Clang doesn't implement this behavior, and instead 16226 /// attempts to error at compile time. 16227 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16228 SourceLocation Loc) { 16229 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16230 FunctionDecl *FD; 16231 ParmVarDecl *Param; 16232 16233 public: 16234 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16235 : FD(FD), Param(Param) {} 16236 16237 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16238 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16239 StringRef CCName; 16240 switch (CC) { 16241 case CC_X86StdCall: 16242 CCName = "stdcall"; 16243 break; 16244 case CC_X86FastCall: 16245 CCName = "fastcall"; 16246 break; 16247 case CC_X86VectorCall: 16248 CCName = "vectorcall"; 16249 break; 16250 default: 16251 llvm_unreachable("CC does not need mangling"); 16252 } 16253 16254 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16255 << Param->getDeclName() << FD->getDeclName() << CCName; 16256 } 16257 }; 16258 16259 for (ParmVarDecl *Param : FD->parameters()) { 16260 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16261 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16262 } 16263 } 16264 16265 namespace { 16266 enum class OdrUseContext { 16267 /// Declarations in this context are not odr-used. 16268 None, 16269 /// Declarations in this context are formally odr-used, but this is a 16270 /// dependent context. 16271 Dependent, 16272 /// Declarations in this context are odr-used but not actually used (yet). 16273 FormallyOdrUsed, 16274 /// Declarations in this context are used. 16275 Used 16276 }; 16277 } 16278 16279 /// Are we within a context in which references to resolved functions or to 16280 /// variables result in odr-use? 16281 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16282 OdrUseContext Result; 16283 16284 switch (SemaRef.ExprEvalContexts.back().Context) { 16285 case Sema::ExpressionEvaluationContext::Unevaluated: 16286 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16287 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16288 return OdrUseContext::None; 16289 16290 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16291 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16292 Result = OdrUseContext::Used; 16293 break; 16294 16295 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16296 Result = OdrUseContext::FormallyOdrUsed; 16297 break; 16298 16299 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16300 // A default argument formally results in odr-use, but doesn't actually 16301 // result in a use in any real sense until it itself is used. 16302 Result = OdrUseContext::FormallyOdrUsed; 16303 break; 16304 } 16305 16306 if (SemaRef.CurContext->isDependentContext()) 16307 return OdrUseContext::Dependent; 16308 16309 return Result; 16310 } 16311 16312 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16313 return Func->isConstexpr() && 16314 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16315 } 16316 16317 /// Mark a function referenced, and check whether it is odr-used 16318 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16319 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16320 bool MightBeOdrUse) { 16321 assert(Func && "No function?"); 16322 16323 Func->setReferenced(); 16324 16325 // Recursive functions aren't really used until they're used from some other 16326 // context. 16327 bool IsRecursiveCall = CurContext == Func; 16328 16329 // C++11 [basic.def.odr]p3: 16330 // A function whose name appears as a potentially-evaluated expression is 16331 // odr-used if it is the unique lookup result or the selected member of a 16332 // set of overloaded functions [...]. 16333 // 16334 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16335 // can just check that here. 16336 OdrUseContext OdrUse = 16337 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16338 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16339 OdrUse = OdrUseContext::FormallyOdrUsed; 16340 16341 // Trivial default constructors and destructors are never actually used. 16342 // FIXME: What about other special members? 16343 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16344 OdrUse == OdrUseContext::Used) { 16345 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16346 if (Constructor->isDefaultConstructor()) 16347 OdrUse = OdrUseContext::FormallyOdrUsed; 16348 if (isa<CXXDestructorDecl>(Func)) 16349 OdrUse = OdrUseContext::FormallyOdrUsed; 16350 } 16351 16352 // C++20 [expr.const]p12: 16353 // A function [...] is needed for constant evaluation if it is [...] a 16354 // constexpr function that is named by an expression that is potentially 16355 // constant evaluated 16356 bool NeededForConstantEvaluation = 16357 isPotentiallyConstantEvaluatedContext(*this) && 16358 isImplicitlyDefinableConstexprFunction(Func); 16359 16360 // Determine whether we require a function definition to exist, per 16361 // C++11 [temp.inst]p3: 16362 // Unless a function template specialization has been explicitly 16363 // instantiated or explicitly specialized, the function template 16364 // specialization is implicitly instantiated when the specialization is 16365 // referenced in a context that requires a function definition to exist. 16366 // C++20 [temp.inst]p7: 16367 // The existence of a definition of a [...] function is considered to 16368 // affect the semantics of the program if the [...] function is needed for 16369 // constant evaluation by an expression 16370 // C++20 [basic.def.odr]p10: 16371 // Every program shall contain exactly one definition of every non-inline 16372 // function or variable that is odr-used in that program outside of a 16373 // discarded statement 16374 // C++20 [special]p1: 16375 // The implementation will implicitly define [defaulted special members] 16376 // if they are odr-used or needed for constant evaluation. 16377 // 16378 // Note that we skip the implicit instantiation of templates that are only 16379 // used in unused default arguments or by recursive calls to themselves. 16380 // This is formally non-conforming, but seems reasonable in practice. 16381 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16382 NeededForConstantEvaluation); 16383 16384 // C++14 [temp.expl.spec]p6: 16385 // If a template [...] is explicitly specialized then that specialization 16386 // shall be declared before the first use of that specialization that would 16387 // cause an implicit instantiation to take place, in every translation unit 16388 // in which such a use occurs 16389 if (NeedDefinition && 16390 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16391 Func->getMemberSpecializationInfo())) 16392 checkSpecializationVisibility(Loc, Func); 16393 16394 if (getLangOpts().CUDA) 16395 CheckCUDACall(Loc, Func); 16396 16397 // If we need a definition, try to create one. 16398 if (NeedDefinition && !Func->getBody()) { 16399 runWithSufficientStackSpace(Loc, [&] { 16400 if (CXXConstructorDecl *Constructor = 16401 dyn_cast<CXXConstructorDecl>(Func)) { 16402 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16403 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16404 if (Constructor->isDefaultConstructor()) { 16405 if (Constructor->isTrivial() && 16406 !Constructor->hasAttr<DLLExportAttr>()) 16407 return; 16408 DefineImplicitDefaultConstructor(Loc, Constructor); 16409 } else if (Constructor->isCopyConstructor()) { 16410 DefineImplicitCopyConstructor(Loc, Constructor); 16411 } else if (Constructor->isMoveConstructor()) { 16412 DefineImplicitMoveConstructor(Loc, Constructor); 16413 } 16414 } else if (Constructor->getInheritedConstructor()) { 16415 DefineInheritingConstructor(Loc, Constructor); 16416 } 16417 } else if (CXXDestructorDecl *Destructor = 16418 dyn_cast<CXXDestructorDecl>(Func)) { 16419 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16420 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16421 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16422 return; 16423 DefineImplicitDestructor(Loc, Destructor); 16424 } 16425 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16426 MarkVTableUsed(Loc, Destructor->getParent()); 16427 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16428 if (MethodDecl->isOverloadedOperator() && 16429 MethodDecl->getOverloadedOperator() == OO_Equal) { 16430 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16431 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16432 if (MethodDecl->isCopyAssignmentOperator()) 16433 DefineImplicitCopyAssignment(Loc, MethodDecl); 16434 else if (MethodDecl->isMoveAssignmentOperator()) 16435 DefineImplicitMoveAssignment(Loc, MethodDecl); 16436 } 16437 } else if (isa<CXXConversionDecl>(MethodDecl) && 16438 MethodDecl->getParent()->isLambda()) { 16439 CXXConversionDecl *Conversion = 16440 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16441 if (Conversion->isLambdaToBlockPointerConversion()) 16442 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16443 else 16444 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16445 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16446 MarkVTableUsed(Loc, MethodDecl->getParent()); 16447 } 16448 16449 if (Func->isDefaulted() && !Func->isDeleted()) { 16450 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16451 if (DCK != DefaultedComparisonKind::None) 16452 DefineDefaultedComparison(Loc, Func, DCK); 16453 } 16454 16455 // Implicit instantiation of function templates and member functions of 16456 // class templates. 16457 if (Func->isImplicitlyInstantiable()) { 16458 TemplateSpecializationKind TSK = 16459 Func->getTemplateSpecializationKindForInstantiation(); 16460 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16461 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16462 if (FirstInstantiation) { 16463 PointOfInstantiation = Loc; 16464 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16465 } else if (TSK != TSK_ImplicitInstantiation) { 16466 // Use the point of use as the point of instantiation, instead of the 16467 // point of explicit instantiation (which we track as the actual point 16468 // of instantiation). This gives better backtraces in diagnostics. 16469 PointOfInstantiation = Loc; 16470 } 16471 16472 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16473 Func->isConstexpr()) { 16474 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16475 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16476 CodeSynthesisContexts.size()) 16477 PendingLocalImplicitInstantiations.push_back( 16478 std::make_pair(Func, PointOfInstantiation)); 16479 else if (Func->isConstexpr()) 16480 // Do not defer instantiations of constexpr functions, to avoid the 16481 // expression evaluator needing to call back into Sema if it sees a 16482 // call to such a function. 16483 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16484 else { 16485 Func->setInstantiationIsPending(true); 16486 PendingInstantiations.push_back( 16487 std::make_pair(Func, PointOfInstantiation)); 16488 // Notify the consumer that a function was implicitly instantiated. 16489 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16490 } 16491 } 16492 } else { 16493 // Walk redefinitions, as some of them may be instantiable. 16494 for (auto i : Func->redecls()) { 16495 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16496 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16497 } 16498 } 16499 }); 16500 } 16501 16502 // C++14 [except.spec]p17: 16503 // An exception-specification is considered to be needed when: 16504 // - the function is odr-used or, if it appears in an unevaluated operand, 16505 // would be odr-used if the expression were potentially-evaluated; 16506 // 16507 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16508 // function is a pure virtual function we're calling, and in that case the 16509 // function was selected by overload resolution and we need to resolve its 16510 // exception specification for a different reason. 16511 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16512 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16513 ResolveExceptionSpec(Loc, FPT); 16514 16515 // If this is the first "real" use, act on that. 16516 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16517 // Keep track of used but undefined functions. 16518 if (!Func->isDefined()) { 16519 if (mightHaveNonExternalLinkage(Func)) 16520 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16521 else if (Func->getMostRecentDecl()->isInlined() && 16522 !LangOpts.GNUInline && 16523 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16524 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16525 else if (isExternalWithNoLinkageType(Func)) 16526 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16527 } 16528 16529 // Some x86 Windows calling conventions mangle the size of the parameter 16530 // pack into the name. Computing the size of the parameters requires the 16531 // parameter types to be complete. Check that now. 16532 if (funcHasParameterSizeMangling(*this, Func)) 16533 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16534 16535 // In the MS C++ ABI, the compiler emits destructor variants where they are 16536 // used. If the destructor is used here but defined elsewhere, mark the 16537 // virtual base destructors referenced. If those virtual base destructors 16538 // are inline, this will ensure they are defined when emitting the complete 16539 // destructor variant. This checking may be redundant if the destructor is 16540 // provided later in this TU. 16541 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16542 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16543 CXXRecordDecl *Parent = Dtor->getParent(); 16544 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16545 CheckCompleteDestructorVariant(Loc, Dtor); 16546 } 16547 } 16548 16549 Func->markUsed(Context); 16550 } 16551 } 16552 16553 /// Directly mark a variable odr-used. Given a choice, prefer to use 16554 /// MarkVariableReferenced since it does additional checks and then 16555 /// calls MarkVarDeclODRUsed. 16556 /// If the variable must be captured: 16557 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16558 /// - else capture it in the DeclContext that maps to the 16559 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16560 static void 16561 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16562 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16563 // Keep track of used but undefined variables. 16564 // FIXME: We shouldn't suppress this warning for static data members. 16565 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16566 (!Var->isExternallyVisible() || Var->isInline() || 16567 SemaRef.isExternalWithNoLinkageType(Var)) && 16568 !(Var->isStaticDataMember() && Var->hasInit())) { 16569 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16570 if (old.isInvalid()) 16571 old = Loc; 16572 } 16573 QualType CaptureType, DeclRefType; 16574 if (SemaRef.LangOpts.OpenMP) 16575 SemaRef.tryCaptureOpenMPLambdas(Var); 16576 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16577 /*EllipsisLoc*/ SourceLocation(), 16578 /*BuildAndDiagnose*/ true, 16579 CaptureType, DeclRefType, 16580 FunctionScopeIndexToStopAt); 16581 16582 Var->markUsed(SemaRef.Context); 16583 } 16584 16585 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16586 SourceLocation Loc, 16587 unsigned CapturingScopeIndex) { 16588 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16589 } 16590 16591 static void 16592 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16593 ValueDecl *var, DeclContext *DC) { 16594 DeclContext *VarDC = var->getDeclContext(); 16595 16596 // If the parameter still belongs to the translation unit, then 16597 // we're actually just using one parameter in the declaration of 16598 // the next. 16599 if (isa<ParmVarDecl>(var) && 16600 isa<TranslationUnitDecl>(VarDC)) 16601 return; 16602 16603 // For C code, don't diagnose about capture if we're not actually in code 16604 // right now; it's impossible to write a non-constant expression outside of 16605 // function context, so we'll get other (more useful) diagnostics later. 16606 // 16607 // For C++, things get a bit more nasty... it would be nice to suppress this 16608 // diagnostic for certain cases like using a local variable in an array bound 16609 // for a member of a local class, but the correct predicate is not obvious. 16610 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16611 return; 16612 16613 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16614 unsigned ContextKind = 3; // unknown 16615 if (isa<CXXMethodDecl>(VarDC) && 16616 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16617 ContextKind = 2; 16618 } else if (isa<FunctionDecl>(VarDC)) { 16619 ContextKind = 0; 16620 } else if (isa<BlockDecl>(VarDC)) { 16621 ContextKind = 1; 16622 } 16623 16624 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16625 << var << ValueKind << ContextKind << VarDC; 16626 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16627 << var; 16628 16629 // FIXME: Add additional diagnostic info about class etc. which prevents 16630 // capture. 16631 } 16632 16633 16634 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16635 bool &SubCapturesAreNested, 16636 QualType &CaptureType, 16637 QualType &DeclRefType) { 16638 // Check whether we've already captured it. 16639 if (CSI->CaptureMap.count(Var)) { 16640 // If we found a capture, any subcaptures are nested. 16641 SubCapturesAreNested = true; 16642 16643 // Retrieve the capture type for this variable. 16644 CaptureType = CSI->getCapture(Var).getCaptureType(); 16645 16646 // Compute the type of an expression that refers to this variable. 16647 DeclRefType = CaptureType.getNonReferenceType(); 16648 16649 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16650 // are mutable in the sense that user can change their value - they are 16651 // private instances of the captured declarations. 16652 const Capture &Cap = CSI->getCapture(Var); 16653 if (Cap.isCopyCapture() && 16654 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16655 !(isa<CapturedRegionScopeInfo>(CSI) && 16656 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16657 DeclRefType.addConst(); 16658 return true; 16659 } 16660 return false; 16661 } 16662 16663 // Only block literals, captured statements, and lambda expressions can 16664 // capture; other scopes don't work. 16665 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16666 SourceLocation Loc, 16667 const bool Diagnose, Sema &S) { 16668 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16669 return getLambdaAwareParentOfDeclContext(DC); 16670 else if (Var->hasLocalStorage()) { 16671 if (Diagnose) 16672 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16673 } 16674 return nullptr; 16675 } 16676 16677 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16678 // certain types of variables (unnamed, variably modified types etc.) 16679 // so check for eligibility. 16680 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16681 SourceLocation Loc, 16682 const bool Diagnose, Sema &S) { 16683 16684 bool IsBlock = isa<BlockScopeInfo>(CSI); 16685 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16686 16687 // Lambdas are not allowed to capture unnamed variables 16688 // (e.g. anonymous unions). 16689 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16690 // assuming that's the intent. 16691 if (IsLambda && !Var->getDeclName()) { 16692 if (Diagnose) { 16693 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16694 S.Diag(Var->getLocation(), diag::note_declared_at); 16695 } 16696 return false; 16697 } 16698 16699 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16700 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16701 if (Diagnose) { 16702 S.Diag(Loc, diag::err_ref_vm_type); 16703 S.Diag(Var->getLocation(), diag::note_previous_decl) 16704 << Var->getDeclName(); 16705 } 16706 return false; 16707 } 16708 // Prohibit structs with flexible array members too. 16709 // We cannot capture what is in the tail end of the struct. 16710 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16711 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16712 if (Diagnose) { 16713 if (IsBlock) 16714 S.Diag(Loc, diag::err_ref_flexarray_type); 16715 else 16716 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16717 << Var->getDeclName(); 16718 S.Diag(Var->getLocation(), diag::note_previous_decl) 16719 << Var->getDeclName(); 16720 } 16721 return false; 16722 } 16723 } 16724 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16725 // Lambdas and captured statements are not allowed to capture __block 16726 // variables; they don't support the expected semantics. 16727 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16728 if (Diagnose) { 16729 S.Diag(Loc, diag::err_capture_block_variable) 16730 << Var->getDeclName() << !IsLambda; 16731 S.Diag(Var->getLocation(), diag::note_previous_decl) 16732 << Var->getDeclName(); 16733 } 16734 return false; 16735 } 16736 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16737 if (S.getLangOpts().OpenCL && IsBlock && 16738 Var->getType()->isBlockPointerType()) { 16739 if (Diagnose) 16740 S.Diag(Loc, diag::err_opencl_block_ref_block); 16741 return false; 16742 } 16743 16744 return true; 16745 } 16746 16747 // Returns true if the capture by block was successful. 16748 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16749 SourceLocation Loc, 16750 const bool BuildAndDiagnose, 16751 QualType &CaptureType, 16752 QualType &DeclRefType, 16753 const bool Nested, 16754 Sema &S, bool Invalid) { 16755 bool ByRef = false; 16756 16757 // Blocks are not allowed to capture arrays, excepting OpenCL. 16758 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16759 // (decayed to pointers). 16760 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16761 if (BuildAndDiagnose) { 16762 S.Diag(Loc, diag::err_ref_array_type); 16763 S.Diag(Var->getLocation(), diag::note_previous_decl) 16764 << Var->getDeclName(); 16765 Invalid = true; 16766 } else { 16767 return false; 16768 } 16769 } 16770 16771 // Forbid the block-capture of autoreleasing variables. 16772 if (!Invalid && 16773 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16774 if (BuildAndDiagnose) { 16775 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16776 << /*block*/ 0; 16777 S.Diag(Var->getLocation(), diag::note_previous_decl) 16778 << Var->getDeclName(); 16779 Invalid = true; 16780 } else { 16781 return false; 16782 } 16783 } 16784 16785 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16786 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16787 QualType PointeeTy = PT->getPointeeType(); 16788 16789 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16790 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16791 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16792 if (BuildAndDiagnose) { 16793 SourceLocation VarLoc = Var->getLocation(); 16794 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16795 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16796 } 16797 } 16798 } 16799 16800 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16801 if (HasBlocksAttr || CaptureType->isReferenceType() || 16802 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16803 // Block capture by reference does not change the capture or 16804 // declaration reference types. 16805 ByRef = true; 16806 } else { 16807 // Block capture by copy introduces 'const'. 16808 CaptureType = CaptureType.getNonReferenceType().withConst(); 16809 DeclRefType = CaptureType; 16810 } 16811 16812 // Actually capture the variable. 16813 if (BuildAndDiagnose) 16814 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16815 CaptureType, Invalid); 16816 16817 return !Invalid; 16818 } 16819 16820 16821 /// Capture the given variable in the captured region. 16822 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16823 VarDecl *Var, 16824 SourceLocation Loc, 16825 const bool BuildAndDiagnose, 16826 QualType &CaptureType, 16827 QualType &DeclRefType, 16828 const bool RefersToCapturedVariable, 16829 Sema &S, bool Invalid) { 16830 // By default, capture variables by reference. 16831 bool ByRef = true; 16832 // Using an LValue reference type is consistent with Lambdas (see below). 16833 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16834 if (S.isOpenMPCapturedDecl(Var)) { 16835 bool HasConst = DeclRefType.isConstQualified(); 16836 DeclRefType = DeclRefType.getUnqualifiedType(); 16837 // Don't lose diagnostics about assignments to const. 16838 if (HasConst) 16839 DeclRefType.addConst(); 16840 } 16841 // Do not capture firstprivates in tasks. 16842 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 16843 OMPC_unknown) 16844 return true; 16845 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16846 RSI->OpenMPCaptureLevel); 16847 } 16848 16849 if (ByRef) 16850 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16851 else 16852 CaptureType = DeclRefType; 16853 16854 // Actually capture the variable. 16855 if (BuildAndDiagnose) 16856 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16857 Loc, SourceLocation(), CaptureType, Invalid); 16858 16859 return !Invalid; 16860 } 16861 16862 /// Capture the given variable in the lambda. 16863 static bool captureInLambda(LambdaScopeInfo *LSI, 16864 VarDecl *Var, 16865 SourceLocation Loc, 16866 const bool BuildAndDiagnose, 16867 QualType &CaptureType, 16868 QualType &DeclRefType, 16869 const bool RefersToCapturedVariable, 16870 const Sema::TryCaptureKind Kind, 16871 SourceLocation EllipsisLoc, 16872 const bool IsTopScope, 16873 Sema &S, bool Invalid) { 16874 // Determine whether we are capturing by reference or by value. 16875 bool ByRef = false; 16876 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16877 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16878 } else { 16879 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16880 } 16881 16882 // Compute the type of the field that will capture this variable. 16883 if (ByRef) { 16884 // C++11 [expr.prim.lambda]p15: 16885 // An entity is captured by reference if it is implicitly or 16886 // explicitly captured but not captured by copy. It is 16887 // unspecified whether additional unnamed non-static data 16888 // members are declared in the closure type for entities 16889 // captured by reference. 16890 // 16891 // FIXME: It is not clear whether we want to build an lvalue reference 16892 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16893 // to do the former, while EDG does the latter. Core issue 1249 will 16894 // clarify, but for now we follow GCC because it's a more permissive and 16895 // easily defensible position. 16896 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16897 } else { 16898 // C++11 [expr.prim.lambda]p14: 16899 // For each entity captured by copy, an unnamed non-static 16900 // data member is declared in the closure type. The 16901 // declaration order of these members is unspecified. The type 16902 // of such a data member is the type of the corresponding 16903 // captured entity if the entity is not a reference to an 16904 // object, or the referenced type otherwise. [Note: If the 16905 // captured entity is a reference to a function, the 16906 // corresponding data member is also a reference to a 16907 // function. - end note ] 16908 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16909 if (!RefType->getPointeeType()->isFunctionType()) 16910 CaptureType = RefType->getPointeeType(); 16911 } 16912 16913 // Forbid the lambda copy-capture of autoreleasing variables. 16914 if (!Invalid && 16915 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16916 if (BuildAndDiagnose) { 16917 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16918 S.Diag(Var->getLocation(), diag::note_previous_decl) 16919 << Var->getDeclName(); 16920 Invalid = true; 16921 } else { 16922 return false; 16923 } 16924 } 16925 16926 // Make sure that by-copy captures are of a complete and non-abstract type. 16927 if (!Invalid && BuildAndDiagnose) { 16928 if (!CaptureType->isDependentType() && 16929 S.RequireCompleteSizedType( 16930 Loc, CaptureType, 16931 diag::err_capture_of_incomplete_or_sizeless_type, 16932 Var->getDeclName())) 16933 Invalid = true; 16934 else if (S.RequireNonAbstractType(Loc, CaptureType, 16935 diag::err_capture_of_abstract_type)) 16936 Invalid = true; 16937 } 16938 } 16939 16940 // Compute the type of a reference to this captured variable. 16941 if (ByRef) 16942 DeclRefType = CaptureType.getNonReferenceType(); 16943 else { 16944 // C++ [expr.prim.lambda]p5: 16945 // The closure type for a lambda-expression has a public inline 16946 // function call operator [...]. This function call operator is 16947 // declared const (9.3.1) if and only if the lambda-expression's 16948 // parameter-declaration-clause is not followed by mutable. 16949 DeclRefType = CaptureType.getNonReferenceType(); 16950 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16951 DeclRefType.addConst(); 16952 } 16953 16954 // Add the capture. 16955 if (BuildAndDiagnose) 16956 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16957 Loc, EllipsisLoc, CaptureType, Invalid); 16958 16959 return !Invalid; 16960 } 16961 16962 bool Sema::tryCaptureVariable( 16963 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16964 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16965 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16966 // An init-capture is notionally from the context surrounding its 16967 // declaration, but its parent DC is the lambda class. 16968 DeclContext *VarDC = Var->getDeclContext(); 16969 if (Var->isInitCapture()) 16970 VarDC = VarDC->getParent(); 16971 16972 DeclContext *DC = CurContext; 16973 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16974 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16975 // We need to sync up the Declaration Context with the 16976 // FunctionScopeIndexToStopAt 16977 if (FunctionScopeIndexToStopAt) { 16978 unsigned FSIndex = FunctionScopes.size() - 1; 16979 while (FSIndex != MaxFunctionScopesIndex) { 16980 DC = getLambdaAwareParentOfDeclContext(DC); 16981 --FSIndex; 16982 } 16983 } 16984 16985 16986 // If the variable is declared in the current context, there is no need to 16987 // capture it. 16988 if (VarDC == DC) return true; 16989 16990 // Capture global variables if it is required to use private copy of this 16991 // variable. 16992 bool IsGlobal = !Var->hasLocalStorage(); 16993 if (IsGlobal && 16994 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16995 MaxFunctionScopesIndex))) 16996 return true; 16997 Var = Var->getCanonicalDecl(); 16998 16999 // Walk up the stack to determine whether we can capture the variable, 17000 // performing the "simple" checks that don't depend on type. We stop when 17001 // we've either hit the declared scope of the variable or find an existing 17002 // capture of that variable. We start from the innermost capturing-entity 17003 // (the DC) and ensure that all intervening capturing-entities 17004 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17005 // declcontext can either capture the variable or have already captured 17006 // the variable. 17007 CaptureType = Var->getType(); 17008 DeclRefType = CaptureType.getNonReferenceType(); 17009 bool Nested = false; 17010 bool Explicit = (Kind != TryCapture_Implicit); 17011 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17012 do { 17013 // Only block literals, captured statements, and lambda expressions can 17014 // capture; other scopes don't work. 17015 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17016 ExprLoc, 17017 BuildAndDiagnose, 17018 *this); 17019 // We need to check for the parent *first* because, if we *have* 17020 // private-captured a global variable, we need to recursively capture it in 17021 // intermediate blocks, lambdas, etc. 17022 if (!ParentDC) { 17023 if (IsGlobal) { 17024 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17025 break; 17026 } 17027 return true; 17028 } 17029 17030 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17031 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17032 17033 17034 // Check whether we've already captured it. 17035 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17036 DeclRefType)) { 17037 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17038 break; 17039 } 17040 // If we are instantiating a generic lambda call operator body, 17041 // we do not want to capture new variables. What was captured 17042 // during either a lambdas transformation or initial parsing 17043 // should be used. 17044 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17045 if (BuildAndDiagnose) { 17046 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17047 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17048 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17049 Diag(Var->getLocation(), diag::note_previous_decl) 17050 << Var->getDeclName(); 17051 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17052 } else 17053 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17054 } 17055 return true; 17056 } 17057 17058 // Try to capture variable-length arrays types. 17059 if (Var->getType()->isVariablyModifiedType()) { 17060 // We're going to walk down into the type and look for VLA 17061 // expressions. 17062 QualType QTy = Var->getType(); 17063 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17064 QTy = PVD->getOriginalType(); 17065 captureVariablyModifiedType(Context, QTy, CSI); 17066 } 17067 17068 if (getLangOpts().OpenMP) { 17069 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17070 // OpenMP private variables should not be captured in outer scope, so 17071 // just break here. Similarly, global variables that are captured in a 17072 // target region should not be captured outside the scope of the region. 17073 if (RSI->CapRegionKind == CR_OpenMP) { 17074 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17075 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17076 // If the variable is private (i.e. not captured) and has variably 17077 // modified type, we still need to capture the type for correct 17078 // codegen in all regions, associated with the construct. Currently, 17079 // it is captured in the innermost captured region only. 17080 if (IsOpenMPPrivateDecl != OMPC_unknown && 17081 Var->getType()->isVariablyModifiedType()) { 17082 QualType QTy = Var->getType(); 17083 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17084 QTy = PVD->getOriginalType(); 17085 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17086 I < E; ++I) { 17087 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17088 FunctionScopes[FunctionScopesIndex - I]); 17089 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17090 "Wrong number of captured regions associated with the " 17091 "OpenMP construct."); 17092 captureVariablyModifiedType(Context, QTy, OuterRSI); 17093 } 17094 } 17095 bool IsTargetCap = 17096 IsOpenMPPrivateDecl != OMPC_private && 17097 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17098 RSI->OpenMPCaptureLevel); 17099 // Do not capture global if it is not privatized in outer regions. 17100 bool IsGlobalCap = 17101 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17102 RSI->OpenMPCaptureLevel); 17103 17104 // When we detect target captures we are looking from inside the 17105 // target region, therefore we need to propagate the capture from the 17106 // enclosing region. Therefore, the capture is not initially nested. 17107 if (IsTargetCap) 17108 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17109 17110 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17111 (IsGlobal && !IsGlobalCap)) { 17112 Nested = !IsTargetCap; 17113 DeclRefType = DeclRefType.getUnqualifiedType(); 17114 CaptureType = Context.getLValueReferenceType(DeclRefType); 17115 break; 17116 } 17117 } 17118 } 17119 } 17120 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17121 // No capture-default, and this is not an explicit capture 17122 // so cannot capture this variable. 17123 if (BuildAndDiagnose) { 17124 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17125 Diag(Var->getLocation(), diag::note_previous_decl) 17126 << Var->getDeclName(); 17127 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17128 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17129 diag::note_lambda_decl); 17130 // FIXME: If we error out because an outer lambda can not implicitly 17131 // capture a variable that an inner lambda explicitly captures, we 17132 // should have the inner lambda do the explicit capture - because 17133 // it makes for cleaner diagnostics later. This would purely be done 17134 // so that the diagnostic does not misleadingly claim that a variable 17135 // can not be captured by a lambda implicitly even though it is captured 17136 // explicitly. Suggestion: 17137 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17138 // at the function head 17139 // - cache the StartingDeclContext - this must be a lambda 17140 // - captureInLambda in the innermost lambda the variable. 17141 } 17142 return true; 17143 } 17144 17145 FunctionScopesIndex--; 17146 DC = ParentDC; 17147 Explicit = false; 17148 } while (!VarDC->Equals(DC)); 17149 17150 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17151 // computing the type of the capture at each step, checking type-specific 17152 // requirements, and adding captures if requested. 17153 // If the variable had already been captured previously, we start capturing 17154 // at the lambda nested within that one. 17155 bool Invalid = false; 17156 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17157 ++I) { 17158 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17159 17160 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17161 // certain types of variables (unnamed, variably modified types etc.) 17162 // so check for eligibility. 17163 if (!Invalid) 17164 Invalid = 17165 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17166 17167 // After encountering an error, if we're actually supposed to capture, keep 17168 // capturing in nested contexts to suppress any follow-on diagnostics. 17169 if (Invalid && !BuildAndDiagnose) 17170 return true; 17171 17172 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17173 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17174 DeclRefType, Nested, *this, Invalid); 17175 Nested = true; 17176 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17177 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17178 CaptureType, DeclRefType, Nested, 17179 *this, Invalid); 17180 Nested = true; 17181 } else { 17182 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17183 Invalid = 17184 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17185 DeclRefType, Nested, Kind, EllipsisLoc, 17186 /*IsTopScope*/ I == N - 1, *this, Invalid); 17187 Nested = true; 17188 } 17189 17190 if (Invalid && !BuildAndDiagnose) 17191 return true; 17192 } 17193 return Invalid; 17194 } 17195 17196 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17197 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17198 QualType CaptureType; 17199 QualType DeclRefType; 17200 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17201 /*BuildAndDiagnose=*/true, CaptureType, 17202 DeclRefType, nullptr); 17203 } 17204 17205 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17206 QualType CaptureType; 17207 QualType DeclRefType; 17208 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17209 /*BuildAndDiagnose=*/false, CaptureType, 17210 DeclRefType, nullptr); 17211 } 17212 17213 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17214 QualType CaptureType; 17215 QualType DeclRefType; 17216 17217 // Determine whether we can capture this variable. 17218 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17219 /*BuildAndDiagnose=*/false, CaptureType, 17220 DeclRefType, nullptr)) 17221 return QualType(); 17222 17223 return DeclRefType; 17224 } 17225 17226 namespace { 17227 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17228 // The produced TemplateArgumentListInfo* points to data stored within this 17229 // object, so should only be used in contexts where the pointer will not be 17230 // used after the CopiedTemplateArgs object is destroyed. 17231 class CopiedTemplateArgs { 17232 bool HasArgs; 17233 TemplateArgumentListInfo TemplateArgStorage; 17234 public: 17235 template<typename RefExpr> 17236 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17237 if (HasArgs) 17238 E->copyTemplateArgumentsInto(TemplateArgStorage); 17239 } 17240 operator TemplateArgumentListInfo*() 17241 #ifdef __has_cpp_attribute 17242 #if __has_cpp_attribute(clang::lifetimebound) 17243 [[clang::lifetimebound]] 17244 #endif 17245 #endif 17246 { 17247 return HasArgs ? &TemplateArgStorage : nullptr; 17248 } 17249 }; 17250 } 17251 17252 /// Walk the set of potential results of an expression and mark them all as 17253 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17254 /// 17255 /// \return A new expression if we found any potential results, ExprEmpty() if 17256 /// not, and ExprError() if we diagnosed an error. 17257 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17258 NonOdrUseReason NOUR) { 17259 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17260 // an object that satisfies the requirements for appearing in a 17261 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17262 // is immediately applied." This function handles the lvalue-to-rvalue 17263 // conversion part. 17264 // 17265 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17266 // transform it into the relevant kind of non-odr-use node and rebuild the 17267 // tree of nodes leading to it. 17268 // 17269 // This is a mini-TreeTransform that only transforms a restricted subset of 17270 // nodes (and only certain operands of them). 17271 17272 // Rebuild a subexpression. 17273 auto Rebuild = [&](Expr *Sub) { 17274 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17275 }; 17276 17277 // Check whether a potential result satisfies the requirements of NOUR. 17278 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17279 // Any entity other than a VarDecl is always odr-used whenever it's named 17280 // in a potentially-evaluated expression. 17281 auto *VD = dyn_cast<VarDecl>(D); 17282 if (!VD) 17283 return true; 17284 17285 // C++2a [basic.def.odr]p4: 17286 // A variable x whose name appears as a potentially-evalauted expression 17287 // e is odr-used by e unless 17288 // -- x is a reference that is usable in constant expressions, or 17289 // -- x is a variable of non-reference type that is usable in constant 17290 // expressions and has no mutable subobjects, and e is an element of 17291 // the set of potential results of an expression of 17292 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17293 // conversion is applied, or 17294 // -- x is a variable of non-reference type, and e is an element of the 17295 // set of potential results of a discarded-value expression to which 17296 // the lvalue-to-rvalue conversion is not applied 17297 // 17298 // We check the first bullet and the "potentially-evaluated" condition in 17299 // BuildDeclRefExpr. We check the type requirements in the second bullet 17300 // in CheckLValueToRValueConversionOperand below. 17301 switch (NOUR) { 17302 case NOUR_None: 17303 case NOUR_Unevaluated: 17304 llvm_unreachable("unexpected non-odr-use-reason"); 17305 17306 case NOUR_Constant: 17307 // Constant references were handled when they were built. 17308 if (VD->getType()->isReferenceType()) 17309 return true; 17310 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17311 if (RD->hasMutableFields()) 17312 return true; 17313 if (!VD->isUsableInConstantExpressions(S.Context)) 17314 return true; 17315 break; 17316 17317 case NOUR_Discarded: 17318 if (VD->getType()->isReferenceType()) 17319 return true; 17320 break; 17321 } 17322 return false; 17323 }; 17324 17325 // Mark that this expression does not constitute an odr-use. 17326 auto MarkNotOdrUsed = [&] { 17327 S.MaybeODRUseExprs.erase(E); 17328 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17329 LSI->markVariableExprAsNonODRUsed(E); 17330 }; 17331 17332 // C++2a [basic.def.odr]p2: 17333 // The set of potential results of an expression e is defined as follows: 17334 switch (E->getStmtClass()) { 17335 // -- If e is an id-expression, ... 17336 case Expr::DeclRefExprClass: { 17337 auto *DRE = cast<DeclRefExpr>(E); 17338 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17339 break; 17340 17341 // Rebuild as a non-odr-use DeclRefExpr. 17342 MarkNotOdrUsed(); 17343 return DeclRefExpr::Create( 17344 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17345 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17346 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17347 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17348 } 17349 17350 case Expr::FunctionParmPackExprClass: { 17351 auto *FPPE = cast<FunctionParmPackExpr>(E); 17352 // If any of the declarations in the pack is odr-used, then the expression 17353 // as a whole constitutes an odr-use. 17354 for (VarDecl *D : *FPPE) 17355 if (IsPotentialResultOdrUsed(D)) 17356 return ExprEmpty(); 17357 17358 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17359 // nothing cares about whether we marked this as an odr-use, but it might 17360 // be useful for non-compiler tools. 17361 MarkNotOdrUsed(); 17362 break; 17363 } 17364 17365 // -- If e is a subscripting operation with an array operand... 17366 case Expr::ArraySubscriptExprClass: { 17367 auto *ASE = cast<ArraySubscriptExpr>(E); 17368 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17369 if (!OldBase->getType()->isArrayType()) 17370 break; 17371 ExprResult Base = Rebuild(OldBase); 17372 if (!Base.isUsable()) 17373 return Base; 17374 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17375 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17376 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17377 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17378 ASE->getRBracketLoc()); 17379 } 17380 17381 case Expr::MemberExprClass: { 17382 auto *ME = cast<MemberExpr>(E); 17383 // -- If e is a class member access expression [...] naming a non-static 17384 // data member... 17385 if (isa<FieldDecl>(ME->getMemberDecl())) { 17386 ExprResult Base = Rebuild(ME->getBase()); 17387 if (!Base.isUsable()) 17388 return Base; 17389 return MemberExpr::Create( 17390 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17391 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17392 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17393 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17394 ME->getObjectKind(), ME->isNonOdrUse()); 17395 } 17396 17397 if (ME->getMemberDecl()->isCXXInstanceMember()) 17398 break; 17399 17400 // -- If e is a class member access expression naming a static data member, 17401 // ... 17402 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17403 break; 17404 17405 // Rebuild as a non-odr-use MemberExpr. 17406 MarkNotOdrUsed(); 17407 return MemberExpr::Create( 17408 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17409 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17410 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17411 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17412 return ExprEmpty(); 17413 } 17414 17415 case Expr::BinaryOperatorClass: { 17416 auto *BO = cast<BinaryOperator>(E); 17417 Expr *LHS = BO->getLHS(); 17418 Expr *RHS = BO->getRHS(); 17419 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17420 if (BO->getOpcode() == BO_PtrMemD) { 17421 ExprResult Sub = Rebuild(LHS); 17422 if (!Sub.isUsable()) 17423 return Sub; 17424 LHS = Sub.get(); 17425 // -- If e is a comma expression, ... 17426 } else if (BO->getOpcode() == BO_Comma) { 17427 ExprResult Sub = Rebuild(RHS); 17428 if (!Sub.isUsable()) 17429 return Sub; 17430 RHS = Sub.get(); 17431 } else { 17432 break; 17433 } 17434 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17435 LHS, RHS); 17436 } 17437 17438 // -- If e has the form (e1)... 17439 case Expr::ParenExprClass: { 17440 auto *PE = cast<ParenExpr>(E); 17441 ExprResult Sub = Rebuild(PE->getSubExpr()); 17442 if (!Sub.isUsable()) 17443 return Sub; 17444 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17445 } 17446 17447 // -- If e is a glvalue conditional expression, ... 17448 // We don't apply this to a binary conditional operator. FIXME: Should we? 17449 case Expr::ConditionalOperatorClass: { 17450 auto *CO = cast<ConditionalOperator>(E); 17451 ExprResult LHS = Rebuild(CO->getLHS()); 17452 if (LHS.isInvalid()) 17453 return ExprError(); 17454 ExprResult RHS = Rebuild(CO->getRHS()); 17455 if (RHS.isInvalid()) 17456 return ExprError(); 17457 if (!LHS.isUsable() && !RHS.isUsable()) 17458 return ExprEmpty(); 17459 if (!LHS.isUsable()) 17460 LHS = CO->getLHS(); 17461 if (!RHS.isUsable()) 17462 RHS = CO->getRHS(); 17463 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17464 CO->getCond(), LHS.get(), RHS.get()); 17465 } 17466 17467 // [Clang extension] 17468 // -- If e has the form __extension__ e1... 17469 case Expr::UnaryOperatorClass: { 17470 auto *UO = cast<UnaryOperator>(E); 17471 if (UO->getOpcode() != UO_Extension) 17472 break; 17473 ExprResult Sub = Rebuild(UO->getSubExpr()); 17474 if (!Sub.isUsable()) 17475 return Sub; 17476 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17477 Sub.get()); 17478 } 17479 17480 // [Clang extension] 17481 // -- If e has the form _Generic(...), the set of potential results is the 17482 // union of the sets of potential results of the associated expressions. 17483 case Expr::GenericSelectionExprClass: { 17484 auto *GSE = cast<GenericSelectionExpr>(E); 17485 17486 SmallVector<Expr *, 4> AssocExprs; 17487 bool AnyChanged = false; 17488 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17489 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17490 if (AssocExpr.isInvalid()) 17491 return ExprError(); 17492 if (AssocExpr.isUsable()) { 17493 AssocExprs.push_back(AssocExpr.get()); 17494 AnyChanged = true; 17495 } else { 17496 AssocExprs.push_back(OrigAssocExpr); 17497 } 17498 } 17499 17500 return AnyChanged ? S.CreateGenericSelectionExpr( 17501 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17502 GSE->getRParenLoc(), GSE->getControllingExpr(), 17503 GSE->getAssocTypeSourceInfos(), AssocExprs) 17504 : ExprEmpty(); 17505 } 17506 17507 // [Clang extension] 17508 // -- If e has the form __builtin_choose_expr(...), the set of potential 17509 // results is the union of the sets of potential results of the 17510 // second and third subexpressions. 17511 case Expr::ChooseExprClass: { 17512 auto *CE = cast<ChooseExpr>(E); 17513 17514 ExprResult LHS = Rebuild(CE->getLHS()); 17515 if (LHS.isInvalid()) 17516 return ExprError(); 17517 17518 ExprResult RHS = Rebuild(CE->getLHS()); 17519 if (RHS.isInvalid()) 17520 return ExprError(); 17521 17522 if (!LHS.get() && !RHS.get()) 17523 return ExprEmpty(); 17524 if (!LHS.isUsable()) 17525 LHS = CE->getLHS(); 17526 if (!RHS.isUsable()) 17527 RHS = CE->getRHS(); 17528 17529 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17530 RHS.get(), CE->getRParenLoc()); 17531 } 17532 17533 // Step through non-syntactic nodes. 17534 case Expr::ConstantExprClass: { 17535 auto *CE = cast<ConstantExpr>(E); 17536 ExprResult Sub = Rebuild(CE->getSubExpr()); 17537 if (!Sub.isUsable()) 17538 return Sub; 17539 return ConstantExpr::Create(S.Context, Sub.get()); 17540 } 17541 17542 // We could mostly rely on the recursive rebuilding to rebuild implicit 17543 // casts, but not at the top level, so rebuild them here. 17544 case Expr::ImplicitCastExprClass: { 17545 auto *ICE = cast<ImplicitCastExpr>(E); 17546 // Only step through the narrow set of cast kinds we expect to encounter. 17547 // Anything else suggests we've left the region in which potential results 17548 // can be found. 17549 switch (ICE->getCastKind()) { 17550 case CK_NoOp: 17551 case CK_DerivedToBase: 17552 case CK_UncheckedDerivedToBase: { 17553 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17554 if (!Sub.isUsable()) 17555 return Sub; 17556 CXXCastPath Path(ICE->path()); 17557 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17558 ICE->getValueKind(), &Path); 17559 } 17560 17561 default: 17562 break; 17563 } 17564 break; 17565 } 17566 17567 default: 17568 break; 17569 } 17570 17571 // Can't traverse through this node. Nothing to do. 17572 return ExprEmpty(); 17573 } 17574 17575 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17576 // Check whether the operand is or contains an object of non-trivial C union 17577 // type. 17578 if (E->getType().isVolatileQualified() && 17579 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17580 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17581 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17582 Sema::NTCUC_LValueToRValueVolatile, 17583 NTCUK_Destruct|NTCUK_Copy); 17584 17585 // C++2a [basic.def.odr]p4: 17586 // [...] an expression of non-volatile-qualified non-class type to which 17587 // the lvalue-to-rvalue conversion is applied [...] 17588 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17589 return E; 17590 17591 ExprResult Result = 17592 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17593 if (Result.isInvalid()) 17594 return ExprError(); 17595 return Result.get() ? Result : E; 17596 } 17597 17598 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17599 Res = CorrectDelayedTyposInExpr(Res); 17600 17601 if (!Res.isUsable()) 17602 return Res; 17603 17604 // If a constant-expression is a reference to a variable where we delay 17605 // deciding whether it is an odr-use, just assume we will apply the 17606 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17607 // (a non-type template argument), we have special handling anyway. 17608 return CheckLValueToRValueConversionOperand(Res.get()); 17609 } 17610 17611 void Sema::CleanupVarDeclMarking() { 17612 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17613 // call. 17614 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17615 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17616 17617 for (Expr *E : LocalMaybeODRUseExprs) { 17618 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17619 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17620 DRE->getLocation(), *this); 17621 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17622 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17623 *this); 17624 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17625 for (VarDecl *VD : *FP) 17626 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17627 } else { 17628 llvm_unreachable("Unexpected expression"); 17629 } 17630 } 17631 17632 assert(MaybeODRUseExprs.empty() && 17633 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17634 } 17635 17636 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17637 VarDecl *Var, Expr *E) { 17638 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17639 isa<FunctionParmPackExpr>(E)) && 17640 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17641 Var->setReferenced(); 17642 17643 if (Var->isInvalidDecl()) 17644 return; 17645 17646 auto *MSI = Var->getMemberSpecializationInfo(); 17647 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17648 : Var->getTemplateSpecializationKind(); 17649 17650 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17651 bool UsableInConstantExpr = 17652 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17653 17654 // C++20 [expr.const]p12: 17655 // A variable [...] is needed for constant evaluation if it is [...] a 17656 // variable whose name appears as a potentially constant evaluated 17657 // expression that is either a contexpr variable or is of non-volatile 17658 // const-qualified integral type or of reference type 17659 bool NeededForConstantEvaluation = 17660 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17661 17662 bool NeedDefinition = 17663 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17664 17665 VarTemplateSpecializationDecl *VarSpec = 17666 dyn_cast<VarTemplateSpecializationDecl>(Var); 17667 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17668 "Can't instantiate a partial template specialization."); 17669 17670 // If this might be a member specialization of a static data member, check 17671 // the specialization is visible. We already did the checks for variable 17672 // template specializations when we created them. 17673 if (NeedDefinition && TSK != TSK_Undeclared && 17674 !isa<VarTemplateSpecializationDecl>(Var)) 17675 SemaRef.checkSpecializationVisibility(Loc, Var); 17676 17677 // Perform implicit instantiation of static data members, static data member 17678 // templates of class templates, and variable template specializations. Delay 17679 // instantiations of variable templates, except for those that could be used 17680 // in a constant expression. 17681 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17682 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17683 // instantiation declaration if a variable is usable in a constant 17684 // expression (among other cases). 17685 bool TryInstantiating = 17686 TSK == TSK_ImplicitInstantiation || 17687 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17688 17689 if (TryInstantiating) { 17690 SourceLocation PointOfInstantiation = 17691 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17692 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17693 if (FirstInstantiation) { 17694 PointOfInstantiation = Loc; 17695 if (MSI) 17696 MSI->setPointOfInstantiation(PointOfInstantiation); 17697 else 17698 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17699 } 17700 17701 bool InstantiationDependent = false; 17702 bool IsNonDependent = 17703 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17704 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17705 : true; 17706 17707 // Do not instantiate specializations that are still type-dependent. 17708 if (IsNonDependent) { 17709 if (UsableInConstantExpr) { 17710 // Do not defer instantiations of variables that could be used in a 17711 // constant expression. 17712 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17713 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17714 }); 17715 } else if (FirstInstantiation || 17716 isa<VarTemplateSpecializationDecl>(Var)) { 17717 // FIXME: For a specialization of a variable template, we don't 17718 // distinguish between "declaration and type implicitly instantiated" 17719 // and "implicit instantiation of definition requested", so we have 17720 // no direct way to avoid enqueueing the pending instantiation 17721 // multiple times. 17722 SemaRef.PendingInstantiations 17723 .push_back(std::make_pair(Var, PointOfInstantiation)); 17724 } 17725 } 17726 } 17727 } 17728 17729 // C++2a [basic.def.odr]p4: 17730 // A variable x whose name appears as a potentially-evaluated expression e 17731 // is odr-used by e unless 17732 // -- x is a reference that is usable in constant expressions 17733 // -- x is a variable of non-reference type that is usable in constant 17734 // expressions and has no mutable subobjects [FIXME], and e is an 17735 // element of the set of potential results of an expression of 17736 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17737 // conversion is applied 17738 // -- x is a variable of non-reference type, and e is an element of the set 17739 // of potential results of a discarded-value expression to which the 17740 // lvalue-to-rvalue conversion is not applied [FIXME] 17741 // 17742 // We check the first part of the second bullet here, and 17743 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17744 // FIXME: To get the third bullet right, we need to delay this even for 17745 // variables that are not usable in constant expressions. 17746 17747 // If we already know this isn't an odr-use, there's nothing more to do. 17748 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17749 if (DRE->isNonOdrUse()) 17750 return; 17751 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17752 if (ME->isNonOdrUse()) 17753 return; 17754 17755 switch (OdrUse) { 17756 case OdrUseContext::None: 17757 assert((!E || isa<FunctionParmPackExpr>(E)) && 17758 "missing non-odr-use marking for unevaluated decl ref"); 17759 break; 17760 17761 case OdrUseContext::FormallyOdrUsed: 17762 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17763 // behavior. 17764 break; 17765 17766 case OdrUseContext::Used: 17767 // If we might later find that this expression isn't actually an odr-use, 17768 // delay the marking. 17769 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17770 SemaRef.MaybeODRUseExprs.insert(E); 17771 else 17772 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17773 break; 17774 17775 case OdrUseContext::Dependent: 17776 // If this is a dependent context, we don't need to mark variables as 17777 // odr-used, but we may still need to track them for lambda capture. 17778 // FIXME: Do we also need to do this inside dependent typeid expressions 17779 // (which are modeled as unevaluated at this point)? 17780 const bool RefersToEnclosingScope = 17781 (SemaRef.CurContext != Var->getDeclContext() && 17782 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17783 if (RefersToEnclosingScope) { 17784 LambdaScopeInfo *const LSI = 17785 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17786 if (LSI && (!LSI->CallOperator || 17787 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17788 // If a variable could potentially be odr-used, defer marking it so 17789 // until we finish analyzing the full expression for any 17790 // lvalue-to-rvalue 17791 // or discarded value conversions that would obviate odr-use. 17792 // Add it to the list of potential captures that will be analyzed 17793 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17794 // unless the variable is a reference that was initialized by a constant 17795 // expression (this will never need to be captured or odr-used). 17796 // 17797 // FIXME: We can simplify this a lot after implementing P0588R1. 17798 assert(E && "Capture variable should be used in an expression."); 17799 if (!Var->getType()->isReferenceType() || 17800 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17801 LSI->addPotentialCapture(E->IgnoreParens()); 17802 } 17803 } 17804 break; 17805 } 17806 } 17807 17808 /// Mark a variable referenced, and check whether it is odr-used 17809 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17810 /// used directly for normal expressions referring to VarDecl. 17811 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17812 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17813 } 17814 17815 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17816 Decl *D, Expr *E, bool MightBeOdrUse) { 17817 if (SemaRef.isInOpenMPDeclareTargetContext()) 17818 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17819 17820 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17821 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17822 return; 17823 } 17824 17825 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17826 17827 // If this is a call to a method via a cast, also mark the method in the 17828 // derived class used in case codegen can devirtualize the call. 17829 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17830 if (!ME) 17831 return; 17832 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17833 if (!MD) 17834 return; 17835 // Only attempt to devirtualize if this is truly a virtual call. 17836 bool IsVirtualCall = MD->isVirtual() && 17837 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17838 if (!IsVirtualCall) 17839 return; 17840 17841 // If it's possible to devirtualize the call, mark the called function 17842 // referenced. 17843 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17844 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17845 if (DM) 17846 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17847 } 17848 17849 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17850 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17851 // TODO: update this with DR# once a defect report is filed. 17852 // C++11 defect. The address of a pure member should not be an ODR use, even 17853 // if it's a qualified reference. 17854 bool OdrUse = true; 17855 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17856 if (Method->isVirtual() && 17857 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17858 OdrUse = false; 17859 17860 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17861 if (!isConstantEvaluated() && FD->isConsteval() && 17862 !RebuildingImmediateInvocation) 17863 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17864 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17865 } 17866 17867 /// Perform reference-marking and odr-use handling for a MemberExpr. 17868 void Sema::MarkMemberReferenced(MemberExpr *E) { 17869 // C++11 [basic.def.odr]p2: 17870 // A non-overloaded function whose name appears as a potentially-evaluated 17871 // expression or a member of a set of candidate functions, if selected by 17872 // overload resolution when referred to from a potentially-evaluated 17873 // expression, is odr-used, unless it is a pure virtual function and its 17874 // name is not explicitly qualified. 17875 bool MightBeOdrUse = true; 17876 if (E->performsVirtualDispatch(getLangOpts())) { 17877 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17878 if (Method->isPure()) 17879 MightBeOdrUse = false; 17880 } 17881 SourceLocation Loc = 17882 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17883 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17884 } 17885 17886 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17887 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17888 for (VarDecl *VD : *E) 17889 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17890 } 17891 17892 /// Perform marking for a reference to an arbitrary declaration. It 17893 /// marks the declaration referenced, and performs odr-use checking for 17894 /// functions and variables. This method should not be used when building a 17895 /// normal expression which refers to a variable. 17896 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17897 bool MightBeOdrUse) { 17898 if (MightBeOdrUse) { 17899 if (auto *VD = dyn_cast<VarDecl>(D)) { 17900 MarkVariableReferenced(Loc, VD); 17901 return; 17902 } 17903 } 17904 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17905 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17906 return; 17907 } 17908 D->setReferenced(); 17909 } 17910 17911 namespace { 17912 // Mark all of the declarations used by a type as referenced. 17913 // FIXME: Not fully implemented yet! We need to have a better understanding 17914 // of when we're entering a context we should not recurse into. 17915 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17916 // TreeTransforms rebuilding the type in a new context. Rather than 17917 // duplicating the TreeTransform logic, we should consider reusing it here. 17918 // Currently that causes problems when rebuilding LambdaExprs. 17919 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17920 Sema &S; 17921 SourceLocation Loc; 17922 17923 public: 17924 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17925 17926 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17927 17928 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17929 }; 17930 } 17931 17932 bool MarkReferencedDecls::TraverseTemplateArgument( 17933 const TemplateArgument &Arg) { 17934 { 17935 // A non-type template argument is a constant-evaluated context. 17936 EnterExpressionEvaluationContext Evaluated( 17937 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17938 if (Arg.getKind() == TemplateArgument::Declaration) { 17939 if (Decl *D = Arg.getAsDecl()) 17940 S.MarkAnyDeclReferenced(Loc, D, true); 17941 } else if (Arg.getKind() == TemplateArgument::Expression) { 17942 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17943 } 17944 } 17945 17946 return Inherited::TraverseTemplateArgument(Arg); 17947 } 17948 17949 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17950 MarkReferencedDecls Marker(*this, Loc); 17951 Marker.TraverseType(T); 17952 } 17953 17954 namespace { 17955 /// Helper class that marks all of the declarations referenced by 17956 /// potentially-evaluated subexpressions as "referenced". 17957 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 17958 public: 17959 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 17960 bool SkipLocalVariables; 17961 17962 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17963 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 17964 17965 void visitUsedDecl(SourceLocation Loc, Decl *D) { 17966 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 17967 } 17968 17969 void VisitDeclRefExpr(DeclRefExpr *E) { 17970 // If we were asked not to visit local variables, don't. 17971 if (SkipLocalVariables) { 17972 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17973 if (VD->hasLocalStorage()) 17974 return; 17975 } 17976 S.MarkDeclRefReferenced(E); 17977 } 17978 17979 void VisitMemberExpr(MemberExpr *E) { 17980 S.MarkMemberReferenced(E); 17981 Visit(E->getBase()); 17982 } 17983 }; 17984 } // namespace 17985 17986 /// Mark any declarations that appear within this expression or any 17987 /// potentially-evaluated subexpressions as "referenced". 17988 /// 17989 /// \param SkipLocalVariables If true, don't mark local variables as 17990 /// 'referenced'. 17991 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17992 bool SkipLocalVariables) { 17993 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17994 } 17995 17996 /// Emit a diagnostic that describes an effect on the run-time behavior 17997 /// of the program being compiled. 17998 /// 17999 /// This routine emits the given diagnostic when the code currently being 18000 /// type-checked is "potentially evaluated", meaning that there is a 18001 /// possibility that the code will actually be executable. Code in sizeof() 18002 /// expressions, code used only during overload resolution, etc., are not 18003 /// potentially evaluated. This routine will suppress such diagnostics or, 18004 /// in the absolutely nutty case of potentially potentially evaluated 18005 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18006 /// later. 18007 /// 18008 /// This routine should be used for all diagnostics that describe the run-time 18009 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18010 /// Failure to do so will likely result in spurious diagnostics or failures 18011 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18012 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18013 const PartialDiagnostic &PD) { 18014 switch (ExprEvalContexts.back().Context) { 18015 case ExpressionEvaluationContext::Unevaluated: 18016 case ExpressionEvaluationContext::UnevaluatedList: 18017 case ExpressionEvaluationContext::UnevaluatedAbstract: 18018 case ExpressionEvaluationContext::DiscardedStatement: 18019 // The argument will never be evaluated, so don't complain. 18020 break; 18021 18022 case ExpressionEvaluationContext::ConstantEvaluated: 18023 // Relevant diagnostics should be produced by constant evaluation. 18024 break; 18025 18026 case ExpressionEvaluationContext::PotentiallyEvaluated: 18027 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18028 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18029 FunctionScopes.back()->PossiblyUnreachableDiags. 18030 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18031 return true; 18032 } 18033 18034 // The initializer of a constexpr variable or of the first declaration of a 18035 // static data member is not syntactically a constant evaluated constant, 18036 // but nonetheless is always required to be a constant expression, so we 18037 // can skip diagnosing. 18038 // FIXME: Using the mangling context here is a hack. 18039 if (auto *VD = dyn_cast_or_null<VarDecl>( 18040 ExprEvalContexts.back().ManglingContextDecl)) { 18041 if (VD->isConstexpr() || 18042 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18043 break; 18044 // FIXME: For any other kind of variable, we should build a CFG for its 18045 // initializer and check whether the context in question is reachable. 18046 } 18047 18048 Diag(Loc, PD); 18049 return true; 18050 } 18051 18052 return false; 18053 } 18054 18055 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18056 const PartialDiagnostic &PD) { 18057 return DiagRuntimeBehavior( 18058 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18059 } 18060 18061 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18062 CallExpr *CE, FunctionDecl *FD) { 18063 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18064 return false; 18065 18066 // If we're inside a decltype's expression, don't check for a valid return 18067 // type or construct temporaries until we know whether this is the last call. 18068 if (ExprEvalContexts.back().ExprContext == 18069 ExpressionEvaluationContextRecord::EK_Decltype) { 18070 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18071 return false; 18072 } 18073 18074 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18075 FunctionDecl *FD; 18076 CallExpr *CE; 18077 18078 public: 18079 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18080 : FD(FD), CE(CE) { } 18081 18082 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18083 if (!FD) { 18084 S.Diag(Loc, diag::err_call_incomplete_return) 18085 << T << CE->getSourceRange(); 18086 return; 18087 } 18088 18089 S.Diag(Loc, diag::err_call_function_incomplete_return) 18090 << CE->getSourceRange() << FD->getDeclName() << T; 18091 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18092 << FD->getDeclName(); 18093 } 18094 } Diagnoser(FD, CE); 18095 18096 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18097 return true; 18098 18099 return false; 18100 } 18101 18102 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18103 // will prevent this condition from triggering, which is what we want. 18104 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18105 SourceLocation Loc; 18106 18107 unsigned diagnostic = diag::warn_condition_is_assignment; 18108 bool IsOrAssign = false; 18109 18110 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18111 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18112 return; 18113 18114 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18115 18116 // Greylist some idioms by putting them into a warning subcategory. 18117 if (ObjCMessageExpr *ME 18118 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18119 Selector Sel = ME->getSelector(); 18120 18121 // self = [<foo> init...] 18122 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18123 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18124 18125 // <foo> = [<bar> nextObject] 18126 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18127 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18128 } 18129 18130 Loc = Op->getOperatorLoc(); 18131 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18132 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18133 return; 18134 18135 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18136 Loc = Op->getOperatorLoc(); 18137 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18138 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18139 else { 18140 // Not an assignment. 18141 return; 18142 } 18143 18144 Diag(Loc, diagnostic) << E->getSourceRange(); 18145 18146 SourceLocation Open = E->getBeginLoc(); 18147 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18148 Diag(Loc, diag::note_condition_assign_silence) 18149 << FixItHint::CreateInsertion(Open, "(") 18150 << FixItHint::CreateInsertion(Close, ")"); 18151 18152 if (IsOrAssign) 18153 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18154 << FixItHint::CreateReplacement(Loc, "!="); 18155 else 18156 Diag(Loc, diag::note_condition_assign_to_comparison) 18157 << FixItHint::CreateReplacement(Loc, "=="); 18158 } 18159 18160 /// Redundant parentheses over an equality comparison can indicate 18161 /// that the user intended an assignment used as condition. 18162 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18163 // Don't warn if the parens came from a macro. 18164 SourceLocation parenLoc = ParenE->getBeginLoc(); 18165 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18166 return; 18167 // Don't warn for dependent expressions. 18168 if (ParenE->isTypeDependent()) 18169 return; 18170 18171 Expr *E = ParenE->IgnoreParens(); 18172 18173 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18174 if (opE->getOpcode() == BO_EQ && 18175 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18176 == Expr::MLV_Valid) { 18177 SourceLocation Loc = opE->getOperatorLoc(); 18178 18179 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18180 SourceRange ParenERange = ParenE->getSourceRange(); 18181 Diag(Loc, diag::note_equality_comparison_silence) 18182 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18183 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18184 Diag(Loc, diag::note_equality_comparison_to_assign) 18185 << FixItHint::CreateReplacement(Loc, "="); 18186 } 18187 } 18188 18189 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18190 bool IsConstexpr) { 18191 DiagnoseAssignmentAsCondition(E); 18192 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18193 DiagnoseEqualityWithExtraParens(parenE); 18194 18195 ExprResult result = CheckPlaceholderExpr(E); 18196 if (result.isInvalid()) return ExprError(); 18197 E = result.get(); 18198 18199 if (!E->isTypeDependent()) { 18200 if (getLangOpts().CPlusPlus) 18201 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18202 18203 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18204 if (ERes.isInvalid()) 18205 return ExprError(); 18206 E = ERes.get(); 18207 18208 QualType T = E->getType(); 18209 if (!T->isScalarType()) { // C99 6.8.4.1p1 18210 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18211 << T << E->getSourceRange(); 18212 return ExprError(); 18213 } 18214 CheckBoolLikeConversion(E, Loc); 18215 } 18216 18217 return E; 18218 } 18219 18220 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18221 Expr *SubExpr, ConditionKind CK) { 18222 // Empty conditions are valid in for-statements. 18223 if (!SubExpr) 18224 return ConditionResult(); 18225 18226 ExprResult Cond; 18227 switch (CK) { 18228 case ConditionKind::Boolean: 18229 Cond = CheckBooleanCondition(Loc, SubExpr); 18230 break; 18231 18232 case ConditionKind::ConstexprIf: 18233 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18234 break; 18235 18236 case ConditionKind::Switch: 18237 Cond = CheckSwitchCondition(Loc, SubExpr); 18238 break; 18239 } 18240 if (Cond.isInvalid()) 18241 return ConditionError(); 18242 18243 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18244 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18245 if (!FullExpr.get()) 18246 return ConditionError(); 18247 18248 return ConditionResult(*this, nullptr, FullExpr, 18249 CK == ConditionKind::ConstexprIf); 18250 } 18251 18252 namespace { 18253 /// A visitor for rebuilding a call to an __unknown_any expression 18254 /// to have an appropriate type. 18255 struct RebuildUnknownAnyFunction 18256 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18257 18258 Sema &S; 18259 18260 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18261 18262 ExprResult VisitStmt(Stmt *S) { 18263 llvm_unreachable("unexpected statement!"); 18264 } 18265 18266 ExprResult VisitExpr(Expr *E) { 18267 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18268 << E->getSourceRange(); 18269 return ExprError(); 18270 } 18271 18272 /// Rebuild an expression which simply semantically wraps another 18273 /// expression which it shares the type and value kind of. 18274 template <class T> ExprResult rebuildSugarExpr(T *E) { 18275 ExprResult SubResult = Visit(E->getSubExpr()); 18276 if (SubResult.isInvalid()) return ExprError(); 18277 18278 Expr *SubExpr = SubResult.get(); 18279 E->setSubExpr(SubExpr); 18280 E->setType(SubExpr->getType()); 18281 E->setValueKind(SubExpr->getValueKind()); 18282 assert(E->getObjectKind() == OK_Ordinary); 18283 return E; 18284 } 18285 18286 ExprResult VisitParenExpr(ParenExpr *E) { 18287 return rebuildSugarExpr(E); 18288 } 18289 18290 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18291 return rebuildSugarExpr(E); 18292 } 18293 18294 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18295 ExprResult SubResult = Visit(E->getSubExpr()); 18296 if (SubResult.isInvalid()) return ExprError(); 18297 18298 Expr *SubExpr = SubResult.get(); 18299 E->setSubExpr(SubExpr); 18300 E->setType(S.Context.getPointerType(SubExpr->getType())); 18301 assert(E->getValueKind() == VK_RValue); 18302 assert(E->getObjectKind() == OK_Ordinary); 18303 return E; 18304 } 18305 18306 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18307 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18308 18309 E->setType(VD->getType()); 18310 18311 assert(E->getValueKind() == VK_RValue); 18312 if (S.getLangOpts().CPlusPlus && 18313 !(isa<CXXMethodDecl>(VD) && 18314 cast<CXXMethodDecl>(VD)->isInstance())) 18315 E->setValueKind(VK_LValue); 18316 18317 return E; 18318 } 18319 18320 ExprResult VisitMemberExpr(MemberExpr *E) { 18321 return resolveDecl(E, E->getMemberDecl()); 18322 } 18323 18324 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18325 return resolveDecl(E, E->getDecl()); 18326 } 18327 }; 18328 } 18329 18330 /// Given a function expression of unknown-any type, try to rebuild it 18331 /// to have a function type. 18332 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18333 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18334 if (Result.isInvalid()) return ExprError(); 18335 return S.DefaultFunctionArrayConversion(Result.get()); 18336 } 18337 18338 namespace { 18339 /// A visitor for rebuilding an expression of type __unknown_anytype 18340 /// into one which resolves the type directly on the referring 18341 /// expression. Strict preservation of the original source 18342 /// structure is not a goal. 18343 struct RebuildUnknownAnyExpr 18344 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18345 18346 Sema &S; 18347 18348 /// The current destination type. 18349 QualType DestType; 18350 18351 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18352 : S(S), DestType(CastType) {} 18353 18354 ExprResult VisitStmt(Stmt *S) { 18355 llvm_unreachable("unexpected statement!"); 18356 } 18357 18358 ExprResult VisitExpr(Expr *E) { 18359 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18360 << E->getSourceRange(); 18361 return ExprError(); 18362 } 18363 18364 ExprResult VisitCallExpr(CallExpr *E); 18365 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18366 18367 /// Rebuild an expression which simply semantically wraps another 18368 /// expression which it shares the type and value kind of. 18369 template <class T> ExprResult rebuildSugarExpr(T *E) { 18370 ExprResult SubResult = Visit(E->getSubExpr()); 18371 if (SubResult.isInvalid()) return ExprError(); 18372 Expr *SubExpr = SubResult.get(); 18373 E->setSubExpr(SubExpr); 18374 E->setType(SubExpr->getType()); 18375 E->setValueKind(SubExpr->getValueKind()); 18376 assert(E->getObjectKind() == OK_Ordinary); 18377 return E; 18378 } 18379 18380 ExprResult VisitParenExpr(ParenExpr *E) { 18381 return rebuildSugarExpr(E); 18382 } 18383 18384 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18385 return rebuildSugarExpr(E); 18386 } 18387 18388 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18389 const PointerType *Ptr = DestType->getAs<PointerType>(); 18390 if (!Ptr) { 18391 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18392 << E->getSourceRange(); 18393 return ExprError(); 18394 } 18395 18396 if (isa<CallExpr>(E->getSubExpr())) { 18397 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18398 << E->getSourceRange(); 18399 return ExprError(); 18400 } 18401 18402 assert(E->getValueKind() == VK_RValue); 18403 assert(E->getObjectKind() == OK_Ordinary); 18404 E->setType(DestType); 18405 18406 // Build the sub-expression as if it were an object of the pointee type. 18407 DestType = Ptr->getPointeeType(); 18408 ExprResult SubResult = Visit(E->getSubExpr()); 18409 if (SubResult.isInvalid()) return ExprError(); 18410 E->setSubExpr(SubResult.get()); 18411 return E; 18412 } 18413 18414 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18415 18416 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18417 18418 ExprResult VisitMemberExpr(MemberExpr *E) { 18419 return resolveDecl(E, E->getMemberDecl()); 18420 } 18421 18422 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18423 return resolveDecl(E, E->getDecl()); 18424 } 18425 }; 18426 } 18427 18428 /// Rebuilds a call expression which yielded __unknown_anytype. 18429 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18430 Expr *CalleeExpr = E->getCallee(); 18431 18432 enum FnKind { 18433 FK_MemberFunction, 18434 FK_FunctionPointer, 18435 FK_BlockPointer 18436 }; 18437 18438 FnKind Kind; 18439 QualType CalleeType = CalleeExpr->getType(); 18440 if (CalleeType == S.Context.BoundMemberTy) { 18441 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18442 Kind = FK_MemberFunction; 18443 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18444 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18445 CalleeType = Ptr->getPointeeType(); 18446 Kind = FK_FunctionPointer; 18447 } else { 18448 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18449 Kind = FK_BlockPointer; 18450 } 18451 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18452 18453 // Verify that this is a legal result type of a function. 18454 if (DestType->isArrayType() || DestType->isFunctionType()) { 18455 unsigned diagID = diag::err_func_returning_array_function; 18456 if (Kind == FK_BlockPointer) 18457 diagID = diag::err_block_returning_array_function; 18458 18459 S.Diag(E->getExprLoc(), diagID) 18460 << DestType->isFunctionType() << DestType; 18461 return ExprError(); 18462 } 18463 18464 // Otherwise, go ahead and set DestType as the call's result. 18465 E->setType(DestType.getNonLValueExprType(S.Context)); 18466 E->setValueKind(Expr::getValueKindForType(DestType)); 18467 assert(E->getObjectKind() == OK_Ordinary); 18468 18469 // Rebuild the function type, replacing the result type with DestType. 18470 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18471 if (Proto) { 18472 // __unknown_anytype(...) is a special case used by the debugger when 18473 // it has no idea what a function's signature is. 18474 // 18475 // We want to build this call essentially under the K&R 18476 // unprototyped rules, but making a FunctionNoProtoType in C++ 18477 // would foul up all sorts of assumptions. However, we cannot 18478 // simply pass all arguments as variadic arguments, nor can we 18479 // portably just call the function under a non-variadic type; see 18480 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18481 // However, it turns out that in practice it is generally safe to 18482 // call a function declared as "A foo(B,C,D);" under the prototype 18483 // "A foo(B,C,D,...);". The only known exception is with the 18484 // Windows ABI, where any variadic function is implicitly cdecl 18485 // regardless of its normal CC. Therefore we change the parameter 18486 // types to match the types of the arguments. 18487 // 18488 // This is a hack, but it is far superior to moving the 18489 // corresponding target-specific code from IR-gen to Sema/AST. 18490 18491 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18492 SmallVector<QualType, 8> ArgTypes; 18493 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18494 ArgTypes.reserve(E->getNumArgs()); 18495 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18496 Expr *Arg = E->getArg(i); 18497 QualType ArgType = Arg->getType(); 18498 if (E->isLValue()) { 18499 ArgType = S.Context.getLValueReferenceType(ArgType); 18500 } else if (E->isXValue()) { 18501 ArgType = S.Context.getRValueReferenceType(ArgType); 18502 } 18503 ArgTypes.push_back(ArgType); 18504 } 18505 ParamTypes = ArgTypes; 18506 } 18507 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18508 Proto->getExtProtoInfo()); 18509 } else { 18510 DestType = S.Context.getFunctionNoProtoType(DestType, 18511 FnType->getExtInfo()); 18512 } 18513 18514 // Rebuild the appropriate pointer-to-function type. 18515 switch (Kind) { 18516 case FK_MemberFunction: 18517 // Nothing to do. 18518 break; 18519 18520 case FK_FunctionPointer: 18521 DestType = S.Context.getPointerType(DestType); 18522 break; 18523 18524 case FK_BlockPointer: 18525 DestType = S.Context.getBlockPointerType(DestType); 18526 break; 18527 } 18528 18529 // Finally, we can recurse. 18530 ExprResult CalleeResult = Visit(CalleeExpr); 18531 if (!CalleeResult.isUsable()) return ExprError(); 18532 E->setCallee(CalleeResult.get()); 18533 18534 // Bind a temporary if necessary. 18535 return S.MaybeBindToTemporary(E); 18536 } 18537 18538 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18539 // Verify that this is a legal result type of a call. 18540 if (DestType->isArrayType() || DestType->isFunctionType()) { 18541 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18542 << DestType->isFunctionType() << DestType; 18543 return ExprError(); 18544 } 18545 18546 // Rewrite the method result type if available. 18547 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18548 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18549 Method->setReturnType(DestType); 18550 } 18551 18552 // Change the type of the message. 18553 E->setType(DestType.getNonReferenceType()); 18554 E->setValueKind(Expr::getValueKindForType(DestType)); 18555 18556 return S.MaybeBindToTemporary(E); 18557 } 18558 18559 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18560 // The only case we should ever see here is a function-to-pointer decay. 18561 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18562 assert(E->getValueKind() == VK_RValue); 18563 assert(E->getObjectKind() == OK_Ordinary); 18564 18565 E->setType(DestType); 18566 18567 // Rebuild the sub-expression as the pointee (function) type. 18568 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18569 18570 ExprResult Result = Visit(E->getSubExpr()); 18571 if (!Result.isUsable()) return ExprError(); 18572 18573 E->setSubExpr(Result.get()); 18574 return E; 18575 } else if (E->getCastKind() == CK_LValueToRValue) { 18576 assert(E->getValueKind() == VK_RValue); 18577 assert(E->getObjectKind() == OK_Ordinary); 18578 18579 assert(isa<BlockPointerType>(E->getType())); 18580 18581 E->setType(DestType); 18582 18583 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18584 DestType = S.Context.getLValueReferenceType(DestType); 18585 18586 ExprResult Result = Visit(E->getSubExpr()); 18587 if (!Result.isUsable()) return ExprError(); 18588 18589 E->setSubExpr(Result.get()); 18590 return E; 18591 } else { 18592 llvm_unreachable("Unhandled cast type!"); 18593 } 18594 } 18595 18596 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18597 ExprValueKind ValueKind = VK_LValue; 18598 QualType Type = DestType; 18599 18600 // We know how to make this work for certain kinds of decls: 18601 18602 // - functions 18603 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18604 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18605 DestType = Ptr->getPointeeType(); 18606 ExprResult Result = resolveDecl(E, VD); 18607 if (Result.isInvalid()) return ExprError(); 18608 return S.ImpCastExprToType(Result.get(), Type, 18609 CK_FunctionToPointerDecay, VK_RValue); 18610 } 18611 18612 if (!Type->isFunctionType()) { 18613 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18614 << VD << E->getSourceRange(); 18615 return ExprError(); 18616 } 18617 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18618 // We must match the FunctionDecl's type to the hack introduced in 18619 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18620 // type. See the lengthy commentary in that routine. 18621 QualType FDT = FD->getType(); 18622 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18623 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18624 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18625 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18626 SourceLocation Loc = FD->getLocation(); 18627 FunctionDecl *NewFD = FunctionDecl::Create( 18628 S.Context, FD->getDeclContext(), Loc, Loc, 18629 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18630 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18631 /*ConstexprKind*/ CSK_unspecified); 18632 18633 if (FD->getQualifier()) 18634 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18635 18636 SmallVector<ParmVarDecl*, 16> Params; 18637 for (const auto &AI : FT->param_types()) { 18638 ParmVarDecl *Param = 18639 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18640 Param->setScopeInfo(0, Params.size()); 18641 Params.push_back(Param); 18642 } 18643 NewFD->setParams(Params); 18644 DRE->setDecl(NewFD); 18645 VD = DRE->getDecl(); 18646 } 18647 } 18648 18649 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18650 if (MD->isInstance()) { 18651 ValueKind = VK_RValue; 18652 Type = S.Context.BoundMemberTy; 18653 } 18654 18655 // Function references aren't l-values in C. 18656 if (!S.getLangOpts().CPlusPlus) 18657 ValueKind = VK_RValue; 18658 18659 // - variables 18660 } else if (isa<VarDecl>(VD)) { 18661 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18662 Type = RefTy->getPointeeType(); 18663 } else if (Type->isFunctionType()) { 18664 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18665 << VD << E->getSourceRange(); 18666 return ExprError(); 18667 } 18668 18669 // - nothing else 18670 } else { 18671 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18672 << VD << E->getSourceRange(); 18673 return ExprError(); 18674 } 18675 18676 // Modifying the declaration like this is friendly to IR-gen but 18677 // also really dangerous. 18678 VD->setType(DestType); 18679 E->setType(Type); 18680 E->setValueKind(ValueKind); 18681 return E; 18682 } 18683 18684 /// Check a cast of an unknown-any type. We intentionally only 18685 /// trigger this for C-style casts. 18686 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18687 Expr *CastExpr, CastKind &CastKind, 18688 ExprValueKind &VK, CXXCastPath &Path) { 18689 // The type we're casting to must be either void or complete. 18690 if (!CastType->isVoidType() && 18691 RequireCompleteType(TypeRange.getBegin(), CastType, 18692 diag::err_typecheck_cast_to_incomplete)) 18693 return ExprError(); 18694 18695 // Rewrite the casted expression from scratch. 18696 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18697 if (!result.isUsable()) return ExprError(); 18698 18699 CastExpr = result.get(); 18700 VK = CastExpr->getValueKind(); 18701 CastKind = CK_NoOp; 18702 18703 return CastExpr; 18704 } 18705 18706 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18707 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18708 } 18709 18710 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18711 Expr *arg, QualType ¶mType) { 18712 // If the syntactic form of the argument is not an explicit cast of 18713 // any sort, just do default argument promotion. 18714 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18715 if (!castArg) { 18716 ExprResult result = DefaultArgumentPromotion(arg); 18717 if (result.isInvalid()) return ExprError(); 18718 paramType = result.get()->getType(); 18719 return result; 18720 } 18721 18722 // Otherwise, use the type that was written in the explicit cast. 18723 assert(!arg->hasPlaceholderType()); 18724 paramType = castArg->getTypeAsWritten(); 18725 18726 // Copy-initialize a parameter of that type. 18727 InitializedEntity entity = 18728 InitializedEntity::InitializeParameter(Context, paramType, 18729 /*consumed*/ false); 18730 return PerformCopyInitialization(entity, callLoc, arg); 18731 } 18732 18733 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18734 Expr *orig = E; 18735 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18736 while (true) { 18737 E = E->IgnoreParenImpCasts(); 18738 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18739 E = call->getCallee(); 18740 diagID = diag::err_uncasted_call_of_unknown_any; 18741 } else { 18742 break; 18743 } 18744 } 18745 18746 SourceLocation loc; 18747 NamedDecl *d; 18748 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18749 loc = ref->getLocation(); 18750 d = ref->getDecl(); 18751 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18752 loc = mem->getMemberLoc(); 18753 d = mem->getMemberDecl(); 18754 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18755 diagID = diag::err_uncasted_call_of_unknown_any; 18756 loc = msg->getSelectorStartLoc(); 18757 d = msg->getMethodDecl(); 18758 if (!d) { 18759 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18760 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18761 << orig->getSourceRange(); 18762 return ExprError(); 18763 } 18764 } else { 18765 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18766 << E->getSourceRange(); 18767 return ExprError(); 18768 } 18769 18770 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18771 18772 // Never recoverable. 18773 return ExprError(); 18774 } 18775 18776 /// Check for operands with placeholder types and complain if found. 18777 /// Returns ExprError() if there was an error and no recovery was possible. 18778 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18779 if (!getLangOpts().CPlusPlus) { 18780 // C cannot handle TypoExpr nodes on either side of a binop because it 18781 // doesn't handle dependent types properly, so make sure any TypoExprs have 18782 // been dealt with before checking the operands. 18783 ExprResult Result = CorrectDelayedTyposInExpr(E); 18784 if (!Result.isUsable()) return ExprError(); 18785 E = Result.get(); 18786 } 18787 18788 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18789 if (!placeholderType) return E; 18790 18791 switch (placeholderType->getKind()) { 18792 18793 // Overloaded expressions. 18794 case BuiltinType::Overload: { 18795 // Try to resolve a single function template specialization. 18796 // This is obligatory. 18797 ExprResult Result = E; 18798 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18799 return Result; 18800 18801 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18802 // leaves Result unchanged on failure. 18803 Result = E; 18804 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18805 return Result; 18806 18807 // If that failed, try to recover with a call. 18808 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18809 /*complain*/ true); 18810 return Result; 18811 } 18812 18813 // Bound member functions. 18814 case BuiltinType::BoundMember: { 18815 ExprResult result = E; 18816 const Expr *BME = E->IgnoreParens(); 18817 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18818 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18819 if (isa<CXXPseudoDestructorExpr>(BME)) { 18820 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18821 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18822 if (ME->getMemberNameInfo().getName().getNameKind() == 18823 DeclarationName::CXXDestructorName) 18824 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18825 } 18826 tryToRecoverWithCall(result, PD, 18827 /*complain*/ true); 18828 return result; 18829 } 18830 18831 // ARC unbridged casts. 18832 case BuiltinType::ARCUnbridgedCast: { 18833 Expr *realCast = stripARCUnbridgedCast(E); 18834 diagnoseARCUnbridgedCast(realCast); 18835 return realCast; 18836 } 18837 18838 // Expressions of unknown type. 18839 case BuiltinType::UnknownAny: 18840 return diagnoseUnknownAnyExpr(*this, E); 18841 18842 // Pseudo-objects. 18843 case BuiltinType::PseudoObject: 18844 return checkPseudoObjectRValue(E); 18845 18846 case BuiltinType::BuiltinFn: { 18847 // Accept __noop without parens by implicitly converting it to a call expr. 18848 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18849 if (DRE) { 18850 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18851 if (FD->getBuiltinID() == Builtin::BI__noop) { 18852 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18853 CK_BuiltinFnToFnPtr) 18854 .get(); 18855 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18856 VK_RValue, SourceLocation()); 18857 } 18858 } 18859 18860 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18861 return ExprError(); 18862 } 18863 18864 // Expressions of unknown type. 18865 case BuiltinType::OMPArraySection: 18866 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18867 return ExprError(); 18868 18869 // Expressions of unknown type. 18870 case BuiltinType::OMPArrayShaping: 18871 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 18872 18873 case BuiltinType::OMPIterator: 18874 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 18875 18876 // Everything else should be impossible. 18877 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18878 case BuiltinType::Id: 18879 #include "clang/Basic/OpenCLImageTypes.def" 18880 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18881 case BuiltinType::Id: 18882 #include "clang/Basic/OpenCLExtensionTypes.def" 18883 #define SVE_TYPE(Name, Id, SingletonId) \ 18884 case BuiltinType::Id: 18885 #include "clang/Basic/AArch64SVEACLETypes.def" 18886 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18887 #define PLACEHOLDER_TYPE(Id, SingletonId) 18888 #include "clang/AST/BuiltinTypes.def" 18889 break; 18890 } 18891 18892 llvm_unreachable("invalid placeholder type!"); 18893 } 18894 18895 bool Sema::CheckCaseExpression(Expr *E) { 18896 if (E->isTypeDependent()) 18897 return true; 18898 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18899 return E->getType()->isIntegralOrEnumerationType(); 18900 return false; 18901 } 18902 18903 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18904 ExprResult 18905 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18906 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18907 "Unknown Objective-C Boolean value!"); 18908 QualType BoolT = Context.ObjCBuiltinBoolTy; 18909 if (!Context.getBOOLDecl()) { 18910 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18911 Sema::LookupOrdinaryName); 18912 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18913 NamedDecl *ND = Result.getFoundDecl(); 18914 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18915 Context.setBOOLDecl(TD); 18916 } 18917 } 18918 if (Context.getBOOLDecl()) 18919 BoolT = Context.getBOOLType(); 18920 return new (Context) 18921 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18922 } 18923 18924 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18925 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18926 SourceLocation RParen) { 18927 18928 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18929 18930 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18931 return Spec.getPlatform() == Platform; 18932 }); 18933 18934 VersionTuple Version; 18935 if (Spec != AvailSpecs.end()) 18936 Version = Spec->getVersion(); 18937 18938 // The use of `@available` in the enclosing function should be analyzed to 18939 // warn when it's used inappropriately (i.e. not if(@available)). 18940 if (getCurFunctionOrMethodDecl()) 18941 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18942 else if (getCurBlock() || getCurLambda()) 18943 getCurFunction()->HasPotentialAvailabilityViolations = true; 18944 18945 return new (Context) 18946 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18947 } 18948 18949 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 18950 ArrayRef<Expr *> SubExprs, QualType T) { 18951 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 18952 // bogus diagnostics and this trick does not work in C. 18953 // FIXME: use containsErrors() to suppress unwanted diags in C. 18954 if (!Context.getLangOpts().RecoveryAST) 18955 return ExprError(); 18956 18957 if (isSFINAEContext()) 18958 return ExprError(); 18959 18960 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 18961 // We don't know the concrete type, fallback to dependent type. 18962 T = Context.DependentTy; 18963 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 18964 } 18965