1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/FixedPoint.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/Overload.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/Support/ConvertUTF.h" 48 using namespace clang; 49 using namespace sema; 50 51 /// Determine whether the use of this declaration is valid, without 52 /// emitting diagnostics. 53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 54 // See if this is an auto-typed variable whose initializer we are parsing. 55 if (ParsingInitForAutoVars.count(D)) 56 return false; 57 58 // See if this is a deleted function. 59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 60 if (FD->isDeleted()) 61 return false; 62 63 // If the function has a deduced return type, and we can't deduce it, 64 // then we can't use it either. 65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 67 return false; 68 69 // See if this is an aligned allocation/deallocation function that is 70 // unavailable. 71 if (TreatUnavailableAsInvalid && 72 isUnavailableAlignedAllocationFunction(*FD)) 73 return false; 74 } 75 76 // See if this function is unavailable. 77 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 78 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 79 return false; 80 81 return true; 82 } 83 84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 85 // Warn if this is used but marked unused. 86 if (const auto *A = D->getAttr<UnusedAttr>()) { 87 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 88 // should diagnose them. 89 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 90 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 91 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 92 if (DC && !DC->hasAttr<UnusedAttr>()) 93 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 94 } 95 } 96 } 97 98 /// Emit a note explaining that this function is deleted. 99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 100 assert(Decl->isDeleted()); 101 102 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 103 104 if (Method && Method->isDeleted() && Method->isDefaulted()) { 105 // If the method was explicitly defaulted, point at that declaration. 106 if (!Method->isImplicit()) 107 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 108 109 // Try to diagnose why this special member function was implicitly 110 // deleted. This might fail, if that reason no longer applies. 111 CXXSpecialMember CSM = getSpecialMember(Method); 112 if (CSM != CXXInvalid) 113 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 114 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 // See if this is a deleted function. 253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // If the function has a deduced return type, and we can't deduce it, 267 // then we can't use it either. 268 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 269 DeduceReturnType(FD, Loc)) 270 return true; 271 272 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 273 return true; 274 } 275 276 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 277 // Lambdas are only default-constructible or assignable in C++2a onwards. 278 if (MD->getParent()->isLambda() && 279 ((isa<CXXConstructorDecl>(MD) && 280 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 281 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 282 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 283 << !isa<CXXConstructorDecl>(MD); 284 } 285 } 286 287 auto getReferencedObjCProp = [](const NamedDecl *D) -> 288 const ObjCPropertyDecl * { 289 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 290 return MD->findPropertyDecl(); 291 return nullptr; 292 }; 293 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 294 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 295 return true; 296 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 297 return true; 298 } 299 300 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 301 // Only the variables omp_in and omp_out are allowed in the combiner. 302 // Only the variables omp_priv and omp_orig are allowed in the 303 // initializer-clause. 304 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 305 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 306 isa<VarDecl>(D)) { 307 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 308 << getCurFunction()->HasOMPDeclareReductionCombiner; 309 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 310 return true; 311 } 312 313 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 314 // List-items in map clauses on this construct may only refer to the declared 315 // variable var and entities that could be referenced by a procedure defined 316 // at the same location 317 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 318 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 319 isa<VarDecl>(D)) { 320 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 321 << DMD->getVarName().getAsString(); 322 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 323 return true; 324 } 325 326 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 327 AvoidPartialAvailabilityChecks, ClassReceiver); 328 329 DiagnoseUnusedOfDecl(*this, D, Loc); 330 331 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 332 333 return false; 334 } 335 336 /// DiagnoseSentinelCalls - This routine checks whether a call or 337 /// message-send is to a declaration with the sentinel attribute, and 338 /// if so, it checks that the requirements of the sentinel are 339 /// satisfied. 340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 341 ArrayRef<Expr *> Args) { 342 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 343 if (!attr) 344 return; 345 346 // The number of formal parameters of the declaration. 347 unsigned numFormalParams; 348 349 // The kind of declaration. This is also an index into a %select in 350 // the diagnostic. 351 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 352 353 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 354 numFormalParams = MD->param_size(); 355 calleeType = CT_Method; 356 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 357 numFormalParams = FD->param_size(); 358 calleeType = CT_Function; 359 } else if (isa<VarDecl>(D)) { 360 QualType type = cast<ValueDecl>(D)->getType(); 361 const FunctionType *fn = nullptr; 362 if (const PointerType *ptr = type->getAs<PointerType>()) { 363 fn = ptr->getPointeeType()->getAs<FunctionType>(); 364 if (!fn) return; 365 calleeType = CT_Function; 366 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 367 fn = ptr->getPointeeType()->castAs<FunctionType>(); 368 calleeType = CT_Block; 369 } else { 370 return; 371 } 372 373 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 374 numFormalParams = proto->getNumParams(); 375 } else { 376 numFormalParams = 0; 377 } 378 } else { 379 return; 380 } 381 382 // "nullPos" is the number of formal parameters at the end which 383 // effectively count as part of the variadic arguments. This is 384 // useful if you would prefer to not have *any* formal parameters, 385 // but the language forces you to have at least one. 386 unsigned nullPos = attr->getNullPos(); 387 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 388 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 389 390 // The number of arguments which should follow the sentinel. 391 unsigned numArgsAfterSentinel = attr->getSentinel(); 392 393 // If there aren't enough arguments for all the formal parameters, 394 // the sentinel, and the args after the sentinel, complain. 395 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 396 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 397 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 398 return; 399 } 400 401 // Otherwise, find the sentinel expression. 402 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 403 if (!sentinelExpr) return; 404 if (sentinelExpr->isValueDependent()) return; 405 if (Context.isSentinelNullExpr(sentinelExpr)) return; 406 407 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 408 // or 'NULL' if those are actually defined in the context. Only use 409 // 'nil' for ObjC methods, where it's much more likely that the 410 // variadic arguments form a list of object pointers. 411 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 412 std::string NullValue; 413 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 414 NullValue = "nil"; 415 else if (getLangOpts().CPlusPlus11) 416 NullValue = "nullptr"; 417 else if (PP.isMacroDefined("NULL")) 418 NullValue = "NULL"; 419 else 420 NullValue = "(void*) 0"; 421 422 if (MissingNilLoc.isInvalid()) 423 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 424 else 425 Diag(MissingNilLoc, diag::warn_missing_sentinel) 426 << int(calleeType) 427 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 429 } 430 431 SourceRange Sema::getExprRange(Expr *E) const { 432 return E ? E->getSourceRange() : SourceRange(); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // Standard Promotions and Conversions 437 //===----------------------------------------------------------------------===// 438 439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 441 // Handle any placeholder expressions which made it here. 442 if (E->getType()->isPlaceholderType()) { 443 ExprResult result = CheckPlaceholderExpr(E); 444 if (result.isInvalid()) return ExprError(); 445 E = result.get(); 446 } 447 448 QualType Ty = E->getType(); 449 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 450 451 if (Ty->isFunctionType()) { 452 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 453 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 454 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 455 return ExprError(); 456 457 E = ImpCastExprToType(E, Context.getPointerType(Ty), 458 CK_FunctionToPointerDecay).get(); 459 } else if (Ty->isArrayType()) { 460 // In C90 mode, arrays only promote to pointers if the array expression is 461 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 462 // type 'array of type' is converted to an expression that has type 'pointer 463 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 464 // that has type 'array of type' ...". The relevant change is "an lvalue" 465 // (C90) to "an expression" (C99). 466 // 467 // C++ 4.2p1: 468 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 469 // T" can be converted to an rvalue of type "pointer to T". 470 // 471 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 472 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 473 CK_ArrayToPointerDecay).get(); 474 } 475 return E; 476 } 477 478 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 479 // Check to see if we are dereferencing a null pointer. If so, 480 // and if not volatile-qualified, this is undefined behavior that the 481 // optimizer will delete, so warn about it. People sometimes try to use this 482 // to get a deterministic trap and are surprised by clang's behavior. This 483 // only handles the pattern "*null", which is a very syntactic check. 484 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 485 if (UO->getOpcode() == UO_Deref && 486 UO->getSubExpr()->IgnoreParenCasts()-> 487 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 488 !UO->getType().isVolatileQualified()) { 489 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 490 S.PDiag(diag::warn_indirection_through_null) 491 << UO->getSubExpr()->getSourceRange()); 492 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 493 S.PDiag(diag::note_indirection_through_null)); 494 } 495 } 496 497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 498 SourceLocation AssignLoc, 499 const Expr* RHS) { 500 const ObjCIvarDecl *IV = OIRE->getDecl(); 501 if (!IV) 502 return; 503 504 DeclarationName MemberName = IV->getDeclName(); 505 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 506 if (!Member || !Member->isStr("isa")) 507 return; 508 509 const Expr *Base = OIRE->getBase(); 510 QualType BaseType = Base->getType(); 511 if (OIRE->isArrow()) 512 BaseType = BaseType->getPointeeType(); 513 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 514 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 515 ObjCInterfaceDecl *ClassDeclared = nullptr; 516 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 517 if (!ClassDeclared->getSuperClass() 518 && (*ClassDeclared->ivar_begin()) == IV) { 519 if (RHS) { 520 NamedDecl *ObjectSetClass = 521 S.LookupSingleName(S.TUScope, 522 &S.Context.Idents.get("object_setClass"), 523 SourceLocation(), S.LookupOrdinaryName); 524 if (ObjectSetClass) { 525 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 526 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 527 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 528 "object_setClass(") 529 << FixItHint::CreateReplacement( 530 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 531 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 532 } 533 else 534 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 535 } else { 536 NamedDecl *ObjectGetClass = 537 S.LookupSingleName(S.TUScope, 538 &S.Context.Idents.get("object_getClass"), 539 SourceLocation(), S.LookupOrdinaryName); 540 if (ObjectGetClass) 541 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 542 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 543 "object_getClass(") 544 << FixItHint::CreateReplacement( 545 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 546 else 547 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 548 } 549 S.Diag(IV->getLocation(), diag::note_ivar_decl); 550 } 551 } 552 } 553 554 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 555 // Handle any placeholder expressions which made it here. 556 if (E->getType()->isPlaceholderType()) { 557 ExprResult result = CheckPlaceholderExpr(E); 558 if (result.isInvalid()) return ExprError(); 559 E = result.get(); 560 } 561 562 // C++ [conv.lval]p1: 563 // A glvalue of a non-function, non-array type T can be 564 // converted to a prvalue. 565 if (!E->isGLValue()) return E; 566 567 QualType T = E->getType(); 568 assert(!T.isNull() && "r-value conversion on typeless expression?"); 569 570 // We don't want to throw lvalue-to-rvalue casts on top of 571 // expressions of certain types in C++. 572 if (getLangOpts().CPlusPlus && 573 (E->getType() == Context.OverloadTy || 574 T->isDependentType() || 575 T->isRecordType())) 576 return E; 577 578 // The C standard is actually really unclear on this point, and 579 // DR106 tells us what the result should be but not why. It's 580 // generally best to say that void types just doesn't undergo 581 // lvalue-to-rvalue at all. Note that expressions of unqualified 582 // 'void' type are never l-values, but qualified void can be. 583 if (T->isVoidType()) 584 return E; 585 586 // OpenCL usually rejects direct accesses to values of 'half' type. 587 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 588 T->isHalfType()) { 589 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 590 << 0 << T; 591 return ExprError(); 592 } 593 594 CheckForNullPointerDereference(*this, E); 595 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 596 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 597 &Context.Idents.get("object_getClass"), 598 SourceLocation(), LookupOrdinaryName); 599 if (ObjectGetClass) 600 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 601 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 602 << FixItHint::CreateReplacement( 603 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 604 else 605 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 606 } 607 else if (const ObjCIvarRefExpr *OIRE = 608 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 609 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 610 611 // C++ [conv.lval]p1: 612 // [...] If T is a non-class type, the type of the prvalue is the 613 // cv-unqualified version of T. Otherwise, the type of the 614 // rvalue is T. 615 // 616 // C99 6.3.2.1p2: 617 // If the lvalue has qualified type, the value has the unqualified 618 // version of the type of the lvalue; otherwise, the value has the 619 // type of the lvalue. 620 if (T.hasQualifiers()) 621 T = T.getUnqualifiedType(); 622 623 // Under the MS ABI, lock down the inheritance model now. 624 if (T->isMemberPointerType() && 625 Context.getTargetInfo().getCXXABI().isMicrosoft()) 626 (void)isCompleteType(E->getExprLoc(), T); 627 628 ExprResult Res = CheckLValueToRValueConversionOperand(E); 629 if (Res.isInvalid()) 630 return Res; 631 E = Res.get(); 632 633 // Loading a __weak object implicitly retains the value, so we need a cleanup to 634 // balance that. 635 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 636 Cleanup.setExprNeedsCleanups(true); 637 638 // C++ [conv.lval]p3: 639 // If T is cv std::nullptr_t, the result is a null pointer constant. 640 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 641 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 642 643 // C11 6.3.2.1p2: 644 // ... if the lvalue has atomic type, the value has the non-atomic version 645 // of the type of the lvalue ... 646 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 647 T = Atomic->getValueType().getUnqualifiedType(); 648 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 649 nullptr, VK_RValue); 650 } 651 652 return Res; 653 } 654 655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 656 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 657 if (Res.isInvalid()) 658 return ExprError(); 659 Res = DefaultLvalueConversion(Res.get()); 660 if (Res.isInvalid()) 661 return ExprError(); 662 return Res; 663 } 664 665 /// CallExprUnaryConversions - a special case of an unary conversion 666 /// performed on a function designator of a call expression. 667 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 668 QualType Ty = E->getType(); 669 ExprResult Res = E; 670 // Only do implicit cast for a function type, but not for a pointer 671 // to function type. 672 if (Ty->isFunctionType()) { 673 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 674 CK_FunctionToPointerDecay).get(); 675 if (Res.isInvalid()) 676 return ExprError(); 677 } 678 Res = DefaultLvalueConversion(Res.get()); 679 if (Res.isInvalid()) 680 return ExprError(); 681 return Res.get(); 682 } 683 684 /// UsualUnaryConversions - Performs various conversions that are common to most 685 /// operators (C99 6.3). The conversions of array and function types are 686 /// sometimes suppressed. For example, the array->pointer conversion doesn't 687 /// apply if the array is an argument to the sizeof or address (&) operators. 688 /// In these instances, this routine should *not* be called. 689 ExprResult Sema::UsualUnaryConversions(Expr *E) { 690 // First, convert to an r-value. 691 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 692 if (Res.isInvalid()) 693 return ExprError(); 694 E = Res.get(); 695 696 QualType Ty = E->getType(); 697 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 698 699 // Half FP have to be promoted to float unless it is natively supported 700 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 701 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 702 703 // Try to perform integral promotions if the object has a theoretically 704 // promotable type. 705 if (Ty->isIntegralOrUnscopedEnumerationType()) { 706 // C99 6.3.1.1p2: 707 // 708 // The following may be used in an expression wherever an int or 709 // unsigned int may be used: 710 // - an object or expression with an integer type whose integer 711 // conversion rank is less than or equal to the rank of int 712 // and unsigned int. 713 // - A bit-field of type _Bool, int, signed int, or unsigned int. 714 // 715 // If an int can represent all values of the original type, the 716 // value is converted to an int; otherwise, it is converted to an 717 // unsigned int. These are called the integer promotions. All 718 // other types are unchanged by the integer promotions. 719 720 QualType PTy = Context.isPromotableBitField(E); 721 if (!PTy.isNull()) { 722 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 723 return E; 724 } 725 if (Ty->isPromotableIntegerType()) { 726 QualType PT = Context.getPromotedIntegerType(Ty); 727 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 728 return E; 729 } 730 } 731 return E; 732 } 733 734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 735 /// do not have a prototype. Arguments that have type float or __fp16 736 /// are promoted to double. All other argument types are converted by 737 /// UsualUnaryConversions(). 738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 739 QualType Ty = E->getType(); 740 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 741 742 ExprResult Res = UsualUnaryConversions(E); 743 if (Res.isInvalid()) 744 return ExprError(); 745 E = Res.get(); 746 747 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 748 // promote to double. 749 // Note that default argument promotion applies only to float (and 750 // half/fp16); it does not apply to _Float16. 751 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 752 if (BTy && (BTy->getKind() == BuiltinType::Half || 753 BTy->getKind() == BuiltinType::Float)) { 754 if (getLangOpts().OpenCL && 755 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 756 if (BTy->getKind() == BuiltinType::Half) { 757 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 758 } 759 } else { 760 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 761 } 762 } 763 764 // C++ performs lvalue-to-rvalue conversion as a default argument 765 // promotion, even on class types, but note: 766 // C++11 [conv.lval]p2: 767 // When an lvalue-to-rvalue conversion occurs in an unevaluated 768 // operand or a subexpression thereof the value contained in the 769 // referenced object is not accessed. Otherwise, if the glvalue 770 // has a class type, the conversion copy-initializes a temporary 771 // of type T from the glvalue and the result of the conversion 772 // is a prvalue for the temporary. 773 // FIXME: add some way to gate this entire thing for correctness in 774 // potentially potentially evaluated contexts. 775 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 776 ExprResult Temp = PerformCopyInitialization( 777 InitializedEntity::InitializeTemporary(E->getType()), 778 E->getExprLoc(), E); 779 if (Temp.isInvalid()) 780 return ExprError(); 781 E = Temp.get(); 782 } 783 784 return E; 785 } 786 787 /// Determine the degree of POD-ness for an expression. 788 /// Incomplete types are considered POD, since this check can be performed 789 /// when we're in an unevaluated context. 790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 791 if (Ty->isIncompleteType()) { 792 // C++11 [expr.call]p7: 793 // After these conversions, if the argument does not have arithmetic, 794 // enumeration, pointer, pointer to member, or class type, the program 795 // is ill-formed. 796 // 797 // Since we've already performed array-to-pointer and function-to-pointer 798 // decay, the only such type in C++ is cv void. This also handles 799 // initializer lists as variadic arguments. 800 if (Ty->isVoidType()) 801 return VAK_Invalid; 802 803 if (Ty->isObjCObjectType()) 804 return VAK_Invalid; 805 return VAK_Valid; 806 } 807 808 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 809 return VAK_Invalid; 810 811 if (Ty.isCXX98PODType(Context)) 812 return VAK_Valid; 813 814 // C++11 [expr.call]p7: 815 // Passing a potentially-evaluated argument of class type (Clause 9) 816 // having a non-trivial copy constructor, a non-trivial move constructor, 817 // or a non-trivial destructor, with no corresponding parameter, 818 // is conditionally-supported with implementation-defined semantics. 819 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 820 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 821 if (!Record->hasNonTrivialCopyConstructor() && 822 !Record->hasNonTrivialMoveConstructor() && 823 !Record->hasNonTrivialDestructor()) 824 return VAK_ValidInCXX11; 825 826 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 827 return VAK_Valid; 828 829 if (Ty->isObjCObjectType()) 830 return VAK_Invalid; 831 832 if (getLangOpts().MSVCCompat) 833 return VAK_MSVCUndefined; 834 835 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 836 // permitted to reject them. We should consider doing so. 837 return VAK_Undefined; 838 } 839 840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 841 // Don't allow one to pass an Objective-C interface to a vararg. 842 const QualType &Ty = E->getType(); 843 VarArgKind VAK = isValidVarArgType(Ty); 844 845 // Complain about passing non-POD types through varargs. 846 switch (VAK) { 847 case VAK_ValidInCXX11: 848 DiagRuntimeBehavior( 849 E->getBeginLoc(), nullptr, 850 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 851 LLVM_FALLTHROUGH; 852 case VAK_Valid: 853 if (Ty->isRecordType()) { 854 // This is unlikely to be what the user intended. If the class has a 855 // 'c_str' member function, the user probably meant to call that. 856 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 857 PDiag(diag::warn_pass_class_arg_to_vararg) 858 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 859 } 860 break; 861 862 case VAK_Undefined: 863 case VAK_MSVCUndefined: 864 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 865 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 866 << getLangOpts().CPlusPlus11 << Ty << CT); 867 break; 868 869 case VAK_Invalid: 870 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 871 Diag(E->getBeginLoc(), 872 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 873 << Ty << CT; 874 else if (Ty->isObjCObjectType()) 875 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 876 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 877 << Ty << CT); 878 else 879 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 880 << isa<InitListExpr>(E) << Ty << CT; 881 break; 882 } 883 } 884 885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 886 /// will create a trap if the resulting type is not a POD type. 887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 888 FunctionDecl *FDecl) { 889 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 890 // Strip the unbridged-cast placeholder expression off, if applicable. 891 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 892 (CT == VariadicMethod || 893 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 894 E = stripARCUnbridgedCast(E); 895 896 // Otherwise, do normal placeholder checking. 897 } else { 898 ExprResult ExprRes = CheckPlaceholderExpr(E); 899 if (ExprRes.isInvalid()) 900 return ExprError(); 901 E = ExprRes.get(); 902 } 903 } 904 905 ExprResult ExprRes = DefaultArgumentPromotion(E); 906 if (ExprRes.isInvalid()) 907 return ExprError(); 908 E = ExprRes.get(); 909 910 // Diagnostics regarding non-POD argument types are 911 // emitted along with format string checking in Sema::CheckFunctionCall(). 912 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 913 // Turn this into a trap. 914 CXXScopeSpec SS; 915 SourceLocation TemplateKWLoc; 916 UnqualifiedId Name; 917 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 918 E->getBeginLoc()); 919 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 920 /*HasTrailingLParen=*/true, 921 /*IsAddressOfOperand=*/false); 922 if (TrapFn.isInvalid()) 923 return ExprError(); 924 925 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 926 None, E->getEndLoc()); 927 if (Call.isInvalid()) 928 return ExprError(); 929 930 ExprResult Comma = 931 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 932 if (Comma.isInvalid()) 933 return ExprError(); 934 return Comma.get(); 935 } 936 937 if (!getLangOpts().CPlusPlus && 938 RequireCompleteType(E->getExprLoc(), E->getType(), 939 diag::err_call_incomplete_argument)) 940 return ExprError(); 941 942 return E; 943 } 944 945 /// Converts an integer to complex float type. Helper function of 946 /// UsualArithmeticConversions() 947 /// 948 /// \return false if the integer expression is an integer type and is 949 /// successfully converted to the complex type. 950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 951 ExprResult &ComplexExpr, 952 QualType IntTy, 953 QualType ComplexTy, 954 bool SkipCast) { 955 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 956 if (SkipCast) return false; 957 if (IntTy->isIntegerType()) { 958 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 959 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 960 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 961 CK_FloatingRealToComplex); 962 } else { 963 assert(IntTy->isComplexIntegerType()); 964 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 965 CK_IntegralComplexToFloatingComplex); 966 } 967 return false; 968 } 969 970 /// Handle arithmetic conversion with complex types. Helper function of 971 /// UsualArithmeticConversions() 972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 973 ExprResult &RHS, QualType LHSType, 974 QualType RHSType, 975 bool IsCompAssign) { 976 // if we have an integer operand, the result is the complex type. 977 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 978 /*skipCast*/false)) 979 return LHSType; 980 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 981 /*skipCast*/IsCompAssign)) 982 return RHSType; 983 984 // This handles complex/complex, complex/float, or float/complex. 985 // When both operands are complex, the shorter operand is converted to the 986 // type of the longer, and that is the type of the result. This corresponds 987 // to what is done when combining two real floating-point operands. 988 // The fun begins when size promotion occur across type domains. 989 // From H&S 6.3.4: When one operand is complex and the other is a real 990 // floating-point type, the less precise type is converted, within it's 991 // real or complex domain, to the precision of the other type. For example, 992 // when combining a "long double" with a "double _Complex", the 993 // "double _Complex" is promoted to "long double _Complex". 994 995 // Compute the rank of the two types, regardless of whether they are complex. 996 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 997 998 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 999 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1000 QualType LHSElementType = 1001 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1002 QualType RHSElementType = 1003 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1004 1005 QualType ResultType = S.Context.getComplexType(LHSElementType); 1006 if (Order < 0) { 1007 // Promote the precision of the LHS if not an assignment. 1008 ResultType = S.Context.getComplexType(RHSElementType); 1009 if (!IsCompAssign) { 1010 if (LHSComplexType) 1011 LHS = 1012 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1013 else 1014 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1015 } 1016 } else if (Order > 0) { 1017 // Promote the precision of the RHS. 1018 if (RHSComplexType) 1019 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1020 else 1021 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1022 } 1023 return ResultType; 1024 } 1025 1026 /// Handle arithmetic conversion from integer to float. Helper function 1027 /// of UsualArithmeticConversions() 1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1029 ExprResult &IntExpr, 1030 QualType FloatTy, QualType IntTy, 1031 bool ConvertFloat, bool ConvertInt) { 1032 if (IntTy->isIntegerType()) { 1033 if (ConvertInt) 1034 // Convert intExpr to the lhs floating point type. 1035 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1036 CK_IntegralToFloating); 1037 return FloatTy; 1038 } 1039 1040 // Convert both sides to the appropriate complex float. 1041 assert(IntTy->isComplexIntegerType()); 1042 QualType result = S.Context.getComplexType(FloatTy); 1043 1044 // _Complex int -> _Complex float 1045 if (ConvertInt) 1046 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1047 CK_IntegralComplexToFloatingComplex); 1048 1049 // float -> _Complex float 1050 if (ConvertFloat) 1051 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1052 CK_FloatingRealToComplex); 1053 1054 return result; 1055 } 1056 1057 /// Handle arithmethic conversion with floating point types. Helper 1058 /// function of UsualArithmeticConversions() 1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1060 ExprResult &RHS, QualType LHSType, 1061 QualType RHSType, bool IsCompAssign) { 1062 bool LHSFloat = LHSType->isRealFloatingType(); 1063 bool RHSFloat = RHSType->isRealFloatingType(); 1064 1065 // If we have two real floating types, convert the smaller operand 1066 // to the bigger result. 1067 if (LHSFloat && RHSFloat) { 1068 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1069 if (order > 0) { 1070 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1071 return LHSType; 1072 } 1073 1074 assert(order < 0 && "illegal float comparison"); 1075 if (!IsCompAssign) 1076 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1077 return RHSType; 1078 } 1079 1080 if (LHSFloat) { 1081 // Half FP has to be promoted to float unless it is natively supported 1082 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1083 LHSType = S.Context.FloatTy; 1084 1085 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1086 /*ConvertFloat=*/!IsCompAssign, 1087 /*ConvertInt=*/ true); 1088 } 1089 assert(RHSFloat); 1090 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1091 /*convertInt=*/ true, 1092 /*convertFloat=*/!IsCompAssign); 1093 } 1094 1095 /// Diagnose attempts to convert between __float128 and long double if 1096 /// there is no support for such conversion. Helper function of 1097 /// UsualArithmeticConversions(). 1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1099 QualType RHSType) { 1100 /* No issue converting if at least one of the types is not a floating point 1101 type or the two types have the same rank. 1102 */ 1103 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1104 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1105 return false; 1106 1107 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1108 "The remaining types must be floating point types."); 1109 1110 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1111 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1112 1113 QualType LHSElemType = LHSComplex ? 1114 LHSComplex->getElementType() : LHSType; 1115 QualType RHSElemType = RHSComplex ? 1116 RHSComplex->getElementType() : RHSType; 1117 1118 // No issue if the two types have the same representation 1119 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1120 &S.Context.getFloatTypeSemantics(RHSElemType)) 1121 return false; 1122 1123 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1124 RHSElemType == S.Context.LongDoubleTy); 1125 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1126 RHSElemType == S.Context.Float128Ty); 1127 1128 // We've handled the situation where __float128 and long double have the same 1129 // representation. We allow all conversions for all possible long double types 1130 // except PPC's double double. 1131 return Float128AndLongDouble && 1132 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1133 &llvm::APFloat::PPCDoubleDouble()); 1134 } 1135 1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1137 1138 namespace { 1139 /// These helper callbacks are placed in an anonymous namespace to 1140 /// permit their use as function template parameters. 1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1142 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1143 } 1144 1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1146 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1147 CK_IntegralComplexCast); 1148 } 1149 } 1150 1151 /// Handle integer arithmetic conversions. Helper function of 1152 /// UsualArithmeticConversions() 1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1155 ExprResult &RHS, QualType LHSType, 1156 QualType RHSType, bool IsCompAssign) { 1157 // The rules for this case are in C99 6.3.1.8 1158 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1159 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1160 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1161 if (LHSSigned == RHSSigned) { 1162 // Same signedness; use the higher-ranked type 1163 if (order >= 0) { 1164 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1165 return LHSType; 1166 } else if (!IsCompAssign) 1167 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1168 return RHSType; 1169 } else if (order != (LHSSigned ? 1 : -1)) { 1170 // The unsigned type has greater than or equal rank to the 1171 // signed type, so use the unsigned type 1172 if (RHSSigned) { 1173 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1174 return LHSType; 1175 } else if (!IsCompAssign) 1176 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1177 return RHSType; 1178 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1179 // The two types are different widths; if we are here, that 1180 // means the signed type is larger than the unsigned type, so 1181 // use the signed type. 1182 if (LHSSigned) { 1183 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1184 return LHSType; 1185 } else if (!IsCompAssign) 1186 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1187 return RHSType; 1188 } else { 1189 // The signed type is higher-ranked than the unsigned type, 1190 // but isn't actually any bigger (like unsigned int and long 1191 // on most 32-bit systems). Use the unsigned type corresponding 1192 // to the signed type. 1193 QualType result = 1194 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1195 RHS = (*doRHSCast)(S, RHS.get(), result); 1196 if (!IsCompAssign) 1197 LHS = (*doLHSCast)(S, LHS.get(), result); 1198 return result; 1199 } 1200 } 1201 1202 /// Handle conversions with GCC complex int extension. Helper function 1203 /// of UsualArithmeticConversions() 1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1205 ExprResult &RHS, QualType LHSType, 1206 QualType RHSType, 1207 bool IsCompAssign) { 1208 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1209 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1210 1211 if (LHSComplexInt && RHSComplexInt) { 1212 QualType LHSEltType = LHSComplexInt->getElementType(); 1213 QualType RHSEltType = RHSComplexInt->getElementType(); 1214 QualType ScalarType = 1215 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1216 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1217 1218 return S.Context.getComplexType(ScalarType); 1219 } 1220 1221 if (LHSComplexInt) { 1222 QualType LHSEltType = LHSComplexInt->getElementType(); 1223 QualType ScalarType = 1224 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1225 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1226 QualType ComplexType = S.Context.getComplexType(ScalarType); 1227 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1228 CK_IntegralRealToComplex); 1229 1230 return ComplexType; 1231 } 1232 1233 assert(RHSComplexInt); 1234 1235 QualType RHSEltType = RHSComplexInt->getElementType(); 1236 QualType ScalarType = 1237 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1238 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1239 QualType ComplexType = S.Context.getComplexType(ScalarType); 1240 1241 if (!IsCompAssign) 1242 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1243 CK_IntegralRealToComplex); 1244 return ComplexType; 1245 } 1246 1247 /// Return the rank of a given fixed point or integer type. The value itself 1248 /// doesn't matter, but the values must be increasing with proper increasing 1249 /// rank as described in N1169 4.1.1. 1250 static unsigned GetFixedPointRank(QualType Ty) { 1251 const auto *BTy = Ty->getAs<BuiltinType>(); 1252 assert(BTy && "Expected a builtin type."); 1253 1254 switch (BTy->getKind()) { 1255 case BuiltinType::ShortFract: 1256 case BuiltinType::UShortFract: 1257 case BuiltinType::SatShortFract: 1258 case BuiltinType::SatUShortFract: 1259 return 1; 1260 case BuiltinType::Fract: 1261 case BuiltinType::UFract: 1262 case BuiltinType::SatFract: 1263 case BuiltinType::SatUFract: 1264 return 2; 1265 case BuiltinType::LongFract: 1266 case BuiltinType::ULongFract: 1267 case BuiltinType::SatLongFract: 1268 case BuiltinType::SatULongFract: 1269 return 3; 1270 case BuiltinType::ShortAccum: 1271 case BuiltinType::UShortAccum: 1272 case BuiltinType::SatShortAccum: 1273 case BuiltinType::SatUShortAccum: 1274 return 4; 1275 case BuiltinType::Accum: 1276 case BuiltinType::UAccum: 1277 case BuiltinType::SatAccum: 1278 case BuiltinType::SatUAccum: 1279 return 5; 1280 case BuiltinType::LongAccum: 1281 case BuiltinType::ULongAccum: 1282 case BuiltinType::SatLongAccum: 1283 case BuiltinType::SatULongAccum: 1284 return 6; 1285 default: 1286 if (BTy->isInteger()) 1287 return 0; 1288 llvm_unreachable("Unexpected fixed point or integer type"); 1289 } 1290 } 1291 1292 /// handleFixedPointConversion - Fixed point operations between fixed 1293 /// point types and integers or other fixed point types do not fall under 1294 /// usual arithmetic conversion since these conversions could result in loss 1295 /// of precsision (N1169 4.1.4). These operations should be calculated with 1296 /// the full precision of their result type (N1169 4.1.6.2.1). 1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1298 QualType RHSTy) { 1299 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1300 "Expected at least one of the operands to be a fixed point type"); 1301 assert((LHSTy->isFixedPointOrIntegerType() || 1302 RHSTy->isFixedPointOrIntegerType()) && 1303 "Special fixed point arithmetic operation conversions are only " 1304 "applied to ints or other fixed point types"); 1305 1306 // If one operand has signed fixed-point type and the other operand has 1307 // unsigned fixed-point type, then the unsigned fixed-point operand is 1308 // converted to its corresponding signed fixed-point type and the resulting 1309 // type is the type of the converted operand. 1310 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1311 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1312 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1313 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1314 1315 // The result type is the type with the highest rank, whereby a fixed-point 1316 // conversion rank is always greater than an integer conversion rank; if the 1317 // type of either of the operands is a saturating fixedpoint type, the result 1318 // type shall be the saturating fixed-point type corresponding to the type 1319 // with the highest rank; the resulting value is converted (taking into 1320 // account rounding and overflow) to the precision of the resulting type. 1321 // Same ranks between signed and unsigned types are resolved earlier, so both 1322 // types are either signed or both unsigned at this point. 1323 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1324 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1325 1326 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1327 1328 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1329 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1330 1331 return ResultTy; 1332 } 1333 1334 /// UsualArithmeticConversions - Performs various conversions that are common to 1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1336 /// routine returns the first non-arithmetic type found. The client is 1337 /// responsible for emitting appropriate error diagnostics. 1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1339 bool IsCompAssign) { 1340 if (!IsCompAssign) { 1341 LHS = UsualUnaryConversions(LHS.get()); 1342 if (LHS.isInvalid()) 1343 return QualType(); 1344 } 1345 1346 RHS = UsualUnaryConversions(RHS.get()); 1347 if (RHS.isInvalid()) 1348 return QualType(); 1349 1350 // For conversion purposes, we ignore any qualifiers. 1351 // For example, "const float" and "float" are equivalent. 1352 QualType LHSType = 1353 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1354 QualType RHSType = 1355 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1356 1357 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1358 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1359 LHSType = AtomicLHS->getValueType(); 1360 1361 // If both types are identical, no conversion is needed. 1362 if (LHSType == RHSType) 1363 return LHSType; 1364 1365 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1366 // The caller can deal with this (e.g. pointer + int). 1367 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1368 return QualType(); 1369 1370 // Apply unary and bitfield promotions to the LHS's type. 1371 QualType LHSUnpromotedType = LHSType; 1372 if (LHSType->isPromotableIntegerType()) 1373 LHSType = Context.getPromotedIntegerType(LHSType); 1374 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1375 if (!LHSBitfieldPromoteTy.isNull()) 1376 LHSType = LHSBitfieldPromoteTy; 1377 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1378 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1379 1380 // If both types are identical, no conversion is needed. 1381 if (LHSType == RHSType) 1382 return LHSType; 1383 1384 // At this point, we have two different arithmetic types. 1385 1386 // Diagnose attempts to convert between __float128 and long double where 1387 // such conversions currently can't be handled. 1388 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1389 return QualType(); 1390 1391 // Handle complex types first (C99 6.3.1.8p1). 1392 if (LHSType->isComplexType() || RHSType->isComplexType()) 1393 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1394 IsCompAssign); 1395 1396 // Now handle "real" floating types (i.e. float, double, long double). 1397 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1398 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1399 IsCompAssign); 1400 1401 // Handle GCC complex int extension. 1402 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1403 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1404 IsCompAssign); 1405 1406 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1407 return handleFixedPointConversion(*this, LHSType, RHSType); 1408 1409 // Finally, we have two differing integer types. 1410 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1411 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1412 } 1413 1414 //===----------------------------------------------------------------------===// 1415 // Semantic Analysis for various Expression Types 1416 //===----------------------------------------------------------------------===// 1417 1418 1419 ExprResult 1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1421 SourceLocation DefaultLoc, 1422 SourceLocation RParenLoc, 1423 Expr *ControllingExpr, 1424 ArrayRef<ParsedType> ArgTypes, 1425 ArrayRef<Expr *> ArgExprs) { 1426 unsigned NumAssocs = ArgTypes.size(); 1427 assert(NumAssocs == ArgExprs.size()); 1428 1429 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1430 for (unsigned i = 0; i < NumAssocs; ++i) { 1431 if (ArgTypes[i]) 1432 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1433 else 1434 Types[i] = nullptr; 1435 } 1436 1437 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1438 ControllingExpr, 1439 llvm::makeArrayRef(Types, NumAssocs), 1440 ArgExprs); 1441 delete [] Types; 1442 return ER; 1443 } 1444 1445 ExprResult 1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1447 SourceLocation DefaultLoc, 1448 SourceLocation RParenLoc, 1449 Expr *ControllingExpr, 1450 ArrayRef<TypeSourceInfo *> Types, 1451 ArrayRef<Expr *> Exprs) { 1452 unsigned NumAssocs = Types.size(); 1453 assert(NumAssocs == Exprs.size()); 1454 1455 // Decay and strip qualifiers for the controlling expression type, and handle 1456 // placeholder type replacement. See committee discussion from WG14 DR423. 1457 { 1458 EnterExpressionEvaluationContext Unevaluated( 1459 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1460 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1461 if (R.isInvalid()) 1462 return ExprError(); 1463 ControllingExpr = R.get(); 1464 } 1465 1466 // The controlling expression is an unevaluated operand, so side effects are 1467 // likely unintended. 1468 if (!inTemplateInstantiation() && 1469 ControllingExpr->HasSideEffects(Context, false)) 1470 Diag(ControllingExpr->getExprLoc(), 1471 diag::warn_side_effects_unevaluated_context); 1472 1473 bool TypeErrorFound = false, 1474 IsResultDependent = ControllingExpr->isTypeDependent(), 1475 ContainsUnexpandedParameterPack 1476 = ControllingExpr->containsUnexpandedParameterPack(); 1477 1478 for (unsigned i = 0; i < NumAssocs; ++i) { 1479 if (Exprs[i]->containsUnexpandedParameterPack()) 1480 ContainsUnexpandedParameterPack = true; 1481 1482 if (Types[i]) { 1483 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1484 ContainsUnexpandedParameterPack = true; 1485 1486 if (Types[i]->getType()->isDependentType()) { 1487 IsResultDependent = true; 1488 } else { 1489 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1490 // complete object type other than a variably modified type." 1491 unsigned D = 0; 1492 if (Types[i]->getType()->isIncompleteType()) 1493 D = diag::err_assoc_type_incomplete; 1494 else if (!Types[i]->getType()->isObjectType()) 1495 D = diag::err_assoc_type_nonobject; 1496 else if (Types[i]->getType()->isVariablyModifiedType()) 1497 D = diag::err_assoc_type_variably_modified; 1498 1499 if (D != 0) { 1500 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1501 << Types[i]->getTypeLoc().getSourceRange() 1502 << Types[i]->getType(); 1503 TypeErrorFound = true; 1504 } 1505 1506 // C11 6.5.1.1p2 "No two generic associations in the same generic 1507 // selection shall specify compatible types." 1508 for (unsigned j = i+1; j < NumAssocs; ++j) 1509 if (Types[j] && !Types[j]->getType()->isDependentType() && 1510 Context.typesAreCompatible(Types[i]->getType(), 1511 Types[j]->getType())) { 1512 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1513 diag::err_assoc_compatible_types) 1514 << Types[j]->getTypeLoc().getSourceRange() 1515 << Types[j]->getType() 1516 << Types[i]->getType(); 1517 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1518 diag::note_compat_assoc) 1519 << Types[i]->getTypeLoc().getSourceRange() 1520 << Types[i]->getType(); 1521 TypeErrorFound = true; 1522 } 1523 } 1524 } 1525 } 1526 if (TypeErrorFound) 1527 return ExprError(); 1528 1529 // If we determined that the generic selection is result-dependent, don't 1530 // try to compute the result expression. 1531 if (IsResultDependent) 1532 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1533 Exprs, DefaultLoc, RParenLoc, 1534 ContainsUnexpandedParameterPack); 1535 1536 SmallVector<unsigned, 1> CompatIndices; 1537 unsigned DefaultIndex = -1U; 1538 for (unsigned i = 0; i < NumAssocs; ++i) { 1539 if (!Types[i]) 1540 DefaultIndex = i; 1541 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1542 Types[i]->getType())) 1543 CompatIndices.push_back(i); 1544 } 1545 1546 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1547 // type compatible with at most one of the types named in its generic 1548 // association list." 1549 if (CompatIndices.size() > 1) { 1550 // We strip parens here because the controlling expression is typically 1551 // parenthesized in macro definitions. 1552 ControllingExpr = ControllingExpr->IgnoreParens(); 1553 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1554 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1555 << (unsigned)CompatIndices.size(); 1556 for (unsigned I : CompatIndices) { 1557 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1558 diag::note_compat_assoc) 1559 << Types[I]->getTypeLoc().getSourceRange() 1560 << Types[I]->getType(); 1561 } 1562 return ExprError(); 1563 } 1564 1565 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1566 // its controlling expression shall have type compatible with exactly one of 1567 // the types named in its generic association list." 1568 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1569 // We strip parens here because the controlling expression is typically 1570 // parenthesized in macro definitions. 1571 ControllingExpr = ControllingExpr->IgnoreParens(); 1572 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1573 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1574 return ExprError(); 1575 } 1576 1577 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1578 // type name that is compatible with the type of the controlling expression, 1579 // then the result expression of the generic selection is the expression 1580 // in that generic association. Otherwise, the result expression of the 1581 // generic selection is the expression in the default generic association." 1582 unsigned ResultIndex = 1583 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1584 1585 return GenericSelectionExpr::Create( 1586 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1587 ContainsUnexpandedParameterPack, ResultIndex); 1588 } 1589 1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1591 /// location of the token and the offset of the ud-suffix within it. 1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1593 unsigned Offset) { 1594 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1595 S.getLangOpts()); 1596 } 1597 1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1601 IdentifierInfo *UDSuffix, 1602 SourceLocation UDSuffixLoc, 1603 ArrayRef<Expr*> Args, 1604 SourceLocation LitEndLoc) { 1605 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1606 1607 QualType ArgTy[2]; 1608 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1609 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1610 if (ArgTy[ArgIdx]->isArrayType()) 1611 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1612 } 1613 1614 DeclarationName OpName = 1615 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1616 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1617 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1618 1619 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1620 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1621 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1622 /*AllowStringTemplate*/ false, 1623 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1624 return ExprError(); 1625 1626 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1627 } 1628 1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1630 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1632 /// multiple tokens. However, the common case is that StringToks points to one 1633 /// string. 1634 /// 1635 ExprResult 1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1637 assert(!StringToks.empty() && "Must have at least one string!"); 1638 1639 StringLiteralParser Literal(StringToks, PP); 1640 if (Literal.hadError) 1641 return ExprError(); 1642 1643 SmallVector<SourceLocation, 4> StringTokLocs; 1644 for (const Token &Tok : StringToks) 1645 StringTokLocs.push_back(Tok.getLocation()); 1646 1647 QualType CharTy = Context.CharTy; 1648 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1649 if (Literal.isWide()) { 1650 CharTy = Context.getWideCharType(); 1651 Kind = StringLiteral::Wide; 1652 } else if (Literal.isUTF8()) { 1653 if (getLangOpts().Char8) 1654 CharTy = Context.Char8Ty; 1655 Kind = StringLiteral::UTF8; 1656 } else if (Literal.isUTF16()) { 1657 CharTy = Context.Char16Ty; 1658 Kind = StringLiteral::UTF16; 1659 } else if (Literal.isUTF32()) { 1660 CharTy = Context.Char32Ty; 1661 Kind = StringLiteral::UTF32; 1662 } else if (Literal.isPascal()) { 1663 CharTy = Context.UnsignedCharTy; 1664 } 1665 1666 // Warn on initializing an array of char from a u8 string literal; this 1667 // becomes ill-formed in C++2a. 1668 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1669 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1670 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1671 1672 // Create removals for all 'u8' prefixes in the string literal(s). This 1673 // ensures C++2a compatibility (but may change the program behavior when 1674 // built by non-Clang compilers for which the execution character set is 1675 // not always UTF-8). 1676 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1677 SourceLocation RemovalDiagLoc; 1678 for (const Token &Tok : StringToks) { 1679 if (Tok.getKind() == tok::utf8_string_literal) { 1680 if (RemovalDiagLoc.isInvalid()) 1681 RemovalDiagLoc = Tok.getLocation(); 1682 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1683 Tok.getLocation(), 1684 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1685 getSourceManager(), getLangOpts()))); 1686 } 1687 } 1688 Diag(RemovalDiagLoc, RemovalDiag); 1689 } 1690 1691 QualType StrTy = 1692 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1693 1694 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1695 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1696 Kind, Literal.Pascal, StrTy, 1697 &StringTokLocs[0], 1698 StringTokLocs.size()); 1699 if (Literal.getUDSuffix().empty()) 1700 return Lit; 1701 1702 // We're building a user-defined literal. 1703 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1704 SourceLocation UDSuffixLoc = 1705 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1706 Literal.getUDSuffixOffset()); 1707 1708 // Make sure we're allowed user-defined literals here. 1709 if (!UDLScope) 1710 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1711 1712 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1713 // operator "" X (str, len) 1714 QualType SizeType = Context.getSizeType(); 1715 1716 DeclarationName OpName = 1717 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1718 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1719 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1720 1721 QualType ArgTy[] = { 1722 Context.getArrayDecayedType(StrTy), SizeType 1723 }; 1724 1725 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1726 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1727 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1728 /*AllowStringTemplate*/ true, 1729 /*DiagnoseMissing*/ true)) { 1730 1731 case LOLR_Cooked: { 1732 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1733 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1734 StringTokLocs[0]); 1735 Expr *Args[] = { Lit, LenArg }; 1736 1737 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1738 } 1739 1740 case LOLR_StringTemplate: { 1741 TemplateArgumentListInfo ExplicitArgs; 1742 1743 unsigned CharBits = Context.getIntWidth(CharTy); 1744 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1745 llvm::APSInt Value(CharBits, CharIsUnsigned); 1746 1747 TemplateArgument TypeArg(CharTy); 1748 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1749 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1750 1751 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1752 Value = Lit->getCodeUnit(I); 1753 TemplateArgument Arg(Context, Value, CharTy); 1754 TemplateArgumentLocInfo ArgInfo; 1755 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1756 } 1757 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1758 &ExplicitArgs); 1759 } 1760 case LOLR_Raw: 1761 case LOLR_Template: 1762 case LOLR_ErrorNoDiagnostic: 1763 llvm_unreachable("unexpected literal operator lookup result"); 1764 case LOLR_Error: 1765 return ExprError(); 1766 } 1767 llvm_unreachable("unexpected literal operator lookup result"); 1768 } 1769 1770 DeclRefExpr * 1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1772 SourceLocation Loc, 1773 const CXXScopeSpec *SS) { 1774 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1775 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1776 } 1777 1778 DeclRefExpr * 1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1780 const DeclarationNameInfo &NameInfo, 1781 const CXXScopeSpec *SS, NamedDecl *FoundD, 1782 SourceLocation TemplateKWLoc, 1783 const TemplateArgumentListInfo *TemplateArgs) { 1784 NestedNameSpecifierLoc NNS = 1785 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1786 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1787 TemplateArgs); 1788 } 1789 1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1791 // A declaration named in an unevaluated operand never constitutes an odr-use. 1792 if (isUnevaluatedContext()) 1793 return NOUR_Unevaluated; 1794 1795 // C++2a [basic.def.odr]p4: 1796 // A variable x whose name appears as a potentially-evaluated expression e 1797 // is odr-used by e unless [...] x is a reference that is usable in 1798 // constant expressions. 1799 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1800 if (VD->getType()->isReferenceType() && 1801 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1802 VD->isUsableInConstantExpressions(Context)) 1803 return NOUR_Constant; 1804 } 1805 1806 // All remaining non-variable cases constitute an odr-use. For variables, we 1807 // need to wait and see how the expression is used. 1808 return NOUR_None; 1809 } 1810 1811 /// BuildDeclRefExpr - Build an expression that references a 1812 /// declaration that does not require a closure capture. 1813 DeclRefExpr * 1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1815 const DeclarationNameInfo &NameInfo, 1816 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1817 SourceLocation TemplateKWLoc, 1818 const TemplateArgumentListInfo *TemplateArgs) { 1819 bool RefersToCapturedVariable = 1820 isa<VarDecl>(D) && 1821 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1822 1823 DeclRefExpr *E = DeclRefExpr::Create( 1824 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1825 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1826 MarkDeclRefReferenced(E); 1827 1828 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1829 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1830 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1831 getCurFunction()->recordUseOfWeak(E); 1832 1833 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1834 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1835 FD = IFD->getAnonField(); 1836 if (FD) { 1837 UnusedPrivateFields.remove(FD); 1838 // Just in case we're building an illegal pointer-to-member. 1839 if (FD->isBitField()) 1840 E->setObjectKind(OK_BitField); 1841 } 1842 1843 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1844 // designates a bit-field. 1845 if (auto *BD = dyn_cast<BindingDecl>(D)) 1846 if (auto *BE = BD->getBinding()) 1847 E->setObjectKind(BE->getObjectKind()); 1848 1849 return E; 1850 } 1851 1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1853 /// possibly a list of template arguments. 1854 /// 1855 /// If this produces template arguments, it is permitted to call 1856 /// DecomposeTemplateName. 1857 /// 1858 /// This actually loses a lot of source location information for 1859 /// non-standard name kinds; we should consider preserving that in 1860 /// some way. 1861 void 1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1863 TemplateArgumentListInfo &Buffer, 1864 DeclarationNameInfo &NameInfo, 1865 const TemplateArgumentListInfo *&TemplateArgs) { 1866 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1867 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1868 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1869 1870 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1871 Id.TemplateId->NumArgs); 1872 translateTemplateArguments(TemplateArgsPtr, Buffer); 1873 1874 TemplateName TName = Id.TemplateId->Template.get(); 1875 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1876 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1877 TemplateArgs = &Buffer; 1878 } else { 1879 NameInfo = GetNameFromUnqualifiedId(Id); 1880 TemplateArgs = nullptr; 1881 } 1882 } 1883 1884 static void emitEmptyLookupTypoDiagnostic( 1885 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1886 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1887 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1888 DeclContext *Ctx = 1889 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1890 if (!TC) { 1891 // Emit a special diagnostic for failed member lookups. 1892 // FIXME: computing the declaration context might fail here (?) 1893 if (Ctx) 1894 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1895 << SS.getRange(); 1896 else 1897 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1898 return; 1899 } 1900 1901 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1902 bool DroppedSpecifier = 1903 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1904 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1905 ? diag::note_implicit_param_decl 1906 : diag::note_previous_decl; 1907 if (!Ctx) 1908 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1909 SemaRef.PDiag(NoteID)); 1910 else 1911 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1912 << Typo << Ctx << DroppedSpecifier 1913 << SS.getRange(), 1914 SemaRef.PDiag(NoteID)); 1915 } 1916 1917 /// Diagnose an empty lookup. 1918 /// 1919 /// \return false if new lookup candidates were found 1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1921 CorrectionCandidateCallback &CCC, 1922 TemplateArgumentListInfo *ExplicitTemplateArgs, 1923 ArrayRef<Expr *> Args, TypoExpr **Out) { 1924 DeclarationName Name = R.getLookupName(); 1925 1926 unsigned diagnostic = diag::err_undeclared_var_use; 1927 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1928 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1929 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1930 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1931 diagnostic = diag::err_undeclared_use; 1932 diagnostic_suggest = diag::err_undeclared_use_suggest; 1933 } 1934 1935 // If the original lookup was an unqualified lookup, fake an 1936 // unqualified lookup. This is useful when (for example) the 1937 // original lookup would not have found something because it was a 1938 // dependent name. 1939 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1940 while (DC) { 1941 if (isa<CXXRecordDecl>(DC)) { 1942 LookupQualifiedName(R, DC); 1943 1944 if (!R.empty()) { 1945 // Don't give errors about ambiguities in this lookup. 1946 R.suppressDiagnostics(); 1947 1948 // During a default argument instantiation the CurContext points 1949 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1950 // function parameter list, hence add an explicit check. 1951 bool isDefaultArgument = 1952 !CodeSynthesisContexts.empty() && 1953 CodeSynthesisContexts.back().Kind == 1954 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1955 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1956 bool isInstance = CurMethod && 1957 CurMethod->isInstance() && 1958 DC == CurMethod->getParent() && !isDefaultArgument; 1959 1960 // Give a code modification hint to insert 'this->'. 1961 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1962 // Actually quite difficult! 1963 if (getLangOpts().MSVCCompat) 1964 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1965 if (isInstance) { 1966 Diag(R.getNameLoc(), diagnostic) << Name 1967 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1968 CheckCXXThisCapture(R.getNameLoc()); 1969 } else { 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 } 1972 1973 // Do we really want to note all of these? 1974 for (NamedDecl *D : R) 1975 Diag(D->getLocation(), diag::note_dependent_var_use); 1976 1977 // Return true if we are inside a default argument instantiation 1978 // and the found name refers to an instance member function, otherwise 1979 // the function calling DiagnoseEmptyLookup will try to create an 1980 // implicit member call and this is wrong for default argument. 1981 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1982 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1983 return true; 1984 } 1985 1986 // Tell the callee to try to recover. 1987 return false; 1988 } 1989 1990 R.clear(); 1991 } 1992 1993 DC = DC->getLookupParent(); 1994 } 1995 1996 // We didn't find anything, so try to correct for a typo. 1997 TypoCorrection Corrected; 1998 if (S && Out) { 1999 SourceLocation TypoLoc = R.getNameLoc(); 2000 assert(!ExplicitTemplateArgs && 2001 "Diagnosing an empty lookup with explicit template args!"); 2002 *Out = CorrectTypoDelayed( 2003 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2004 [=](const TypoCorrection &TC) { 2005 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2006 diagnostic, diagnostic_suggest); 2007 }, 2008 nullptr, CTK_ErrorRecovery); 2009 if (*Out) 2010 return true; 2011 } else if (S && 2012 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2013 S, &SS, CCC, CTK_ErrorRecovery))) { 2014 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2015 bool DroppedSpecifier = 2016 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2017 R.setLookupName(Corrected.getCorrection()); 2018 2019 bool AcceptableWithRecovery = false; 2020 bool AcceptableWithoutRecovery = false; 2021 NamedDecl *ND = Corrected.getFoundDecl(); 2022 if (ND) { 2023 if (Corrected.isOverloaded()) { 2024 OverloadCandidateSet OCS(R.getNameLoc(), 2025 OverloadCandidateSet::CSK_Normal); 2026 OverloadCandidateSet::iterator Best; 2027 for (NamedDecl *CD : Corrected) { 2028 if (FunctionTemplateDecl *FTD = 2029 dyn_cast<FunctionTemplateDecl>(CD)) 2030 AddTemplateOverloadCandidate( 2031 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2032 Args, OCS); 2033 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2034 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2035 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2036 Args, OCS); 2037 } 2038 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2039 case OR_Success: 2040 ND = Best->FoundDecl; 2041 Corrected.setCorrectionDecl(ND); 2042 break; 2043 default: 2044 // FIXME: Arbitrarily pick the first declaration for the note. 2045 Corrected.setCorrectionDecl(ND); 2046 break; 2047 } 2048 } 2049 R.addDecl(ND); 2050 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2051 CXXRecordDecl *Record = nullptr; 2052 if (Corrected.getCorrectionSpecifier()) { 2053 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2054 Record = Ty->getAsCXXRecordDecl(); 2055 } 2056 if (!Record) 2057 Record = cast<CXXRecordDecl>( 2058 ND->getDeclContext()->getRedeclContext()); 2059 R.setNamingClass(Record); 2060 } 2061 2062 auto *UnderlyingND = ND->getUnderlyingDecl(); 2063 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2064 isa<FunctionTemplateDecl>(UnderlyingND); 2065 // FIXME: If we ended up with a typo for a type name or 2066 // Objective-C class name, we're in trouble because the parser 2067 // is in the wrong place to recover. Suggest the typo 2068 // correction, but don't make it a fix-it since we're not going 2069 // to recover well anyway. 2070 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2071 getAsTypeTemplateDecl(UnderlyingND) || 2072 isa<ObjCInterfaceDecl>(UnderlyingND); 2073 } else { 2074 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2075 // because we aren't able to recover. 2076 AcceptableWithoutRecovery = true; 2077 } 2078 2079 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2080 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2081 ? diag::note_implicit_param_decl 2082 : diag::note_previous_decl; 2083 if (SS.isEmpty()) 2084 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2085 PDiag(NoteID), AcceptableWithRecovery); 2086 else 2087 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2088 << Name << computeDeclContext(SS, false) 2089 << DroppedSpecifier << SS.getRange(), 2090 PDiag(NoteID), AcceptableWithRecovery); 2091 2092 // Tell the callee whether to try to recover. 2093 return !AcceptableWithRecovery; 2094 } 2095 } 2096 R.clear(); 2097 2098 // Emit a special diagnostic for failed member lookups. 2099 // FIXME: computing the declaration context might fail here (?) 2100 if (!SS.isEmpty()) { 2101 Diag(R.getNameLoc(), diag::err_no_member) 2102 << Name << computeDeclContext(SS, false) 2103 << SS.getRange(); 2104 return true; 2105 } 2106 2107 // Give up, we can't recover. 2108 Diag(R.getNameLoc(), diagnostic) << Name; 2109 return true; 2110 } 2111 2112 /// In Microsoft mode, if we are inside a template class whose parent class has 2113 /// dependent base classes, and we can't resolve an unqualified identifier, then 2114 /// assume the identifier is a member of a dependent base class. We can only 2115 /// recover successfully in static methods, instance methods, and other contexts 2116 /// where 'this' is available. This doesn't precisely match MSVC's 2117 /// instantiation model, but it's close enough. 2118 static Expr * 2119 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2120 DeclarationNameInfo &NameInfo, 2121 SourceLocation TemplateKWLoc, 2122 const TemplateArgumentListInfo *TemplateArgs) { 2123 // Only try to recover from lookup into dependent bases in static methods or 2124 // contexts where 'this' is available. 2125 QualType ThisType = S.getCurrentThisType(); 2126 const CXXRecordDecl *RD = nullptr; 2127 if (!ThisType.isNull()) 2128 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2129 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2130 RD = MD->getParent(); 2131 if (!RD || !RD->hasAnyDependentBases()) 2132 return nullptr; 2133 2134 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2135 // is available, suggest inserting 'this->' as a fixit. 2136 SourceLocation Loc = NameInfo.getLoc(); 2137 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2138 DB << NameInfo.getName() << RD; 2139 2140 if (!ThisType.isNull()) { 2141 DB << FixItHint::CreateInsertion(Loc, "this->"); 2142 return CXXDependentScopeMemberExpr::Create( 2143 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2144 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2145 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2146 } 2147 2148 // Synthesize a fake NNS that points to the derived class. This will 2149 // perform name lookup during template instantiation. 2150 CXXScopeSpec SS; 2151 auto *NNS = 2152 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2153 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2154 return DependentScopeDeclRefExpr::Create( 2155 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2156 TemplateArgs); 2157 } 2158 2159 ExprResult 2160 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2161 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2162 bool HasTrailingLParen, bool IsAddressOfOperand, 2163 CorrectionCandidateCallback *CCC, 2164 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2165 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2166 "cannot be direct & operand and have a trailing lparen"); 2167 if (SS.isInvalid()) 2168 return ExprError(); 2169 2170 TemplateArgumentListInfo TemplateArgsBuffer; 2171 2172 // Decompose the UnqualifiedId into the following data. 2173 DeclarationNameInfo NameInfo; 2174 const TemplateArgumentListInfo *TemplateArgs; 2175 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2176 2177 DeclarationName Name = NameInfo.getName(); 2178 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2179 SourceLocation NameLoc = NameInfo.getLoc(); 2180 2181 if (II && II->isEditorPlaceholder()) { 2182 // FIXME: When typed placeholders are supported we can create a typed 2183 // placeholder expression node. 2184 return ExprError(); 2185 } 2186 2187 // C++ [temp.dep.expr]p3: 2188 // An id-expression is type-dependent if it contains: 2189 // -- an identifier that was declared with a dependent type, 2190 // (note: handled after lookup) 2191 // -- a template-id that is dependent, 2192 // (note: handled in BuildTemplateIdExpr) 2193 // -- a conversion-function-id that specifies a dependent type, 2194 // -- a nested-name-specifier that contains a class-name that 2195 // names a dependent type. 2196 // Determine whether this is a member of an unknown specialization; 2197 // we need to handle these differently. 2198 bool DependentID = false; 2199 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2200 Name.getCXXNameType()->isDependentType()) { 2201 DependentID = true; 2202 } else if (SS.isSet()) { 2203 if (DeclContext *DC = computeDeclContext(SS, false)) { 2204 if (RequireCompleteDeclContext(SS, DC)) 2205 return ExprError(); 2206 } else { 2207 DependentID = true; 2208 } 2209 } 2210 2211 if (DependentID) 2212 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2213 IsAddressOfOperand, TemplateArgs); 2214 2215 // Perform the required lookup. 2216 LookupResult R(*this, NameInfo, 2217 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2218 ? LookupObjCImplicitSelfParam 2219 : LookupOrdinaryName); 2220 if (TemplateKWLoc.isValid() || TemplateArgs) { 2221 // Lookup the template name again to correctly establish the context in 2222 // which it was found. This is really unfortunate as we already did the 2223 // lookup to determine that it was a template name in the first place. If 2224 // this becomes a performance hit, we can work harder to preserve those 2225 // results until we get here but it's likely not worth it. 2226 bool MemberOfUnknownSpecialization; 2227 AssumedTemplateKind AssumedTemplate; 2228 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2229 MemberOfUnknownSpecialization, TemplateKWLoc, 2230 &AssumedTemplate)) 2231 return ExprError(); 2232 2233 if (MemberOfUnknownSpecialization || 2234 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2235 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2236 IsAddressOfOperand, TemplateArgs); 2237 } else { 2238 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2239 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2240 2241 // If the result might be in a dependent base class, this is a dependent 2242 // id-expression. 2243 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2244 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2245 IsAddressOfOperand, TemplateArgs); 2246 2247 // If this reference is in an Objective-C method, then we need to do 2248 // some special Objective-C lookup, too. 2249 if (IvarLookupFollowUp) { 2250 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2251 if (E.isInvalid()) 2252 return ExprError(); 2253 2254 if (Expr *Ex = E.getAs<Expr>()) 2255 return Ex; 2256 } 2257 } 2258 2259 if (R.isAmbiguous()) 2260 return ExprError(); 2261 2262 // This could be an implicitly declared function reference (legal in C90, 2263 // extension in C99, forbidden in C++). 2264 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2265 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2266 if (D) R.addDecl(D); 2267 } 2268 2269 // Determine whether this name might be a candidate for 2270 // argument-dependent lookup. 2271 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2272 2273 if (R.empty() && !ADL) { 2274 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2275 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2276 TemplateKWLoc, TemplateArgs)) 2277 return E; 2278 } 2279 2280 // Don't diagnose an empty lookup for inline assembly. 2281 if (IsInlineAsmIdentifier) 2282 return ExprError(); 2283 2284 // If this name wasn't predeclared and if this is not a function 2285 // call, diagnose the problem. 2286 TypoExpr *TE = nullptr; 2287 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2288 : nullptr); 2289 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2290 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2291 "Typo correction callback misconfigured"); 2292 if (CCC) { 2293 // Make sure the callback knows what the typo being diagnosed is. 2294 CCC->setTypoName(II); 2295 if (SS.isValid()) 2296 CCC->setTypoNNS(SS.getScopeRep()); 2297 } 2298 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2299 // a template name, but we happen to have always already looked up the name 2300 // before we get here if it must be a template name. 2301 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2302 None, &TE)) { 2303 if (TE && KeywordReplacement) { 2304 auto &State = getTypoExprState(TE); 2305 auto BestTC = State.Consumer->getNextCorrection(); 2306 if (BestTC.isKeyword()) { 2307 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2308 if (State.DiagHandler) 2309 State.DiagHandler(BestTC); 2310 KeywordReplacement->startToken(); 2311 KeywordReplacement->setKind(II->getTokenID()); 2312 KeywordReplacement->setIdentifierInfo(II); 2313 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2314 // Clean up the state associated with the TypoExpr, since it has 2315 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2316 clearDelayedTypo(TE); 2317 // Signal that a correction to a keyword was performed by returning a 2318 // valid-but-null ExprResult. 2319 return (Expr*)nullptr; 2320 } 2321 State.Consumer->resetCorrectionStream(); 2322 } 2323 return TE ? TE : ExprError(); 2324 } 2325 2326 assert(!R.empty() && 2327 "DiagnoseEmptyLookup returned false but added no results"); 2328 2329 // If we found an Objective-C instance variable, let 2330 // LookupInObjCMethod build the appropriate expression to 2331 // reference the ivar. 2332 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2333 R.clear(); 2334 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2335 // In a hopelessly buggy code, Objective-C instance variable 2336 // lookup fails and no expression will be built to reference it. 2337 if (!E.isInvalid() && !E.get()) 2338 return ExprError(); 2339 return E; 2340 } 2341 } 2342 2343 // This is guaranteed from this point on. 2344 assert(!R.empty() || ADL); 2345 2346 // Check whether this might be a C++ implicit instance member access. 2347 // C++ [class.mfct.non-static]p3: 2348 // When an id-expression that is not part of a class member access 2349 // syntax and not used to form a pointer to member is used in the 2350 // body of a non-static member function of class X, if name lookup 2351 // resolves the name in the id-expression to a non-static non-type 2352 // member of some class C, the id-expression is transformed into a 2353 // class member access expression using (*this) as the 2354 // postfix-expression to the left of the . operator. 2355 // 2356 // But we don't actually need to do this for '&' operands if R 2357 // resolved to a function or overloaded function set, because the 2358 // expression is ill-formed if it actually works out to be a 2359 // non-static member function: 2360 // 2361 // C++ [expr.ref]p4: 2362 // Otherwise, if E1.E2 refers to a non-static member function. . . 2363 // [t]he expression can be used only as the left-hand operand of a 2364 // member function call. 2365 // 2366 // There are other safeguards against such uses, but it's important 2367 // to get this right here so that we don't end up making a 2368 // spuriously dependent expression if we're inside a dependent 2369 // instance method. 2370 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2371 bool MightBeImplicitMember; 2372 if (!IsAddressOfOperand) 2373 MightBeImplicitMember = true; 2374 else if (!SS.isEmpty()) 2375 MightBeImplicitMember = false; 2376 else if (R.isOverloadedResult()) 2377 MightBeImplicitMember = false; 2378 else if (R.isUnresolvableResult()) 2379 MightBeImplicitMember = true; 2380 else 2381 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2382 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2383 isa<MSPropertyDecl>(R.getFoundDecl()); 2384 2385 if (MightBeImplicitMember) 2386 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2387 R, TemplateArgs, S); 2388 } 2389 2390 if (TemplateArgs || TemplateKWLoc.isValid()) { 2391 2392 // In C++1y, if this is a variable template id, then check it 2393 // in BuildTemplateIdExpr(). 2394 // The single lookup result must be a variable template declaration. 2395 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2396 Id.TemplateId->Kind == TNK_Var_template) { 2397 assert(R.getAsSingle<VarTemplateDecl>() && 2398 "There should only be one declaration found."); 2399 } 2400 2401 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2402 } 2403 2404 return BuildDeclarationNameExpr(SS, R, ADL); 2405 } 2406 2407 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2408 /// declaration name, generally during template instantiation. 2409 /// There's a large number of things which don't need to be done along 2410 /// this path. 2411 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2412 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2413 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2414 DeclContext *DC = computeDeclContext(SS, false); 2415 if (!DC) 2416 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2417 NameInfo, /*TemplateArgs=*/nullptr); 2418 2419 if (RequireCompleteDeclContext(SS, DC)) 2420 return ExprError(); 2421 2422 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2423 LookupQualifiedName(R, DC); 2424 2425 if (R.isAmbiguous()) 2426 return ExprError(); 2427 2428 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2429 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2430 NameInfo, /*TemplateArgs=*/nullptr); 2431 2432 if (R.empty()) { 2433 Diag(NameInfo.getLoc(), diag::err_no_member) 2434 << NameInfo.getName() << DC << SS.getRange(); 2435 return ExprError(); 2436 } 2437 2438 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2439 // Diagnose a missing typename if this resolved unambiguously to a type in 2440 // a dependent context. If we can recover with a type, downgrade this to 2441 // a warning in Microsoft compatibility mode. 2442 unsigned DiagID = diag::err_typename_missing; 2443 if (RecoveryTSI && getLangOpts().MSVCCompat) 2444 DiagID = diag::ext_typename_missing; 2445 SourceLocation Loc = SS.getBeginLoc(); 2446 auto D = Diag(Loc, DiagID); 2447 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2448 << SourceRange(Loc, NameInfo.getEndLoc()); 2449 2450 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2451 // context. 2452 if (!RecoveryTSI) 2453 return ExprError(); 2454 2455 // Only issue the fixit if we're prepared to recover. 2456 D << FixItHint::CreateInsertion(Loc, "typename "); 2457 2458 // Recover by pretending this was an elaborated type. 2459 QualType Ty = Context.getTypeDeclType(TD); 2460 TypeLocBuilder TLB; 2461 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2462 2463 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2464 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2465 QTL.setElaboratedKeywordLoc(SourceLocation()); 2466 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2467 2468 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2469 2470 return ExprEmpty(); 2471 } 2472 2473 // Defend against this resolving to an implicit member access. We usually 2474 // won't get here if this might be a legitimate a class member (we end up in 2475 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2476 // a pointer-to-member or in an unevaluated context in C++11. 2477 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2478 return BuildPossibleImplicitMemberExpr(SS, 2479 /*TemplateKWLoc=*/SourceLocation(), 2480 R, /*TemplateArgs=*/nullptr, S); 2481 2482 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2483 } 2484 2485 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2486 /// detected that we're currently inside an ObjC method. Perform some 2487 /// additional lookup. 2488 /// 2489 /// Ideally, most of this would be done by lookup, but there's 2490 /// actually quite a lot of extra work involved. 2491 /// 2492 /// Returns a null sentinel to indicate trivial success. 2493 ExprResult 2494 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2495 IdentifierInfo *II, bool AllowBuiltinCreation) { 2496 SourceLocation Loc = Lookup.getNameLoc(); 2497 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2498 2499 // Check for error condition which is already reported. 2500 if (!CurMethod) 2501 return ExprError(); 2502 2503 // There are two cases to handle here. 1) scoped lookup could have failed, 2504 // in which case we should look for an ivar. 2) scoped lookup could have 2505 // found a decl, but that decl is outside the current instance method (i.e. 2506 // a global variable). In these two cases, we do a lookup for an ivar with 2507 // this name, if the lookup sucedes, we replace it our current decl. 2508 2509 // If we're in a class method, we don't normally want to look for 2510 // ivars. But if we don't find anything else, and there's an 2511 // ivar, that's an error. 2512 bool IsClassMethod = CurMethod->isClassMethod(); 2513 2514 bool LookForIvars; 2515 if (Lookup.empty()) 2516 LookForIvars = true; 2517 else if (IsClassMethod) 2518 LookForIvars = false; 2519 else 2520 LookForIvars = (Lookup.isSingleResult() && 2521 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2522 ObjCInterfaceDecl *IFace = nullptr; 2523 if (LookForIvars) { 2524 IFace = CurMethod->getClassInterface(); 2525 ObjCInterfaceDecl *ClassDeclared; 2526 ObjCIvarDecl *IV = nullptr; 2527 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2528 // Diagnose using an ivar in a class method. 2529 if (IsClassMethod) 2530 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2531 << IV->getDeclName()); 2532 2533 // If we're referencing an invalid decl, just return this as a silent 2534 // error node. The error diagnostic was already emitted on the decl. 2535 if (IV->isInvalidDecl()) 2536 return ExprError(); 2537 2538 // Check if referencing a field with __attribute__((deprecated)). 2539 if (DiagnoseUseOfDecl(IV, Loc)) 2540 return ExprError(); 2541 2542 // Diagnose the use of an ivar outside of the declaring class. 2543 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2544 !declaresSameEntity(ClassDeclared, IFace) && 2545 !getLangOpts().DebuggerSupport) 2546 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2547 2548 // FIXME: This should use a new expr for a direct reference, don't 2549 // turn this into Self->ivar, just return a BareIVarExpr or something. 2550 IdentifierInfo &II = Context.Idents.get("self"); 2551 UnqualifiedId SelfName; 2552 SelfName.setIdentifier(&II, SourceLocation()); 2553 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2554 CXXScopeSpec SelfScopeSpec; 2555 SourceLocation TemplateKWLoc; 2556 ExprResult SelfExpr = 2557 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2558 /*HasTrailingLParen=*/false, 2559 /*IsAddressOfOperand=*/false); 2560 if (SelfExpr.isInvalid()) 2561 return ExprError(); 2562 2563 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2564 if (SelfExpr.isInvalid()) 2565 return ExprError(); 2566 2567 MarkAnyDeclReferenced(Loc, IV, true); 2568 2569 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2570 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2571 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2572 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2573 2574 ObjCIvarRefExpr *Result = new (Context) 2575 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2576 IV->getLocation(), SelfExpr.get(), true, true); 2577 2578 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2579 if (!isUnevaluatedContext() && 2580 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2581 getCurFunction()->recordUseOfWeak(Result); 2582 } 2583 if (getLangOpts().ObjCAutoRefCount) 2584 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2585 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2586 2587 return Result; 2588 } 2589 } else if (CurMethod->isInstanceMethod()) { 2590 // We should warn if a local variable hides an ivar. 2591 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2592 ObjCInterfaceDecl *ClassDeclared; 2593 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2594 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2595 declaresSameEntity(IFace, ClassDeclared)) 2596 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2597 } 2598 } 2599 } else if (Lookup.isSingleResult() && 2600 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2601 // If accessing a stand-alone ivar in a class method, this is an error. 2602 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2603 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2604 << IV->getDeclName()); 2605 } 2606 2607 if (Lookup.empty() && II && AllowBuiltinCreation) { 2608 // FIXME. Consolidate this with similar code in LookupName. 2609 if (unsigned BuiltinID = II->getBuiltinID()) { 2610 if (!(getLangOpts().CPlusPlus && 2611 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2612 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2613 S, Lookup.isForRedeclaration(), 2614 Lookup.getNameLoc()); 2615 if (D) Lookup.addDecl(D); 2616 } 2617 } 2618 } 2619 // Sentinel value saying that we didn't do anything special. 2620 return ExprResult((Expr *)nullptr); 2621 } 2622 2623 /// Cast a base object to a member's actual type. 2624 /// 2625 /// Logically this happens in three phases: 2626 /// 2627 /// * First we cast from the base type to the naming class. 2628 /// The naming class is the class into which we were looking 2629 /// when we found the member; it's the qualifier type if a 2630 /// qualifier was provided, and otherwise it's the base type. 2631 /// 2632 /// * Next we cast from the naming class to the declaring class. 2633 /// If the member we found was brought into a class's scope by 2634 /// a using declaration, this is that class; otherwise it's 2635 /// the class declaring the member. 2636 /// 2637 /// * Finally we cast from the declaring class to the "true" 2638 /// declaring class of the member. This conversion does not 2639 /// obey access control. 2640 ExprResult 2641 Sema::PerformObjectMemberConversion(Expr *From, 2642 NestedNameSpecifier *Qualifier, 2643 NamedDecl *FoundDecl, 2644 NamedDecl *Member) { 2645 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2646 if (!RD) 2647 return From; 2648 2649 QualType DestRecordType; 2650 QualType DestType; 2651 QualType FromRecordType; 2652 QualType FromType = From->getType(); 2653 bool PointerConversions = false; 2654 if (isa<FieldDecl>(Member)) { 2655 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2656 auto FromPtrType = FromType->getAs<PointerType>(); 2657 DestRecordType = Context.getAddrSpaceQualType( 2658 DestRecordType, FromPtrType 2659 ? FromType->getPointeeType().getAddressSpace() 2660 : FromType.getAddressSpace()); 2661 2662 if (FromPtrType) { 2663 DestType = Context.getPointerType(DestRecordType); 2664 FromRecordType = FromPtrType->getPointeeType(); 2665 PointerConversions = true; 2666 } else { 2667 DestType = DestRecordType; 2668 FromRecordType = FromType; 2669 } 2670 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2671 if (Method->isStatic()) 2672 return From; 2673 2674 DestType = Method->getThisType(); 2675 DestRecordType = DestType->getPointeeType(); 2676 2677 if (FromType->getAs<PointerType>()) { 2678 FromRecordType = FromType->getPointeeType(); 2679 PointerConversions = true; 2680 } else { 2681 FromRecordType = FromType; 2682 DestType = DestRecordType; 2683 } 2684 } else { 2685 // No conversion necessary. 2686 return From; 2687 } 2688 2689 if (DestType->isDependentType() || FromType->isDependentType()) 2690 return From; 2691 2692 // If the unqualified types are the same, no conversion is necessary. 2693 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2694 return From; 2695 2696 SourceRange FromRange = From->getSourceRange(); 2697 SourceLocation FromLoc = FromRange.getBegin(); 2698 2699 ExprValueKind VK = From->getValueKind(); 2700 2701 // C++ [class.member.lookup]p8: 2702 // [...] Ambiguities can often be resolved by qualifying a name with its 2703 // class name. 2704 // 2705 // If the member was a qualified name and the qualified referred to a 2706 // specific base subobject type, we'll cast to that intermediate type 2707 // first and then to the object in which the member is declared. That allows 2708 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2709 // 2710 // class Base { public: int x; }; 2711 // class Derived1 : public Base { }; 2712 // class Derived2 : public Base { }; 2713 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2714 // 2715 // void VeryDerived::f() { 2716 // x = 17; // error: ambiguous base subobjects 2717 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2718 // } 2719 if (Qualifier && Qualifier->getAsType()) { 2720 QualType QType = QualType(Qualifier->getAsType(), 0); 2721 assert(QType->isRecordType() && "lookup done with non-record type"); 2722 2723 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2724 2725 // In C++98, the qualifier type doesn't actually have to be a base 2726 // type of the object type, in which case we just ignore it. 2727 // Otherwise build the appropriate casts. 2728 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2729 CXXCastPath BasePath; 2730 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2731 FromLoc, FromRange, &BasePath)) 2732 return ExprError(); 2733 2734 if (PointerConversions) 2735 QType = Context.getPointerType(QType); 2736 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2737 VK, &BasePath).get(); 2738 2739 FromType = QType; 2740 FromRecordType = QRecordType; 2741 2742 // If the qualifier type was the same as the destination type, 2743 // we're done. 2744 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2745 return From; 2746 } 2747 } 2748 2749 bool IgnoreAccess = false; 2750 2751 // If we actually found the member through a using declaration, cast 2752 // down to the using declaration's type. 2753 // 2754 // Pointer equality is fine here because only one declaration of a 2755 // class ever has member declarations. 2756 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2757 assert(isa<UsingShadowDecl>(FoundDecl)); 2758 QualType URecordType = Context.getTypeDeclType( 2759 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2760 2761 // We only need to do this if the naming-class to declaring-class 2762 // conversion is non-trivial. 2763 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2764 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2765 CXXCastPath BasePath; 2766 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2767 FromLoc, FromRange, &BasePath)) 2768 return ExprError(); 2769 2770 QualType UType = URecordType; 2771 if (PointerConversions) 2772 UType = Context.getPointerType(UType); 2773 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2774 VK, &BasePath).get(); 2775 FromType = UType; 2776 FromRecordType = URecordType; 2777 } 2778 2779 // We don't do access control for the conversion from the 2780 // declaring class to the true declaring class. 2781 IgnoreAccess = true; 2782 } 2783 2784 CXXCastPath BasePath; 2785 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2786 FromLoc, FromRange, &BasePath, 2787 IgnoreAccess)) 2788 return ExprError(); 2789 2790 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2791 VK, &BasePath); 2792 } 2793 2794 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2795 const LookupResult &R, 2796 bool HasTrailingLParen) { 2797 // Only when used directly as the postfix-expression of a call. 2798 if (!HasTrailingLParen) 2799 return false; 2800 2801 // Never if a scope specifier was provided. 2802 if (SS.isSet()) 2803 return false; 2804 2805 // Only in C++ or ObjC++. 2806 if (!getLangOpts().CPlusPlus) 2807 return false; 2808 2809 // Turn off ADL when we find certain kinds of declarations during 2810 // normal lookup: 2811 for (NamedDecl *D : R) { 2812 // C++0x [basic.lookup.argdep]p3: 2813 // -- a declaration of a class member 2814 // Since using decls preserve this property, we check this on the 2815 // original decl. 2816 if (D->isCXXClassMember()) 2817 return false; 2818 2819 // C++0x [basic.lookup.argdep]p3: 2820 // -- a block-scope function declaration that is not a 2821 // using-declaration 2822 // NOTE: we also trigger this for function templates (in fact, we 2823 // don't check the decl type at all, since all other decl types 2824 // turn off ADL anyway). 2825 if (isa<UsingShadowDecl>(D)) 2826 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2827 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2828 return false; 2829 2830 // C++0x [basic.lookup.argdep]p3: 2831 // -- a declaration that is neither a function or a function 2832 // template 2833 // And also for builtin functions. 2834 if (isa<FunctionDecl>(D)) { 2835 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2836 2837 // But also builtin functions. 2838 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2839 return false; 2840 } else if (!isa<FunctionTemplateDecl>(D)) 2841 return false; 2842 } 2843 2844 return true; 2845 } 2846 2847 2848 /// Diagnoses obvious problems with the use of the given declaration 2849 /// as an expression. This is only actually called for lookups that 2850 /// were not overloaded, and it doesn't promise that the declaration 2851 /// will in fact be used. 2852 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2853 if (D->isInvalidDecl()) 2854 return true; 2855 2856 if (isa<TypedefNameDecl>(D)) { 2857 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2858 return true; 2859 } 2860 2861 if (isa<ObjCInterfaceDecl>(D)) { 2862 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2863 return true; 2864 } 2865 2866 if (isa<NamespaceDecl>(D)) { 2867 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2868 return true; 2869 } 2870 2871 return false; 2872 } 2873 2874 // Certain multiversion types should be treated as overloaded even when there is 2875 // only one result. 2876 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2877 assert(R.isSingleResult() && "Expected only a single result"); 2878 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2879 return FD && 2880 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2881 } 2882 2883 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2884 LookupResult &R, bool NeedsADL, 2885 bool AcceptInvalidDecl) { 2886 // If this is a single, fully-resolved result and we don't need ADL, 2887 // just build an ordinary singleton decl ref. 2888 if (!NeedsADL && R.isSingleResult() && 2889 !R.getAsSingle<FunctionTemplateDecl>() && 2890 !ShouldLookupResultBeMultiVersionOverload(R)) 2891 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2892 R.getRepresentativeDecl(), nullptr, 2893 AcceptInvalidDecl); 2894 2895 // We only need to check the declaration if there's exactly one 2896 // result, because in the overloaded case the results can only be 2897 // functions and function templates. 2898 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2899 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2900 return ExprError(); 2901 2902 // Otherwise, just build an unresolved lookup expression. Suppress 2903 // any lookup-related diagnostics; we'll hash these out later, when 2904 // we've picked a target. 2905 R.suppressDiagnostics(); 2906 2907 UnresolvedLookupExpr *ULE 2908 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2909 SS.getWithLocInContext(Context), 2910 R.getLookupNameInfo(), 2911 NeedsADL, R.isOverloadedResult(), 2912 R.begin(), R.end()); 2913 2914 return ULE; 2915 } 2916 2917 static void 2918 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2919 ValueDecl *var, DeclContext *DC); 2920 2921 /// Complete semantic analysis for a reference to the given declaration. 2922 ExprResult Sema::BuildDeclarationNameExpr( 2923 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2924 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2925 bool AcceptInvalidDecl) { 2926 assert(D && "Cannot refer to a NULL declaration"); 2927 assert(!isa<FunctionTemplateDecl>(D) && 2928 "Cannot refer unambiguously to a function template"); 2929 2930 SourceLocation Loc = NameInfo.getLoc(); 2931 if (CheckDeclInExpr(*this, Loc, D)) 2932 return ExprError(); 2933 2934 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2935 // Specifically diagnose references to class templates that are missing 2936 // a template argument list. 2937 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2938 return ExprError(); 2939 } 2940 2941 // Make sure that we're referring to a value. 2942 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2943 if (!VD) { 2944 Diag(Loc, diag::err_ref_non_value) 2945 << D << SS.getRange(); 2946 Diag(D->getLocation(), diag::note_declared_at); 2947 return ExprError(); 2948 } 2949 2950 // Check whether this declaration can be used. Note that we suppress 2951 // this check when we're going to perform argument-dependent lookup 2952 // on this function name, because this might not be the function 2953 // that overload resolution actually selects. 2954 if (DiagnoseUseOfDecl(VD, Loc)) 2955 return ExprError(); 2956 2957 // Only create DeclRefExpr's for valid Decl's. 2958 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2959 return ExprError(); 2960 2961 // Handle members of anonymous structs and unions. If we got here, 2962 // and the reference is to a class member indirect field, then this 2963 // must be the subject of a pointer-to-member expression. 2964 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2965 if (!indirectField->isCXXClassMember()) 2966 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2967 indirectField); 2968 2969 { 2970 QualType type = VD->getType(); 2971 if (type.isNull()) 2972 return ExprError(); 2973 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2974 // C++ [except.spec]p17: 2975 // An exception-specification is considered to be needed when: 2976 // - in an expression, the function is the unique lookup result or 2977 // the selected member of a set of overloaded functions. 2978 ResolveExceptionSpec(Loc, FPT); 2979 type = VD->getType(); 2980 } 2981 ExprValueKind valueKind = VK_RValue; 2982 2983 switch (D->getKind()) { 2984 // Ignore all the non-ValueDecl kinds. 2985 #define ABSTRACT_DECL(kind) 2986 #define VALUE(type, base) 2987 #define DECL(type, base) \ 2988 case Decl::type: 2989 #include "clang/AST/DeclNodes.inc" 2990 llvm_unreachable("invalid value decl kind"); 2991 2992 // These shouldn't make it here. 2993 case Decl::ObjCAtDefsField: 2994 llvm_unreachable("forming non-member reference to ivar?"); 2995 2996 // Enum constants are always r-values and never references. 2997 // Unresolved using declarations are dependent. 2998 case Decl::EnumConstant: 2999 case Decl::UnresolvedUsingValue: 3000 case Decl::OMPDeclareReduction: 3001 case Decl::OMPDeclareMapper: 3002 valueKind = VK_RValue; 3003 break; 3004 3005 // Fields and indirect fields that got here must be for 3006 // pointer-to-member expressions; we just call them l-values for 3007 // internal consistency, because this subexpression doesn't really 3008 // exist in the high-level semantics. 3009 case Decl::Field: 3010 case Decl::IndirectField: 3011 case Decl::ObjCIvar: 3012 assert(getLangOpts().CPlusPlus && 3013 "building reference to field in C?"); 3014 3015 // These can't have reference type in well-formed programs, but 3016 // for internal consistency we do this anyway. 3017 type = type.getNonReferenceType(); 3018 valueKind = VK_LValue; 3019 break; 3020 3021 // Non-type template parameters are either l-values or r-values 3022 // depending on the type. 3023 case Decl::NonTypeTemplateParm: { 3024 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3025 type = reftype->getPointeeType(); 3026 valueKind = VK_LValue; // even if the parameter is an r-value reference 3027 break; 3028 } 3029 3030 // For non-references, we need to strip qualifiers just in case 3031 // the template parameter was declared as 'const int' or whatever. 3032 valueKind = VK_RValue; 3033 type = type.getUnqualifiedType(); 3034 break; 3035 } 3036 3037 case Decl::Var: 3038 case Decl::VarTemplateSpecialization: 3039 case Decl::VarTemplatePartialSpecialization: 3040 case Decl::Decomposition: 3041 case Decl::OMPCapturedExpr: 3042 // In C, "extern void blah;" is valid and is an r-value. 3043 if (!getLangOpts().CPlusPlus && 3044 !type.hasQualifiers() && 3045 type->isVoidType()) { 3046 valueKind = VK_RValue; 3047 break; 3048 } 3049 LLVM_FALLTHROUGH; 3050 3051 case Decl::ImplicitParam: 3052 case Decl::ParmVar: { 3053 // These are always l-values. 3054 valueKind = VK_LValue; 3055 type = type.getNonReferenceType(); 3056 3057 // FIXME: Does the addition of const really only apply in 3058 // potentially-evaluated contexts? Since the variable isn't actually 3059 // captured in an unevaluated context, it seems that the answer is no. 3060 if (!isUnevaluatedContext()) { 3061 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3062 if (!CapturedType.isNull()) 3063 type = CapturedType; 3064 } 3065 3066 break; 3067 } 3068 3069 case Decl::Binding: { 3070 // These are always lvalues. 3071 valueKind = VK_LValue; 3072 type = type.getNonReferenceType(); 3073 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3074 // decides how that's supposed to work. 3075 auto *BD = cast<BindingDecl>(VD); 3076 if (BD->getDeclContext() != CurContext) { 3077 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3078 if (DD && DD->hasLocalStorage()) 3079 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3080 } 3081 break; 3082 } 3083 3084 case Decl::Function: { 3085 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3086 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3087 type = Context.BuiltinFnTy; 3088 valueKind = VK_RValue; 3089 break; 3090 } 3091 } 3092 3093 const FunctionType *fty = type->castAs<FunctionType>(); 3094 3095 // If we're referring to a function with an __unknown_anytype 3096 // result type, make the entire expression __unknown_anytype. 3097 if (fty->getReturnType() == Context.UnknownAnyTy) { 3098 type = Context.UnknownAnyTy; 3099 valueKind = VK_RValue; 3100 break; 3101 } 3102 3103 // Functions are l-values in C++. 3104 if (getLangOpts().CPlusPlus) { 3105 valueKind = VK_LValue; 3106 break; 3107 } 3108 3109 // C99 DR 316 says that, if a function type comes from a 3110 // function definition (without a prototype), that type is only 3111 // used for checking compatibility. Therefore, when referencing 3112 // the function, we pretend that we don't have the full function 3113 // type. 3114 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3115 isa<FunctionProtoType>(fty)) 3116 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3117 fty->getExtInfo()); 3118 3119 // Functions are r-values in C. 3120 valueKind = VK_RValue; 3121 break; 3122 } 3123 3124 case Decl::CXXDeductionGuide: 3125 llvm_unreachable("building reference to deduction guide"); 3126 3127 case Decl::MSProperty: 3128 valueKind = VK_LValue; 3129 break; 3130 3131 case Decl::CXXMethod: 3132 // If we're referring to a method with an __unknown_anytype 3133 // result type, make the entire expression __unknown_anytype. 3134 // This should only be possible with a type written directly. 3135 if (const FunctionProtoType *proto 3136 = dyn_cast<FunctionProtoType>(VD->getType())) 3137 if (proto->getReturnType() == Context.UnknownAnyTy) { 3138 type = Context.UnknownAnyTy; 3139 valueKind = VK_RValue; 3140 break; 3141 } 3142 3143 // C++ methods are l-values if static, r-values if non-static. 3144 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3145 valueKind = VK_LValue; 3146 break; 3147 } 3148 LLVM_FALLTHROUGH; 3149 3150 case Decl::CXXConversion: 3151 case Decl::CXXDestructor: 3152 case Decl::CXXConstructor: 3153 valueKind = VK_RValue; 3154 break; 3155 } 3156 3157 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3158 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3159 TemplateArgs); 3160 } 3161 } 3162 3163 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3164 SmallString<32> &Target) { 3165 Target.resize(CharByteWidth * (Source.size() + 1)); 3166 char *ResultPtr = &Target[0]; 3167 const llvm::UTF8 *ErrorPtr; 3168 bool success = 3169 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3170 (void)success; 3171 assert(success); 3172 Target.resize(ResultPtr - &Target[0]); 3173 } 3174 3175 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3176 PredefinedExpr::IdentKind IK) { 3177 // Pick the current block, lambda, captured statement or function. 3178 Decl *currentDecl = nullptr; 3179 if (const BlockScopeInfo *BSI = getCurBlock()) 3180 currentDecl = BSI->TheDecl; 3181 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3182 currentDecl = LSI->CallOperator; 3183 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3184 currentDecl = CSI->TheCapturedDecl; 3185 else 3186 currentDecl = getCurFunctionOrMethodDecl(); 3187 3188 if (!currentDecl) { 3189 Diag(Loc, diag::ext_predef_outside_function); 3190 currentDecl = Context.getTranslationUnitDecl(); 3191 } 3192 3193 QualType ResTy; 3194 StringLiteral *SL = nullptr; 3195 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3196 ResTy = Context.DependentTy; 3197 else { 3198 // Pre-defined identifiers are of type char[x], where x is the length of 3199 // the string. 3200 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3201 unsigned Length = Str.length(); 3202 3203 llvm::APInt LengthI(32, Length + 1); 3204 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3205 ResTy = 3206 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3207 SmallString<32> RawChars; 3208 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3209 Str, RawChars); 3210 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3211 /*IndexTypeQuals*/ 0); 3212 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3213 /*Pascal*/ false, ResTy, Loc); 3214 } else { 3215 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3216 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3217 /*IndexTypeQuals*/ 0); 3218 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3219 /*Pascal*/ false, ResTy, Loc); 3220 } 3221 } 3222 3223 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3224 } 3225 3226 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3227 PredefinedExpr::IdentKind IK; 3228 3229 switch (Kind) { 3230 default: llvm_unreachable("Unknown simple primary expr!"); 3231 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3232 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3233 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3234 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3235 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3236 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3237 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3238 } 3239 3240 return BuildPredefinedExpr(Loc, IK); 3241 } 3242 3243 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3244 SmallString<16> CharBuffer; 3245 bool Invalid = false; 3246 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3247 if (Invalid) 3248 return ExprError(); 3249 3250 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3251 PP, Tok.getKind()); 3252 if (Literal.hadError()) 3253 return ExprError(); 3254 3255 QualType Ty; 3256 if (Literal.isWide()) 3257 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3258 else if (Literal.isUTF8() && getLangOpts().Char8) 3259 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3260 else if (Literal.isUTF16()) 3261 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3262 else if (Literal.isUTF32()) 3263 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3264 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3265 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3266 else 3267 Ty = Context.CharTy; // 'x' -> char in C++ 3268 3269 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3270 if (Literal.isWide()) 3271 Kind = CharacterLiteral::Wide; 3272 else if (Literal.isUTF16()) 3273 Kind = CharacterLiteral::UTF16; 3274 else if (Literal.isUTF32()) 3275 Kind = CharacterLiteral::UTF32; 3276 else if (Literal.isUTF8()) 3277 Kind = CharacterLiteral::UTF8; 3278 3279 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3280 Tok.getLocation()); 3281 3282 if (Literal.getUDSuffix().empty()) 3283 return Lit; 3284 3285 // We're building a user-defined literal. 3286 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3287 SourceLocation UDSuffixLoc = 3288 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3289 3290 // Make sure we're allowed user-defined literals here. 3291 if (!UDLScope) 3292 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3293 3294 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3295 // operator "" X (ch) 3296 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3297 Lit, Tok.getLocation()); 3298 } 3299 3300 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3301 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3302 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3303 Context.IntTy, Loc); 3304 } 3305 3306 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3307 QualType Ty, SourceLocation Loc) { 3308 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3309 3310 using llvm::APFloat; 3311 APFloat Val(Format); 3312 3313 APFloat::opStatus result = Literal.GetFloatValue(Val); 3314 3315 // Overflow is always an error, but underflow is only an error if 3316 // we underflowed to zero (APFloat reports denormals as underflow). 3317 if ((result & APFloat::opOverflow) || 3318 ((result & APFloat::opUnderflow) && Val.isZero())) { 3319 unsigned diagnostic; 3320 SmallString<20> buffer; 3321 if (result & APFloat::opOverflow) { 3322 diagnostic = diag::warn_float_overflow; 3323 APFloat::getLargest(Format).toString(buffer); 3324 } else { 3325 diagnostic = diag::warn_float_underflow; 3326 APFloat::getSmallest(Format).toString(buffer); 3327 } 3328 3329 S.Diag(Loc, diagnostic) 3330 << Ty 3331 << StringRef(buffer.data(), buffer.size()); 3332 } 3333 3334 bool isExact = (result == APFloat::opOK); 3335 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3336 } 3337 3338 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3339 assert(E && "Invalid expression"); 3340 3341 if (E->isValueDependent()) 3342 return false; 3343 3344 QualType QT = E->getType(); 3345 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3346 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3347 return true; 3348 } 3349 3350 llvm::APSInt ValueAPS; 3351 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3352 3353 if (R.isInvalid()) 3354 return true; 3355 3356 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3357 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3358 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3359 << ValueAPS.toString(10) << ValueIsPositive; 3360 return true; 3361 } 3362 3363 return false; 3364 } 3365 3366 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3367 // Fast path for a single digit (which is quite common). A single digit 3368 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3369 if (Tok.getLength() == 1) { 3370 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3371 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3372 } 3373 3374 SmallString<128> SpellingBuffer; 3375 // NumericLiteralParser wants to overread by one character. Add padding to 3376 // the buffer in case the token is copied to the buffer. If getSpelling() 3377 // returns a StringRef to the memory buffer, it should have a null char at 3378 // the EOF, so it is also safe. 3379 SpellingBuffer.resize(Tok.getLength() + 1); 3380 3381 // Get the spelling of the token, which eliminates trigraphs, etc. 3382 bool Invalid = false; 3383 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3384 if (Invalid) 3385 return ExprError(); 3386 3387 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3388 if (Literal.hadError) 3389 return ExprError(); 3390 3391 if (Literal.hasUDSuffix()) { 3392 // We're building a user-defined literal. 3393 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3394 SourceLocation UDSuffixLoc = 3395 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3396 3397 // Make sure we're allowed user-defined literals here. 3398 if (!UDLScope) 3399 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3400 3401 QualType CookedTy; 3402 if (Literal.isFloatingLiteral()) { 3403 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3404 // long double, the literal is treated as a call of the form 3405 // operator "" X (f L) 3406 CookedTy = Context.LongDoubleTy; 3407 } else { 3408 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3409 // unsigned long long, the literal is treated as a call of the form 3410 // operator "" X (n ULL) 3411 CookedTy = Context.UnsignedLongLongTy; 3412 } 3413 3414 DeclarationName OpName = 3415 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3416 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3417 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3418 3419 SourceLocation TokLoc = Tok.getLocation(); 3420 3421 // Perform literal operator lookup to determine if we're building a raw 3422 // literal or a cooked one. 3423 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3424 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3425 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3426 /*AllowStringTemplate*/ false, 3427 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3428 case LOLR_ErrorNoDiagnostic: 3429 // Lookup failure for imaginary constants isn't fatal, there's still the 3430 // GNU extension producing _Complex types. 3431 break; 3432 case LOLR_Error: 3433 return ExprError(); 3434 case LOLR_Cooked: { 3435 Expr *Lit; 3436 if (Literal.isFloatingLiteral()) { 3437 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3438 } else { 3439 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3440 if (Literal.GetIntegerValue(ResultVal)) 3441 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3442 << /* Unsigned */ 1; 3443 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3444 Tok.getLocation()); 3445 } 3446 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3447 } 3448 3449 case LOLR_Raw: { 3450 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3451 // literal is treated as a call of the form 3452 // operator "" X ("n") 3453 unsigned Length = Literal.getUDSuffixOffset(); 3454 QualType StrTy = Context.getConstantArrayType( 3455 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3456 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3457 Expr *Lit = StringLiteral::Create( 3458 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3459 /*Pascal*/false, StrTy, &TokLoc, 1); 3460 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3461 } 3462 3463 case LOLR_Template: { 3464 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3465 // template), L is treated as a call fo the form 3466 // operator "" X <'c1', 'c2', ... 'ck'>() 3467 // where n is the source character sequence c1 c2 ... ck. 3468 TemplateArgumentListInfo ExplicitArgs; 3469 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3470 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3471 llvm::APSInt Value(CharBits, CharIsUnsigned); 3472 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3473 Value = TokSpelling[I]; 3474 TemplateArgument Arg(Context, Value, Context.CharTy); 3475 TemplateArgumentLocInfo ArgInfo; 3476 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3477 } 3478 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3479 &ExplicitArgs); 3480 } 3481 case LOLR_StringTemplate: 3482 llvm_unreachable("unexpected literal operator lookup result"); 3483 } 3484 } 3485 3486 Expr *Res; 3487 3488 if (Literal.isFixedPointLiteral()) { 3489 QualType Ty; 3490 3491 if (Literal.isAccum) { 3492 if (Literal.isHalf) { 3493 Ty = Context.ShortAccumTy; 3494 } else if (Literal.isLong) { 3495 Ty = Context.LongAccumTy; 3496 } else { 3497 Ty = Context.AccumTy; 3498 } 3499 } else if (Literal.isFract) { 3500 if (Literal.isHalf) { 3501 Ty = Context.ShortFractTy; 3502 } else if (Literal.isLong) { 3503 Ty = Context.LongFractTy; 3504 } else { 3505 Ty = Context.FractTy; 3506 } 3507 } 3508 3509 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3510 3511 bool isSigned = !Literal.isUnsigned; 3512 unsigned scale = Context.getFixedPointScale(Ty); 3513 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3514 3515 llvm::APInt Val(bit_width, 0, isSigned); 3516 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3517 bool ValIsZero = Val.isNullValue() && !Overflowed; 3518 3519 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3520 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3521 // Clause 6.4.4 - The value of a constant shall be in the range of 3522 // representable values for its type, with exception for constants of a 3523 // fract type with a value of exactly 1; such a constant shall denote 3524 // the maximal value for the type. 3525 --Val; 3526 else if (Val.ugt(MaxVal) || Overflowed) 3527 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3528 3529 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3530 Tok.getLocation(), scale); 3531 } else if (Literal.isFloatingLiteral()) { 3532 QualType Ty; 3533 if (Literal.isHalf){ 3534 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3535 Ty = Context.HalfTy; 3536 else { 3537 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3538 return ExprError(); 3539 } 3540 } else if (Literal.isFloat) 3541 Ty = Context.FloatTy; 3542 else if (Literal.isLong) 3543 Ty = Context.LongDoubleTy; 3544 else if (Literal.isFloat16) 3545 Ty = Context.Float16Ty; 3546 else if (Literal.isFloat128) 3547 Ty = Context.Float128Ty; 3548 else 3549 Ty = Context.DoubleTy; 3550 3551 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3552 3553 if (Ty == Context.DoubleTy) { 3554 if (getLangOpts().SinglePrecisionConstants) { 3555 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3556 if (BTy->getKind() != BuiltinType::Float) { 3557 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3558 } 3559 } else if (getLangOpts().OpenCL && 3560 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3561 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3562 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3563 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3564 } 3565 } 3566 } else if (!Literal.isIntegerLiteral()) { 3567 return ExprError(); 3568 } else { 3569 QualType Ty; 3570 3571 // 'long long' is a C99 or C++11 feature. 3572 if (!getLangOpts().C99 && Literal.isLongLong) { 3573 if (getLangOpts().CPlusPlus) 3574 Diag(Tok.getLocation(), 3575 getLangOpts().CPlusPlus11 ? 3576 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3577 else 3578 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3579 } 3580 3581 // Get the value in the widest-possible width. 3582 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3583 llvm::APInt ResultVal(MaxWidth, 0); 3584 3585 if (Literal.GetIntegerValue(ResultVal)) { 3586 // If this value didn't fit into uintmax_t, error and force to ull. 3587 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3588 << /* Unsigned */ 1; 3589 Ty = Context.UnsignedLongLongTy; 3590 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3591 "long long is not intmax_t?"); 3592 } else { 3593 // If this value fits into a ULL, try to figure out what else it fits into 3594 // according to the rules of C99 6.4.4.1p5. 3595 3596 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3597 // be an unsigned int. 3598 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3599 3600 // Check from smallest to largest, picking the smallest type we can. 3601 unsigned Width = 0; 3602 3603 // Microsoft specific integer suffixes are explicitly sized. 3604 if (Literal.MicrosoftInteger) { 3605 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3606 Width = 8; 3607 Ty = Context.CharTy; 3608 } else { 3609 Width = Literal.MicrosoftInteger; 3610 Ty = Context.getIntTypeForBitwidth(Width, 3611 /*Signed=*/!Literal.isUnsigned); 3612 } 3613 } 3614 3615 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3616 // Are int/unsigned possibilities? 3617 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3618 3619 // Does it fit in a unsigned int? 3620 if (ResultVal.isIntN(IntSize)) { 3621 // Does it fit in a signed int? 3622 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3623 Ty = Context.IntTy; 3624 else if (AllowUnsigned) 3625 Ty = Context.UnsignedIntTy; 3626 Width = IntSize; 3627 } 3628 } 3629 3630 // Are long/unsigned long possibilities? 3631 if (Ty.isNull() && !Literal.isLongLong) { 3632 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3633 3634 // Does it fit in a unsigned long? 3635 if (ResultVal.isIntN(LongSize)) { 3636 // Does it fit in a signed long? 3637 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3638 Ty = Context.LongTy; 3639 else if (AllowUnsigned) 3640 Ty = Context.UnsignedLongTy; 3641 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3642 // is compatible. 3643 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3644 const unsigned LongLongSize = 3645 Context.getTargetInfo().getLongLongWidth(); 3646 Diag(Tok.getLocation(), 3647 getLangOpts().CPlusPlus 3648 ? Literal.isLong 3649 ? diag::warn_old_implicitly_unsigned_long_cxx 3650 : /*C++98 UB*/ diag:: 3651 ext_old_implicitly_unsigned_long_cxx 3652 : diag::warn_old_implicitly_unsigned_long) 3653 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3654 : /*will be ill-formed*/ 1); 3655 Ty = Context.UnsignedLongTy; 3656 } 3657 Width = LongSize; 3658 } 3659 } 3660 3661 // Check long long if needed. 3662 if (Ty.isNull()) { 3663 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3664 3665 // Does it fit in a unsigned long long? 3666 if (ResultVal.isIntN(LongLongSize)) { 3667 // Does it fit in a signed long long? 3668 // To be compatible with MSVC, hex integer literals ending with the 3669 // LL or i64 suffix are always signed in Microsoft mode. 3670 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3671 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3672 Ty = Context.LongLongTy; 3673 else if (AllowUnsigned) 3674 Ty = Context.UnsignedLongLongTy; 3675 Width = LongLongSize; 3676 } 3677 } 3678 3679 // If we still couldn't decide a type, we probably have something that 3680 // does not fit in a signed long long, but has no U suffix. 3681 if (Ty.isNull()) { 3682 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3683 Ty = Context.UnsignedLongLongTy; 3684 Width = Context.getTargetInfo().getLongLongWidth(); 3685 } 3686 3687 if (ResultVal.getBitWidth() != Width) 3688 ResultVal = ResultVal.trunc(Width); 3689 } 3690 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3691 } 3692 3693 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3694 if (Literal.isImaginary) { 3695 Res = new (Context) ImaginaryLiteral(Res, 3696 Context.getComplexType(Res->getType())); 3697 3698 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3699 } 3700 return Res; 3701 } 3702 3703 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3704 assert(E && "ActOnParenExpr() missing expr"); 3705 return new (Context) ParenExpr(L, R, E); 3706 } 3707 3708 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3709 SourceLocation Loc, 3710 SourceRange ArgRange) { 3711 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3712 // scalar or vector data type argument..." 3713 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3714 // type (C99 6.2.5p18) or void. 3715 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3716 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3717 << T << ArgRange; 3718 return true; 3719 } 3720 3721 assert((T->isVoidType() || !T->isIncompleteType()) && 3722 "Scalar types should always be complete"); 3723 return false; 3724 } 3725 3726 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3727 SourceLocation Loc, 3728 SourceRange ArgRange, 3729 UnaryExprOrTypeTrait TraitKind) { 3730 // Invalid types must be hard errors for SFINAE in C++. 3731 if (S.LangOpts.CPlusPlus) 3732 return true; 3733 3734 // C99 6.5.3.4p1: 3735 if (T->isFunctionType() && 3736 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3737 TraitKind == UETT_PreferredAlignOf)) { 3738 // sizeof(function)/alignof(function) is allowed as an extension. 3739 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3740 << TraitKind << ArgRange; 3741 return false; 3742 } 3743 3744 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3745 // this is an error (OpenCL v1.1 s6.3.k) 3746 if (T->isVoidType()) { 3747 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3748 : diag::ext_sizeof_alignof_void_type; 3749 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3750 return false; 3751 } 3752 3753 return true; 3754 } 3755 3756 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3757 SourceLocation Loc, 3758 SourceRange ArgRange, 3759 UnaryExprOrTypeTrait TraitKind) { 3760 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3761 // runtime doesn't allow it. 3762 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3763 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3764 << T << (TraitKind == UETT_SizeOf) 3765 << ArgRange; 3766 return true; 3767 } 3768 3769 return false; 3770 } 3771 3772 /// Check whether E is a pointer from a decayed array type (the decayed 3773 /// pointer type is equal to T) and emit a warning if it is. 3774 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3775 Expr *E) { 3776 // Don't warn if the operation changed the type. 3777 if (T != E->getType()) 3778 return; 3779 3780 // Now look for array decays. 3781 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3782 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3783 return; 3784 3785 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3786 << ICE->getType() 3787 << ICE->getSubExpr()->getType(); 3788 } 3789 3790 /// Check the constraints on expression operands to unary type expression 3791 /// and type traits. 3792 /// 3793 /// Completes any types necessary and validates the constraints on the operand 3794 /// expression. The logic mostly mirrors the type-based overload, but may modify 3795 /// the expression as it completes the type for that expression through template 3796 /// instantiation, etc. 3797 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3798 UnaryExprOrTypeTrait ExprKind) { 3799 QualType ExprTy = E->getType(); 3800 assert(!ExprTy->isReferenceType()); 3801 3802 if (ExprKind == UETT_VecStep) 3803 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3804 E->getSourceRange()); 3805 3806 // Whitelist some types as extensions 3807 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3808 E->getSourceRange(), ExprKind)) 3809 return false; 3810 3811 // 'alignof' applied to an expression only requires the base element type of 3812 // the expression to be complete. 'sizeof' requires the expression's type to 3813 // be complete (and will attempt to complete it if it's an array of unknown 3814 // bound). 3815 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3816 if (RequireCompleteType(E->getExprLoc(), 3817 Context.getBaseElementType(E->getType()), 3818 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3819 E->getSourceRange())) 3820 return true; 3821 } else { 3822 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3823 ExprKind, E->getSourceRange())) 3824 return true; 3825 } 3826 3827 // Completing the expression's type may have changed it. 3828 ExprTy = E->getType(); 3829 assert(!ExprTy->isReferenceType()); 3830 3831 if (ExprTy->isFunctionType()) { 3832 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3833 << ExprKind << E->getSourceRange(); 3834 return true; 3835 } 3836 3837 // The operand for sizeof and alignof is in an unevaluated expression context, 3838 // so side effects could result in unintended consequences. 3839 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3840 ExprKind == UETT_PreferredAlignOf) && 3841 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3842 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3843 3844 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3845 E->getSourceRange(), ExprKind)) 3846 return true; 3847 3848 if (ExprKind == UETT_SizeOf) { 3849 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3850 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3851 QualType OType = PVD->getOriginalType(); 3852 QualType Type = PVD->getType(); 3853 if (Type->isPointerType() && OType->isArrayType()) { 3854 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3855 << Type << OType; 3856 Diag(PVD->getLocation(), diag::note_declared_at); 3857 } 3858 } 3859 } 3860 3861 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3862 // decays into a pointer and returns an unintended result. This is most 3863 // likely a typo for "sizeof(array) op x". 3864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3865 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3866 BO->getLHS()); 3867 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3868 BO->getRHS()); 3869 } 3870 } 3871 3872 return false; 3873 } 3874 3875 /// Check the constraints on operands to unary expression and type 3876 /// traits. 3877 /// 3878 /// This will complete any types necessary, and validate the various constraints 3879 /// on those operands. 3880 /// 3881 /// The UsualUnaryConversions() function is *not* called by this routine. 3882 /// C99 6.3.2.1p[2-4] all state: 3883 /// Except when it is the operand of the sizeof operator ... 3884 /// 3885 /// C++ [expr.sizeof]p4 3886 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3887 /// standard conversions are not applied to the operand of sizeof. 3888 /// 3889 /// This policy is followed for all of the unary trait expressions. 3890 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3891 SourceLocation OpLoc, 3892 SourceRange ExprRange, 3893 UnaryExprOrTypeTrait ExprKind) { 3894 if (ExprType->isDependentType()) 3895 return false; 3896 3897 // C++ [expr.sizeof]p2: 3898 // When applied to a reference or a reference type, the result 3899 // is the size of the referenced type. 3900 // C++11 [expr.alignof]p3: 3901 // When alignof is applied to a reference type, the result 3902 // shall be the alignment of the referenced type. 3903 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3904 ExprType = Ref->getPointeeType(); 3905 3906 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3907 // When alignof or _Alignof is applied to an array type, the result 3908 // is the alignment of the element type. 3909 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3910 ExprKind == UETT_OpenMPRequiredSimdAlign) 3911 ExprType = Context.getBaseElementType(ExprType); 3912 3913 if (ExprKind == UETT_VecStep) 3914 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3915 3916 // Whitelist some types as extensions 3917 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3918 ExprKind)) 3919 return false; 3920 3921 if (RequireCompleteType(OpLoc, ExprType, 3922 diag::err_sizeof_alignof_incomplete_type, 3923 ExprKind, ExprRange)) 3924 return true; 3925 3926 if (ExprType->isFunctionType()) { 3927 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3928 << ExprKind << ExprRange; 3929 return true; 3930 } 3931 3932 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3933 ExprKind)) 3934 return true; 3935 3936 return false; 3937 } 3938 3939 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3940 E = E->IgnoreParens(); 3941 3942 // Cannot know anything else if the expression is dependent. 3943 if (E->isTypeDependent()) 3944 return false; 3945 3946 if (E->getObjectKind() == OK_BitField) { 3947 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3948 << 1 << E->getSourceRange(); 3949 return true; 3950 } 3951 3952 ValueDecl *D = nullptr; 3953 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3954 D = DRE->getDecl(); 3955 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3956 D = ME->getMemberDecl(); 3957 } 3958 3959 // If it's a field, require the containing struct to have a 3960 // complete definition so that we can compute the layout. 3961 // 3962 // This can happen in C++11 onwards, either by naming the member 3963 // in a way that is not transformed into a member access expression 3964 // (in an unevaluated operand, for instance), or by naming the member 3965 // in a trailing-return-type. 3966 // 3967 // For the record, since __alignof__ on expressions is a GCC 3968 // extension, GCC seems to permit this but always gives the 3969 // nonsensical answer 0. 3970 // 3971 // We don't really need the layout here --- we could instead just 3972 // directly check for all the appropriate alignment-lowing 3973 // attributes --- but that would require duplicating a lot of 3974 // logic that just isn't worth duplicating for such a marginal 3975 // use-case. 3976 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3977 // Fast path this check, since we at least know the record has a 3978 // definition if we can find a member of it. 3979 if (!FD->getParent()->isCompleteDefinition()) { 3980 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3981 << E->getSourceRange(); 3982 return true; 3983 } 3984 3985 // Otherwise, if it's a field, and the field doesn't have 3986 // reference type, then it must have a complete type (or be a 3987 // flexible array member, which we explicitly want to 3988 // white-list anyway), which makes the following checks trivial. 3989 if (!FD->getType()->isReferenceType()) 3990 return false; 3991 } 3992 3993 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3994 } 3995 3996 bool Sema::CheckVecStepExpr(Expr *E) { 3997 E = E->IgnoreParens(); 3998 3999 // Cannot know anything else if the expression is dependent. 4000 if (E->isTypeDependent()) 4001 return false; 4002 4003 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4004 } 4005 4006 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4007 CapturingScopeInfo *CSI) { 4008 assert(T->isVariablyModifiedType()); 4009 assert(CSI != nullptr); 4010 4011 // We're going to walk down into the type and look for VLA expressions. 4012 do { 4013 const Type *Ty = T.getTypePtr(); 4014 switch (Ty->getTypeClass()) { 4015 #define TYPE(Class, Base) 4016 #define ABSTRACT_TYPE(Class, Base) 4017 #define NON_CANONICAL_TYPE(Class, Base) 4018 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4019 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4020 #include "clang/AST/TypeNodes.def" 4021 T = QualType(); 4022 break; 4023 // These types are never variably-modified. 4024 case Type::Builtin: 4025 case Type::Complex: 4026 case Type::Vector: 4027 case Type::ExtVector: 4028 case Type::Record: 4029 case Type::Enum: 4030 case Type::Elaborated: 4031 case Type::TemplateSpecialization: 4032 case Type::ObjCObject: 4033 case Type::ObjCInterface: 4034 case Type::ObjCObjectPointer: 4035 case Type::ObjCTypeParam: 4036 case Type::Pipe: 4037 llvm_unreachable("type class is never variably-modified!"); 4038 case Type::Adjusted: 4039 T = cast<AdjustedType>(Ty)->getOriginalType(); 4040 break; 4041 case Type::Decayed: 4042 T = cast<DecayedType>(Ty)->getPointeeType(); 4043 break; 4044 case Type::Pointer: 4045 T = cast<PointerType>(Ty)->getPointeeType(); 4046 break; 4047 case Type::BlockPointer: 4048 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4049 break; 4050 case Type::LValueReference: 4051 case Type::RValueReference: 4052 T = cast<ReferenceType>(Ty)->getPointeeType(); 4053 break; 4054 case Type::MemberPointer: 4055 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4056 break; 4057 case Type::ConstantArray: 4058 case Type::IncompleteArray: 4059 // Losing element qualification here is fine. 4060 T = cast<ArrayType>(Ty)->getElementType(); 4061 break; 4062 case Type::VariableArray: { 4063 // Losing element qualification here is fine. 4064 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4065 4066 // Unknown size indication requires no size computation. 4067 // Otherwise, evaluate and record it. 4068 auto Size = VAT->getSizeExpr(); 4069 if (Size && !CSI->isVLATypeCaptured(VAT) && 4070 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4071 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4072 4073 T = VAT->getElementType(); 4074 break; 4075 } 4076 case Type::FunctionProto: 4077 case Type::FunctionNoProto: 4078 T = cast<FunctionType>(Ty)->getReturnType(); 4079 break; 4080 case Type::Paren: 4081 case Type::TypeOf: 4082 case Type::UnaryTransform: 4083 case Type::Attributed: 4084 case Type::SubstTemplateTypeParm: 4085 case Type::PackExpansion: 4086 case Type::MacroQualified: 4087 // Keep walking after single level desugaring. 4088 T = T.getSingleStepDesugaredType(Context); 4089 break; 4090 case Type::Typedef: 4091 T = cast<TypedefType>(Ty)->desugar(); 4092 break; 4093 case Type::Decltype: 4094 T = cast<DecltypeType>(Ty)->desugar(); 4095 break; 4096 case Type::Auto: 4097 case Type::DeducedTemplateSpecialization: 4098 T = cast<DeducedType>(Ty)->getDeducedType(); 4099 break; 4100 case Type::TypeOfExpr: 4101 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4102 break; 4103 case Type::Atomic: 4104 T = cast<AtomicType>(Ty)->getValueType(); 4105 break; 4106 } 4107 } while (!T.isNull() && T->isVariablyModifiedType()); 4108 } 4109 4110 /// Build a sizeof or alignof expression given a type operand. 4111 ExprResult 4112 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4113 SourceLocation OpLoc, 4114 UnaryExprOrTypeTrait ExprKind, 4115 SourceRange R) { 4116 if (!TInfo) 4117 return ExprError(); 4118 4119 QualType T = TInfo->getType(); 4120 4121 if (!T->isDependentType() && 4122 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4123 return ExprError(); 4124 4125 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4126 if (auto *TT = T->getAs<TypedefType>()) { 4127 for (auto I = FunctionScopes.rbegin(), 4128 E = std::prev(FunctionScopes.rend()); 4129 I != E; ++I) { 4130 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4131 if (CSI == nullptr) 4132 break; 4133 DeclContext *DC = nullptr; 4134 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4135 DC = LSI->CallOperator; 4136 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4137 DC = CRSI->TheCapturedDecl; 4138 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4139 DC = BSI->TheDecl; 4140 if (DC) { 4141 if (DC->containsDecl(TT->getDecl())) 4142 break; 4143 captureVariablyModifiedType(Context, T, CSI); 4144 } 4145 } 4146 } 4147 } 4148 4149 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4150 return new (Context) UnaryExprOrTypeTraitExpr( 4151 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4152 } 4153 4154 /// Build a sizeof or alignof expression given an expression 4155 /// operand. 4156 ExprResult 4157 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4158 UnaryExprOrTypeTrait ExprKind) { 4159 ExprResult PE = CheckPlaceholderExpr(E); 4160 if (PE.isInvalid()) 4161 return ExprError(); 4162 4163 E = PE.get(); 4164 4165 // Verify that the operand is valid. 4166 bool isInvalid = false; 4167 if (E->isTypeDependent()) { 4168 // Delay type-checking for type-dependent expressions. 4169 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4170 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4171 } else if (ExprKind == UETT_VecStep) { 4172 isInvalid = CheckVecStepExpr(E); 4173 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4174 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4175 isInvalid = true; 4176 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4177 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4178 isInvalid = true; 4179 } else { 4180 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4181 } 4182 4183 if (isInvalid) 4184 return ExprError(); 4185 4186 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4187 PE = TransformToPotentiallyEvaluated(E); 4188 if (PE.isInvalid()) return ExprError(); 4189 E = PE.get(); 4190 } 4191 4192 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4193 return new (Context) UnaryExprOrTypeTraitExpr( 4194 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4195 } 4196 4197 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4198 /// expr and the same for @c alignof and @c __alignof 4199 /// Note that the ArgRange is invalid if isType is false. 4200 ExprResult 4201 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4202 UnaryExprOrTypeTrait ExprKind, bool IsType, 4203 void *TyOrEx, SourceRange ArgRange) { 4204 // If error parsing type, ignore. 4205 if (!TyOrEx) return ExprError(); 4206 4207 if (IsType) { 4208 TypeSourceInfo *TInfo; 4209 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4210 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4211 } 4212 4213 Expr *ArgEx = (Expr *)TyOrEx; 4214 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4215 return Result; 4216 } 4217 4218 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4219 bool IsReal) { 4220 if (V.get()->isTypeDependent()) 4221 return S.Context.DependentTy; 4222 4223 // _Real and _Imag are only l-values for normal l-values. 4224 if (V.get()->getObjectKind() != OK_Ordinary) { 4225 V = S.DefaultLvalueConversion(V.get()); 4226 if (V.isInvalid()) 4227 return QualType(); 4228 } 4229 4230 // These operators return the element type of a complex type. 4231 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4232 return CT->getElementType(); 4233 4234 // Otherwise they pass through real integer and floating point types here. 4235 if (V.get()->getType()->isArithmeticType()) 4236 return V.get()->getType(); 4237 4238 // Test for placeholders. 4239 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4240 if (PR.isInvalid()) return QualType(); 4241 if (PR.get() != V.get()) { 4242 V = PR; 4243 return CheckRealImagOperand(S, V, Loc, IsReal); 4244 } 4245 4246 // Reject anything else. 4247 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4248 << (IsReal ? "__real" : "__imag"); 4249 return QualType(); 4250 } 4251 4252 4253 4254 ExprResult 4255 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4256 tok::TokenKind Kind, Expr *Input) { 4257 UnaryOperatorKind Opc; 4258 switch (Kind) { 4259 default: llvm_unreachable("Unknown unary op!"); 4260 case tok::plusplus: Opc = UO_PostInc; break; 4261 case tok::minusminus: Opc = UO_PostDec; break; 4262 } 4263 4264 // Since this might is a postfix expression, get rid of ParenListExprs. 4265 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4266 if (Result.isInvalid()) return ExprError(); 4267 Input = Result.get(); 4268 4269 return BuildUnaryOp(S, OpLoc, Opc, Input); 4270 } 4271 4272 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4273 /// 4274 /// \return true on error 4275 static bool checkArithmeticOnObjCPointer(Sema &S, 4276 SourceLocation opLoc, 4277 Expr *op) { 4278 assert(op->getType()->isObjCObjectPointerType()); 4279 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4280 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4281 return false; 4282 4283 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4284 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4285 << op->getSourceRange(); 4286 return true; 4287 } 4288 4289 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4290 auto *BaseNoParens = Base->IgnoreParens(); 4291 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4292 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4293 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4294 } 4295 4296 ExprResult 4297 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4298 Expr *idx, SourceLocation rbLoc) { 4299 if (base && !base->getType().isNull() && 4300 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4301 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4302 /*Length=*/nullptr, rbLoc); 4303 4304 // Since this might be a postfix expression, get rid of ParenListExprs. 4305 if (isa<ParenListExpr>(base)) { 4306 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4307 if (result.isInvalid()) return ExprError(); 4308 base = result.get(); 4309 } 4310 4311 // A comma-expression as the index is deprecated in C++2a onwards. 4312 if (getLangOpts().CPlusPlus2a && 4313 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4314 (isa<CXXOperatorCallExpr>(idx) && 4315 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4316 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4317 << SourceRange(base->getBeginLoc(), rbLoc); 4318 } 4319 4320 // Handle any non-overload placeholder types in the base and index 4321 // expressions. We can't handle overloads here because the other 4322 // operand might be an overloadable type, in which case the overload 4323 // resolution for the operator overload should get the first crack 4324 // at the overload. 4325 bool IsMSPropertySubscript = false; 4326 if (base->getType()->isNonOverloadPlaceholderType()) { 4327 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4328 if (!IsMSPropertySubscript) { 4329 ExprResult result = CheckPlaceholderExpr(base); 4330 if (result.isInvalid()) 4331 return ExprError(); 4332 base = result.get(); 4333 } 4334 } 4335 if (idx->getType()->isNonOverloadPlaceholderType()) { 4336 ExprResult result = CheckPlaceholderExpr(idx); 4337 if (result.isInvalid()) return ExprError(); 4338 idx = result.get(); 4339 } 4340 4341 // Build an unanalyzed expression if either operand is type-dependent. 4342 if (getLangOpts().CPlusPlus && 4343 (base->isTypeDependent() || idx->isTypeDependent())) { 4344 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4345 VK_LValue, OK_Ordinary, rbLoc); 4346 } 4347 4348 // MSDN, property (C++) 4349 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4350 // This attribute can also be used in the declaration of an empty array in a 4351 // class or structure definition. For example: 4352 // __declspec(property(get=GetX, put=PutX)) int x[]; 4353 // The above statement indicates that x[] can be used with one or more array 4354 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4355 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4356 if (IsMSPropertySubscript) { 4357 // Build MS property subscript expression if base is MS property reference 4358 // or MS property subscript. 4359 return new (Context) MSPropertySubscriptExpr( 4360 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4361 } 4362 4363 // Use C++ overloaded-operator rules if either operand has record 4364 // type. The spec says to do this if either type is *overloadable*, 4365 // but enum types can't declare subscript operators or conversion 4366 // operators, so there's nothing interesting for overload resolution 4367 // to do if there aren't any record types involved. 4368 // 4369 // ObjC pointers have their own subscripting logic that is not tied 4370 // to overload resolution and so should not take this path. 4371 if (getLangOpts().CPlusPlus && 4372 (base->getType()->isRecordType() || 4373 (!base->getType()->isObjCObjectPointerType() && 4374 idx->getType()->isRecordType()))) { 4375 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4376 } 4377 4378 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4379 4380 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4381 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4382 4383 return Res; 4384 } 4385 4386 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4387 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4388 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4389 4390 // For expressions like `&(*s).b`, the base is recorded and what should be 4391 // checked. 4392 const MemberExpr *Member = nullptr; 4393 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4394 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4395 4396 LastRecord.PossibleDerefs.erase(StrippedExpr); 4397 } 4398 4399 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4400 QualType ResultTy = E->getType(); 4401 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4402 4403 // Bail if the element is an array since it is not memory access. 4404 if (isa<ArrayType>(ResultTy)) 4405 return; 4406 4407 if (ResultTy->hasAttr(attr::NoDeref)) { 4408 LastRecord.PossibleDerefs.insert(E); 4409 return; 4410 } 4411 4412 // Check if the base type is a pointer to a member access of a struct 4413 // marked with noderef. 4414 const Expr *Base = E->getBase(); 4415 QualType BaseTy = Base->getType(); 4416 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4417 // Not a pointer access 4418 return; 4419 4420 const MemberExpr *Member = nullptr; 4421 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4422 Member->isArrow()) 4423 Base = Member->getBase(); 4424 4425 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4426 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4427 LastRecord.PossibleDerefs.insert(E); 4428 } 4429 } 4430 4431 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4432 Expr *LowerBound, 4433 SourceLocation ColonLoc, Expr *Length, 4434 SourceLocation RBLoc) { 4435 if (Base->getType()->isPlaceholderType() && 4436 !Base->getType()->isSpecificPlaceholderType( 4437 BuiltinType::OMPArraySection)) { 4438 ExprResult Result = CheckPlaceholderExpr(Base); 4439 if (Result.isInvalid()) 4440 return ExprError(); 4441 Base = Result.get(); 4442 } 4443 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4444 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4445 if (Result.isInvalid()) 4446 return ExprError(); 4447 Result = DefaultLvalueConversion(Result.get()); 4448 if (Result.isInvalid()) 4449 return ExprError(); 4450 LowerBound = Result.get(); 4451 } 4452 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4453 ExprResult Result = CheckPlaceholderExpr(Length); 4454 if (Result.isInvalid()) 4455 return ExprError(); 4456 Result = DefaultLvalueConversion(Result.get()); 4457 if (Result.isInvalid()) 4458 return ExprError(); 4459 Length = Result.get(); 4460 } 4461 4462 // Build an unanalyzed expression if either operand is type-dependent. 4463 if (Base->isTypeDependent() || 4464 (LowerBound && 4465 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4466 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4467 return new (Context) 4468 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4469 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4470 } 4471 4472 // Perform default conversions. 4473 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4474 QualType ResultTy; 4475 if (OriginalTy->isAnyPointerType()) { 4476 ResultTy = OriginalTy->getPointeeType(); 4477 } else if (OriginalTy->isArrayType()) { 4478 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4479 } else { 4480 return ExprError( 4481 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4482 << Base->getSourceRange()); 4483 } 4484 // C99 6.5.2.1p1 4485 if (LowerBound) { 4486 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4487 LowerBound); 4488 if (Res.isInvalid()) 4489 return ExprError(Diag(LowerBound->getExprLoc(), 4490 diag::err_omp_typecheck_section_not_integer) 4491 << 0 << LowerBound->getSourceRange()); 4492 LowerBound = Res.get(); 4493 4494 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4495 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4496 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4497 << 0 << LowerBound->getSourceRange(); 4498 } 4499 if (Length) { 4500 auto Res = 4501 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4502 if (Res.isInvalid()) 4503 return ExprError(Diag(Length->getExprLoc(), 4504 diag::err_omp_typecheck_section_not_integer) 4505 << 1 << Length->getSourceRange()); 4506 Length = Res.get(); 4507 4508 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4509 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4510 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4511 << 1 << Length->getSourceRange(); 4512 } 4513 4514 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4515 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4516 // type. Note that functions are not objects, and that (in C99 parlance) 4517 // incomplete types are not object types. 4518 if (ResultTy->isFunctionType()) { 4519 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4520 << ResultTy << Base->getSourceRange(); 4521 return ExprError(); 4522 } 4523 4524 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4525 diag::err_omp_section_incomplete_type, Base)) 4526 return ExprError(); 4527 4528 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4529 Expr::EvalResult Result; 4530 if (LowerBound->EvaluateAsInt(Result, Context)) { 4531 // OpenMP 4.5, [2.4 Array Sections] 4532 // The array section must be a subset of the original array. 4533 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4534 if (LowerBoundValue.isNegative()) { 4535 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4536 << LowerBound->getSourceRange(); 4537 return ExprError(); 4538 } 4539 } 4540 } 4541 4542 if (Length) { 4543 Expr::EvalResult Result; 4544 if (Length->EvaluateAsInt(Result, Context)) { 4545 // OpenMP 4.5, [2.4 Array Sections] 4546 // The length must evaluate to non-negative integers. 4547 llvm::APSInt LengthValue = Result.Val.getInt(); 4548 if (LengthValue.isNegative()) { 4549 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4550 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4551 << Length->getSourceRange(); 4552 return ExprError(); 4553 } 4554 } 4555 } else if (ColonLoc.isValid() && 4556 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4557 !OriginalTy->isVariableArrayType()))) { 4558 // OpenMP 4.5, [2.4 Array Sections] 4559 // When the size of the array dimension is not known, the length must be 4560 // specified explicitly. 4561 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4562 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4563 return ExprError(); 4564 } 4565 4566 if (!Base->getType()->isSpecificPlaceholderType( 4567 BuiltinType::OMPArraySection)) { 4568 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4569 if (Result.isInvalid()) 4570 return ExprError(); 4571 Base = Result.get(); 4572 } 4573 return new (Context) 4574 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4575 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4576 } 4577 4578 ExprResult 4579 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4580 Expr *Idx, SourceLocation RLoc) { 4581 Expr *LHSExp = Base; 4582 Expr *RHSExp = Idx; 4583 4584 ExprValueKind VK = VK_LValue; 4585 ExprObjectKind OK = OK_Ordinary; 4586 4587 // Per C++ core issue 1213, the result is an xvalue if either operand is 4588 // a non-lvalue array, and an lvalue otherwise. 4589 if (getLangOpts().CPlusPlus11) { 4590 for (auto *Op : {LHSExp, RHSExp}) { 4591 Op = Op->IgnoreImplicit(); 4592 if (Op->getType()->isArrayType() && !Op->isLValue()) 4593 VK = VK_XValue; 4594 } 4595 } 4596 4597 // Perform default conversions. 4598 if (!LHSExp->getType()->getAs<VectorType>()) { 4599 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4600 if (Result.isInvalid()) 4601 return ExprError(); 4602 LHSExp = Result.get(); 4603 } 4604 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4605 if (Result.isInvalid()) 4606 return ExprError(); 4607 RHSExp = Result.get(); 4608 4609 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4610 4611 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4612 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4613 // in the subscript position. As a result, we need to derive the array base 4614 // and index from the expression types. 4615 Expr *BaseExpr, *IndexExpr; 4616 QualType ResultType; 4617 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4618 BaseExpr = LHSExp; 4619 IndexExpr = RHSExp; 4620 ResultType = Context.DependentTy; 4621 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4622 BaseExpr = LHSExp; 4623 IndexExpr = RHSExp; 4624 ResultType = PTy->getPointeeType(); 4625 } else if (const ObjCObjectPointerType *PTy = 4626 LHSTy->getAs<ObjCObjectPointerType>()) { 4627 BaseExpr = LHSExp; 4628 IndexExpr = RHSExp; 4629 4630 // Use custom logic if this should be the pseudo-object subscript 4631 // expression. 4632 if (!LangOpts.isSubscriptPointerArithmetic()) 4633 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4634 nullptr); 4635 4636 ResultType = PTy->getPointeeType(); 4637 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4638 // Handle the uncommon case of "123[Ptr]". 4639 BaseExpr = RHSExp; 4640 IndexExpr = LHSExp; 4641 ResultType = PTy->getPointeeType(); 4642 } else if (const ObjCObjectPointerType *PTy = 4643 RHSTy->getAs<ObjCObjectPointerType>()) { 4644 // Handle the uncommon case of "123[Ptr]". 4645 BaseExpr = RHSExp; 4646 IndexExpr = LHSExp; 4647 ResultType = PTy->getPointeeType(); 4648 if (!LangOpts.isSubscriptPointerArithmetic()) { 4649 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4650 << ResultType << BaseExpr->getSourceRange(); 4651 return ExprError(); 4652 } 4653 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4654 BaseExpr = LHSExp; // vectors: V[123] 4655 IndexExpr = RHSExp; 4656 // We apply C++ DR1213 to vector subscripting too. 4657 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4658 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4659 if (Materialized.isInvalid()) 4660 return ExprError(); 4661 LHSExp = Materialized.get(); 4662 } 4663 VK = LHSExp->getValueKind(); 4664 if (VK != VK_RValue) 4665 OK = OK_VectorComponent; 4666 4667 ResultType = VTy->getElementType(); 4668 QualType BaseType = BaseExpr->getType(); 4669 Qualifiers BaseQuals = BaseType.getQualifiers(); 4670 Qualifiers MemberQuals = ResultType.getQualifiers(); 4671 Qualifiers Combined = BaseQuals + MemberQuals; 4672 if (Combined != MemberQuals) 4673 ResultType = Context.getQualifiedType(ResultType, Combined); 4674 } else if (LHSTy->isArrayType()) { 4675 // If we see an array that wasn't promoted by 4676 // DefaultFunctionArrayLvalueConversion, it must be an array that 4677 // wasn't promoted because of the C90 rule that doesn't 4678 // allow promoting non-lvalue arrays. Warn, then 4679 // force the promotion here. 4680 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4681 << LHSExp->getSourceRange(); 4682 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4683 CK_ArrayToPointerDecay).get(); 4684 LHSTy = LHSExp->getType(); 4685 4686 BaseExpr = LHSExp; 4687 IndexExpr = RHSExp; 4688 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4689 } else if (RHSTy->isArrayType()) { 4690 // Same as previous, except for 123[f().a] case 4691 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4692 << RHSExp->getSourceRange(); 4693 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4694 CK_ArrayToPointerDecay).get(); 4695 RHSTy = RHSExp->getType(); 4696 4697 BaseExpr = RHSExp; 4698 IndexExpr = LHSExp; 4699 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4700 } else { 4701 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4702 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4703 } 4704 // C99 6.5.2.1p1 4705 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4706 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4707 << IndexExpr->getSourceRange()); 4708 4709 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4710 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4711 && !IndexExpr->isTypeDependent()) 4712 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4713 4714 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4715 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4716 // type. Note that Functions are not objects, and that (in C99 parlance) 4717 // incomplete types are not object types. 4718 if (ResultType->isFunctionType()) { 4719 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4720 << ResultType << BaseExpr->getSourceRange(); 4721 return ExprError(); 4722 } 4723 4724 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4725 // GNU extension: subscripting on pointer to void 4726 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4727 << BaseExpr->getSourceRange(); 4728 4729 // C forbids expressions of unqualified void type from being l-values. 4730 // See IsCForbiddenLValueType. 4731 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4732 } else if (!ResultType->isDependentType() && 4733 RequireCompleteType(LLoc, ResultType, 4734 diag::err_subscript_incomplete_type, BaseExpr)) 4735 return ExprError(); 4736 4737 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4738 !ResultType.isCForbiddenLValueType()); 4739 4740 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4741 FunctionScopes.size() > 1) { 4742 if (auto *TT = 4743 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4744 for (auto I = FunctionScopes.rbegin(), 4745 E = std::prev(FunctionScopes.rend()); 4746 I != E; ++I) { 4747 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4748 if (CSI == nullptr) 4749 break; 4750 DeclContext *DC = nullptr; 4751 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4752 DC = LSI->CallOperator; 4753 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4754 DC = CRSI->TheCapturedDecl; 4755 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4756 DC = BSI->TheDecl; 4757 if (DC) { 4758 if (DC->containsDecl(TT->getDecl())) 4759 break; 4760 captureVariablyModifiedType( 4761 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4762 } 4763 } 4764 } 4765 } 4766 4767 return new (Context) 4768 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4769 } 4770 4771 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4772 ParmVarDecl *Param) { 4773 if (Param->hasUnparsedDefaultArg()) { 4774 Diag(CallLoc, 4775 diag::err_use_of_default_argument_to_function_declared_later) << 4776 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4777 Diag(UnparsedDefaultArgLocs[Param], 4778 diag::note_default_argument_declared_here); 4779 return true; 4780 } 4781 4782 if (Param->hasUninstantiatedDefaultArg()) { 4783 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4784 4785 EnterExpressionEvaluationContext EvalContext( 4786 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4787 4788 // Instantiate the expression. 4789 // 4790 // FIXME: Pass in a correct Pattern argument, otherwise 4791 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4792 // 4793 // template<typename T> 4794 // struct A { 4795 // static int FooImpl(); 4796 // 4797 // template<typename Tp> 4798 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4799 // // template argument list [[T], [Tp]], should be [[Tp]]. 4800 // friend A<Tp> Foo(int a); 4801 // }; 4802 // 4803 // template<typename T> 4804 // A<T> Foo(int a = A<T>::FooImpl()); 4805 MultiLevelTemplateArgumentList MutiLevelArgList 4806 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4807 4808 InstantiatingTemplate Inst(*this, CallLoc, Param, 4809 MutiLevelArgList.getInnermost()); 4810 if (Inst.isInvalid()) 4811 return true; 4812 if (Inst.isAlreadyInstantiating()) { 4813 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4814 Param->setInvalidDecl(); 4815 return true; 4816 } 4817 4818 ExprResult Result; 4819 { 4820 // C++ [dcl.fct.default]p5: 4821 // The names in the [default argument] expression are bound, and 4822 // the semantic constraints are checked, at the point where the 4823 // default argument expression appears. 4824 ContextRAII SavedContext(*this, FD); 4825 LocalInstantiationScope Local(*this); 4826 runWithSufficientStackSpace(CallLoc, [&] { 4827 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4828 /*DirectInit*/false); 4829 }); 4830 } 4831 if (Result.isInvalid()) 4832 return true; 4833 4834 // Check the expression as an initializer for the parameter. 4835 InitializedEntity Entity 4836 = InitializedEntity::InitializeParameter(Context, Param); 4837 InitializationKind Kind = InitializationKind::CreateCopy( 4838 Param->getLocation(), 4839 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4840 Expr *ResultE = Result.getAs<Expr>(); 4841 4842 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4843 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4844 if (Result.isInvalid()) 4845 return true; 4846 4847 Result = 4848 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4849 /*DiscardedValue*/ false); 4850 if (Result.isInvalid()) 4851 return true; 4852 4853 // Remember the instantiated default argument. 4854 Param->setDefaultArg(Result.getAs<Expr>()); 4855 if (ASTMutationListener *L = getASTMutationListener()) { 4856 L->DefaultArgumentInstantiated(Param); 4857 } 4858 } 4859 4860 // If the default argument expression is not set yet, we are building it now. 4861 if (!Param->hasInit()) { 4862 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4863 Param->setInvalidDecl(); 4864 return true; 4865 } 4866 4867 // If the default expression creates temporaries, we need to 4868 // push them to the current stack of expression temporaries so they'll 4869 // be properly destroyed. 4870 // FIXME: We should really be rebuilding the default argument with new 4871 // bound temporaries; see the comment in PR5810. 4872 // We don't need to do that with block decls, though, because 4873 // blocks in default argument expression can never capture anything. 4874 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4875 // Set the "needs cleanups" bit regardless of whether there are 4876 // any explicit objects. 4877 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4878 4879 // Append all the objects to the cleanup list. Right now, this 4880 // should always be a no-op, because blocks in default argument 4881 // expressions should never be able to capture anything. 4882 assert(!Init->getNumObjects() && 4883 "default argument expression has capturing blocks?"); 4884 } 4885 4886 // We already type-checked the argument, so we know it works. 4887 // Just mark all of the declarations in this potentially-evaluated expression 4888 // as being "referenced". 4889 EnterExpressionEvaluationContext EvalContext( 4890 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4891 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4892 /*SkipLocalVariables=*/true); 4893 return false; 4894 } 4895 4896 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4897 FunctionDecl *FD, ParmVarDecl *Param) { 4898 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4899 return ExprError(); 4900 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4901 } 4902 4903 Sema::VariadicCallType 4904 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4905 Expr *Fn) { 4906 if (Proto && Proto->isVariadic()) { 4907 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4908 return VariadicConstructor; 4909 else if (Fn && Fn->getType()->isBlockPointerType()) 4910 return VariadicBlock; 4911 else if (FDecl) { 4912 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4913 if (Method->isInstance()) 4914 return VariadicMethod; 4915 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4916 return VariadicMethod; 4917 return VariadicFunction; 4918 } 4919 return VariadicDoesNotApply; 4920 } 4921 4922 namespace { 4923 class FunctionCallCCC final : public FunctionCallFilterCCC { 4924 public: 4925 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4926 unsigned NumArgs, MemberExpr *ME) 4927 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4928 FunctionName(FuncName) {} 4929 4930 bool ValidateCandidate(const TypoCorrection &candidate) override { 4931 if (!candidate.getCorrectionSpecifier() || 4932 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4933 return false; 4934 } 4935 4936 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4937 } 4938 4939 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4940 return std::make_unique<FunctionCallCCC>(*this); 4941 } 4942 4943 private: 4944 const IdentifierInfo *const FunctionName; 4945 }; 4946 } 4947 4948 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4949 FunctionDecl *FDecl, 4950 ArrayRef<Expr *> Args) { 4951 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4952 DeclarationName FuncName = FDecl->getDeclName(); 4953 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4954 4955 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4956 if (TypoCorrection Corrected = S.CorrectTypo( 4957 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4958 S.getScopeForContext(S.CurContext), nullptr, CCC, 4959 Sema::CTK_ErrorRecovery)) { 4960 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4961 if (Corrected.isOverloaded()) { 4962 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4963 OverloadCandidateSet::iterator Best; 4964 for (NamedDecl *CD : Corrected) { 4965 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4966 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4967 OCS); 4968 } 4969 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4970 case OR_Success: 4971 ND = Best->FoundDecl; 4972 Corrected.setCorrectionDecl(ND); 4973 break; 4974 default: 4975 break; 4976 } 4977 } 4978 ND = ND->getUnderlyingDecl(); 4979 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4980 return Corrected; 4981 } 4982 } 4983 return TypoCorrection(); 4984 } 4985 4986 /// ConvertArgumentsForCall - Converts the arguments specified in 4987 /// Args/NumArgs to the parameter types of the function FDecl with 4988 /// function prototype Proto. Call is the call expression itself, and 4989 /// Fn is the function expression. For a C++ member function, this 4990 /// routine does not attempt to convert the object argument. Returns 4991 /// true if the call is ill-formed. 4992 bool 4993 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4994 FunctionDecl *FDecl, 4995 const FunctionProtoType *Proto, 4996 ArrayRef<Expr *> Args, 4997 SourceLocation RParenLoc, 4998 bool IsExecConfig) { 4999 // Bail out early if calling a builtin with custom typechecking. 5000 if (FDecl) 5001 if (unsigned ID = FDecl->getBuiltinID()) 5002 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5003 return false; 5004 5005 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5006 // assignment, to the types of the corresponding parameter, ... 5007 unsigned NumParams = Proto->getNumParams(); 5008 bool Invalid = false; 5009 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5010 unsigned FnKind = Fn->getType()->isBlockPointerType() 5011 ? 1 /* block */ 5012 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5013 : 0 /* function */); 5014 5015 // If too few arguments are available (and we don't have default 5016 // arguments for the remaining parameters), don't make the call. 5017 if (Args.size() < NumParams) { 5018 if (Args.size() < MinArgs) { 5019 TypoCorrection TC; 5020 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5021 unsigned diag_id = 5022 MinArgs == NumParams && !Proto->isVariadic() 5023 ? diag::err_typecheck_call_too_few_args_suggest 5024 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5025 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5026 << static_cast<unsigned>(Args.size()) 5027 << TC.getCorrectionRange()); 5028 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5029 Diag(RParenLoc, 5030 MinArgs == NumParams && !Proto->isVariadic() 5031 ? diag::err_typecheck_call_too_few_args_one 5032 : diag::err_typecheck_call_too_few_args_at_least_one) 5033 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5034 else 5035 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5036 ? diag::err_typecheck_call_too_few_args 5037 : diag::err_typecheck_call_too_few_args_at_least) 5038 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5039 << Fn->getSourceRange(); 5040 5041 // Emit the location of the prototype. 5042 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5043 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5044 5045 return true; 5046 } 5047 // We reserve space for the default arguments when we create 5048 // the call expression, before calling ConvertArgumentsForCall. 5049 assert((Call->getNumArgs() == NumParams) && 5050 "We should have reserved space for the default arguments before!"); 5051 } 5052 5053 // If too many are passed and not variadic, error on the extras and drop 5054 // them. 5055 if (Args.size() > NumParams) { 5056 if (!Proto->isVariadic()) { 5057 TypoCorrection TC; 5058 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5059 unsigned diag_id = 5060 MinArgs == NumParams && !Proto->isVariadic() 5061 ? diag::err_typecheck_call_too_many_args_suggest 5062 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5063 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5064 << static_cast<unsigned>(Args.size()) 5065 << TC.getCorrectionRange()); 5066 } else if (NumParams == 1 && FDecl && 5067 FDecl->getParamDecl(0)->getDeclName()) 5068 Diag(Args[NumParams]->getBeginLoc(), 5069 MinArgs == NumParams 5070 ? diag::err_typecheck_call_too_many_args_one 5071 : diag::err_typecheck_call_too_many_args_at_most_one) 5072 << FnKind << FDecl->getParamDecl(0) 5073 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5074 << SourceRange(Args[NumParams]->getBeginLoc(), 5075 Args.back()->getEndLoc()); 5076 else 5077 Diag(Args[NumParams]->getBeginLoc(), 5078 MinArgs == NumParams 5079 ? diag::err_typecheck_call_too_many_args 5080 : diag::err_typecheck_call_too_many_args_at_most) 5081 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5082 << Fn->getSourceRange() 5083 << SourceRange(Args[NumParams]->getBeginLoc(), 5084 Args.back()->getEndLoc()); 5085 5086 // Emit the location of the prototype. 5087 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5088 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5089 5090 // This deletes the extra arguments. 5091 Call->shrinkNumArgs(NumParams); 5092 return true; 5093 } 5094 } 5095 SmallVector<Expr *, 8> AllArgs; 5096 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5097 5098 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5099 AllArgs, CallType); 5100 if (Invalid) 5101 return true; 5102 unsigned TotalNumArgs = AllArgs.size(); 5103 for (unsigned i = 0; i < TotalNumArgs; ++i) 5104 Call->setArg(i, AllArgs[i]); 5105 5106 return false; 5107 } 5108 5109 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5110 const FunctionProtoType *Proto, 5111 unsigned FirstParam, ArrayRef<Expr *> Args, 5112 SmallVectorImpl<Expr *> &AllArgs, 5113 VariadicCallType CallType, bool AllowExplicit, 5114 bool IsListInitialization) { 5115 unsigned NumParams = Proto->getNumParams(); 5116 bool Invalid = false; 5117 size_t ArgIx = 0; 5118 // Continue to check argument types (even if we have too few/many args). 5119 for (unsigned i = FirstParam; i < NumParams; i++) { 5120 QualType ProtoArgType = Proto->getParamType(i); 5121 5122 Expr *Arg; 5123 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5124 if (ArgIx < Args.size()) { 5125 Arg = Args[ArgIx++]; 5126 5127 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5128 diag::err_call_incomplete_argument, Arg)) 5129 return true; 5130 5131 // Strip the unbridged-cast placeholder expression off, if applicable. 5132 bool CFAudited = false; 5133 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5134 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5135 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5136 Arg = stripARCUnbridgedCast(Arg); 5137 else if (getLangOpts().ObjCAutoRefCount && 5138 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5139 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5140 CFAudited = true; 5141 5142 if (Proto->getExtParameterInfo(i).isNoEscape()) 5143 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5144 BE->getBlockDecl()->setDoesNotEscape(); 5145 5146 InitializedEntity Entity = 5147 Param ? InitializedEntity::InitializeParameter(Context, Param, 5148 ProtoArgType) 5149 : InitializedEntity::InitializeParameter( 5150 Context, ProtoArgType, Proto->isParamConsumed(i)); 5151 5152 // Remember that parameter belongs to a CF audited API. 5153 if (CFAudited) 5154 Entity.setParameterCFAudited(); 5155 5156 ExprResult ArgE = PerformCopyInitialization( 5157 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5158 if (ArgE.isInvalid()) 5159 return true; 5160 5161 Arg = ArgE.getAs<Expr>(); 5162 } else { 5163 assert(Param && "can't use default arguments without a known callee"); 5164 5165 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5166 if (ArgExpr.isInvalid()) 5167 return true; 5168 5169 Arg = ArgExpr.getAs<Expr>(); 5170 } 5171 5172 // Check for array bounds violations for each argument to the call. This 5173 // check only triggers warnings when the argument isn't a more complex Expr 5174 // with its own checking, such as a BinaryOperator. 5175 CheckArrayAccess(Arg); 5176 5177 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5178 CheckStaticArrayArgument(CallLoc, Param, Arg); 5179 5180 AllArgs.push_back(Arg); 5181 } 5182 5183 // If this is a variadic call, handle args passed through "...". 5184 if (CallType != VariadicDoesNotApply) { 5185 // Assume that extern "C" functions with variadic arguments that 5186 // return __unknown_anytype aren't *really* variadic. 5187 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5188 FDecl->isExternC()) { 5189 for (Expr *A : Args.slice(ArgIx)) { 5190 QualType paramType; // ignored 5191 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5192 Invalid |= arg.isInvalid(); 5193 AllArgs.push_back(arg.get()); 5194 } 5195 5196 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5197 } else { 5198 for (Expr *A : Args.slice(ArgIx)) { 5199 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5200 Invalid |= Arg.isInvalid(); 5201 AllArgs.push_back(Arg.get()); 5202 } 5203 } 5204 5205 // Check for array bounds violations. 5206 for (Expr *A : Args.slice(ArgIx)) 5207 CheckArrayAccess(A); 5208 } 5209 return Invalid; 5210 } 5211 5212 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5213 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5214 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5215 TL = DTL.getOriginalLoc(); 5216 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5217 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5218 << ATL.getLocalSourceRange(); 5219 } 5220 5221 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5222 /// array parameter, check that it is non-null, and that if it is formed by 5223 /// array-to-pointer decay, the underlying array is sufficiently large. 5224 /// 5225 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5226 /// array type derivation, then for each call to the function, the value of the 5227 /// corresponding actual argument shall provide access to the first element of 5228 /// an array with at least as many elements as specified by the size expression. 5229 void 5230 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5231 ParmVarDecl *Param, 5232 const Expr *ArgExpr) { 5233 // Static array parameters are not supported in C++. 5234 if (!Param || getLangOpts().CPlusPlus) 5235 return; 5236 5237 QualType OrigTy = Param->getOriginalType(); 5238 5239 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5240 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5241 return; 5242 5243 if (ArgExpr->isNullPointerConstant(Context, 5244 Expr::NPC_NeverValueDependent)) { 5245 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5246 DiagnoseCalleeStaticArrayParam(*this, Param); 5247 return; 5248 } 5249 5250 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5251 if (!CAT) 5252 return; 5253 5254 const ConstantArrayType *ArgCAT = 5255 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5256 if (!ArgCAT) 5257 return; 5258 5259 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5260 ArgCAT->getElementType())) { 5261 if (ArgCAT->getSize().ult(CAT->getSize())) { 5262 Diag(CallLoc, diag::warn_static_array_too_small) 5263 << ArgExpr->getSourceRange() 5264 << (unsigned)ArgCAT->getSize().getZExtValue() 5265 << (unsigned)CAT->getSize().getZExtValue() << 0; 5266 DiagnoseCalleeStaticArrayParam(*this, Param); 5267 } 5268 return; 5269 } 5270 5271 Optional<CharUnits> ArgSize = 5272 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5273 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5274 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5275 Diag(CallLoc, diag::warn_static_array_too_small) 5276 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5277 << (unsigned)ParmSize->getQuantity() << 1; 5278 DiagnoseCalleeStaticArrayParam(*this, Param); 5279 } 5280 } 5281 5282 /// Given a function expression of unknown-any type, try to rebuild it 5283 /// to have a function type. 5284 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5285 5286 /// Is the given type a placeholder that we need to lower out 5287 /// immediately during argument processing? 5288 static bool isPlaceholderToRemoveAsArg(QualType type) { 5289 // Placeholders are never sugared. 5290 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5291 if (!placeholder) return false; 5292 5293 switch (placeholder->getKind()) { 5294 // Ignore all the non-placeholder types. 5295 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5296 case BuiltinType::Id: 5297 #include "clang/Basic/OpenCLImageTypes.def" 5298 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5299 case BuiltinType::Id: 5300 #include "clang/Basic/OpenCLExtensionTypes.def" 5301 // In practice we'll never use this, since all SVE types are sugared 5302 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5303 #define SVE_TYPE(Name, Id, SingletonId) \ 5304 case BuiltinType::Id: 5305 #include "clang/Basic/AArch64SVEACLETypes.def" 5306 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5307 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5308 #include "clang/AST/BuiltinTypes.def" 5309 return false; 5310 5311 // We cannot lower out overload sets; they might validly be resolved 5312 // by the call machinery. 5313 case BuiltinType::Overload: 5314 return false; 5315 5316 // Unbridged casts in ARC can be handled in some call positions and 5317 // should be left in place. 5318 case BuiltinType::ARCUnbridgedCast: 5319 return false; 5320 5321 // Pseudo-objects should be converted as soon as possible. 5322 case BuiltinType::PseudoObject: 5323 return true; 5324 5325 // The debugger mode could theoretically but currently does not try 5326 // to resolve unknown-typed arguments based on known parameter types. 5327 case BuiltinType::UnknownAny: 5328 return true; 5329 5330 // These are always invalid as call arguments and should be reported. 5331 case BuiltinType::BoundMember: 5332 case BuiltinType::BuiltinFn: 5333 case BuiltinType::OMPArraySection: 5334 return true; 5335 5336 } 5337 llvm_unreachable("bad builtin type kind"); 5338 } 5339 5340 /// Check an argument list for placeholders that we won't try to 5341 /// handle later. 5342 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5343 // Apply this processing to all the arguments at once instead of 5344 // dying at the first failure. 5345 bool hasInvalid = false; 5346 for (size_t i = 0, e = args.size(); i != e; i++) { 5347 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5348 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5349 if (result.isInvalid()) hasInvalid = true; 5350 else args[i] = result.get(); 5351 } else if (hasInvalid) { 5352 (void)S.CorrectDelayedTyposInExpr(args[i]); 5353 } 5354 } 5355 return hasInvalid; 5356 } 5357 5358 /// If a builtin function has a pointer argument with no explicit address 5359 /// space, then it should be able to accept a pointer to any address 5360 /// space as input. In order to do this, we need to replace the 5361 /// standard builtin declaration with one that uses the same address space 5362 /// as the call. 5363 /// 5364 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5365 /// it does not contain any pointer arguments without 5366 /// an address space qualifer. Otherwise the rewritten 5367 /// FunctionDecl is returned. 5368 /// TODO: Handle pointer return types. 5369 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5370 FunctionDecl *FDecl, 5371 MultiExprArg ArgExprs) { 5372 5373 QualType DeclType = FDecl->getType(); 5374 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5375 5376 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5377 ArgExprs.size() < FT->getNumParams()) 5378 return nullptr; 5379 5380 bool NeedsNewDecl = false; 5381 unsigned i = 0; 5382 SmallVector<QualType, 8> OverloadParams; 5383 5384 for (QualType ParamType : FT->param_types()) { 5385 5386 // Convert array arguments to pointer to simplify type lookup. 5387 ExprResult ArgRes = 5388 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5389 if (ArgRes.isInvalid()) 5390 return nullptr; 5391 Expr *Arg = ArgRes.get(); 5392 QualType ArgType = Arg->getType(); 5393 if (!ParamType->isPointerType() || 5394 ParamType.getQualifiers().hasAddressSpace() || 5395 !ArgType->isPointerType() || 5396 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5397 OverloadParams.push_back(ParamType); 5398 continue; 5399 } 5400 5401 QualType PointeeType = ParamType->getPointeeType(); 5402 if (PointeeType.getQualifiers().hasAddressSpace()) 5403 continue; 5404 5405 NeedsNewDecl = true; 5406 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5407 5408 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5409 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5410 } 5411 5412 if (!NeedsNewDecl) 5413 return nullptr; 5414 5415 FunctionProtoType::ExtProtoInfo EPI; 5416 EPI.Variadic = FT->isVariadic(); 5417 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5418 OverloadParams, EPI); 5419 DeclContext *Parent = FDecl->getParent(); 5420 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5421 FDecl->getLocation(), 5422 FDecl->getLocation(), 5423 FDecl->getIdentifier(), 5424 OverloadTy, 5425 /*TInfo=*/nullptr, 5426 SC_Extern, false, 5427 /*hasPrototype=*/true); 5428 SmallVector<ParmVarDecl*, 16> Params; 5429 FT = cast<FunctionProtoType>(OverloadTy); 5430 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5431 QualType ParamType = FT->getParamType(i); 5432 ParmVarDecl *Parm = 5433 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5434 SourceLocation(), nullptr, ParamType, 5435 /*TInfo=*/nullptr, SC_None, nullptr); 5436 Parm->setScopeInfo(0, i); 5437 Params.push_back(Parm); 5438 } 5439 OverloadDecl->setParams(Params); 5440 return OverloadDecl; 5441 } 5442 5443 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5444 FunctionDecl *Callee, 5445 MultiExprArg ArgExprs) { 5446 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5447 // similar attributes) really don't like it when functions are called with an 5448 // invalid number of args. 5449 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5450 /*PartialOverloading=*/false) && 5451 !Callee->isVariadic()) 5452 return; 5453 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5454 return; 5455 5456 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5457 S.Diag(Fn->getBeginLoc(), 5458 isa<CXXMethodDecl>(Callee) 5459 ? diag::err_ovl_no_viable_member_function_in_call 5460 : diag::err_ovl_no_viable_function_in_call) 5461 << Callee << Callee->getSourceRange(); 5462 S.Diag(Callee->getLocation(), 5463 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5464 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5465 return; 5466 } 5467 } 5468 5469 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5470 const UnresolvedMemberExpr *const UME, Sema &S) { 5471 5472 const auto GetFunctionLevelDCIfCXXClass = 5473 [](Sema &S) -> const CXXRecordDecl * { 5474 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5475 if (!DC || !DC->getParent()) 5476 return nullptr; 5477 5478 // If the call to some member function was made from within a member 5479 // function body 'M' return return 'M's parent. 5480 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5481 return MD->getParent()->getCanonicalDecl(); 5482 // else the call was made from within a default member initializer of a 5483 // class, so return the class. 5484 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5485 return RD->getCanonicalDecl(); 5486 return nullptr; 5487 }; 5488 // If our DeclContext is neither a member function nor a class (in the 5489 // case of a lambda in a default member initializer), we can't have an 5490 // enclosing 'this'. 5491 5492 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5493 if (!CurParentClass) 5494 return false; 5495 5496 // The naming class for implicit member functions call is the class in which 5497 // name lookup starts. 5498 const CXXRecordDecl *const NamingClass = 5499 UME->getNamingClass()->getCanonicalDecl(); 5500 assert(NamingClass && "Must have naming class even for implicit access"); 5501 5502 // If the unresolved member functions were found in a 'naming class' that is 5503 // related (either the same or derived from) to the class that contains the 5504 // member function that itself contained the implicit member access. 5505 5506 return CurParentClass == NamingClass || 5507 CurParentClass->isDerivedFrom(NamingClass); 5508 } 5509 5510 static void 5511 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5512 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5513 5514 if (!UME) 5515 return; 5516 5517 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5518 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5519 // already been captured, or if this is an implicit member function call (if 5520 // it isn't, an attempt to capture 'this' should already have been made). 5521 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5522 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5523 return; 5524 5525 // Check if the naming class in which the unresolved members were found is 5526 // related (same as or is a base of) to the enclosing class. 5527 5528 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5529 return; 5530 5531 5532 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5533 // If the enclosing function is not dependent, then this lambda is 5534 // capture ready, so if we can capture this, do so. 5535 if (!EnclosingFunctionCtx->isDependentContext()) { 5536 // If the current lambda and all enclosing lambdas can capture 'this' - 5537 // then go ahead and capture 'this' (since our unresolved overload set 5538 // contains at least one non-static member function). 5539 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5540 S.CheckCXXThisCapture(CallLoc); 5541 } else if (S.CurContext->isDependentContext()) { 5542 // ... since this is an implicit member reference, that might potentially 5543 // involve a 'this' capture, mark 'this' for potential capture in 5544 // enclosing lambdas. 5545 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5546 CurLSI->addPotentialThisCapture(CallLoc); 5547 } 5548 } 5549 5550 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5551 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5552 Expr *ExecConfig) { 5553 ExprResult Call = 5554 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5555 if (Call.isInvalid()) 5556 return Call; 5557 5558 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5559 // language modes. 5560 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5561 if (ULE->hasExplicitTemplateArgs() && 5562 ULE->decls_begin() == ULE->decls_end()) { 5563 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5564 ? diag::warn_cxx17_compat_adl_only_template_id 5565 : diag::ext_adl_only_template_id) 5566 << ULE->getName(); 5567 } 5568 } 5569 5570 return Call; 5571 } 5572 5573 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5574 /// This provides the location of the left/right parens and a list of comma 5575 /// locations. 5576 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5577 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5578 Expr *ExecConfig, bool IsExecConfig) { 5579 // Since this might be a postfix expression, get rid of ParenListExprs. 5580 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5581 if (Result.isInvalid()) return ExprError(); 5582 Fn = Result.get(); 5583 5584 if (checkArgsForPlaceholders(*this, ArgExprs)) 5585 return ExprError(); 5586 5587 if (getLangOpts().CPlusPlus) { 5588 // If this is a pseudo-destructor expression, build the call immediately. 5589 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5590 if (!ArgExprs.empty()) { 5591 // Pseudo-destructor calls should not have any arguments. 5592 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5593 << FixItHint::CreateRemoval( 5594 SourceRange(ArgExprs.front()->getBeginLoc(), 5595 ArgExprs.back()->getEndLoc())); 5596 } 5597 5598 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5599 VK_RValue, RParenLoc); 5600 } 5601 if (Fn->getType() == Context.PseudoObjectTy) { 5602 ExprResult result = CheckPlaceholderExpr(Fn); 5603 if (result.isInvalid()) return ExprError(); 5604 Fn = result.get(); 5605 } 5606 5607 // Determine whether this is a dependent call inside a C++ template, 5608 // in which case we won't do any semantic analysis now. 5609 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5610 if (ExecConfig) { 5611 return CUDAKernelCallExpr::Create( 5612 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5613 Context.DependentTy, VK_RValue, RParenLoc); 5614 } else { 5615 5616 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5617 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5618 Fn->getBeginLoc()); 5619 5620 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5621 VK_RValue, RParenLoc); 5622 } 5623 } 5624 5625 // Determine whether this is a call to an object (C++ [over.call.object]). 5626 if (Fn->getType()->isRecordType()) 5627 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5628 RParenLoc); 5629 5630 if (Fn->getType() == Context.UnknownAnyTy) { 5631 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5632 if (result.isInvalid()) return ExprError(); 5633 Fn = result.get(); 5634 } 5635 5636 if (Fn->getType() == Context.BoundMemberTy) { 5637 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5638 RParenLoc); 5639 } 5640 } 5641 5642 // Check for overloaded calls. This can happen even in C due to extensions. 5643 if (Fn->getType() == Context.OverloadTy) { 5644 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5645 5646 // We aren't supposed to apply this logic if there's an '&' involved. 5647 if (!find.HasFormOfMemberPointer) { 5648 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5649 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5650 VK_RValue, RParenLoc); 5651 OverloadExpr *ovl = find.Expression; 5652 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5653 return BuildOverloadedCallExpr( 5654 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5655 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5656 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5657 RParenLoc); 5658 } 5659 } 5660 5661 // If we're directly calling a function, get the appropriate declaration. 5662 if (Fn->getType() == Context.UnknownAnyTy) { 5663 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5664 if (result.isInvalid()) return ExprError(); 5665 Fn = result.get(); 5666 } 5667 5668 Expr *NakedFn = Fn->IgnoreParens(); 5669 5670 bool CallingNDeclIndirectly = false; 5671 NamedDecl *NDecl = nullptr; 5672 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5673 if (UnOp->getOpcode() == UO_AddrOf) { 5674 CallingNDeclIndirectly = true; 5675 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5676 } 5677 } 5678 5679 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5680 NDecl = DRE->getDecl(); 5681 5682 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5683 if (FDecl && FDecl->getBuiltinID()) { 5684 // Rewrite the function decl for this builtin by replacing parameters 5685 // with no explicit address space with the address space of the arguments 5686 // in ArgExprs. 5687 if ((FDecl = 5688 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5689 NDecl = FDecl; 5690 Fn = DeclRefExpr::Create( 5691 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5692 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5693 nullptr, DRE->isNonOdrUse()); 5694 } 5695 } 5696 } else if (isa<MemberExpr>(NakedFn)) 5697 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5698 5699 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5700 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5701 FD, /*Complain=*/true, Fn->getBeginLoc())) 5702 return ExprError(); 5703 5704 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5705 return ExprError(); 5706 5707 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5708 } 5709 5710 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5711 ExecConfig, IsExecConfig); 5712 } 5713 5714 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5715 /// 5716 /// __builtin_astype( value, dst type ) 5717 /// 5718 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5719 SourceLocation BuiltinLoc, 5720 SourceLocation RParenLoc) { 5721 ExprValueKind VK = VK_RValue; 5722 ExprObjectKind OK = OK_Ordinary; 5723 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5724 QualType SrcTy = E->getType(); 5725 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5726 return ExprError(Diag(BuiltinLoc, 5727 diag::err_invalid_astype_of_different_size) 5728 << DstTy 5729 << SrcTy 5730 << E->getSourceRange()); 5731 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5732 } 5733 5734 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5735 /// provided arguments. 5736 /// 5737 /// __builtin_convertvector( value, dst type ) 5738 /// 5739 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5740 SourceLocation BuiltinLoc, 5741 SourceLocation RParenLoc) { 5742 TypeSourceInfo *TInfo; 5743 GetTypeFromParser(ParsedDestTy, &TInfo); 5744 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5745 } 5746 5747 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5748 /// i.e. an expression not of \p OverloadTy. The expression should 5749 /// unary-convert to an expression of function-pointer or 5750 /// block-pointer type. 5751 /// 5752 /// \param NDecl the declaration being called, if available 5753 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5754 SourceLocation LParenLoc, 5755 ArrayRef<Expr *> Args, 5756 SourceLocation RParenLoc, Expr *Config, 5757 bool IsExecConfig, ADLCallKind UsesADL) { 5758 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5759 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5760 5761 // Functions with 'interrupt' attribute cannot be called directly. 5762 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5763 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5764 return ExprError(); 5765 } 5766 5767 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5768 // so there's some risk when calling out to non-interrupt handler functions 5769 // that the callee might not preserve them. This is easy to diagnose here, 5770 // but can be very challenging to debug. 5771 if (auto *Caller = getCurFunctionDecl()) 5772 if (Caller->hasAttr<ARMInterruptAttr>()) { 5773 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5774 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5775 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5776 } 5777 5778 // Promote the function operand. 5779 // We special-case function promotion here because we only allow promoting 5780 // builtin functions to function pointers in the callee of a call. 5781 ExprResult Result; 5782 QualType ResultTy; 5783 if (BuiltinID && 5784 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5785 // Extract the return type from the (builtin) function pointer type. 5786 // FIXME Several builtins still have setType in 5787 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5788 // Builtins.def to ensure they are correct before removing setType calls. 5789 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5790 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5791 ResultTy = FDecl->getCallResultType(); 5792 } else { 5793 Result = CallExprUnaryConversions(Fn); 5794 ResultTy = Context.BoolTy; 5795 } 5796 if (Result.isInvalid()) 5797 return ExprError(); 5798 Fn = Result.get(); 5799 5800 // Check for a valid function type, but only if it is not a builtin which 5801 // requires custom type checking. These will be handled by 5802 // CheckBuiltinFunctionCall below just after creation of the call expression. 5803 const FunctionType *FuncT = nullptr; 5804 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5805 retry: 5806 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5807 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5808 // have type pointer to function". 5809 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5810 if (!FuncT) 5811 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5812 << Fn->getType() << Fn->getSourceRange()); 5813 } else if (const BlockPointerType *BPT = 5814 Fn->getType()->getAs<BlockPointerType>()) { 5815 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5816 } else { 5817 // Handle calls to expressions of unknown-any type. 5818 if (Fn->getType() == Context.UnknownAnyTy) { 5819 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5820 if (rewrite.isInvalid()) 5821 return ExprError(); 5822 Fn = rewrite.get(); 5823 goto retry; 5824 } 5825 5826 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5827 << Fn->getType() << Fn->getSourceRange()); 5828 } 5829 } 5830 5831 // Get the number of parameters in the function prototype, if any. 5832 // We will allocate space for max(Args.size(), NumParams) arguments 5833 // in the call expression. 5834 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5835 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5836 5837 CallExpr *TheCall; 5838 if (Config) { 5839 assert(UsesADL == ADLCallKind::NotADL && 5840 "CUDAKernelCallExpr should not use ADL"); 5841 TheCall = 5842 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5843 ResultTy, VK_RValue, RParenLoc, NumParams); 5844 } else { 5845 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5846 RParenLoc, NumParams, UsesADL); 5847 } 5848 5849 if (!getLangOpts().CPlusPlus) { 5850 // Forget about the nulled arguments since typo correction 5851 // do not handle them well. 5852 TheCall->shrinkNumArgs(Args.size()); 5853 // C cannot always handle TypoExpr nodes in builtin calls and direct 5854 // function calls as their argument checking don't necessarily handle 5855 // dependent types properly, so make sure any TypoExprs have been 5856 // dealt with. 5857 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5858 if (!Result.isUsable()) return ExprError(); 5859 CallExpr *TheOldCall = TheCall; 5860 TheCall = dyn_cast<CallExpr>(Result.get()); 5861 bool CorrectedTypos = TheCall != TheOldCall; 5862 if (!TheCall) return Result; 5863 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5864 5865 // A new call expression node was created if some typos were corrected. 5866 // However it may not have been constructed with enough storage. In this 5867 // case, rebuild the node with enough storage. The waste of space is 5868 // immaterial since this only happens when some typos were corrected. 5869 if (CorrectedTypos && Args.size() < NumParams) { 5870 if (Config) 5871 TheCall = CUDAKernelCallExpr::Create( 5872 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5873 RParenLoc, NumParams); 5874 else 5875 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5876 RParenLoc, NumParams, UsesADL); 5877 } 5878 // We can now handle the nulled arguments for the default arguments. 5879 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5880 } 5881 5882 // Bail out early if calling a builtin with custom type checking. 5883 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5884 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5885 5886 if (getLangOpts().CUDA) { 5887 if (Config) { 5888 // CUDA: Kernel calls must be to global functions 5889 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5890 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5891 << FDecl << Fn->getSourceRange()); 5892 5893 // CUDA: Kernel function must have 'void' return type 5894 if (!FuncT->getReturnType()->isVoidType()) 5895 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5896 << Fn->getType() << Fn->getSourceRange()); 5897 } else { 5898 // CUDA: Calls to global functions must be configured 5899 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5900 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5901 << FDecl << Fn->getSourceRange()); 5902 } 5903 } 5904 5905 // Check for a valid return type 5906 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5907 FDecl)) 5908 return ExprError(); 5909 5910 // We know the result type of the call, set it. 5911 TheCall->setType(FuncT->getCallResultType(Context)); 5912 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5913 5914 if (Proto) { 5915 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5916 IsExecConfig)) 5917 return ExprError(); 5918 } else { 5919 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5920 5921 if (FDecl) { 5922 // Check if we have too few/too many template arguments, based 5923 // on our knowledge of the function definition. 5924 const FunctionDecl *Def = nullptr; 5925 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5926 Proto = Def->getType()->getAs<FunctionProtoType>(); 5927 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5928 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5929 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5930 } 5931 5932 // If the function we're calling isn't a function prototype, but we have 5933 // a function prototype from a prior declaratiom, use that prototype. 5934 if (!FDecl->hasPrototype()) 5935 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5936 } 5937 5938 // Promote the arguments (C99 6.5.2.2p6). 5939 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5940 Expr *Arg = Args[i]; 5941 5942 if (Proto && i < Proto->getNumParams()) { 5943 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5944 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5945 ExprResult ArgE = 5946 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5947 if (ArgE.isInvalid()) 5948 return true; 5949 5950 Arg = ArgE.getAs<Expr>(); 5951 5952 } else { 5953 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5954 5955 if (ArgE.isInvalid()) 5956 return true; 5957 5958 Arg = ArgE.getAs<Expr>(); 5959 } 5960 5961 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5962 diag::err_call_incomplete_argument, Arg)) 5963 return ExprError(); 5964 5965 TheCall->setArg(i, Arg); 5966 } 5967 } 5968 5969 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5970 if (!Method->isStatic()) 5971 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5972 << Fn->getSourceRange()); 5973 5974 // Check for sentinels 5975 if (NDecl) 5976 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5977 5978 // Do special checking on direct calls to functions. 5979 if (FDecl) { 5980 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5981 return ExprError(); 5982 5983 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 5984 5985 if (BuiltinID) 5986 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5987 } else if (NDecl) { 5988 if (CheckPointerCall(NDecl, TheCall, Proto)) 5989 return ExprError(); 5990 } else { 5991 if (CheckOtherCall(TheCall, Proto)) 5992 return ExprError(); 5993 } 5994 5995 return MaybeBindToTemporary(TheCall); 5996 } 5997 5998 ExprResult 5999 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6000 SourceLocation RParenLoc, Expr *InitExpr) { 6001 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6002 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6003 6004 TypeSourceInfo *TInfo; 6005 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6006 if (!TInfo) 6007 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6008 6009 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6010 } 6011 6012 ExprResult 6013 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6014 SourceLocation RParenLoc, Expr *LiteralExpr) { 6015 QualType literalType = TInfo->getType(); 6016 6017 if (literalType->isArrayType()) { 6018 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6019 diag::err_illegal_decl_array_incomplete_type, 6020 SourceRange(LParenLoc, 6021 LiteralExpr->getSourceRange().getEnd()))) 6022 return ExprError(); 6023 if (literalType->isVariableArrayType()) 6024 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6025 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6026 } else if (!literalType->isDependentType() && 6027 RequireCompleteType(LParenLoc, literalType, 6028 diag::err_typecheck_decl_incomplete_type, 6029 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6030 return ExprError(); 6031 6032 InitializedEntity Entity 6033 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6034 InitializationKind Kind 6035 = InitializationKind::CreateCStyleCast(LParenLoc, 6036 SourceRange(LParenLoc, RParenLoc), 6037 /*InitList=*/true); 6038 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6039 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6040 &literalType); 6041 if (Result.isInvalid()) 6042 return ExprError(); 6043 LiteralExpr = Result.get(); 6044 6045 bool isFileScope = !CurContext->isFunctionOrMethod(); 6046 6047 // In C, compound literals are l-values for some reason. 6048 // For GCC compatibility, in C++, file-scope array compound literals with 6049 // constant initializers are also l-values, and compound literals are 6050 // otherwise prvalues. 6051 // 6052 // (GCC also treats C++ list-initialized file-scope array prvalues with 6053 // constant initializers as l-values, but that's non-conforming, so we don't 6054 // follow it there.) 6055 // 6056 // FIXME: It would be better to handle the lvalue cases as materializing and 6057 // lifetime-extending a temporary object, but our materialized temporaries 6058 // representation only supports lifetime extension from a variable, not "out 6059 // of thin air". 6060 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6061 // is bound to the result of applying array-to-pointer decay to the compound 6062 // literal. 6063 // FIXME: GCC supports compound literals of reference type, which should 6064 // obviously have a value kind derived from the kind of reference involved. 6065 ExprValueKind VK = 6066 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6067 ? VK_RValue 6068 : VK_LValue; 6069 6070 if (isFileScope) 6071 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6072 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6073 Expr *Init = ILE->getInit(i); 6074 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6075 } 6076 6077 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6078 VK, LiteralExpr, isFileScope); 6079 if (isFileScope) { 6080 if (!LiteralExpr->isTypeDependent() && 6081 !LiteralExpr->isValueDependent() && 6082 !literalType->isDependentType()) // C99 6.5.2.5p3 6083 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6084 return ExprError(); 6085 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6086 literalType.getAddressSpace() != LangAS::Default) { 6087 // Embedded-C extensions to C99 6.5.2.5: 6088 // "If the compound literal occurs inside the body of a function, the 6089 // type name shall not be qualified by an address-space qualifier." 6090 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6091 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6092 return ExprError(); 6093 } 6094 6095 // Compound literals that have automatic storage duration are destroyed at 6096 // the end of the scope. Emit diagnostics if it is or contains a C union type 6097 // that is non-trivial to destruct. 6098 if (!isFileScope) 6099 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6100 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6101 NTCUC_CompoundLiteral, NTCUK_Destruct); 6102 6103 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6104 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6105 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6106 E->getInitializer()->getExprLoc()); 6107 6108 return MaybeBindToTemporary(E); 6109 } 6110 6111 ExprResult 6112 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6113 SourceLocation RBraceLoc) { 6114 // Only produce each kind of designated initialization diagnostic once. 6115 SourceLocation FirstDesignator; 6116 bool DiagnosedArrayDesignator = false; 6117 bool DiagnosedNestedDesignator = false; 6118 bool DiagnosedMixedDesignator = false; 6119 6120 // Check that any designated initializers are syntactically valid in the 6121 // current language mode. 6122 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6123 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6124 if (FirstDesignator.isInvalid()) 6125 FirstDesignator = DIE->getBeginLoc(); 6126 6127 if (!getLangOpts().CPlusPlus) 6128 break; 6129 6130 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6131 DiagnosedNestedDesignator = true; 6132 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6133 << DIE->getDesignatorsSourceRange(); 6134 } 6135 6136 for (auto &Desig : DIE->designators()) { 6137 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6138 DiagnosedArrayDesignator = true; 6139 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6140 << Desig.getSourceRange(); 6141 } 6142 } 6143 6144 if (!DiagnosedMixedDesignator && 6145 !isa<DesignatedInitExpr>(InitArgList[0])) { 6146 DiagnosedMixedDesignator = true; 6147 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6148 << DIE->getSourceRange(); 6149 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6150 << InitArgList[0]->getSourceRange(); 6151 } 6152 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6153 isa<DesignatedInitExpr>(InitArgList[0])) { 6154 DiagnosedMixedDesignator = true; 6155 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6156 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6157 << DIE->getSourceRange(); 6158 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6159 << InitArgList[I]->getSourceRange(); 6160 } 6161 } 6162 6163 if (FirstDesignator.isValid()) { 6164 // Only diagnose designated initiaization as a C++20 extension if we didn't 6165 // already diagnose use of (non-C++20) C99 designator syntax. 6166 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6167 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6168 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6169 ? diag::warn_cxx17_compat_designated_init 6170 : diag::ext_cxx_designated_init); 6171 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6172 Diag(FirstDesignator, diag::ext_designated_init); 6173 } 6174 } 6175 6176 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6177 } 6178 6179 ExprResult 6180 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6181 SourceLocation RBraceLoc) { 6182 // Semantic analysis for initializers is done by ActOnDeclarator() and 6183 // CheckInitializer() - it requires knowledge of the object being initialized. 6184 6185 // Immediately handle non-overload placeholders. Overloads can be 6186 // resolved contextually, but everything else here can't. 6187 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6188 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6189 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6190 6191 // Ignore failures; dropping the entire initializer list because 6192 // of one failure would be terrible for indexing/etc. 6193 if (result.isInvalid()) continue; 6194 6195 InitArgList[I] = result.get(); 6196 } 6197 } 6198 6199 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6200 RBraceLoc); 6201 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6202 return E; 6203 } 6204 6205 /// Do an explicit extend of the given block pointer if we're in ARC. 6206 void Sema::maybeExtendBlockObject(ExprResult &E) { 6207 assert(E.get()->getType()->isBlockPointerType()); 6208 assert(E.get()->isRValue()); 6209 6210 // Only do this in an r-value context. 6211 if (!getLangOpts().ObjCAutoRefCount) return; 6212 6213 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6214 CK_ARCExtendBlockObject, E.get(), 6215 /*base path*/ nullptr, VK_RValue); 6216 Cleanup.setExprNeedsCleanups(true); 6217 } 6218 6219 /// Prepare a conversion of the given expression to an ObjC object 6220 /// pointer type. 6221 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6222 QualType type = E.get()->getType(); 6223 if (type->isObjCObjectPointerType()) { 6224 return CK_BitCast; 6225 } else if (type->isBlockPointerType()) { 6226 maybeExtendBlockObject(E); 6227 return CK_BlockPointerToObjCPointerCast; 6228 } else { 6229 assert(type->isPointerType()); 6230 return CK_CPointerToObjCPointerCast; 6231 } 6232 } 6233 6234 /// Prepares for a scalar cast, performing all the necessary stages 6235 /// except the final cast and returning the kind required. 6236 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6237 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6238 // Also, callers should have filtered out the invalid cases with 6239 // pointers. Everything else should be possible. 6240 6241 QualType SrcTy = Src.get()->getType(); 6242 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6243 return CK_NoOp; 6244 6245 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6246 case Type::STK_MemberPointer: 6247 llvm_unreachable("member pointer type in C"); 6248 6249 case Type::STK_CPointer: 6250 case Type::STK_BlockPointer: 6251 case Type::STK_ObjCObjectPointer: 6252 switch (DestTy->getScalarTypeKind()) { 6253 case Type::STK_CPointer: { 6254 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6255 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6256 if (SrcAS != DestAS) 6257 return CK_AddressSpaceConversion; 6258 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6259 return CK_NoOp; 6260 return CK_BitCast; 6261 } 6262 case Type::STK_BlockPointer: 6263 return (SrcKind == Type::STK_BlockPointer 6264 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6265 case Type::STK_ObjCObjectPointer: 6266 if (SrcKind == Type::STK_ObjCObjectPointer) 6267 return CK_BitCast; 6268 if (SrcKind == Type::STK_CPointer) 6269 return CK_CPointerToObjCPointerCast; 6270 maybeExtendBlockObject(Src); 6271 return CK_BlockPointerToObjCPointerCast; 6272 case Type::STK_Bool: 6273 return CK_PointerToBoolean; 6274 case Type::STK_Integral: 6275 return CK_PointerToIntegral; 6276 case Type::STK_Floating: 6277 case Type::STK_FloatingComplex: 6278 case Type::STK_IntegralComplex: 6279 case Type::STK_MemberPointer: 6280 case Type::STK_FixedPoint: 6281 llvm_unreachable("illegal cast from pointer"); 6282 } 6283 llvm_unreachable("Should have returned before this"); 6284 6285 case Type::STK_FixedPoint: 6286 switch (DestTy->getScalarTypeKind()) { 6287 case Type::STK_FixedPoint: 6288 return CK_FixedPointCast; 6289 case Type::STK_Bool: 6290 return CK_FixedPointToBoolean; 6291 case Type::STK_Integral: 6292 return CK_FixedPointToIntegral; 6293 case Type::STK_Floating: 6294 case Type::STK_IntegralComplex: 6295 case Type::STK_FloatingComplex: 6296 Diag(Src.get()->getExprLoc(), 6297 diag::err_unimplemented_conversion_with_fixed_point_type) 6298 << DestTy; 6299 return CK_IntegralCast; 6300 case Type::STK_CPointer: 6301 case Type::STK_ObjCObjectPointer: 6302 case Type::STK_BlockPointer: 6303 case Type::STK_MemberPointer: 6304 llvm_unreachable("illegal cast to pointer type"); 6305 } 6306 llvm_unreachable("Should have returned before this"); 6307 6308 case Type::STK_Bool: // casting from bool is like casting from an integer 6309 case Type::STK_Integral: 6310 switch (DestTy->getScalarTypeKind()) { 6311 case Type::STK_CPointer: 6312 case Type::STK_ObjCObjectPointer: 6313 case Type::STK_BlockPointer: 6314 if (Src.get()->isNullPointerConstant(Context, 6315 Expr::NPC_ValueDependentIsNull)) 6316 return CK_NullToPointer; 6317 return CK_IntegralToPointer; 6318 case Type::STK_Bool: 6319 return CK_IntegralToBoolean; 6320 case Type::STK_Integral: 6321 return CK_IntegralCast; 6322 case Type::STK_Floating: 6323 return CK_IntegralToFloating; 6324 case Type::STK_IntegralComplex: 6325 Src = ImpCastExprToType(Src.get(), 6326 DestTy->castAs<ComplexType>()->getElementType(), 6327 CK_IntegralCast); 6328 return CK_IntegralRealToComplex; 6329 case Type::STK_FloatingComplex: 6330 Src = ImpCastExprToType(Src.get(), 6331 DestTy->castAs<ComplexType>()->getElementType(), 6332 CK_IntegralToFloating); 6333 return CK_FloatingRealToComplex; 6334 case Type::STK_MemberPointer: 6335 llvm_unreachable("member pointer type in C"); 6336 case Type::STK_FixedPoint: 6337 return CK_IntegralToFixedPoint; 6338 } 6339 llvm_unreachable("Should have returned before this"); 6340 6341 case Type::STK_Floating: 6342 switch (DestTy->getScalarTypeKind()) { 6343 case Type::STK_Floating: 6344 return CK_FloatingCast; 6345 case Type::STK_Bool: 6346 return CK_FloatingToBoolean; 6347 case Type::STK_Integral: 6348 return CK_FloatingToIntegral; 6349 case Type::STK_FloatingComplex: 6350 Src = ImpCastExprToType(Src.get(), 6351 DestTy->castAs<ComplexType>()->getElementType(), 6352 CK_FloatingCast); 6353 return CK_FloatingRealToComplex; 6354 case Type::STK_IntegralComplex: 6355 Src = ImpCastExprToType(Src.get(), 6356 DestTy->castAs<ComplexType>()->getElementType(), 6357 CK_FloatingToIntegral); 6358 return CK_IntegralRealToComplex; 6359 case Type::STK_CPointer: 6360 case Type::STK_ObjCObjectPointer: 6361 case Type::STK_BlockPointer: 6362 llvm_unreachable("valid float->pointer cast?"); 6363 case Type::STK_MemberPointer: 6364 llvm_unreachable("member pointer type in C"); 6365 case Type::STK_FixedPoint: 6366 Diag(Src.get()->getExprLoc(), 6367 diag::err_unimplemented_conversion_with_fixed_point_type) 6368 << SrcTy; 6369 return CK_IntegralCast; 6370 } 6371 llvm_unreachable("Should have returned before this"); 6372 6373 case Type::STK_FloatingComplex: 6374 switch (DestTy->getScalarTypeKind()) { 6375 case Type::STK_FloatingComplex: 6376 return CK_FloatingComplexCast; 6377 case Type::STK_IntegralComplex: 6378 return CK_FloatingComplexToIntegralComplex; 6379 case Type::STK_Floating: { 6380 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6381 if (Context.hasSameType(ET, DestTy)) 6382 return CK_FloatingComplexToReal; 6383 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6384 return CK_FloatingCast; 6385 } 6386 case Type::STK_Bool: 6387 return CK_FloatingComplexToBoolean; 6388 case Type::STK_Integral: 6389 Src = ImpCastExprToType(Src.get(), 6390 SrcTy->castAs<ComplexType>()->getElementType(), 6391 CK_FloatingComplexToReal); 6392 return CK_FloatingToIntegral; 6393 case Type::STK_CPointer: 6394 case Type::STK_ObjCObjectPointer: 6395 case Type::STK_BlockPointer: 6396 llvm_unreachable("valid complex float->pointer cast?"); 6397 case Type::STK_MemberPointer: 6398 llvm_unreachable("member pointer type in C"); 6399 case Type::STK_FixedPoint: 6400 Diag(Src.get()->getExprLoc(), 6401 diag::err_unimplemented_conversion_with_fixed_point_type) 6402 << SrcTy; 6403 return CK_IntegralCast; 6404 } 6405 llvm_unreachable("Should have returned before this"); 6406 6407 case Type::STK_IntegralComplex: 6408 switch (DestTy->getScalarTypeKind()) { 6409 case Type::STK_FloatingComplex: 6410 return CK_IntegralComplexToFloatingComplex; 6411 case Type::STK_IntegralComplex: 6412 return CK_IntegralComplexCast; 6413 case Type::STK_Integral: { 6414 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6415 if (Context.hasSameType(ET, DestTy)) 6416 return CK_IntegralComplexToReal; 6417 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6418 return CK_IntegralCast; 6419 } 6420 case Type::STK_Bool: 6421 return CK_IntegralComplexToBoolean; 6422 case Type::STK_Floating: 6423 Src = ImpCastExprToType(Src.get(), 6424 SrcTy->castAs<ComplexType>()->getElementType(), 6425 CK_IntegralComplexToReal); 6426 return CK_IntegralToFloating; 6427 case Type::STK_CPointer: 6428 case Type::STK_ObjCObjectPointer: 6429 case Type::STK_BlockPointer: 6430 llvm_unreachable("valid complex int->pointer cast?"); 6431 case Type::STK_MemberPointer: 6432 llvm_unreachable("member pointer type in C"); 6433 case Type::STK_FixedPoint: 6434 Diag(Src.get()->getExprLoc(), 6435 diag::err_unimplemented_conversion_with_fixed_point_type) 6436 << SrcTy; 6437 return CK_IntegralCast; 6438 } 6439 llvm_unreachable("Should have returned before this"); 6440 } 6441 6442 llvm_unreachable("Unhandled scalar cast"); 6443 } 6444 6445 static bool breakDownVectorType(QualType type, uint64_t &len, 6446 QualType &eltType) { 6447 // Vectors are simple. 6448 if (const VectorType *vecType = type->getAs<VectorType>()) { 6449 len = vecType->getNumElements(); 6450 eltType = vecType->getElementType(); 6451 assert(eltType->isScalarType()); 6452 return true; 6453 } 6454 6455 // We allow lax conversion to and from non-vector types, but only if 6456 // they're real types (i.e. non-complex, non-pointer scalar types). 6457 if (!type->isRealType()) return false; 6458 6459 len = 1; 6460 eltType = type; 6461 return true; 6462 } 6463 6464 /// Are the two types lax-compatible vector types? That is, given 6465 /// that one of them is a vector, do they have equal storage sizes, 6466 /// where the storage size is the number of elements times the element 6467 /// size? 6468 /// 6469 /// This will also return false if either of the types is neither a 6470 /// vector nor a real type. 6471 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6472 assert(destTy->isVectorType() || srcTy->isVectorType()); 6473 6474 // Disallow lax conversions between scalars and ExtVectors (these 6475 // conversions are allowed for other vector types because common headers 6476 // depend on them). Most scalar OP ExtVector cases are handled by the 6477 // splat path anyway, which does what we want (convert, not bitcast). 6478 // What this rules out for ExtVectors is crazy things like char4*float. 6479 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6480 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6481 6482 uint64_t srcLen, destLen; 6483 QualType srcEltTy, destEltTy; 6484 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6485 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6486 6487 // ASTContext::getTypeSize will return the size rounded up to a 6488 // power of 2, so instead of using that, we need to use the raw 6489 // element size multiplied by the element count. 6490 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6491 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6492 6493 return (srcLen * srcEltSize == destLen * destEltSize); 6494 } 6495 6496 /// Is this a legal conversion between two types, one of which is 6497 /// known to be a vector type? 6498 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6499 assert(destTy->isVectorType() || srcTy->isVectorType()); 6500 6501 if (!Context.getLangOpts().LaxVectorConversions) 6502 return false; 6503 return areLaxCompatibleVectorTypes(srcTy, destTy); 6504 } 6505 6506 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6507 CastKind &Kind) { 6508 assert(VectorTy->isVectorType() && "Not a vector type!"); 6509 6510 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6511 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6512 return Diag(R.getBegin(), 6513 Ty->isVectorType() ? 6514 diag::err_invalid_conversion_between_vectors : 6515 diag::err_invalid_conversion_between_vector_and_integer) 6516 << VectorTy << Ty << R; 6517 } else 6518 return Diag(R.getBegin(), 6519 diag::err_invalid_conversion_between_vector_and_scalar) 6520 << VectorTy << Ty << R; 6521 6522 Kind = CK_BitCast; 6523 return false; 6524 } 6525 6526 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6527 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6528 6529 if (DestElemTy == SplattedExpr->getType()) 6530 return SplattedExpr; 6531 6532 assert(DestElemTy->isFloatingType() || 6533 DestElemTy->isIntegralOrEnumerationType()); 6534 6535 CastKind CK; 6536 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6537 // OpenCL requires that we convert `true` boolean expressions to -1, but 6538 // only when splatting vectors. 6539 if (DestElemTy->isFloatingType()) { 6540 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6541 // in two steps: boolean to signed integral, then to floating. 6542 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6543 CK_BooleanToSignedIntegral); 6544 SplattedExpr = CastExprRes.get(); 6545 CK = CK_IntegralToFloating; 6546 } else { 6547 CK = CK_BooleanToSignedIntegral; 6548 } 6549 } else { 6550 ExprResult CastExprRes = SplattedExpr; 6551 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6552 if (CastExprRes.isInvalid()) 6553 return ExprError(); 6554 SplattedExpr = CastExprRes.get(); 6555 } 6556 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6557 } 6558 6559 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6560 Expr *CastExpr, CastKind &Kind) { 6561 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6562 6563 QualType SrcTy = CastExpr->getType(); 6564 6565 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6566 // an ExtVectorType. 6567 // In OpenCL, casts between vectors of different types are not allowed. 6568 // (See OpenCL 6.2). 6569 if (SrcTy->isVectorType()) { 6570 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6571 (getLangOpts().OpenCL && 6572 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6573 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6574 << DestTy << SrcTy << R; 6575 return ExprError(); 6576 } 6577 Kind = CK_BitCast; 6578 return CastExpr; 6579 } 6580 6581 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6582 // conversion will take place first from scalar to elt type, and then 6583 // splat from elt type to vector. 6584 if (SrcTy->isPointerType()) 6585 return Diag(R.getBegin(), 6586 diag::err_invalid_conversion_between_vector_and_scalar) 6587 << DestTy << SrcTy << R; 6588 6589 Kind = CK_VectorSplat; 6590 return prepareVectorSplat(DestTy, CastExpr); 6591 } 6592 6593 ExprResult 6594 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6595 Declarator &D, ParsedType &Ty, 6596 SourceLocation RParenLoc, Expr *CastExpr) { 6597 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6598 "ActOnCastExpr(): missing type or expr"); 6599 6600 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6601 if (D.isInvalidType()) 6602 return ExprError(); 6603 6604 if (getLangOpts().CPlusPlus) { 6605 // Check that there are no default arguments (C++ only). 6606 CheckExtraCXXDefaultArguments(D); 6607 } else { 6608 // Make sure any TypoExprs have been dealt with. 6609 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6610 if (!Res.isUsable()) 6611 return ExprError(); 6612 CastExpr = Res.get(); 6613 } 6614 6615 checkUnusedDeclAttributes(D); 6616 6617 QualType castType = castTInfo->getType(); 6618 Ty = CreateParsedType(castType, castTInfo); 6619 6620 bool isVectorLiteral = false; 6621 6622 // Check for an altivec or OpenCL literal, 6623 // i.e. all the elements are integer constants. 6624 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6625 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6626 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6627 && castType->isVectorType() && (PE || PLE)) { 6628 if (PLE && PLE->getNumExprs() == 0) { 6629 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6630 return ExprError(); 6631 } 6632 if (PE || PLE->getNumExprs() == 1) { 6633 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6634 if (!E->getType()->isVectorType()) 6635 isVectorLiteral = true; 6636 } 6637 else 6638 isVectorLiteral = true; 6639 } 6640 6641 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6642 // then handle it as such. 6643 if (isVectorLiteral) 6644 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6645 6646 // If the Expr being casted is a ParenListExpr, handle it specially. 6647 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6648 // sequence of BinOp comma operators. 6649 if (isa<ParenListExpr>(CastExpr)) { 6650 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6651 if (Result.isInvalid()) return ExprError(); 6652 CastExpr = Result.get(); 6653 } 6654 6655 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6656 !getSourceManager().isInSystemMacro(LParenLoc)) 6657 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6658 6659 CheckTollFreeBridgeCast(castType, CastExpr); 6660 6661 CheckObjCBridgeRelatedCast(castType, CastExpr); 6662 6663 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6664 6665 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6666 } 6667 6668 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6669 SourceLocation RParenLoc, Expr *E, 6670 TypeSourceInfo *TInfo) { 6671 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6672 "Expected paren or paren list expression"); 6673 6674 Expr **exprs; 6675 unsigned numExprs; 6676 Expr *subExpr; 6677 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6678 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6679 LiteralLParenLoc = PE->getLParenLoc(); 6680 LiteralRParenLoc = PE->getRParenLoc(); 6681 exprs = PE->getExprs(); 6682 numExprs = PE->getNumExprs(); 6683 } else { // isa<ParenExpr> by assertion at function entrance 6684 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6685 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6686 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6687 exprs = &subExpr; 6688 numExprs = 1; 6689 } 6690 6691 QualType Ty = TInfo->getType(); 6692 assert(Ty->isVectorType() && "Expected vector type"); 6693 6694 SmallVector<Expr *, 8> initExprs; 6695 const VectorType *VTy = Ty->getAs<VectorType>(); 6696 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6697 6698 // '(...)' form of vector initialization in AltiVec: the number of 6699 // initializers must be one or must match the size of the vector. 6700 // If a single value is specified in the initializer then it will be 6701 // replicated to all the components of the vector 6702 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6703 // The number of initializers must be one or must match the size of the 6704 // vector. If a single value is specified in the initializer then it will 6705 // be replicated to all the components of the vector 6706 if (numExprs == 1) { 6707 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6708 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6709 if (Literal.isInvalid()) 6710 return ExprError(); 6711 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6712 PrepareScalarCast(Literal, ElemTy)); 6713 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6714 } 6715 else if (numExprs < numElems) { 6716 Diag(E->getExprLoc(), 6717 diag::err_incorrect_number_of_vector_initializers); 6718 return ExprError(); 6719 } 6720 else 6721 initExprs.append(exprs, exprs + numExprs); 6722 } 6723 else { 6724 // For OpenCL, when the number of initializers is a single value, 6725 // it will be replicated to all components of the vector. 6726 if (getLangOpts().OpenCL && 6727 VTy->getVectorKind() == VectorType::GenericVector && 6728 numExprs == 1) { 6729 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6730 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6731 if (Literal.isInvalid()) 6732 return ExprError(); 6733 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6734 PrepareScalarCast(Literal, ElemTy)); 6735 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6736 } 6737 6738 initExprs.append(exprs, exprs + numExprs); 6739 } 6740 // FIXME: This means that pretty-printing the final AST will produce curly 6741 // braces instead of the original commas. 6742 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6743 initExprs, LiteralRParenLoc); 6744 initE->setType(Ty); 6745 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6746 } 6747 6748 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6749 /// the ParenListExpr into a sequence of comma binary operators. 6750 ExprResult 6751 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6752 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6753 if (!E) 6754 return OrigExpr; 6755 6756 ExprResult Result(E->getExpr(0)); 6757 6758 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6759 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6760 E->getExpr(i)); 6761 6762 if (Result.isInvalid()) return ExprError(); 6763 6764 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6765 } 6766 6767 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6768 SourceLocation R, 6769 MultiExprArg Val) { 6770 return ParenListExpr::Create(Context, L, Val, R); 6771 } 6772 6773 /// Emit a specialized diagnostic when one expression is a null pointer 6774 /// constant and the other is not a pointer. Returns true if a diagnostic is 6775 /// emitted. 6776 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6777 SourceLocation QuestionLoc) { 6778 Expr *NullExpr = LHSExpr; 6779 Expr *NonPointerExpr = RHSExpr; 6780 Expr::NullPointerConstantKind NullKind = 6781 NullExpr->isNullPointerConstant(Context, 6782 Expr::NPC_ValueDependentIsNotNull); 6783 6784 if (NullKind == Expr::NPCK_NotNull) { 6785 NullExpr = RHSExpr; 6786 NonPointerExpr = LHSExpr; 6787 NullKind = 6788 NullExpr->isNullPointerConstant(Context, 6789 Expr::NPC_ValueDependentIsNotNull); 6790 } 6791 6792 if (NullKind == Expr::NPCK_NotNull) 6793 return false; 6794 6795 if (NullKind == Expr::NPCK_ZeroExpression) 6796 return false; 6797 6798 if (NullKind == Expr::NPCK_ZeroLiteral) { 6799 // In this case, check to make sure that we got here from a "NULL" 6800 // string in the source code. 6801 NullExpr = NullExpr->IgnoreParenImpCasts(); 6802 SourceLocation loc = NullExpr->getExprLoc(); 6803 if (!findMacroSpelling(loc, "NULL")) 6804 return false; 6805 } 6806 6807 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6808 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6809 << NonPointerExpr->getType() << DiagType 6810 << NonPointerExpr->getSourceRange(); 6811 return true; 6812 } 6813 6814 /// Return false if the condition expression is valid, true otherwise. 6815 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6816 QualType CondTy = Cond->getType(); 6817 6818 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6819 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6820 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6821 << CondTy << Cond->getSourceRange(); 6822 return true; 6823 } 6824 6825 // C99 6.5.15p2 6826 if (CondTy->isScalarType()) return false; 6827 6828 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6829 << CondTy << Cond->getSourceRange(); 6830 return true; 6831 } 6832 6833 /// Handle when one or both operands are void type. 6834 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6835 ExprResult &RHS) { 6836 Expr *LHSExpr = LHS.get(); 6837 Expr *RHSExpr = RHS.get(); 6838 6839 if (!LHSExpr->getType()->isVoidType()) 6840 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6841 << RHSExpr->getSourceRange(); 6842 if (!RHSExpr->getType()->isVoidType()) 6843 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6844 << LHSExpr->getSourceRange(); 6845 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6846 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6847 return S.Context.VoidTy; 6848 } 6849 6850 /// Return false if the NullExpr can be promoted to PointerTy, 6851 /// true otherwise. 6852 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6853 QualType PointerTy) { 6854 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6855 !NullExpr.get()->isNullPointerConstant(S.Context, 6856 Expr::NPC_ValueDependentIsNull)) 6857 return true; 6858 6859 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6860 return false; 6861 } 6862 6863 /// Checks compatibility between two pointers and return the resulting 6864 /// type. 6865 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6866 ExprResult &RHS, 6867 SourceLocation Loc) { 6868 QualType LHSTy = LHS.get()->getType(); 6869 QualType RHSTy = RHS.get()->getType(); 6870 6871 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6872 // Two identical pointers types are always compatible. 6873 return LHSTy; 6874 } 6875 6876 QualType lhptee, rhptee; 6877 6878 // Get the pointee types. 6879 bool IsBlockPointer = false; 6880 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6881 lhptee = LHSBTy->getPointeeType(); 6882 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6883 IsBlockPointer = true; 6884 } else { 6885 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6886 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6887 } 6888 6889 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6890 // differently qualified versions of compatible types, the result type is 6891 // a pointer to an appropriately qualified version of the composite 6892 // type. 6893 6894 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6895 // clause doesn't make sense for our extensions. E.g. address space 2 should 6896 // be incompatible with address space 3: they may live on different devices or 6897 // anything. 6898 Qualifiers lhQual = lhptee.getQualifiers(); 6899 Qualifiers rhQual = rhptee.getQualifiers(); 6900 6901 LangAS ResultAddrSpace = LangAS::Default; 6902 LangAS LAddrSpace = lhQual.getAddressSpace(); 6903 LangAS RAddrSpace = rhQual.getAddressSpace(); 6904 6905 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6906 // spaces is disallowed. 6907 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6908 ResultAddrSpace = LAddrSpace; 6909 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6910 ResultAddrSpace = RAddrSpace; 6911 else { 6912 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6913 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6914 << RHS.get()->getSourceRange(); 6915 return QualType(); 6916 } 6917 6918 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6919 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6920 lhQual.removeCVRQualifiers(); 6921 rhQual.removeCVRQualifiers(); 6922 6923 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6924 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6925 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6926 // qual types are compatible iff 6927 // * corresponded types are compatible 6928 // * CVR qualifiers are equal 6929 // * address spaces are equal 6930 // Thus for conditional operator we merge CVR and address space unqualified 6931 // pointees and if there is a composite type we return a pointer to it with 6932 // merged qualifiers. 6933 LHSCastKind = 6934 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6935 RHSCastKind = 6936 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6937 lhQual.removeAddressSpace(); 6938 rhQual.removeAddressSpace(); 6939 6940 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6941 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6942 6943 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6944 6945 if (CompositeTy.isNull()) { 6946 // In this situation, we assume void* type. No especially good 6947 // reason, but this is what gcc does, and we do have to pick 6948 // to get a consistent AST. 6949 QualType incompatTy; 6950 incompatTy = S.Context.getPointerType( 6951 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6952 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6953 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6954 6955 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6956 // for casts between types with incompatible address space qualifiers. 6957 // For the following code the compiler produces casts between global and 6958 // local address spaces of the corresponded innermost pointees: 6959 // local int *global *a; 6960 // global int *global *b; 6961 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6962 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6963 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6964 << RHS.get()->getSourceRange(); 6965 6966 return incompatTy; 6967 } 6968 6969 // The pointer types are compatible. 6970 // In case of OpenCL ResultTy should have the address space qualifier 6971 // which is a superset of address spaces of both the 2nd and the 3rd 6972 // operands of the conditional operator. 6973 QualType ResultTy = [&, ResultAddrSpace]() { 6974 if (S.getLangOpts().OpenCL) { 6975 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6976 CompositeQuals.setAddressSpace(ResultAddrSpace); 6977 return S.Context 6978 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6979 .withCVRQualifiers(MergedCVRQual); 6980 } 6981 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6982 }(); 6983 if (IsBlockPointer) 6984 ResultTy = S.Context.getBlockPointerType(ResultTy); 6985 else 6986 ResultTy = S.Context.getPointerType(ResultTy); 6987 6988 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6989 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6990 return ResultTy; 6991 } 6992 6993 /// Return the resulting type when the operands are both block pointers. 6994 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6995 ExprResult &LHS, 6996 ExprResult &RHS, 6997 SourceLocation Loc) { 6998 QualType LHSTy = LHS.get()->getType(); 6999 QualType RHSTy = RHS.get()->getType(); 7000 7001 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7002 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7003 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7004 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7005 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7006 return destType; 7007 } 7008 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7009 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7010 << RHS.get()->getSourceRange(); 7011 return QualType(); 7012 } 7013 7014 // We have 2 block pointer types. 7015 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7016 } 7017 7018 /// Return the resulting type when the operands are both pointers. 7019 static QualType 7020 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7021 ExprResult &RHS, 7022 SourceLocation Loc) { 7023 // get the pointer types 7024 QualType LHSTy = LHS.get()->getType(); 7025 QualType RHSTy = RHS.get()->getType(); 7026 7027 // get the "pointed to" types 7028 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7029 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7030 7031 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7032 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7033 // Figure out necessary qualifiers (C99 6.5.15p6) 7034 QualType destPointee 7035 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7036 QualType destType = S.Context.getPointerType(destPointee); 7037 // Add qualifiers if necessary. 7038 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7039 // Promote to void*. 7040 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7041 return destType; 7042 } 7043 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7044 QualType destPointee 7045 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7046 QualType destType = S.Context.getPointerType(destPointee); 7047 // Add qualifiers if necessary. 7048 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7049 // Promote to void*. 7050 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7051 return destType; 7052 } 7053 7054 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7055 } 7056 7057 /// Return false if the first expression is not an integer and the second 7058 /// expression is not a pointer, true otherwise. 7059 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7060 Expr* PointerExpr, SourceLocation Loc, 7061 bool IsIntFirstExpr) { 7062 if (!PointerExpr->getType()->isPointerType() || 7063 !Int.get()->getType()->isIntegerType()) 7064 return false; 7065 7066 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7067 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7068 7069 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7070 << Expr1->getType() << Expr2->getType() 7071 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7072 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7073 CK_IntegralToPointer); 7074 return true; 7075 } 7076 7077 /// Simple conversion between integer and floating point types. 7078 /// 7079 /// Used when handling the OpenCL conditional operator where the 7080 /// condition is a vector while the other operands are scalar. 7081 /// 7082 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7083 /// types are either integer or floating type. Between the two 7084 /// operands, the type with the higher rank is defined as the "result 7085 /// type". The other operand needs to be promoted to the same type. No 7086 /// other type promotion is allowed. We cannot use 7087 /// UsualArithmeticConversions() for this purpose, since it always 7088 /// promotes promotable types. 7089 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7090 ExprResult &RHS, 7091 SourceLocation QuestionLoc) { 7092 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7093 if (LHS.isInvalid()) 7094 return QualType(); 7095 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7096 if (RHS.isInvalid()) 7097 return QualType(); 7098 7099 // For conversion purposes, we ignore any qualifiers. 7100 // For example, "const float" and "float" are equivalent. 7101 QualType LHSType = 7102 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7103 QualType RHSType = 7104 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7105 7106 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7107 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7108 << LHSType << LHS.get()->getSourceRange(); 7109 return QualType(); 7110 } 7111 7112 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7113 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7114 << RHSType << RHS.get()->getSourceRange(); 7115 return QualType(); 7116 } 7117 7118 // If both types are identical, no conversion is needed. 7119 if (LHSType == RHSType) 7120 return LHSType; 7121 7122 // Now handle "real" floating types (i.e. float, double, long double). 7123 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7124 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7125 /*IsCompAssign = */ false); 7126 7127 // Finally, we have two differing integer types. 7128 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7129 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7130 } 7131 7132 /// Convert scalar operands to a vector that matches the 7133 /// condition in length. 7134 /// 7135 /// Used when handling the OpenCL conditional operator where the 7136 /// condition is a vector while the other operands are scalar. 7137 /// 7138 /// We first compute the "result type" for the scalar operands 7139 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7140 /// into a vector of that type where the length matches the condition 7141 /// vector type. s6.11.6 requires that the element types of the result 7142 /// and the condition must have the same number of bits. 7143 static QualType 7144 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7145 QualType CondTy, SourceLocation QuestionLoc) { 7146 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7147 if (ResTy.isNull()) return QualType(); 7148 7149 const VectorType *CV = CondTy->getAs<VectorType>(); 7150 assert(CV); 7151 7152 // Determine the vector result type 7153 unsigned NumElements = CV->getNumElements(); 7154 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7155 7156 // Ensure that all types have the same number of bits 7157 if (S.Context.getTypeSize(CV->getElementType()) 7158 != S.Context.getTypeSize(ResTy)) { 7159 // Since VectorTy is created internally, it does not pretty print 7160 // with an OpenCL name. Instead, we just print a description. 7161 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7162 SmallString<64> Str; 7163 llvm::raw_svector_ostream OS(Str); 7164 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7165 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7166 << CondTy << OS.str(); 7167 return QualType(); 7168 } 7169 7170 // Convert operands to the vector result type 7171 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7172 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7173 7174 return VectorTy; 7175 } 7176 7177 /// Return false if this is a valid OpenCL condition vector 7178 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7179 SourceLocation QuestionLoc) { 7180 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7181 // integral type. 7182 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7183 assert(CondTy); 7184 QualType EleTy = CondTy->getElementType(); 7185 if (EleTy->isIntegerType()) return false; 7186 7187 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7188 << Cond->getType() << Cond->getSourceRange(); 7189 return true; 7190 } 7191 7192 /// Return false if the vector condition type and the vector 7193 /// result type are compatible. 7194 /// 7195 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7196 /// number of elements, and their element types have the same number 7197 /// of bits. 7198 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7199 SourceLocation QuestionLoc) { 7200 const VectorType *CV = CondTy->getAs<VectorType>(); 7201 const VectorType *RV = VecResTy->getAs<VectorType>(); 7202 assert(CV && RV); 7203 7204 if (CV->getNumElements() != RV->getNumElements()) { 7205 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7206 << CondTy << VecResTy; 7207 return true; 7208 } 7209 7210 QualType CVE = CV->getElementType(); 7211 QualType RVE = RV->getElementType(); 7212 7213 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7214 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7215 << CondTy << VecResTy; 7216 return true; 7217 } 7218 7219 return false; 7220 } 7221 7222 /// Return the resulting type for the conditional operator in 7223 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7224 /// s6.3.i) when the condition is a vector type. 7225 static QualType 7226 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7227 ExprResult &LHS, ExprResult &RHS, 7228 SourceLocation QuestionLoc) { 7229 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7230 if (Cond.isInvalid()) 7231 return QualType(); 7232 QualType CondTy = Cond.get()->getType(); 7233 7234 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7235 return QualType(); 7236 7237 // If either operand is a vector then find the vector type of the 7238 // result as specified in OpenCL v1.1 s6.3.i. 7239 if (LHS.get()->getType()->isVectorType() || 7240 RHS.get()->getType()->isVectorType()) { 7241 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7242 /*isCompAssign*/false, 7243 /*AllowBothBool*/true, 7244 /*AllowBoolConversions*/false); 7245 if (VecResTy.isNull()) return QualType(); 7246 // The result type must match the condition type as specified in 7247 // OpenCL v1.1 s6.11.6. 7248 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7249 return QualType(); 7250 return VecResTy; 7251 } 7252 7253 // Both operands are scalar. 7254 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7255 } 7256 7257 /// Return true if the Expr is block type 7258 static bool checkBlockType(Sema &S, const Expr *E) { 7259 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7260 QualType Ty = CE->getCallee()->getType(); 7261 if (Ty->isBlockPointerType()) { 7262 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7263 return true; 7264 } 7265 } 7266 return false; 7267 } 7268 7269 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7270 /// In that case, LHS = cond. 7271 /// C99 6.5.15 7272 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7273 ExprResult &RHS, ExprValueKind &VK, 7274 ExprObjectKind &OK, 7275 SourceLocation QuestionLoc) { 7276 7277 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7278 if (!LHSResult.isUsable()) return QualType(); 7279 LHS = LHSResult; 7280 7281 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7282 if (!RHSResult.isUsable()) return QualType(); 7283 RHS = RHSResult; 7284 7285 // C++ is sufficiently different to merit its own checker. 7286 if (getLangOpts().CPlusPlus) 7287 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7288 7289 VK = VK_RValue; 7290 OK = OK_Ordinary; 7291 7292 // The OpenCL operator with a vector condition is sufficiently 7293 // different to merit its own checker. 7294 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7295 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7296 7297 // First, check the condition. 7298 Cond = UsualUnaryConversions(Cond.get()); 7299 if (Cond.isInvalid()) 7300 return QualType(); 7301 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7302 return QualType(); 7303 7304 // Now check the two expressions. 7305 if (LHS.get()->getType()->isVectorType() || 7306 RHS.get()->getType()->isVectorType()) 7307 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7308 /*AllowBothBool*/true, 7309 /*AllowBoolConversions*/false); 7310 7311 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7312 if (LHS.isInvalid() || RHS.isInvalid()) 7313 return QualType(); 7314 7315 QualType LHSTy = LHS.get()->getType(); 7316 QualType RHSTy = RHS.get()->getType(); 7317 7318 // Diagnose attempts to convert between __float128 and long double where 7319 // such conversions currently can't be handled. 7320 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7321 Diag(QuestionLoc, 7322 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7323 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7324 return QualType(); 7325 } 7326 7327 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7328 // selection operator (?:). 7329 if (getLangOpts().OpenCL && 7330 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7331 return QualType(); 7332 } 7333 7334 // If both operands have arithmetic type, do the usual arithmetic conversions 7335 // to find a common type: C99 6.5.15p3,5. 7336 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7337 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7338 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7339 7340 return ResTy; 7341 } 7342 7343 // If both operands are the same structure or union type, the result is that 7344 // type. 7345 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7346 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7347 if (LHSRT->getDecl() == RHSRT->getDecl()) 7348 // "If both the operands have structure or union type, the result has 7349 // that type." This implies that CV qualifiers are dropped. 7350 return LHSTy.getUnqualifiedType(); 7351 // FIXME: Type of conditional expression must be complete in C mode. 7352 } 7353 7354 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7355 // The following || allows only one side to be void (a GCC-ism). 7356 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7357 return checkConditionalVoidType(*this, LHS, RHS); 7358 } 7359 7360 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7361 // the type of the other operand." 7362 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7363 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7364 7365 // All objective-c pointer type analysis is done here. 7366 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7367 QuestionLoc); 7368 if (LHS.isInvalid() || RHS.isInvalid()) 7369 return QualType(); 7370 if (!compositeType.isNull()) 7371 return compositeType; 7372 7373 7374 // Handle block pointer types. 7375 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7376 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7377 QuestionLoc); 7378 7379 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7380 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7381 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7382 QuestionLoc); 7383 7384 // GCC compatibility: soften pointer/integer mismatch. Note that 7385 // null pointers have been filtered out by this point. 7386 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7387 /*IsIntFirstExpr=*/true)) 7388 return RHSTy; 7389 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7390 /*IsIntFirstExpr=*/false)) 7391 return LHSTy; 7392 7393 // Emit a better diagnostic if one of the expressions is a null pointer 7394 // constant and the other is not a pointer type. In this case, the user most 7395 // likely forgot to take the address of the other expression. 7396 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7397 return QualType(); 7398 7399 // Otherwise, the operands are not compatible. 7400 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7401 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7402 << RHS.get()->getSourceRange(); 7403 return QualType(); 7404 } 7405 7406 /// FindCompositeObjCPointerType - Helper method to find composite type of 7407 /// two objective-c pointer types of the two input expressions. 7408 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7409 SourceLocation QuestionLoc) { 7410 QualType LHSTy = LHS.get()->getType(); 7411 QualType RHSTy = RHS.get()->getType(); 7412 7413 // Handle things like Class and struct objc_class*. Here we case the result 7414 // to the pseudo-builtin, because that will be implicitly cast back to the 7415 // redefinition type if an attempt is made to access its fields. 7416 if (LHSTy->isObjCClassType() && 7417 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7418 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7419 return LHSTy; 7420 } 7421 if (RHSTy->isObjCClassType() && 7422 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7423 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7424 return RHSTy; 7425 } 7426 // And the same for struct objc_object* / id 7427 if (LHSTy->isObjCIdType() && 7428 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7429 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7430 return LHSTy; 7431 } 7432 if (RHSTy->isObjCIdType() && 7433 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7434 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7435 return RHSTy; 7436 } 7437 // And the same for struct objc_selector* / SEL 7438 if (Context.isObjCSelType(LHSTy) && 7439 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7440 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7441 return LHSTy; 7442 } 7443 if (Context.isObjCSelType(RHSTy) && 7444 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7445 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7446 return RHSTy; 7447 } 7448 // Check constraints for Objective-C object pointers types. 7449 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7450 7451 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7452 // Two identical object pointer types are always compatible. 7453 return LHSTy; 7454 } 7455 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7456 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7457 QualType compositeType = LHSTy; 7458 7459 // If both operands are interfaces and either operand can be 7460 // assigned to the other, use that type as the composite 7461 // type. This allows 7462 // xxx ? (A*) a : (B*) b 7463 // where B is a subclass of A. 7464 // 7465 // Additionally, as for assignment, if either type is 'id' 7466 // allow silent coercion. Finally, if the types are 7467 // incompatible then make sure to use 'id' as the composite 7468 // type so the result is acceptable for sending messages to. 7469 7470 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7471 // It could return the composite type. 7472 if (!(compositeType = 7473 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7474 // Nothing more to do. 7475 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7476 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7477 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7478 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7479 } else if ((LHSTy->isObjCQualifiedIdType() || 7480 RHSTy->isObjCQualifiedIdType()) && 7481 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7482 // Need to handle "id<xx>" explicitly. 7483 // GCC allows qualified id and any Objective-C type to devolve to 7484 // id. Currently localizing to here until clear this should be 7485 // part of ObjCQualifiedIdTypesAreCompatible. 7486 compositeType = Context.getObjCIdType(); 7487 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7488 compositeType = Context.getObjCIdType(); 7489 } else { 7490 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7491 << LHSTy << RHSTy 7492 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7493 QualType incompatTy = Context.getObjCIdType(); 7494 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7495 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7496 return incompatTy; 7497 } 7498 // The object pointer types are compatible. 7499 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7500 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7501 return compositeType; 7502 } 7503 // Check Objective-C object pointer types and 'void *' 7504 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7505 if (getLangOpts().ObjCAutoRefCount) { 7506 // ARC forbids the implicit conversion of object pointers to 'void *', 7507 // so these types are not compatible. 7508 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7509 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7510 LHS = RHS = true; 7511 return QualType(); 7512 } 7513 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7514 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7515 QualType destPointee 7516 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7517 QualType destType = Context.getPointerType(destPointee); 7518 // Add qualifiers if necessary. 7519 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7520 // Promote to void*. 7521 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7522 return destType; 7523 } 7524 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7525 if (getLangOpts().ObjCAutoRefCount) { 7526 // ARC forbids the implicit conversion of object pointers to 'void *', 7527 // so these types are not compatible. 7528 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7529 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7530 LHS = RHS = true; 7531 return QualType(); 7532 } 7533 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7534 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7535 QualType destPointee 7536 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7537 QualType destType = Context.getPointerType(destPointee); 7538 // Add qualifiers if necessary. 7539 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7540 // Promote to void*. 7541 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7542 return destType; 7543 } 7544 return QualType(); 7545 } 7546 7547 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7548 /// ParenRange in parentheses. 7549 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7550 const PartialDiagnostic &Note, 7551 SourceRange ParenRange) { 7552 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7553 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7554 EndLoc.isValid()) { 7555 Self.Diag(Loc, Note) 7556 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7557 << FixItHint::CreateInsertion(EndLoc, ")"); 7558 } else { 7559 // We can't display the parentheses, so just show the bare note. 7560 Self.Diag(Loc, Note) << ParenRange; 7561 } 7562 } 7563 7564 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7565 return BinaryOperator::isAdditiveOp(Opc) || 7566 BinaryOperator::isMultiplicativeOp(Opc) || 7567 BinaryOperator::isShiftOp(Opc); 7568 } 7569 7570 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7571 /// expression, either using a built-in or overloaded operator, 7572 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7573 /// expression. 7574 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7575 Expr **RHSExprs) { 7576 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7577 E = E->IgnoreImpCasts(); 7578 E = E->IgnoreConversionOperator(); 7579 E = E->IgnoreImpCasts(); 7580 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7581 E = MTE->GetTemporaryExpr(); 7582 E = E->IgnoreImpCasts(); 7583 } 7584 7585 // Built-in binary operator. 7586 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7587 if (IsArithmeticOp(OP->getOpcode())) { 7588 *Opcode = OP->getOpcode(); 7589 *RHSExprs = OP->getRHS(); 7590 return true; 7591 } 7592 } 7593 7594 // Overloaded operator. 7595 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7596 if (Call->getNumArgs() != 2) 7597 return false; 7598 7599 // Make sure this is really a binary operator that is safe to pass into 7600 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7601 OverloadedOperatorKind OO = Call->getOperator(); 7602 if (OO < OO_Plus || OO > OO_Arrow || 7603 OO == OO_PlusPlus || OO == OO_MinusMinus) 7604 return false; 7605 7606 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7607 if (IsArithmeticOp(OpKind)) { 7608 *Opcode = OpKind; 7609 *RHSExprs = Call->getArg(1); 7610 return true; 7611 } 7612 } 7613 7614 return false; 7615 } 7616 7617 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7618 /// or is a logical expression such as (x==y) which has int type, but is 7619 /// commonly interpreted as boolean. 7620 static bool ExprLooksBoolean(Expr *E) { 7621 E = E->IgnoreParenImpCasts(); 7622 7623 if (E->getType()->isBooleanType()) 7624 return true; 7625 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7626 return OP->isComparisonOp() || OP->isLogicalOp(); 7627 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7628 return OP->getOpcode() == UO_LNot; 7629 if (E->getType()->isPointerType()) 7630 return true; 7631 // FIXME: What about overloaded operator calls returning "unspecified boolean 7632 // type"s (commonly pointer-to-members)? 7633 7634 return false; 7635 } 7636 7637 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7638 /// and binary operator are mixed in a way that suggests the programmer assumed 7639 /// the conditional operator has higher precedence, for example: 7640 /// "int x = a + someBinaryCondition ? 1 : 2". 7641 static void DiagnoseConditionalPrecedence(Sema &Self, 7642 SourceLocation OpLoc, 7643 Expr *Condition, 7644 Expr *LHSExpr, 7645 Expr *RHSExpr) { 7646 BinaryOperatorKind CondOpcode; 7647 Expr *CondRHS; 7648 7649 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7650 return; 7651 if (!ExprLooksBoolean(CondRHS)) 7652 return; 7653 7654 // The condition is an arithmetic binary expression, with a right- 7655 // hand side that looks boolean, so warn. 7656 7657 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7658 << Condition->getSourceRange() 7659 << BinaryOperator::getOpcodeStr(CondOpcode); 7660 7661 SuggestParentheses( 7662 Self, OpLoc, 7663 Self.PDiag(diag::note_precedence_silence) 7664 << BinaryOperator::getOpcodeStr(CondOpcode), 7665 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7666 7667 SuggestParentheses(Self, OpLoc, 7668 Self.PDiag(diag::note_precedence_conditional_first), 7669 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7670 } 7671 7672 /// Compute the nullability of a conditional expression. 7673 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7674 QualType LHSTy, QualType RHSTy, 7675 ASTContext &Ctx) { 7676 if (!ResTy->isAnyPointerType()) 7677 return ResTy; 7678 7679 auto GetNullability = [&Ctx](QualType Ty) { 7680 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7681 if (Kind) 7682 return *Kind; 7683 return NullabilityKind::Unspecified; 7684 }; 7685 7686 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7687 NullabilityKind MergedKind; 7688 7689 // Compute nullability of a binary conditional expression. 7690 if (IsBin) { 7691 if (LHSKind == NullabilityKind::NonNull) 7692 MergedKind = NullabilityKind::NonNull; 7693 else 7694 MergedKind = RHSKind; 7695 // Compute nullability of a normal conditional expression. 7696 } else { 7697 if (LHSKind == NullabilityKind::Nullable || 7698 RHSKind == NullabilityKind::Nullable) 7699 MergedKind = NullabilityKind::Nullable; 7700 else if (LHSKind == NullabilityKind::NonNull) 7701 MergedKind = RHSKind; 7702 else if (RHSKind == NullabilityKind::NonNull) 7703 MergedKind = LHSKind; 7704 else 7705 MergedKind = NullabilityKind::Unspecified; 7706 } 7707 7708 // Return if ResTy already has the correct nullability. 7709 if (GetNullability(ResTy) == MergedKind) 7710 return ResTy; 7711 7712 // Strip all nullability from ResTy. 7713 while (ResTy->getNullability(Ctx)) 7714 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7715 7716 // Create a new AttributedType with the new nullability kind. 7717 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7718 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7719 } 7720 7721 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7722 /// in the case of a the GNU conditional expr extension. 7723 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7724 SourceLocation ColonLoc, 7725 Expr *CondExpr, Expr *LHSExpr, 7726 Expr *RHSExpr) { 7727 if (!getLangOpts().CPlusPlus) { 7728 // C cannot handle TypoExpr nodes in the condition because it 7729 // doesn't handle dependent types properly, so make sure any TypoExprs have 7730 // been dealt with before checking the operands. 7731 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7732 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7733 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7734 7735 if (!CondResult.isUsable()) 7736 return ExprError(); 7737 7738 if (LHSExpr) { 7739 if (!LHSResult.isUsable()) 7740 return ExprError(); 7741 } 7742 7743 if (!RHSResult.isUsable()) 7744 return ExprError(); 7745 7746 CondExpr = CondResult.get(); 7747 LHSExpr = LHSResult.get(); 7748 RHSExpr = RHSResult.get(); 7749 } 7750 7751 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7752 // was the condition. 7753 OpaqueValueExpr *opaqueValue = nullptr; 7754 Expr *commonExpr = nullptr; 7755 if (!LHSExpr) { 7756 commonExpr = CondExpr; 7757 // Lower out placeholder types first. This is important so that we don't 7758 // try to capture a placeholder. This happens in few cases in C++; such 7759 // as Objective-C++'s dictionary subscripting syntax. 7760 if (commonExpr->hasPlaceholderType()) { 7761 ExprResult result = CheckPlaceholderExpr(commonExpr); 7762 if (!result.isUsable()) return ExprError(); 7763 commonExpr = result.get(); 7764 } 7765 // We usually want to apply unary conversions *before* saving, except 7766 // in the special case of a C++ l-value conditional. 7767 if (!(getLangOpts().CPlusPlus 7768 && !commonExpr->isTypeDependent() 7769 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7770 && commonExpr->isGLValue() 7771 && commonExpr->isOrdinaryOrBitFieldObject() 7772 && RHSExpr->isOrdinaryOrBitFieldObject() 7773 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7774 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7775 if (commonRes.isInvalid()) 7776 return ExprError(); 7777 commonExpr = commonRes.get(); 7778 } 7779 7780 // If the common expression is a class or array prvalue, materialize it 7781 // so that we can safely refer to it multiple times. 7782 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7783 commonExpr->getType()->isArrayType())) { 7784 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7785 if (MatExpr.isInvalid()) 7786 return ExprError(); 7787 commonExpr = MatExpr.get(); 7788 } 7789 7790 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7791 commonExpr->getType(), 7792 commonExpr->getValueKind(), 7793 commonExpr->getObjectKind(), 7794 commonExpr); 7795 LHSExpr = CondExpr = opaqueValue; 7796 } 7797 7798 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7799 ExprValueKind VK = VK_RValue; 7800 ExprObjectKind OK = OK_Ordinary; 7801 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7802 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7803 VK, OK, QuestionLoc); 7804 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7805 RHS.isInvalid()) 7806 return ExprError(); 7807 7808 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7809 RHS.get()); 7810 7811 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7812 7813 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7814 Context); 7815 7816 if (!commonExpr) 7817 return new (Context) 7818 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7819 RHS.get(), result, VK, OK); 7820 7821 return new (Context) BinaryConditionalOperator( 7822 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7823 ColonLoc, result, VK, OK); 7824 } 7825 7826 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7827 // being closely modeled after the C99 spec:-). The odd characteristic of this 7828 // routine is it effectively iqnores the qualifiers on the top level pointee. 7829 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7830 // FIXME: add a couple examples in this comment. 7831 static Sema::AssignConvertType 7832 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7833 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7834 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7835 7836 // get the "pointed to" type (ignoring qualifiers at the top level) 7837 const Type *lhptee, *rhptee; 7838 Qualifiers lhq, rhq; 7839 std::tie(lhptee, lhq) = 7840 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7841 std::tie(rhptee, rhq) = 7842 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7843 7844 Sema::AssignConvertType ConvTy = Sema::Compatible; 7845 7846 // C99 6.5.16.1p1: This following citation is common to constraints 7847 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7848 // qualifiers of the type *pointed to* by the right; 7849 7850 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7851 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7852 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7853 // Ignore lifetime for further calculation. 7854 lhq.removeObjCLifetime(); 7855 rhq.removeObjCLifetime(); 7856 } 7857 7858 if (!lhq.compatiblyIncludes(rhq)) { 7859 // Treat address-space mismatches as fatal. 7860 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7861 return Sema::IncompatiblePointerDiscardsQualifiers; 7862 7863 // It's okay to add or remove GC or lifetime qualifiers when converting to 7864 // and from void*. 7865 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7866 .compatiblyIncludes( 7867 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7868 && (lhptee->isVoidType() || rhptee->isVoidType())) 7869 ; // keep old 7870 7871 // Treat lifetime mismatches as fatal. 7872 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7873 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7874 7875 // For GCC/MS compatibility, other qualifier mismatches are treated 7876 // as still compatible in C. 7877 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7878 } 7879 7880 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7881 // incomplete type and the other is a pointer to a qualified or unqualified 7882 // version of void... 7883 if (lhptee->isVoidType()) { 7884 if (rhptee->isIncompleteOrObjectType()) 7885 return ConvTy; 7886 7887 // As an extension, we allow cast to/from void* to function pointer. 7888 assert(rhptee->isFunctionType()); 7889 return Sema::FunctionVoidPointer; 7890 } 7891 7892 if (rhptee->isVoidType()) { 7893 if (lhptee->isIncompleteOrObjectType()) 7894 return ConvTy; 7895 7896 // As an extension, we allow cast to/from void* to function pointer. 7897 assert(lhptee->isFunctionType()); 7898 return Sema::FunctionVoidPointer; 7899 } 7900 7901 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7902 // unqualified versions of compatible types, ... 7903 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7904 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7905 // Check if the pointee types are compatible ignoring the sign. 7906 // We explicitly check for char so that we catch "char" vs 7907 // "unsigned char" on systems where "char" is unsigned. 7908 if (lhptee->isCharType()) 7909 ltrans = S.Context.UnsignedCharTy; 7910 else if (lhptee->hasSignedIntegerRepresentation()) 7911 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7912 7913 if (rhptee->isCharType()) 7914 rtrans = S.Context.UnsignedCharTy; 7915 else if (rhptee->hasSignedIntegerRepresentation()) 7916 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7917 7918 if (ltrans == rtrans) { 7919 // Types are compatible ignoring the sign. Qualifier incompatibility 7920 // takes priority over sign incompatibility because the sign 7921 // warning can be disabled. 7922 if (ConvTy != Sema::Compatible) 7923 return ConvTy; 7924 7925 return Sema::IncompatiblePointerSign; 7926 } 7927 7928 // If we are a multi-level pointer, it's possible that our issue is simply 7929 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7930 // the eventual target type is the same and the pointers have the same 7931 // level of indirection, this must be the issue. 7932 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7933 do { 7934 std::tie(lhptee, lhq) = 7935 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 7936 std::tie(rhptee, rhq) = 7937 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 7938 7939 // Inconsistent address spaces at this point is invalid, even if the 7940 // address spaces would be compatible. 7941 // FIXME: This doesn't catch address space mismatches for pointers of 7942 // different nesting levels, like: 7943 // __local int *** a; 7944 // int ** b = a; 7945 // It's not clear how to actually determine when such pointers are 7946 // invalidly incompatible. 7947 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 7948 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 7949 7950 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7951 7952 if (lhptee == rhptee) 7953 return Sema::IncompatibleNestedPointerQualifiers; 7954 } 7955 7956 // General pointer incompatibility takes priority over qualifiers. 7957 return Sema::IncompatiblePointer; 7958 } 7959 if (!S.getLangOpts().CPlusPlus && 7960 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7961 return Sema::IncompatiblePointer; 7962 return ConvTy; 7963 } 7964 7965 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7966 /// block pointer types are compatible or whether a block and normal pointer 7967 /// are compatible. It is more restrict than comparing two function pointer 7968 // types. 7969 static Sema::AssignConvertType 7970 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7971 QualType RHSType) { 7972 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7973 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7974 7975 QualType lhptee, rhptee; 7976 7977 // get the "pointed to" type (ignoring qualifiers at the top level) 7978 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7979 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7980 7981 // In C++, the types have to match exactly. 7982 if (S.getLangOpts().CPlusPlus) 7983 return Sema::IncompatibleBlockPointer; 7984 7985 Sema::AssignConvertType ConvTy = Sema::Compatible; 7986 7987 // For blocks we enforce that qualifiers are identical. 7988 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7989 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7990 if (S.getLangOpts().OpenCL) { 7991 LQuals.removeAddressSpace(); 7992 RQuals.removeAddressSpace(); 7993 } 7994 if (LQuals != RQuals) 7995 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7996 7997 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7998 // assignment. 7999 // The current behavior is similar to C++ lambdas. A block might be 8000 // assigned to a variable iff its return type and parameters are compatible 8001 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8002 // an assignment. Presumably it should behave in way that a function pointer 8003 // assignment does in C, so for each parameter and return type: 8004 // * CVR and address space of LHS should be a superset of CVR and address 8005 // space of RHS. 8006 // * unqualified types should be compatible. 8007 if (S.getLangOpts().OpenCL) { 8008 if (!S.Context.typesAreBlockPointerCompatible( 8009 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8010 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8011 return Sema::IncompatibleBlockPointer; 8012 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8013 return Sema::IncompatibleBlockPointer; 8014 8015 return ConvTy; 8016 } 8017 8018 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8019 /// for assignment compatibility. 8020 static Sema::AssignConvertType 8021 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8022 QualType RHSType) { 8023 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8024 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8025 8026 if (LHSType->isObjCBuiltinType()) { 8027 // Class is not compatible with ObjC object pointers. 8028 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8029 !RHSType->isObjCQualifiedClassType()) 8030 return Sema::IncompatiblePointer; 8031 return Sema::Compatible; 8032 } 8033 if (RHSType->isObjCBuiltinType()) { 8034 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8035 !LHSType->isObjCQualifiedClassType()) 8036 return Sema::IncompatiblePointer; 8037 return Sema::Compatible; 8038 } 8039 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 8040 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 8041 8042 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8043 // make an exception for id<P> 8044 !LHSType->isObjCQualifiedIdType()) 8045 return Sema::CompatiblePointerDiscardsQualifiers; 8046 8047 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8048 return Sema::Compatible; 8049 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8050 return Sema::IncompatibleObjCQualifiedId; 8051 return Sema::IncompatiblePointer; 8052 } 8053 8054 Sema::AssignConvertType 8055 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8056 QualType LHSType, QualType RHSType) { 8057 // Fake up an opaque expression. We don't actually care about what 8058 // cast operations are required, so if CheckAssignmentConstraints 8059 // adds casts to this they'll be wasted, but fortunately that doesn't 8060 // usually happen on valid code. 8061 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8062 ExprResult RHSPtr = &RHSExpr; 8063 CastKind K; 8064 8065 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8066 } 8067 8068 /// This helper function returns true if QT is a vector type that has element 8069 /// type ElementType. 8070 static bool isVector(QualType QT, QualType ElementType) { 8071 if (const VectorType *VT = QT->getAs<VectorType>()) 8072 return VT->getElementType() == ElementType; 8073 return false; 8074 } 8075 8076 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8077 /// has code to accommodate several GCC extensions when type checking 8078 /// pointers. Here are some objectionable examples that GCC considers warnings: 8079 /// 8080 /// int a, *pint; 8081 /// short *pshort; 8082 /// struct foo *pfoo; 8083 /// 8084 /// pint = pshort; // warning: assignment from incompatible pointer type 8085 /// a = pint; // warning: assignment makes integer from pointer without a cast 8086 /// pint = a; // warning: assignment makes pointer from integer without a cast 8087 /// pint = pfoo; // warning: assignment from incompatible pointer type 8088 /// 8089 /// As a result, the code for dealing with pointers is more complex than the 8090 /// C99 spec dictates. 8091 /// 8092 /// Sets 'Kind' for any result kind except Incompatible. 8093 Sema::AssignConvertType 8094 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8095 CastKind &Kind, bool ConvertRHS) { 8096 QualType RHSType = RHS.get()->getType(); 8097 QualType OrigLHSType = LHSType; 8098 8099 // Get canonical types. We're not formatting these types, just comparing 8100 // them. 8101 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8102 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8103 8104 // Common case: no conversion required. 8105 if (LHSType == RHSType) { 8106 Kind = CK_NoOp; 8107 return Compatible; 8108 } 8109 8110 // If we have an atomic type, try a non-atomic assignment, then just add an 8111 // atomic qualification step. 8112 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8113 Sema::AssignConvertType result = 8114 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8115 if (result != Compatible) 8116 return result; 8117 if (Kind != CK_NoOp && ConvertRHS) 8118 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8119 Kind = CK_NonAtomicToAtomic; 8120 return Compatible; 8121 } 8122 8123 // If the left-hand side is a reference type, then we are in a 8124 // (rare!) case where we've allowed the use of references in C, 8125 // e.g., as a parameter type in a built-in function. In this case, 8126 // just make sure that the type referenced is compatible with the 8127 // right-hand side type. The caller is responsible for adjusting 8128 // LHSType so that the resulting expression does not have reference 8129 // type. 8130 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8131 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8132 Kind = CK_LValueBitCast; 8133 return Compatible; 8134 } 8135 return Incompatible; 8136 } 8137 8138 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8139 // to the same ExtVector type. 8140 if (LHSType->isExtVectorType()) { 8141 if (RHSType->isExtVectorType()) 8142 return Incompatible; 8143 if (RHSType->isArithmeticType()) { 8144 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8145 if (ConvertRHS) 8146 RHS = prepareVectorSplat(LHSType, RHS.get()); 8147 Kind = CK_VectorSplat; 8148 return Compatible; 8149 } 8150 } 8151 8152 // Conversions to or from vector type. 8153 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8154 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8155 // Allow assignments of an AltiVec vector type to an equivalent GCC 8156 // vector type and vice versa 8157 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8158 Kind = CK_BitCast; 8159 return Compatible; 8160 } 8161 8162 // If we are allowing lax vector conversions, and LHS and RHS are both 8163 // vectors, the total size only needs to be the same. This is a bitcast; 8164 // no bits are changed but the result type is different. 8165 if (isLaxVectorConversion(RHSType, LHSType)) { 8166 Kind = CK_BitCast; 8167 return IncompatibleVectors; 8168 } 8169 } 8170 8171 // When the RHS comes from another lax conversion (e.g. binops between 8172 // scalars and vectors) the result is canonicalized as a vector. When the 8173 // LHS is also a vector, the lax is allowed by the condition above. Handle 8174 // the case where LHS is a scalar. 8175 if (LHSType->isScalarType()) { 8176 const VectorType *VecType = RHSType->getAs<VectorType>(); 8177 if (VecType && VecType->getNumElements() == 1 && 8178 isLaxVectorConversion(RHSType, LHSType)) { 8179 ExprResult *VecExpr = &RHS; 8180 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8181 Kind = CK_BitCast; 8182 return Compatible; 8183 } 8184 } 8185 8186 return Incompatible; 8187 } 8188 8189 // Diagnose attempts to convert between __float128 and long double where 8190 // such conversions currently can't be handled. 8191 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8192 return Incompatible; 8193 8194 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8195 // discards the imaginary part. 8196 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8197 !LHSType->getAs<ComplexType>()) 8198 return Incompatible; 8199 8200 // Arithmetic conversions. 8201 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8202 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8203 if (ConvertRHS) 8204 Kind = PrepareScalarCast(RHS, LHSType); 8205 return Compatible; 8206 } 8207 8208 // Conversions to normal pointers. 8209 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8210 // U* -> T* 8211 if (isa<PointerType>(RHSType)) { 8212 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8213 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8214 if (AddrSpaceL != AddrSpaceR) 8215 Kind = CK_AddressSpaceConversion; 8216 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8217 Kind = CK_NoOp; 8218 else 8219 Kind = CK_BitCast; 8220 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8221 } 8222 8223 // int -> T* 8224 if (RHSType->isIntegerType()) { 8225 Kind = CK_IntegralToPointer; // FIXME: null? 8226 return IntToPointer; 8227 } 8228 8229 // C pointers are not compatible with ObjC object pointers, 8230 // with two exceptions: 8231 if (isa<ObjCObjectPointerType>(RHSType)) { 8232 // - conversions to void* 8233 if (LHSPointer->getPointeeType()->isVoidType()) { 8234 Kind = CK_BitCast; 8235 return Compatible; 8236 } 8237 8238 // - conversions from 'Class' to the redefinition type 8239 if (RHSType->isObjCClassType() && 8240 Context.hasSameType(LHSType, 8241 Context.getObjCClassRedefinitionType())) { 8242 Kind = CK_BitCast; 8243 return Compatible; 8244 } 8245 8246 Kind = CK_BitCast; 8247 return IncompatiblePointer; 8248 } 8249 8250 // U^ -> void* 8251 if (RHSType->getAs<BlockPointerType>()) { 8252 if (LHSPointer->getPointeeType()->isVoidType()) { 8253 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8254 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8255 ->getPointeeType() 8256 .getAddressSpace(); 8257 Kind = 8258 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8259 return Compatible; 8260 } 8261 } 8262 8263 return Incompatible; 8264 } 8265 8266 // Conversions to block pointers. 8267 if (isa<BlockPointerType>(LHSType)) { 8268 // U^ -> T^ 8269 if (RHSType->isBlockPointerType()) { 8270 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8271 ->getPointeeType() 8272 .getAddressSpace(); 8273 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8274 ->getPointeeType() 8275 .getAddressSpace(); 8276 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8277 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8278 } 8279 8280 // int or null -> T^ 8281 if (RHSType->isIntegerType()) { 8282 Kind = CK_IntegralToPointer; // FIXME: null 8283 return IntToBlockPointer; 8284 } 8285 8286 // id -> T^ 8287 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8288 Kind = CK_AnyPointerToBlockPointerCast; 8289 return Compatible; 8290 } 8291 8292 // void* -> T^ 8293 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8294 if (RHSPT->getPointeeType()->isVoidType()) { 8295 Kind = CK_AnyPointerToBlockPointerCast; 8296 return Compatible; 8297 } 8298 8299 return Incompatible; 8300 } 8301 8302 // Conversions to Objective-C pointers. 8303 if (isa<ObjCObjectPointerType>(LHSType)) { 8304 // A* -> B* 8305 if (RHSType->isObjCObjectPointerType()) { 8306 Kind = CK_BitCast; 8307 Sema::AssignConvertType result = 8308 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8309 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8310 result == Compatible && 8311 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8312 result = IncompatibleObjCWeakRef; 8313 return result; 8314 } 8315 8316 // int or null -> A* 8317 if (RHSType->isIntegerType()) { 8318 Kind = CK_IntegralToPointer; // FIXME: null 8319 return IntToPointer; 8320 } 8321 8322 // In general, C pointers are not compatible with ObjC object pointers, 8323 // with two exceptions: 8324 if (isa<PointerType>(RHSType)) { 8325 Kind = CK_CPointerToObjCPointerCast; 8326 8327 // - conversions from 'void*' 8328 if (RHSType->isVoidPointerType()) { 8329 return Compatible; 8330 } 8331 8332 // - conversions to 'Class' from its redefinition type 8333 if (LHSType->isObjCClassType() && 8334 Context.hasSameType(RHSType, 8335 Context.getObjCClassRedefinitionType())) { 8336 return Compatible; 8337 } 8338 8339 return IncompatiblePointer; 8340 } 8341 8342 // Only under strict condition T^ is compatible with an Objective-C pointer. 8343 if (RHSType->isBlockPointerType() && 8344 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8345 if (ConvertRHS) 8346 maybeExtendBlockObject(RHS); 8347 Kind = CK_BlockPointerToObjCPointerCast; 8348 return Compatible; 8349 } 8350 8351 return Incompatible; 8352 } 8353 8354 // Conversions from pointers that are not covered by the above. 8355 if (isa<PointerType>(RHSType)) { 8356 // T* -> _Bool 8357 if (LHSType == Context.BoolTy) { 8358 Kind = CK_PointerToBoolean; 8359 return Compatible; 8360 } 8361 8362 // T* -> int 8363 if (LHSType->isIntegerType()) { 8364 Kind = CK_PointerToIntegral; 8365 return PointerToInt; 8366 } 8367 8368 return Incompatible; 8369 } 8370 8371 // Conversions from Objective-C pointers that are not covered by the above. 8372 if (isa<ObjCObjectPointerType>(RHSType)) { 8373 // T* -> _Bool 8374 if (LHSType == Context.BoolTy) { 8375 Kind = CK_PointerToBoolean; 8376 return Compatible; 8377 } 8378 8379 // T* -> int 8380 if (LHSType->isIntegerType()) { 8381 Kind = CK_PointerToIntegral; 8382 return PointerToInt; 8383 } 8384 8385 return Incompatible; 8386 } 8387 8388 // struct A -> struct B 8389 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8390 if (Context.typesAreCompatible(LHSType, RHSType)) { 8391 Kind = CK_NoOp; 8392 return Compatible; 8393 } 8394 } 8395 8396 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8397 Kind = CK_IntToOCLSampler; 8398 return Compatible; 8399 } 8400 8401 return Incompatible; 8402 } 8403 8404 /// Constructs a transparent union from an expression that is 8405 /// used to initialize the transparent union. 8406 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8407 ExprResult &EResult, QualType UnionType, 8408 FieldDecl *Field) { 8409 // Build an initializer list that designates the appropriate member 8410 // of the transparent union. 8411 Expr *E = EResult.get(); 8412 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8413 E, SourceLocation()); 8414 Initializer->setType(UnionType); 8415 Initializer->setInitializedFieldInUnion(Field); 8416 8417 // Build a compound literal constructing a value of the transparent 8418 // union type from this initializer list. 8419 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8420 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8421 VK_RValue, Initializer, false); 8422 } 8423 8424 Sema::AssignConvertType 8425 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8426 ExprResult &RHS) { 8427 QualType RHSType = RHS.get()->getType(); 8428 8429 // If the ArgType is a Union type, we want to handle a potential 8430 // transparent_union GCC extension. 8431 const RecordType *UT = ArgType->getAsUnionType(); 8432 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8433 return Incompatible; 8434 8435 // The field to initialize within the transparent union. 8436 RecordDecl *UD = UT->getDecl(); 8437 FieldDecl *InitField = nullptr; 8438 // It's compatible if the expression matches any of the fields. 8439 for (auto *it : UD->fields()) { 8440 if (it->getType()->isPointerType()) { 8441 // If the transparent union contains a pointer type, we allow: 8442 // 1) void pointer 8443 // 2) null pointer constant 8444 if (RHSType->isPointerType()) 8445 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8446 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8447 InitField = it; 8448 break; 8449 } 8450 8451 if (RHS.get()->isNullPointerConstant(Context, 8452 Expr::NPC_ValueDependentIsNull)) { 8453 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8454 CK_NullToPointer); 8455 InitField = it; 8456 break; 8457 } 8458 } 8459 8460 CastKind Kind; 8461 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8462 == Compatible) { 8463 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8464 InitField = it; 8465 break; 8466 } 8467 } 8468 8469 if (!InitField) 8470 return Incompatible; 8471 8472 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8473 return Compatible; 8474 } 8475 8476 Sema::AssignConvertType 8477 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8478 bool Diagnose, 8479 bool DiagnoseCFAudited, 8480 bool ConvertRHS) { 8481 // We need to be able to tell the caller whether we diagnosed a problem, if 8482 // they ask us to issue diagnostics. 8483 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8484 8485 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8486 // we can't avoid *all* modifications at the moment, so we need some somewhere 8487 // to put the updated value. 8488 ExprResult LocalRHS = CallerRHS; 8489 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8490 8491 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8492 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8493 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8494 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8495 Diag(RHS.get()->getExprLoc(), 8496 diag::warn_noderef_to_dereferenceable_pointer) 8497 << RHS.get()->getSourceRange(); 8498 } 8499 } 8500 } 8501 8502 if (getLangOpts().CPlusPlus) { 8503 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8504 // C++ 5.17p3: If the left operand is not of class type, the 8505 // expression is implicitly converted (C++ 4) to the 8506 // cv-unqualified type of the left operand. 8507 QualType RHSType = RHS.get()->getType(); 8508 if (Diagnose) { 8509 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8510 AA_Assigning); 8511 } else { 8512 ImplicitConversionSequence ICS = 8513 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8514 /*SuppressUserConversions=*/false, 8515 /*AllowExplicit=*/false, 8516 /*InOverloadResolution=*/false, 8517 /*CStyle=*/false, 8518 /*AllowObjCWritebackConversion=*/false); 8519 if (ICS.isFailure()) 8520 return Incompatible; 8521 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8522 ICS, AA_Assigning); 8523 } 8524 if (RHS.isInvalid()) 8525 return Incompatible; 8526 Sema::AssignConvertType result = Compatible; 8527 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8528 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8529 result = IncompatibleObjCWeakRef; 8530 return result; 8531 } 8532 8533 // FIXME: Currently, we fall through and treat C++ classes like C 8534 // structures. 8535 // FIXME: We also fall through for atomics; not sure what should 8536 // happen there, though. 8537 } else if (RHS.get()->getType() == Context.OverloadTy) { 8538 // As a set of extensions to C, we support overloading on functions. These 8539 // functions need to be resolved here. 8540 DeclAccessPair DAP; 8541 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8542 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8543 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8544 else 8545 return Incompatible; 8546 } 8547 8548 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8549 // a null pointer constant. 8550 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8551 LHSType->isBlockPointerType()) && 8552 RHS.get()->isNullPointerConstant(Context, 8553 Expr::NPC_ValueDependentIsNull)) { 8554 if (Diagnose || ConvertRHS) { 8555 CastKind Kind; 8556 CXXCastPath Path; 8557 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8558 /*IgnoreBaseAccess=*/false, Diagnose); 8559 if (ConvertRHS) 8560 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8561 } 8562 return Compatible; 8563 } 8564 8565 // OpenCL queue_t type assignment. 8566 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8567 Context, Expr::NPC_ValueDependentIsNull)) { 8568 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8569 return Compatible; 8570 } 8571 8572 // This check seems unnatural, however it is necessary to ensure the proper 8573 // conversion of functions/arrays. If the conversion were done for all 8574 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8575 // expressions that suppress this implicit conversion (&, sizeof). 8576 // 8577 // Suppress this for references: C++ 8.5.3p5. 8578 if (!LHSType->isReferenceType()) { 8579 // FIXME: We potentially allocate here even if ConvertRHS is false. 8580 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8581 if (RHS.isInvalid()) 8582 return Incompatible; 8583 } 8584 CastKind Kind; 8585 Sema::AssignConvertType result = 8586 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8587 8588 // C99 6.5.16.1p2: The value of the right operand is converted to the 8589 // type of the assignment expression. 8590 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8591 // so that we can use references in built-in functions even in C. 8592 // The getNonReferenceType() call makes sure that the resulting expression 8593 // does not have reference type. 8594 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8595 QualType Ty = LHSType.getNonLValueExprType(Context); 8596 Expr *E = RHS.get(); 8597 8598 // Check for various Objective-C errors. If we are not reporting 8599 // diagnostics and just checking for errors, e.g., during overload 8600 // resolution, return Incompatible to indicate the failure. 8601 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8602 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8603 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8604 if (!Diagnose) 8605 return Incompatible; 8606 } 8607 if (getLangOpts().ObjC && 8608 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8609 E->getType(), E, Diagnose) || 8610 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8611 if (!Diagnose) 8612 return Incompatible; 8613 // Replace the expression with a corrected version and continue so we 8614 // can find further errors. 8615 RHS = E; 8616 return Compatible; 8617 } 8618 8619 if (ConvertRHS) 8620 RHS = ImpCastExprToType(E, Ty, Kind); 8621 } 8622 8623 return result; 8624 } 8625 8626 namespace { 8627 /// The original operand to an operator, prior to the application of the usual 8628 /// arithmetic conversions and converting the arguments of a builtin operator 8629 /// candidate. 8630 struct OriginalOperand { 8631 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8632 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8633 Op = MTE->GetTemporaryExpr(); 8634 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8635 Op = BTE->getSubExpr(); 8636 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8637 Orig = ICE->getSubExprAsWritten(); 8638 Conversion = ICE->getConversionFunction(); 8639 } 8640 } 8641 8642 QualType getType() const { return Orig->getType(); } 8643 8644 Expr *Orig; 8645 NamedDecl *Conversion; 8646 }; 8647 } 8648 8649 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8650 ExprResult &RHS) { 8651 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8652 8653 Diag(Loc, diag::err_typecheck_invalid_operands) 8654 << OrigLHS.getType() << OrigRHS.getType() 8655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8656 8657 // If a user-defined conversion was applied to either of the operands prior 8658 // to applying the built-in operator rules, tell the user about it. 8659 if (OrigLHS.Conversion) { 8660 Diag(OrigLHS.Conversion->getLocation(), 8661 diag::note_typecheck_invalid_operands_converted) 8662 << 0 << LHS.get()->getType(); 8663 } 8664 if (OrigRHS.Conversion) { 8665 Diag(OrigRHS.Conversion->getLocation(), 8666 diag::note_typecheck_invalid_operands_converted) 8667 << 1 << RHS.get()->getType(); 8668 } 8669 8670 return QualType(); 8671 } 8672 8673 // Diagnose cases where a scalar was implicitly converted to a vector and 8674 // diagnose the underlying types. Otherwise, diagnose the error 8675 // as invalid vector logical operands for non-C++ cases. 8676 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8677 ExprResult &RHS) { 8678 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8679 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8680 8681 bool LHSNatVec = LHSType->isVectorType(); 8682 bool RHSNatVec = RHSType->isVectorType(); 8683 8684 if (!(LHSNatVec && RHSNatVec)) { 8685 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8686 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8687 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8688 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8689 << Vector->getSourceRange(); 8690 return QualType(); 8691 } 8692 8693 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8694 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8695 << RHS.get()->getSourceRange(); 8696 8697 return QualType(); 8698 } 8699 8700 /// Try to convert a value of non-vector type to a vector type by converting 8701 /// the type to the element type of the vector and then performing a splat. 8702 /// If the language is OpenCL, we only use conversions that promote scalar 8703 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8704 /// for float->int. 8705 /// 8706 /// OpenCL V2.0 6.2.6.p2: 8707 /// An error shall occur if any scalar operand type has greater rank 8708 /// than the type of the vector element. 8709 /// 8710 /// \param scalar - if non-null, actually perform the conversions 8711 /// \return true if the operation fails (but without diagnosing the failure) 8712 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8713 QualType scalarTy, 8714 QualType vectorEltTy, 8715 QualType vectorTy, 8716 unsigned &DiagID) { 8717 // The conversion to apply to the scalar before splatting it, 8718 // if necessary. 8719 CastKind scalarCast = CK_NoOp; 8720 8721 if (vectorEltTy->isIntegralType(S.Context)) { 8722 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8723 (scalarTy->isIntegerType() && 8724 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8725 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8726 return true; 8727 } 8728 if (!scalarTy->isIntegralType(S.Context)) 8729 return true; 8730 scalarCast = CK_IntegralCast; 8731 } else if (vectorEltTy->isRealFloatingType()) { 8732 if (scalarTy->isRealFloatingType()) { 8733 if (S.getLangOpts().OpenCL && 8734 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8735 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8736 return true; 8737 } 8738 scalarCast = CK_FloatingCast; 8739 } 8740 else if (scalarTy->isIntegralType(S.Context)) 8741 scalarCast = CK_IntegralToFloating; 8742 else 8743 return true; 8744 } else { 8745 return true; 8746 } 8747 8748 // Adjust scalar if desired. 8749 if (scalar) { 8750 if (scalarCast != CK_NoOp) 8751 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8752 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8753 } 8754 return false; 8755 } 8756 8757 /// Convert vector E to a vector with the same number of elements but different 8758 /// element type. 8759 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8760 const auto *VecTy = E->getType()->getAs<VectorType>(); 8761 assert(VecTy && "Expression E must be a vector"); 8762 QualType NewVecTy = S.Context.getVectorType(ElementType, 8763 VecTy->getNumElements(), 8764 VecTy->getVectorKind()); 8765 8766 // Look through the implicit cast. Return the subexpression if its type is 8767 // NewVecTy. 8768 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8769 if (ICE->getSubExpr()->getType() == NewVecTy) 8770 return ICE->getSubExpr(); 8771 8772 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8773 return S.ImpCastExprToType(E, NewVecTy, Cast); 8774 } 8775 8776 /// Test if a (constant) integer Int can be casted to another integer type 8777 /// IntTy without losing precision. 8778 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8779 QualType OtherIntTy) { 8780 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8781 8782 // Reject cases where the value of the Int is unknown as that would 8783 // possibly cause truncation, but accept cases where the scalar can be 8784 // demoted without loss of precision. 8785 Expr::EvalResult EVResult; 8786 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8787 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8788 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8789 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8790 8791 if (CstInt) { 8792 // If the scalar is constant and is of a higher order and has more active 8793 // bits that the vector element type, reject it. 8794 llvm::APSInt Result = EVResult.Val.getInt(); 8795 unsigned NumBits = IntSigned 8796 ? (Result.isNegative() ? Result.getMinSignedBits() 8797 : Result.getActiveBits()) 8798 : Result.getActiveBits(); 8799 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8800 return true; 8801 8802 // If the signedness of the scalar type and the vector element type 8803 // differs and the number of bits is greater than that of the vector 8804 // element reject it. 8805 return (IntSigned != OtherIntSigned && 8806 NumBits > S.Context.getIntWidth(OtherIntTy)); 8807 } 8808 8809 // Reject cases where the value of the scalar is not constant and it's 8810 // order is greater than that of the vector element type. 8811 return (Order < 0); 8812 } 8813 8814 /// Test if a (constant) integer Int can be casted to floating point type 8815 /// FloatTy without losing precision. 8816 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8817 QualType FloatTy) { 8818 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8819 8820 // Determine if the integer constant can be expressed as a floating point 8821 // number of the appropriate type. 8822 Expr::EvalResult EVResult; 8823 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8824 8825 uint64_t Bits = 0; 8826 if (CstInt) { 8827 // Reject constants that would be truncated if they were converted to 8828 // the floating point type. Test by simple to/from conversion. 8829 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8830 // could be avoided if there was a convertFromAPInt method 8831 // which could signal back if implicit truncation occurred. 8832 llvm::APSInt Result = EVResult.Val.getInt(); 8833 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8834 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8835 llvm::APFloat::rmTowardZero); 8836 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8837 !IntTy->hasSignedIntegerRepresentation()); 8838 bool Ignored = false; 8839 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8840 &Ignored); 8841 if (Result != ConvertBack) 8842 return true; 8843 } else { 8844 // Reject types that cannot be fully encoded into the mantissa of 8845 // the float. 8846 Bits = S.Context.getTypeSize(IntTy); 8847 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8848 S.Context.getFloatTypeSemantics(FloatTy)); 8849 if (Bits > FloatPrec) 8850 return true; 8851 } 8852 8853 return false; 8854 } 8855 8856 /// Attempt to convert and splat Scalar into a vector whose types matches 8857 /// Vector following GCC conversion rules. The rule is that implicit 8858 /// conversion can occur when Scalar can be casted to match Vector's element 8859 /// type without causing truncation of Scalar. 8860 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8861 ExprResult *Vector) { 8862 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8863 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8864 const VectorType *VT = VectorTy->getAs<VectorType>(); 8865 8866 assert(!isa<ExtVectorType>(VT) && 8867 "ExtVectorTypes should not be handled here!"); 8868 8869 QualType VectorEltTy = VT->getElementType(); 8870 8871 // Reject cases where the vector element type or the scalar element type are 8872 // not integral or floating point types. 8873 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8874 return true; 8875 8876 // The conversion to apply to the scalar before splatting it, 8877 // if necessary. 8878 CastKind ScalarCast = CK_NoOp; 8879 8880 // Accept cases where the vector elements are integers and the scalar is 8881 // an integer. 8882 // FIXME: Notionally if the scalar was a floating point value with a precise 8883 // integral representation, we could cast it to an appropriate integer 8884 // type and then perform the rest of the checks here. GCC will perform 8885 // this conversion in some cases as determined by the input language. 8886 // We should accept it on a language independent basis. 8887 if (VectorEltTy->isIntegralType(S.Context) && 8888 ScalarTy->isIntegralType(S.Context) && 8889 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8890 8891 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8892 return true; 8893 8894 ScalarCast = CK_IntegralCast; 8895 } else if (VectorEltTy->isRealFloatingType()) { 8896 if (ScalarTy->isRealFloatingType()) { 8897 8898 // Reject cases where the scalar type is not a constant and has a higher 8899 // Order than the vector element type. 8900 llvm::APFloat Result(0.0); 8901 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8902 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8903 if (!CstScalar && Order < 0) 8904 return true; 8905 8906 // If the scalar cannot be safely casted to the vector element type, 8907 // reject it. 8908 if (CstScalar) { 8909 bool Truncated = false; 8910 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8911 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8912 if (Truncated) 8913 return true; 8914 } 8915 8916 ScalarCast = CK_FloatingCast; 8917 } else if (ScalarTy->isIntegralType(S.Context)) { 8918 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8919 return true; 8920 8921 ScalarCast = CK_IntegralToFloating; 8922 } else 8923 return true; 8924 } 8925 8926 // Adjust scalar if desired. 8927 if (Scalar) { 8928 if (ScalarCast != CK_NoOp) 8929 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8930 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8931 } 8932 return false; 8933 } 8934 8935 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8936 SourceLocation Loc, bool IsCompAssign, 8937 bool AllowBothBool, 8938 bool AllowBoolConversions) { 8939 if (!IsCompAssign) { 8940 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8941 if (LHS.isInvalid()) 8942 return QualType(); 8943 } 8944 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8945 if (RHS.isInvalid()) 8946 return QualType(); 8947 8948 // For conversion purposes, we ignore any qualifiers. 8949 // For example, "const float" and "float" are equivalent. 8950 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8951 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8952 8953 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8954 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8955 assert(LHSVecType || RHSVecType); 8956 8957 // AltiVec-style "vector bool op vector bool" combinations are allowed 8958 // for some operators but not others. 8959 if (!AllowBothBool && 8960 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8961 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8962 return InvalidOperands(Loc, LHS, RHS); 8963 8964 // If the vector types are identical, return. 8965 if (Context.hasSameType(LHSType, RHSType)) 8966 return LHSType; 8967 8968 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8969 if (LHSVecType && RHSVecType && 8970 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8971 if (isa<ExtVectorType>(LHSVecType)) { 8972 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8973 return LHSType; 8974 } 8975 8976 if (!IsCompAssign) 8977 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8978 return RHSType; 8979 } 8980 8981 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8982 // can be mixed, with the result being the non-bool type. The non-bool 8983 // operand must have integer element type. 8984 if (AllowBoolConversions && LHSVecType && RHSVecType && 8985 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8986 (Context.getTypeSize(LHSVecType->getElementType()) == 8987 Context.getTypeSize(RHSVecType->getElementType()))) { 8988 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8989 LHSVecType->getElementType()->isIntegerType() && 8990 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8991 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8992 return LHSType; 8993 } 8994 if (!IsCompAssign && 8995 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8996 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8997 RHSVecType->getElementType()->isIntegerType()) { 8998 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8999 return RHSType; 9000 } 9001 } 9002 9003 // If there's a vector type and a scalar, try to convert the scalar to 9004 // the vector element type and splat. 9005 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9006 if (!RHSVecType) { 9007 if (isa<ExtVectorType>(LHSVecType)) { 9008 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9009 LHSVecType->getElementType(), LHSType, 9010 DiagID)) 9011 return LHSType; 9012 } else { 9013 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9014 return LHSType; 9015 } 9016 } 9017 if (!LHSVecType) { 9018 if (isa<ExtVectorType>(RHSVecType)) { 9019 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9020 LHSType, RHSVecType->getElementType(), 9021 RHSType, DiagID)) 9022 return RHSType; 9023 } else { 9024 if (LHS.get()->getValueKind() == VK_LValue || 9025 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9026 return RHSType; 9027 } 9028 } 9029 9030 // FIXME: The code below also handles conversion between vectors and 9031 // non-scalars, we should break this down into fine grained specific checks 9032 // and emit proper diagnostics. 9033 QualType VecType = LHSVecType ? LHSType : RHSType; 9034 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9035 QualType OtherType = LHSVecType ? RHSType : LHSType; 9036 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9037 if (isLaxVectorConversion(OtherType, VecType)) { 9038 // If we're allowing lax vector conversions, only the total (data) size 9039 // needs to be the same. For non compound assignment, if one of the types is 9040 // scalar, the result is always the vector type. 9041 if (!IsCompAssign) { 9042 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9043 return VecType; 9044 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9045 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9046 // type. Note that this is already done by non-compound assignments in 9047 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9048 // <1 x T> -> T. The result is also a vector type. 9049 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9050 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9051 ExprResult *RHSExpr = &RHS; 9052 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9053 return VecType; 9054 } 9055 } 9056 9057 // Okay, the expression is invalid. 9058 9059 // If there's a non-vector, non-real operand, diagnose that. 9060 if ((!RHSVecType && !RHSType->isRealType()) || 9061 (!LHSVecType && !LHSType->isRealType())) { 9062 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9063 << LHSType << RHSType 9064 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9065 return QualType(); 9066 } 9067 9068 // OpenCL V1.1 6.2.6.p1: 9069 // If the operands are of more than one vector type, then an error shall 9070 // occur. Implicit conversions between vector types are not permitted, per 9071 // section 6.2.1. 9072 if (getLangOpts().OpenCL && 9073 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9074 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9075 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9076 << RHSType; 9077 return QualType(); 9078 } 9079 9080 9081 // If there is a vector type that is not a ExtVector and a scalar, we reach 9082 // this point if scalar could not be converted to the vector's element type 9083 // without truncation. 9084 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9085 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9086 QualType Scalar = LHSVecType ? RHSType : LHSType; 9087 QualType Vector = LHSVecType ? LHSType : RHSType; 9088 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9089 Diag(Loc, 9090 diag::err_typecheck_vector_not_convertable_implict_truncation) 9091 << ScalarOrVector << Scalar << Vector; 9092 9093 return QualType(); 9094 } 9095 9096 // Otherwise, use the generic diagnostic. 9097 Diag(Loc, DiagID) 9098 << LHSType << RHSType 9099 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9100 return QualType(); 9101 } 9102 9103 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9104 // expression. These are mainly cases where the null pointer is used as an 9105 // integer instead of a pointer. 9106 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9107 SourceLocation Loc, bool IsCompare) { 9108 // The canonical way to check for a GNU null is with isNullPointerConstant, 9109 // but we use a bit of a hack here for speed; this is a relatively 9110 // hot path, and isNullPointerConstant is slow. 9111 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9112 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9113 9114 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9115 9116 // Avoid analyzing cases where the result will either be invalid (and 9117 // diagnosed as such) or entirely valid and not something to warn about. 9118 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9119 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9120 return; 9121 9122 // Comparison operations would not make sense with a null pointer no matter 9123 // what the other expression is. 9124 if (!IsCompare) { 9125 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9126 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9127 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9128 return; 9129 } 9130 9131 // The rest of the operations only make sense with a null pointer 9132 // if the other expression is a pointer. 9133 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9134 NonNullType->canDecayToPointerType()) 9135 return; 9136 9137 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9138 << LHSNull /* LHS is NULL */ << NonNullType 9139 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9140 } 9141 9142 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9143 SourceLocation Loc) { 9144 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9145 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9146 if (!LUE || !RUE) 9147 return; 9148 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9149 RUE->getKind() != UETT_SizeOf) 9150 return; 9151 9152 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9153 QualType LHSTy = LHSArg->getType(); 9154 QualType RHSTy; 9155 9156 if (RUE->isArgumentType()) 9157 RHSTy = RUE->getArgumentType(); 9158 else 9159 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9160 9161 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9162 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9163 return; 9164 9165 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9166 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9167 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9168 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9169 << LHSArgDecl; 9170 } 9171 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9172 QualType ArrayElemTy = ArrayTy->getElementType(); 9173 if (ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9174 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9175 return; 9176 S.Diag(Loc, diag::warn_division_sizeof_array) 9177 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9178 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9179 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9180 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9181 << LHSArgDecl; 9182 } 9183 } 9184 } 9185 9186 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9187 ExprResult &RHS, 9188 SourceLocation Loc, bool IsDiv) { 9189 // Check for division/remainder by zero. 9190 Expr::EvalResult RHSValue; 9191 if (!RHS.get()->isValueDependent() && 9192 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9193 RHSValue.Val.getInt() == 0) 9194 S.DiagRuntimeBehavior(Loc, RHS.get(), 9195 S.PDiag(diag::warn_remainder_division_by_zero) 9196 << IsDiv << RHS.get()->getSourceRange()); 9197 } 9198 9199 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9200 SourceLocation Loc, 9201 bool IsCompAssign, bool IsDiv) { 9202 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9203 9204 if (LHS.get()->getType()->isVectorType() || 9205 RHS.get()->getType()->isVectorType()) 9206 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9207 /*AllowBothBool*/getLangOpts().AltiVec, 9208 /*AllowBoolConversions*/false); 9209 9210 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9211 if (LHS.isInvalid() || RHS.isInvalid()) 9212 return QualType(); 9213 9214 9215 if (compType.isNull() || !compType->isArithmeticType()) 9216 return InvalidOperands(Loc, LHS, RHS); 9217 if (IsDiv) { 9218 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9219 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9220 } 9221 return compType; 9222 } 9223 9224 QualType Sema::CheckRemainderOperands( 9225 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9226 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9227 9228 if (LHS.get()->getType()->isVectorType() || 9229 RHS.get()->getType()->isVectorType()) { 9230 if (LHS.get()->getType()->hasIntegerRepresentation() && 9231 RHS.get()->getType()->hasIntegerRepresentation()) 9232 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9233 /*AllowBothBool*/getLangOpts().AltiVec, 9234 /*AllowBoolConversions*/false); 9235 return InvalidOperands(Loc, LHS, RHS); 9236 } 9237 9238 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9239 if (LHS.isInvalid() || RHS.isInvalid()) 9240 return QualType(); 9241 9242 if (compType.isNull() || !compType->isIntegerType()) 9243 return InvalidOperands(Loc, LHS, RHS); 9244 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9245 return compType; 9246 } 9247 9248 /// Diagnose invalid arithmetic on two void pointers. 9249 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9250 Expr *LHSExpr, Expr *RHSExpr) { 9251 S.Diag(Loc, S.getLangOpts().CPlusPlus 9252 ? diag::err_typecheck_pointer_arith_void_type 9253 : diag::ext_gnu_void_ptr) 9254 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9255 << RHSExpr->getSourceRange(); 9256 } 9257 9258 /// Diagnose invalid arithmetic on a void pointer. 9259 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9260 Expr *Pointer) { 9261 S.Diag(Loc, S.getLangOpts().CPlusPlus 9262 ? diag::err_typecheck_pointer_arith_void_type 9263 : diag::ext_gnu_void_ptr) 9264 << 0 /* one pointer */ << Pointer->getSourceRange(); 9265 } 9266 9267 /// Diagnose invalid arithmetic on a null pointer. 9268 /// 9269 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9270 /// idiom, which we recognize as a GNU extension. 9271 /// 9272 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9273 Expr *Pointer, bool IsGNUIdiom) { 9274 if (IsGNUIdiom) 9275 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9276 << Pointer->getSourceRange(); 9277 else 9278 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9279 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9280 } 9281 9282 /// Diagnose invalid arithmetic on two function pointers. 9283 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9284 Expr *LHS, Expr *RHS) { 9285 assert(LHS->getType()->isAnyPointerType()); 9286 assert(RHS->getType()->isAnyPointerType()); 9287 S.Diag(Loc, S.getLangOpts().CPlusPlus 9288 ? diag::err_typecheck_pointer_arith_function_type 9289 : diag::ext_gnu_ptr_func_arith) 9290 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9291 // We only show the second type if it differs from the first. 9292 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9293 RHS->getType()) 9294 << RHS->getType()->getPointeeType() 9295 << LHS->getSourceRange() << RHS->getSourceRange(); 9296 } 9297 9298 /// Diagnose invalid arithmetic on a function pointer. 9299 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9300 Expr *Pointer) { 9301 assert(Pointer->getType()->isAnyPointerType()); 9302 S.Diag(Loc, S.getLangOpts().CPlusPlus 9303 ? diag::err_typecheck_pointer_arith_function_type 9304 : diag::ext_gnu_ptr_func_arith) 9305 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9306 << 0 /* one pointer, so only one type */ 9307 << Pointer->getSourceRange(); 9308 } 9309 9310 /// Emit error if Operand is incomplete pointer type 9311 /// 9312 /// \returns True if pointer has incomplete type 9313 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9314 Expr *Operand) { 9315 QualType ResType = Operand->getType(); 9316 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9317 ResType = ResAtomicType->getValueType(); 9318 9319 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9320 QualType PointeeTy = ResType->getPointeeType(); 9321 return S.RequireCompleteType(Loc, PointeeTy, 9322 diag::err_typecheck_arithmetic_incomplete_type, 9323 PointeeTy, Operand->getSourceRange()); 9324 } 9325 9326 /// Check the validity of an arithmetic pointer operand. 9327 /// 9328 /// If the operand has pointer type, this code will check for pointer types 9329 /// which are invalid in arithmetic operations. These will be diagnosed 9330 /// appropriately, including whether or not the use is supported as an 9331 /// extension. 9332 /// 9333 /// \returns True when the operand is valid to use (even if as an extension). 9334 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9335 Expr *Operand) { 9336 QualType ResType = Operand->getType(); 9337 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9338 ResType = ResAtomicType->getValueType(); 9339 9340 if (!ResType->isAnyPointerType()) return true; 9341 9342 QualType PointeeTy = ResType->getPointeeType(); 9343 if (PointeeTy->isVoidType()) { 9344 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9345 return !S.getLangOpts().CPlusPlus; 9346 } 9347 if (PointeeTy->isFunctionType()) { 9348 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9349 return !S.getLangOpts().CPlusPlus; 9350 } 9351 9352 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9353 9354 return true; 9355 } 9356 9357 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9358 /// operands. 9359 /// 9360 /// This routine will diagnose any invalid arithmetic on pointer operands much 9361 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9362 /// for emitting a single diagnostic even for operations where both LHS and RHS 9363 /// are (potentially problematic) pointers. 9364 /// 9365 /// \returns True when the operand is valid to use (even if as an extension). 9366 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9367 Expr *LHSExpr, Expr *RHSExpr) { 9368 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9369 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9370 if (!isLHSPointer && !isRHSPointer) return true; 9371 9372 QualType LHSPointeeTy, RHSPointeeTy; 9373 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9374 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9375 9376 // if both are pointers check if operation is valid wrt address spaces 9377 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9378 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9379 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9380 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9381 S.Diag(Loc, 9382 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9383 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9384 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9385 return false; 9386 } 9387 } 9388 9389 // Check for arithmetic on pointers to incomplete types. 9390 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9391 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9392 if (isLHSVoidPtr || isRHSVoidPtr) { 9393 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9394 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9395 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9396 9397 return !S.getLangOpts().CPlusPlus; 9398 } 9399 9400 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9401 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9402 if (isLHSFuncPtr || isRHSFuncPtr) { 9403 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9404 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9405 RHSExpr); 9406 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9407 9408 return !S.getLangOpts().CPlusPlus; 9409 } 9410 9411 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9412 return false; 9413 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9414 return false; 9415 9416 return true; 9417 } 9418 9419 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9420 /// literal. 9421 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9422 Expr *LHSExpr, Expr *RHSExpr) { 9423 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9424 Expr* IndexExpr = RHSExpr; 9425 if (!StrExpr) { 9426 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9427 IndexExpr = LHSExpr; 9428 } 9429 9430 bool IsStringPlusInt = StrExpr && 9431 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9432 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9433 return; 9434 9435 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9436 Self.Diag(OpLoc, diag::warn_string_plus_int) 9437 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9438 9439 // Only print a fixit for "str" + int, not for int + "str". 9440 if (IndexExpr == RHSExpr) { 9441 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9442 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9443 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9444 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9445 << FixItHint::CreateInsertion(EndLoc, "]"); 9446 } else 9447 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9448 } 9449 9450 /// Emit a warning when adding a char literal to a string. 9451 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9452 Expr *LHSExpr, Expr *RHSExpr) { 9453 const Expr *StringRefExpr = LHSExpr; 9454 const CharacterLiteral *CharExpr = 9455 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9456 9457 if (!CharExpr) { 9458 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9459 StringRefExpr = RHSExpr; 9460 } 9461 9462 if (!CharExpr || !StringRefExpr) 9463 return; 9464 9465 const QualType StringType = StringRefExpr->getType(); 9466 9467 // Return if not a PointerType. 9468 if (!StringType->isAnyPointerType()) 9469 return; 9470 9471 // Return if not a CharacterType. 9472 if (!StringType->getPointeeType()->isAnyCharacterType()) 9473 return; 9474 9475 ASTContext &Ctx = Self.getASTContext(); 9476 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9477 9478 const QualType CharType = CharExpr->getType(); 9479 if (!CharType->isAnyCharacterType() && 9480 CharType->isIntegerType() && 9481 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9482 Self.Diag(OpLoc, diag::warn_string_plus_char) 9483 << DiagRange << Ctx.CharTy; 9484 } else { 9485 Self.Diag(OpLoc, diag::warn_string_plus_char) 9486 << DiagRange << CharExpr->getType(); 9487 } 9488 9489 // Only print a fixit for str + char, not for char + str. 9490 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9491 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9492 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9493 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9494 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9495 << FixItHint::CreateInsertion(EndLoc, "]"); 9496 } else { 9497 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9498 } 9499 } 9500 9501 /// Emit error when two pointers are incompatible. 9502 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9503 Expr *LHSExpr, Expr *RHSExpr) { 9504 assert(LHSExpr->getType()->isAnyPointerType()); 9505 assert(RHSExpr->getType()->isAnyPointerType()); 9506 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9507 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9508 << RHSExpr->getSourceRange(); 9509 } 9510 9511 // C99 6.5.6 9512 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9513 SourceLocation Loc, BinaryOperatorKind Opc, 9514 QualType* CompLHSTy) { 9515 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9516 9517 if (LHS.get()->getType()->isVectorType() || 9518 RHS.get()->getType()->isVectorType()) { 9519 QualType compType = CheckVectorOperands( 9520 LHS, RHS, Loc, CompLHSTy, 9521 /*AllowBothBool*/getLangOpts().AltiVec, 9522 /*AllowBoolConversions*/getLangOpts().ZVector); 9523 if (CompLHSTy) *CompLHSTy = compType; 9524 return compType; 9525 } 9526 9527 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9528 if (LHS.isInvalid() || RHS.isInvalid()) 9529 return QualType(); 9530 9531 // Diagnose "string literal" '+' int and string '+' "char literal". 9532 if (Opc == BO_Add) { 9533 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9534 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9535 } 9536 9537 // handle the common case first (both operands are arithmetic). 9538 if (!compType.isNull() && compType->isArithmeticType()) { 9539 if (CompLHSTy) *CompLHSTy = compType; 9540 return compType; 9541 } 9542 9543 // Type-checking. Ultimately the pointer's going to be in PExp; 9544 // note that we bias towards the LHS being the pointer. 9545 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9546 9547 bool isObjCPointer; 9548 if (PExp->getType()->isPointerType()) { 9549 isObjCPointer = false; 9550 } else if (PExp->getType()->isObjCObjectPointerType()) { 9551 isObjCPointer = true; 9552 } else { 9553 std::swap(PExp, IExp); 9554 if (PExp->getType()->isPointerType()) { 9555 isObjCPointer = false; 9556 } else if (PExp->getType()->isObjCObjectPointerType()) { 9557 isObjCPointer = true; 9558 } else { 9559 return InvalidOperands(Loc, LHS, RHS); 9560 } 9561 } 9562 assert(PExp->getType()->isAnyPointerType()); 9563 9564 if (!IExp->getType()->isIntegerType()) 9565 return InvalidOperands(Loc, LHS, RHS); 9566 9567 // Adding to a null pointer results in undefined behavior. 9568 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9569 Context, Expr::NPC_ValueDependentIsNotNull)) { 9570 // In C++ adding zero to a null pointer is defined. 9571 Expr::EvalResult KnownVal; 9572 if (!getLangOpts().CPlusPlus || 9573 (!IExp->isValueDependent() && 9574 (!IExp->EvaluateAsInt(KnownVal, Context) || 9575 KnownVal.Val.getInt() != 0))) { 9576 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9577 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9578 Context, BO_Add, PExp, IExp); 9579 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9580 } 9581 } 9582 9583 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9584 return QualType(); 9585 9586 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9587 return QualType(); 9588 9589 // Check array bounds for pointer arithemtic 9590 CheckArrayAccess(PExp, IExp); 9591 9592 if (CompLHSTy) { 9593 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9594 if (LHSTy.isNull()) { 9595 LHSTy = LHS.get()->getType(); 9596 if (LHSTy->isPromotableIntegerType()) 9597 LHSTy = Context.getPromotedIntegerType(LHSTy); 9598 } 9599 *CompLHSTy = LHSTy; 9600 } 9601 9602 return PExp->getType(); 9603 } 9604 9605 // C99 6.5.6 9606 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9607 SourceLocation Loc, 9608 QualType* CompLHSTy) { 9609 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9610 9611 if (LHS.get()->getType()->isVectorType() || 9612 RHS.get()->getType()->isVectorType()) { 9613 QualType compType = CheckVectorOperands( 9614 LHS, RHS, Loc, CompLHSTy, 9615 /*AllowBothBool*/getLangOpts().AltiVec, 9616 /*AllowBoolConversions*/getLangOpts().ZVector); 9617 if (CompLHSTy) *CompLHSTy = compType; 9618 return compType; 9619 } 9620 9621 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9622 if (LHS.isInvalid() || RHS.isInvalid()) 9623 return QualType(); 9624 9625 // Enforce type constraints: C99 6.5.6p3. 9626 9627 // Handle the common case first (both operands are arithmetic). 9628 if (!compType.isNull() && compType->isArithmeticType()) { 9629 if (CompLHSTy) *CompLHSTy = compType; 9630 return compType; 9631 } 9632 9633 // Either ptr - int or ptr - ptr. 9634 if (LHS.get()->getType()->isAnyPointerType()) { 9635 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9636 9637 // Diagnose bad cases where we step over interface counts. 9638 if (LHS.get()->getType()->isObjCObjectPointerType() && 9639 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9640 return QualType(); 9641 9642 // The result type of a pointer-int computation is the pointer type. 9643 if (RHS.get()->getType()->isIntegerType()) { 9644 // Subtracting from a null pointer should produce a warning. 9645 // The last argument to the diagnose call says this doesn't match the 9646 // GNU int-to-pointer idiom. 9647 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9648 Expr::NPC_ValueDependentIsNotNull)) { 9649 // In C++ adding zero to a null pointer is defined. 9650 Expr::EvalResult KnownVal; 9651 if (!getLangOpts().CPlusPlus || 9652 (!RHS.get()->isValueDependent() && 9653 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9654 KnownVal.Val.getInt() != 0))) { 9655 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9656 } 9657 } 9658 9659 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9660 return QualType(); 9661 9662 // Check array bounds for pointer arithemtic 9663 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9664 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9665 9666 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9667 return LHS.get()->getType(); 9668 } 9669 9670 // Handle pointer-pointer subtractions. 9671 if (const PointerType *RHSPTy 9672 = RHS.get()->getType()->getAs<PointerType>()) { 9673 QualType rpointee = RHSPTy->getPointeeType(); 9674 9675 if (getLangOpts().CPlusPlus) { 9676 // Pointee types must be the same: C++ [expr.add] 9677 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9678 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9679 } 9680 } else { 9681 // Pointee types must be compatible C99 6.5.6p3 9682 if (!Context.typesAreCompatible( 9683 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9684 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9685 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9686 return QualType(); 9687 } 9688 } 9689 9690 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9691 LHS.get(), RHS.get())) 9692 return QualType(); 9693 9694 // FIXME: Add warnings for nullptr - ptr. 9695 9696 // The pointee type may have zero size. As an extension, a structure or 9697 // union may have zero size or an array may have zero length. In this 9698 // case subtraction does not make sense. 9699 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9700 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9701 if (ElementSize.isZero()) { 9702 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9703 << rpointee.getUnqualifiedType() 9704 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9705 } 9706 } 9707 9708 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9709 return Context.getPointerDiffType(); 9710 } 9711 } 9712 9713 return InvalidOperands(Loc, LHS, RHS); 9714 } 9715 9716 static bool isScopedEnumerationType(QualType T) { 9717 if (const EnumType *ET = T->getAs<EnumType>()) 9718 return ET->getDecl()->isScoped(); 9719 return false; 9720 } 9721 9722 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9723 SourceLocation Loc, BinaryOperatorKind Opc, 9724 QualType LHSType) { 9725 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9726 // so skip remaining warnings as we don't want to modify values within Sema. 9727 if (S.getLangOpts().OpenCL) 9728 return; 9729 9730 // Check right/shifter operand 9731 Expr::EvalResult RHSResult; 9732 if (RHS.get()->isValueDependent() || 9733 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9734 return; 9735 llvm::APSInt Right = RHSResult.Val.getInt(); 9736 9737 if (Right.isNegative()) { 9738 S.DiagRuntimeBehavior(Loc, RHS.get(), 9739 S.PDiag(diag::warn_shift_negative) 9740 << RHS.get()->getSourceRange()); 9741 return; 9742 } 9743 llvm::APInt LeftBits(Right.getBitWidth(), 9744 S.Context.getTypeSize(LHS.get()->getType())); 9745 if (Right.uge(LeftBits)) { 9746 S.DiagRuntimeBehavior(Loc, RHS.get(), 9747 S.PDiag(diag::warn_shift_gt_typewidth) 9748 << RHS.get()->getSourceRange()); 9749 return; 9750 } 9751 if (Opc != BO_Shl) 9752 return; 9753 9754 // When left shifting an ICE which is signed, we can check for overflow which 9755 // according to C++ standards prior to C++2a has undefined behavior 9756 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9757 // more than the maximum value representable in the result type, so never 9758 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9759 // expression is still probably a bug.) 9760 Expr::EvalResult LHSResult; 9761 if (LHS.get()->isValueDependent() || 9762 LHSType->hasUnsignedIntegerRepresentation() || 9763 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9764 return; 9765 llvm::APSInt Left = LHSResult.Val.getInt(); 9766 9767 // If LHS does not have a signed type and non-negative value 9768 // then, the behavior is undefined before C++2a. Warn about it. 9769 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9770 !S.getLangOpts().CPlusPlus2a) { 9771 S.DiagRuntimeBehavior(Loc, LHS.get(), 9772 S.PDiag(diag::warn_shift_lhs_negative) 9773 << LHS.get()->getSourceRange()); 9774 return; 9775 } 9776 9777 llvm::APInt ResultBits = 9778 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9779 if (LeftBits.uge(ResultBits)) 9780 return; 9781 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9782 Result = Result.shl(Right); 9783 9784 // Print the bit representation of the signed integer as an unsigned 9785 // hexadecimal number. 9786 SmallString<40> HexResult; 9787 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9788 9789 // If we are only missing a sign bit, this is less likely to result in actual 9790 // bugs -- if the result is cast back to an unsigned type, it will have the 9791 // expected value. Thus we place this behind a different warning that can be 9792 // turned off separately if needed. 9793 if (LeftBits == ResultBits - 1) { 9794 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9795 << HexResult << LHSType 9796 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9797 return; 9798 } 9799 9800 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9801 << HexResult.str() << Result.getMinSignedBits() << LHSType 9802 << Left.getBitWidth() << LHS.get()->getSourceRange() 9803 << RHS.get()->getSourceRange(); 9804 } 9805 9806 /// Return the resulting type when a vector is shifted 9807 /// by a scalar or vector shift amount. 9808 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9809 SourceLocation Loc, bool IsCompAssign) { 9810 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9811 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9812 !LHS.get()->getType()->isVectorType()) { 9813 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9814 << RHS.get()->getType() << LHS.get()->getType() 9815 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9816 return QualType(); 9817 } 9818 9819 if (!IsCompAssign) { 9820 LHS = S.UsualUnaryConversions(LHS.get()); 9821 if (LHS.isInvalid()) return QualType(); 9822 } 9823 9824 RHS = S.UsualUnaryConversions(RHS.get()); 9825 if (RHS.isInvalid()) return QualType(); 9826 9827 QualType LHSType = LHS.get()->getType(); 9828 // Note that LHS might be a scalar because the routine calls not only in 9829 // OpenCL case. 9830 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9831 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9832 9833 // Note that RHS might not be a vector. 9834 QualType RHSType = RHS.get()->getType(); 9835 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9836 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9837 9838 // The operands need to be integers. 9839 if (!LHSEleType->isIntegerType()) { 9840 S.Diag(Loc, diag::err_typecheck_expect_int) 9841 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9842 return QualType(); 9843 } 9844 9845 if (!RHSEleType->isIntegerType()) { 9846 S.Diag(Loc, diag::err_typecheck_expect_int) 9847 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9848 return QualType(); 9849 } 9850 9851 if (!LHSVecTy) { 9852 assert(RHSVecTy); 9853 if (IsCompAssign) 9854 return RHSType; 9855 if (LHSEleType != RHSEleType) { 9856 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9857 LHSEleType = RHSEleType; 9858 } 9859 QualType VecTy = 9860 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9861 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9862 LHSType = VecTy; 9863 } else if (RHSVecTy) { 9864 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9865 // are applied component-wise. So if RHS is a vector, then ensure 9866 // that the number of elements is the same as LHS... 9867 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9868 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9869 << LHS.get()->getType() << RHS.get()->getType() 9870 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9871 return QualType(); 9872 } 9873 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9874 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9875 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9876 if (LHSBT != RHSBT && 9877 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9878 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9879 << LHS.get()->getType() << RHS.get()->getType() 9880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9881 } 9882 } 9883 } else { 9884 // ...else expand RHS to match the number of elements in LHS. 9885 QualType VecTy = 9886 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9887 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9888 } 9889 9890 return LHSType; 9891 } 9892 9893 // C99 6.5.7 9894 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9895 SourceLocation Loc, BinaryOperatorKind Opc, 9896 bool IsCompAssign) { 9897 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9898 9899 // Vector shifts promote their scalar inputs to vector type. 9900 if (LHS.get()->getType()->isVectorType() || 9901 RHS.get()->getType()->isVectorType()) { 9902 if (LangOpts.ZVector) { 9903 // The shift operators for the z vector extensions work basically 9904 // like general shifts, except that neither the LHS nor the RHS is 9905 // allowed to be a "vector bool". 9906 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9907 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9908 return InvalidOperands(Loc, LHS, RHS); 9909 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9910 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9911 return InvalidOperands(Loc, LHS, RHS); 9912 } 9913 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9914 } 9915 9916 // Shifts don't perform usual arithmetic conversions, they just do integer 9917 // promotions on each operand. C99 6.5.7p3 9918 9919 // For the LHS, do usual unary conversions, but then reset them away 9920 // if this is a compound assignment. 9921 ExprResult OldLHS = LHS; 9922 LHS = UsualUnaryConversions(LHS.get()); 9923 if (LHS.isInvalid()) 9924 return QualType(); 9925 QualType LHSType = LHS.get()->getType(); 9926 if (IsCompAssign) LHS = OldLHS; 9927 9928 // The RHS is simpler. 9929 RHS = UsualUnaryConversions(RHS.get()); 9930 if (RHS.isInvalid()) 9931 return QualType(); 9932 QualType RHSType = RHS.get()->getType(); 9933 9934 // C99 6.5.7p2: Each of the operands shall have integer type. 9935 if (!LHSType->hasIntegerRepresentation() || 9936 !RHSType->hasIntegerRepresentation()) 9937 return InvalidOperands(Loc, LHS, RHS); 9938 9939 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9940 // hasIntegerRepresentation() above instead of this. 9941 if (isScopedEnumerationType(LHSType) || 9942 isScopedEnumerationType(RHSType)) { 9943 return InvalidOperands(Loc, LHS, RHS); 9944 } 9945 // Sanity-check shift operands 9946 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9947 9948 // "The type of the result is that of the promoted left operand." 9949 return LHSType; 9950 } 9951 9952 /// If two different enums are compared, raise a warning. 9953 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9954 Expr *RHS) { 9955 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9956 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9957 9958 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9959 if (!LHSEnumType) 9960 return; 9961 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9962 if (!RHSEnumType) 9963 return; 9964 9965 // Ignore anonymous enums. 9966 if (!LHSEnumType->getDecl()->getIdentifier() && 9967 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9968 return; 9969 if (!RHSEnumType->getDecl()->getIdentifier() && 9970 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9971 return; 9972 9973 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9974 return; 9975 9976 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9977 << LHSStrippedType << RHSStrippedType 9978 << LHS->getSourceRange() << RHS->getSourceRange(); 9979 } 9980 9981 /// Diagnose bad pointer comparisons. 9982 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9983 ExprResult &LHS, ExprResult &RHS, 9984 bool IsError) { 9985 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9986 : diag::ext_typecheck_comparison_of_distinct_pointers) 9987 << LHS.get()->getType() << RHS.get()->getType() 9988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9989 } 9990 9991 /// Returns false if the pointers are converted to a composite type, 9992 /// true otherwise. 9993 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9994 ExprResult &LHS, ExprResult &RHS) { 9995 // C++ [expr.rel]p2: 9996 // [...] Pointer conversions (4.10) and qualification 9997 // conversions (4.4) are performed on pointer operands (or on 9998 // a pointer operand and a null pointer constant) to bring 9999 // them to their composite pointer type. [...] 10000 // 10001 // C++ [expr.eq]p1 uses the same notion for (in)equality 10002 // comparisons of pointers. 10003 10004 QualType LHSType = LHS.get()->getType(); 10005 QualType RHSType = RHS.get()->getType(); 10006 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10007 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10008 10009 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10010 if (T.isNull()) { 10011 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 10012 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 10013 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10014 else 10015 S.InvalidOperands(Loc, LHS, RHS); 10016 return true; 10017 } 10018 10019 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10020 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10021 return false; 10022 } 10023 10024 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10025 ExprResult &LHS, 10026 ExprResult &RHS, 10027 bool IsError) { 10028 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10029 : diag::ext_typecheck_comparison_of_fptr_to_void) 10030 << LHS.get()->getType() << RHS.get()->getType() 10031 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10032 } 10033 10034 static bool isObjCObjectLiteral(ExprResult &E) { 10035 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10036 case Stmt::ObjCArrayLiteralClass: 10037 case Stmt::ObjCDictionaryLiteralClass: 10038 case Stmt::ObjCStringLiteralClass: 10039 case Stmt::ObjCBoxedExprClass: 10040 return true; 10041 default: 10042 // Note that ObjCBoolLiteral is NOT an object literal! 10043 return false; 10044 } 10045 } 10046 10047 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10048 const ObjCObjectPointerType *Type = 10049 LHS->getType()->getAs<ObjCObjectPointerType>(); 10050 10051 // If this is not actually an Objective-C object, bail out. 10052 if (!Type) 10053 return false; 10054 10055 // Get the LHS object's interface type. 10056 QualType InterfaceType = Type->getPointeeType(); 10057 10058 // If the RHS isn't an Objective-C object, bail out. 10059 if (!RHS->getType()->isObjCObjectPointerType()) 10060 return false; 10061 10062 // Try to find the -isEqual: method. 10063 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10064 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10065 InterfaceType, 10066 /*IsInstance=*/true); 10067 if (!Method) { 10068 if (Type->isObjCIdType()) { 10069 // For 'id', just check the global pool. 10070 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10071 /*receiverId=*/true); 10072 } else { 10073 // Check protocols. 10074 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10075 /*IsInstance=*/true); 10076 } 10077 } 10078 10079 if (!Method) 10080 return false; 10081 10082 QualType T = Method->parameters()[0]->getType(); 10083 if (!T->isObjCObjectPointerType()) 10084 return false; 10085 10086 QualType R = Method->getReturnType(); 10087 if (!R->isScalarType()) 10088 return false; 10089 10090 return true; 10091 } 10092 10093 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10094 FromE = FromE->IgnoreParenImpCasts(); 10095 switch (FromE->getStmtClass()) { 10096 default: 10097 break; 10098 case Stmt::ObjCStringLiteralClass: 10099 // "string literal" 10100 return LK_String; 10101 case Stmt::ObjCArrayLiteralClass: 10102 // "array literal" 10103 return LK_Array; 10104 case Stmt::ObjCDictionaryLiteralClass: 10105 // "dictionary literal" 10106 return LK_Dictionary; 10107 case Stmt::BlockExprClass: 10108 return LK_Block; 10109 case Stmt::ObjCBoxedExprClass: { 10110 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10111 switch (Inner->getStmtClass()) { 10112 case Stmt::IntegerLiteralClass: 10113 case Stmt::FloatingLiteralClass: 10114 case Stmt::CharacterLiteralClass: 10115 case Stmt::ObjCBoolLiteralExprClass: 10116 case Stmt::CXXBoolLiteralExprClass: 10117 // "numeric literal" 10118 return LK_Numeric; 10119 case Stmt::ImplicitCastExprClass: { 10120 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10121 // Boolean literals can be represented by implicit casts. 10122 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10123 return LK_Numeric; 10124 break; 10125 } 10126 default: 10127 break; 10128 } 10129 return LK_Boxed; 10130 } 10131 } 10132 return LK_None; 10133 } 10134 10135 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10136 ExprResult &LHS, ExprResult &RHS, 10137 BinaryOperator::Opcode Opc){ 10138 Expr *Literal; 10139 Expr *Other; 10140 if (isObjCObjectLiteral(LHS)) { 10141 Literal = LHS.get(); 10142 Other = RHS.get(); 10143 } else { 10144 Literal = RHS.get(); 10145 Other = LHS.get(); 10146 } 10147 10148 // Don't warn on comparisons against nil. 10149 Other = Other->IgnoreParenCasts(); 10150 if (Other->isNullPointerConstant(S.getASTContext(), 10151 Expr::NPC_ValueDependentIsNotNull)) 10152 return; 10153 10154 // This should be kept in sync with warn_objc_literal_comparison. 10155 // LK_String should always be after the other literals, since it has its own 10156 // warning flag. 10157 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10158 assert(LiteralKind != Sema::LK_Block); 10159 if (LiteralKind == Sema::LK_None) { 10160 llvm_unreachable("Unknown Objective-C object literal kind"); 10161 } 10162 10163 if (LiteralKind == Sema::LK_String) 10164 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10165 << Literal->getSourceRange(); 10166 else 10167 S.Diag(Loc, diag::warn_objc_literal_comparison) 10168 << LiteralKind << Literal->getSourceRange(); 10169 10170 if (BinaryOperator::isEqualityOp(Opc) && 10171 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10172 SourceLocation Start = LHS.get()->getBeginLoc(); 10173 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10174 CharSourceRange OpRange = 10175 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10176 10177 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10178 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10179 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10180 << FixItHint::CreateInsertion(End, "]"); 10181 } 10182 } 10183 10184 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10185 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10186 ExprResult &RHS, SourceLocation Loc, 10187 BinaryOperatorKind Opc) { 10188 // Check that left hand side is !something. 10189 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10190 if (!UO || UO->getOpcode() != UO_LNot) return; 10191 10192 // Only check if the right hand side is non-bool arithmetic type. 10193 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10194 10195 // Make sure that the something in !something is not bool. 10196 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10197 if (SubExpr->isKnownToHaveBooleanValue()) return; 10198 10199 // Emit warning. 10200 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10201 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10202 << Loc << IsBitwiseOp; 10203 10204 // First note suggest !(x < y) 10205 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10206 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10207 FirstClose = S.getLocForEndOfToken(FirstClose); 10208 if (FirstClose.isInvalid()) 10209 FirstOpen = SourceLocation(); 10210 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10211 << IsBitwiseOp 10212 << FixItHint::CreateInsertion(FirstOpen, "(") 10213 << FixItHint::CreateInsertion(FirstClose, ")"); 10214 10215 // Second note suggests (!x) < y 10216 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10217 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10218 SecondClose = S.getLocForEndOfToken(SecondClose); 10219 if (SecondClose.isInvalid()) 10220 SecondOpen = SourceLocation(); 10221 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10222 << FixItHint::CreateInsertion(SecondOpen, "(") 10223 << FixItHint::CreateInsertion(SecondClose, ")"); 10224 } 10225 10226 // Get the decl for a simple expression: a reference to a variable, 10227 // an implicit C++ field reference, or an implicit ObjC ivar reference. 10228 static ValueDecl *getCompareDecl(Expr *E) { 10229 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 10230 return DR->getDecl(); 10231 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 10232 if (Ivar->isFreeIvar()) 10233 return Ivar->getDecl(); 10234 } 10235 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10236 if (Mem->isImplicitAccess()) 10237 return Mem->getMemberDecl(); 10238 } 10239 return nullptr; 10240 } 10241 10242 /// Diagnose some forms of syntactically-obvious tautological comparison. 10243 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10244 Expr *LHS, Expr *RHS, 10245 BinaryOperatorKind Opc) { 10246 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10247 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10248 10249 QualType LHSType = LHS->getType(); 10250 QualType RHSType = RHS->getType(); 10251 if (LHSType->hasFloatingRepresentation() || 10252 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10253 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10254 S.inTemplateInstantiation()) 10255 return; 10256 10257 // Comparisons between two array types are ill-formed for operator<=>, so 10258 // we shouldn't emit any additional warnings about it. 10259 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10260 return; 10261 10262 // For non-floating point types, check for self-comparisons of the form 10263 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10264 // often indicate logic errors in the program. 10265 // 10266 // NOTE: Don't warn about comparison expressions resulting from macro 10267 // expansion. Also don't warn about comparisons which are only self 10268 // comparisons within a template instantiation. The warnings should catch 10269 // obvious cases in the definition of the template anyways. The idea is to 10270 // warn when the typed comparison operator will always evaluate to the same 10271 // result. 10272 ValueDecl *DL = getCompareDecl(LHSStripped); 10273 ValueDecl *DR = getCompareDecl(RHSStripped); 10274 10275 // Used for indexing into %select in warn_comparison_always 10276 enum { 10277 AlwaysConstant, 10278 AlwaysTrue, 10279 AlwaysFalse, 10280 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10281 }; 10282 if (DL && DR && declaresSameEntity(DL, DR)) { 10283 unsigned Result; 10284 switch (Opc) { 10285 case BO_EQ: case BO_LE: case BO_GE: 10286 Result = AlwaysTrue; 10287 break; 10288 case BO_NE: case BO_LT: case BO_GT: 10289 Result = AlwaysFalse; 10290 break; 10291 case BO_Cmp: 10292 Result = AlwaysEqual; 10293 break; 10294 default: 10295 Result = AlwaysConstant; 10296 break; 10297 } 10298 S.DiagRuntimeBehavior(Loc, nullptr, 10299 S.PDiag(diag::warn_comparison_always) 10300 << 0 /*self-comparison*/ 10301 << Result); 10302 } else if (DL && DR && 10303 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10304 !DL->isWeak() && !DR->isWeak()) { 10305 // What is it always going to evaluate to? 10306 unsigned Result; 10307 switch(Opc) { 10308 case BO_EQ: // e.g. array1 == array2 10309 Result = AlwaysFalse; 10310 break; 10311 case BO_NE: // e.g. array1 != array2 10312 Result = AlwaysTrue; 10313 break; 10314 default: // e.g. array1 <= array2 10315 // The best we can say is 'a constant' 10316 Result = AlwaysConstant; 10317 break; 10318 } 10319 S.DiagRuntimeBehavior(Loc, nullptr, 10320 S.PDiag(diag::warn_comparison_always) 10321 << 1 /*array comparison*/ 10322 << Result); 10323 } 10324 10325 if (isa<CastExpr>(LHSStripped)) 10326 LHSStripped = LHSStripped->IgnoreParenCasts(); 10327 if (isa<CastExpr>(RHSStripped)) 10328 RHSStripped = RHSStripped->IgnoreParenCasts(); 10329 10330 // Warn about comparisons against a string constant (unless the other 10331 // operand is null); the user probably wants strcmp. 10332 Expr *LiteralString = nullptr; 10333 Expr *LiteralStringStripped = nullptr; 10334 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10335 !RHSStripped->isNullPointerConstant(S.Context, 10336 Expr::NPC_ValueDependentIsNull)) { 10337 LiteralString = LHS; 10338 LiteralStringStripped = LHSStripped; 10339 } else if ((isa<StringLiteral>(RHSStripped) || 10340 isa<ObjCEncodeExpr>(RHSStripped)) && 10341 !LHSStripped->isNullPointerConstant(S.Context, 10342 Expr::NPC_ValueDependentIsNull)) { 10343 LiteralString = RHS; 10344 LiteralStringStripped = RHSStripped; 10345 } 10346 10347 if (LiteralString) { 10348 S.DiagRuntimeBehavior(Loc, nullptr, 10349 S.PDiag(diag::warn_stringcompare) 10350 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10351 << LiteralString->getSourceRange()); 10352 } 10353 } 10354 10355 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10356 switch (CK) { 10357 default: { 10358 #ifndef NDEBUG 10359 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10360 << "\n"; 10361 #endif 10362 llvm_unreachable("unhandled cast kind"); 10363 } 10364 case CK_UserDefinedConversion: 10365 return ICK_Identity; 10366 case CK_LValueToRValue: 10367 return ICK_Lvalue_To_Rvalue; 10368 case CK_ArrayToPointerDecay: 10369 return ICK_Array_To_Pointer; 10370 case CK_FunctionToPointerDecay: 10371 return ICK_Function_To_Pointer; 10372 case CK_IntegralCast: 10373 return ICK_Integral_Conversion; 10374 case CK_FloatingCast: 10375 return ICK_Floating_Conversion; 10376 case CK_IntegralToFloating: 10377 case CK_FloatingToIntegral: 10378 return ICK_Floating_Integral; 10379 case CK_IntegralComplexCast: 10380 case CK_FloatingComplexCast: 10381 case CK_FloatingComplexToIntegralComplex: 10382 case CK_IntegralComplexToFloatingComplex: 10383 return ICK_Complex_Conversion; 10384 case CK_FloatingComplexToReal: 10385 case CK_FloatingRealToComplex: 10386 case CK_IntegralComplexToReal: 10387 case CK_IntegralRealToComplex: 10388 return ICK_Complex_Real; 10389 } 10390 } 10391 10392 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10393 QualType FromType, 10394 SourceLocation Loc) { 10395 // Check for a narrowing implicit conversion. 10396 StandardConversionSequence SCS; 10397 SCS.setAsIdentityConversion(); 10398 SCS.setToType(0, FromType); 10399 SCS.setToType(1, ToType); 10400 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10401 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10402 10403 APValue PreNarrowingValue; 10404 QualType PreNarrowingType; 10405 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10406 PreNarrowingType, 10407 /*IgnoreFloatToIntegralConversion*/ true)) { 10408 case NK_Dependent_Narrowing: 10409 // Implicit conversion to a narrower type, but the expression is 10410 // value-dependent so we can't tell whether it's actually narrowing. 10411 case NK_Not_Narrowing: 10412 return false; 10413 10414 case NK_Constant_Narrowing: 10415 // Implicit conversion to a narrower type, and the value is not a constant 10416 // expression. 10417 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10418 << /*Constant*/ 1 10419 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10420 return true; 10421 10422 case NK_Variable_Narrowing: 10423 // Implicit conversion to a narrower type, and the value is not a constant 10424 // expression. 10425 case NK_Type_Narrowing: 10426 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10427 << /*Constant*/ 0 << FromType << ToType; 10428 // TODO: It's not a constant expression, but what if the user intended it 10429 // to be? Can we produce notes to help them figure out why it isn't? 10430 return true; 10431 } 10432 llvm_unreachable("unhandled case in switch"); 10433 } 10434 10435 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10436 ExprResult &LHS, 10437 ExprResult &RHS, 10438 SourceLocation Loc) { 10439 using CCT = ComparisonCategoryType; 10440 10441 QualType LHSType = LHS.get()->getType(); 10442 QualType RHSType = RHS.get()->getType(); 10443 // Dig out the original argument type and expression before implicit casts 10444 // were applied. These are the types/expressions we need to check the 10445 // [expr.spaceship] requirements against. 10446 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10447 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10448 QualType LHSStrippedType = LHSStripped.get()->getType(); 10449 QualType RHSStrippedType = RHSStripped.get()->getType(); 10450 10451 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10452 // other is not, the program is ill-formed. 10453 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10454 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10455 return QualType(); 10456 } 10457 10458 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10459 RHSStrippedType->isEnumeralType(); 10460 if (NumEnumArgs == 1) { 10461 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10462 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10463 if (OtherTy->hasFloatingRepresentation()) { 10464 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10465 return QualType(); 10466 } 10467 } 10468 if (NumEnumArgs == 2) { 10469 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10470 // type E, the operator yields the result of converting the operands 10471 // to the underlying type of E and applying <=> to the converted operands. 10472 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10473 S.InvalidOperands(Loc, LHS, RHS); 10474 return QualType(); 10475 } 10476 QualType IntType = 10477 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10478 assert(IntType->isArithmeticType()); 10479 10480 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10481 // promote the boolean type, and all other promotable integer types, to 10482 // avoid this. 10483 if (IntType->isPromotableIntegerType()) 10484 IntType = S.Context.getPromotedIntegerType(IntType); 10485 10486 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10487 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10488 LHSType = RHSType = IntType; 10489 } 10490 10491 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10492 // usual arithmetic conversions are applied to the operands. 10493 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10494 if (LHS.isInvalid() || RHS.isInvalid()) 10495 return QualType(); 10496 if (Type.isNull()) 10497 return S.InvalidOperands(Loc, LHS, RHS); 10498 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10499 10500 bool HasNarrowing = checkThreeWayNarrowingConversion( 10501 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10502 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10503 RHS.get()->getBeginLoc()); 10504 if (HasNarrowing) 10505 return QualType(); 10506 10507 assert(!Type.isNull() && "composite type for <=> has not been set"); 10508 10509 auto TypeKind = [&]() { 10510 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10511 if (CT->getElementType()->hasFloatingRepresentation()) 10512 return CCT::WeakEquality; 10513 return CCT::StrongEquality; 10514 } 10515 if (Type->isIntegralOrEnumerationType()) 10516 return CCT::StrongOrdering; 10517 if (Type->hasFloatingRepresentation()) 10518 return CCT::PartialOrdering; 10519 llvm_unreachable("other types are unimplemented"); 10520 }(); 10521 10522 return S.CheckComparisonCategoryType(TypeKind, Loc); 10523 } 10524 10525 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10526 ExprResult &RHS, 10527 SourceLocation Loc, 10528 BinaryOperatorKind Opc) { 10529 if (Opc == BO_Cmp) 10530 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10531 10532 // C99 6.5.8p3 / C99 6.5.9p4 10533 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10534 if (LHS.isInvalid() || RHS.isInvalid()) 10535 return QualType(); 10536 if (Type.isNull()) 10537 return S.InvalidOperands(Loc, LHS, RHS); 10538 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10539 10540 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10541 10542 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10543 return S.InvalidOperands(Loc, LHS, RHS); 10544 10545 // Check for comparisons of floating point operands using != and ==. 10546 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10547 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10548 10549 // The result of comparisons is 'bool' in C++, 'int' in C. 10550 return S.Context.getLogicalOperationType(); 10551 } 10552 10553 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10554 if (!NullE.get()->getType()->isAnyPointerType()) 10555 return; 10556 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10557 if (!E.get()->getType()->isAnyPointerType() && 10558 E.get()->isNullPointerConstant(Context, 10559 Expr::NPC_ValueDependentIsNotNull) == 10560 Expr::NPCK_ZeroExpression) { 10561 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10562 if (CL->getValue() == 0) 10563 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10564 << NullValue 10565 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10566 NullValue ? "NULL" : "(void *)0"); 10567 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10568 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10569 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10570 if (T == Context.CharTy) 10571 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10572 << NullValue 10573 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10574 NullValue ? "NULL" : "(void *)0"); 10575 } 10576 } 10577 } 10578 10579 // C99 6.5.8, C++ [expr.rel] 10580 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10581 SourceLocation Loc, 10582 BinaryOperatorKind Opc) { 10583 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10584 bool IsThreeWay = Opc == BO_Cmp; 10585 auto IsAnyPointerType = [](ExprResult E) { 10586 QualType Ty = E.get()->getType(); 10587 return Ty->isPointerType() || Ty->isMemberPointerType(); 10588 }; 10589 10590 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10591 // type, array-to-pointer, ..., conversions are performed on both operands to 10592 // bring them to their composite type. 10593 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10594 // any type-related checks. 10595 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10596 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10597 if (LHS.isInvalid()) 10598 return QualType(); 10599 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10600 if (RHS.isInvalid()) 10601 return QualType(); 10602 } else { 10603 LHS = DefaultLvalueConversion(LHS.get()); 10604 if (LHS.isInvalid()) 10605 return QualType(); 10606 RHS = DefaultLvalueConversion(RHS.get()); 10607 if (RHS.isInvalid()) 10608 return QualType(); 10609 } 10610 10611 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10612 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10613 CheckPtrComparisonWithNullChar(LHS, RHS); 10614 CheckPtrComparisonWithNullChar(RHS, LHS); 10615 } 10616 10617 // Handle vector comparisons separately. 10618 if (LHS.get()->getType()->isVectorType() || 10619 RHS.get()->getType()->isVectorType()) 10620 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10621 10622 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10623 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10624 10625 QualType LHSType = LHS.get()->getType(); 10626 QualType RHSType = RHS.get()->getType(); 10627 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10628 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10629 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10630 10631 const Expr::NullPointerConstantKind LHSNullKind = 10632 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10633 const Expr::NullPointerConstantKind RHSNullKind = 10634 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10635 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10636 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10637 10638 auto computeResultTy = [&]() { 10639 if (Opc != BO_Cmp) 10640 return Context.getLogicalOperationType(); 10641 assert(getLangOpts().CPlusPlus); 10642 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10643 10644 QualType CompositeTy = LHS.get()->getType(); 10645 assert(!CompositeTy->isReferenceType()); 10646 10647 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10648 return CheckComparisonCategoryType(Kind, Loc); 10649 }; 10650 10651 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10652 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10653 // result is of type std::strong_equality 10654 if (CompositeTy->isFunctionPointerType() || 10655 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10656 // FIXME: consider making the function pointer case produce 10657 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10658 // and direction polls 10659 return buildResultTy(ComparisonCategoryType::StrongEquality); 10660 10661 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10662 // pointer type, p <=> q is of type std::strong_ordering. 10663 if (CompositeTy->isPointerType()) { 10664 // P0946R0: Comparisons between a null pointer constant and an object 10665 // pointer result in std::strong_equality 10666 if (LHSIsNull != RHSIsNull) 10667 return buildResultTy(ComparisonCategoryType::StrongEquality); 10668 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10669 } 10670 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10671 // TODO: Extend support for operator<=> to ObjC types. 10672 return InvalidOperands(Loc, LHS, RHS); 10673 }; 10674 10675 10676 if (!IsRelational && LHSIsNull != RHSIsNull) { 10677 bool IsEquality = Opc == BO_EQ; 10678 if (RHSIsNull) 10679 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10680 RHS.get()->getSourceRange()); 10681 else 10682 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10683 LHS.get()->getSourceRange()); 10684 } 10685 10686 if ((LHSType->isIntegerType() && !LHSIsNull) || 10687 (RHSType->isIntegerType() && !RHSIsNull)) { 10688 // Skip normal pointer conversion checks in this case; we have better 10689 // diagnostics for this below. 10690 } else if (getLangOpts().CPlusPlus) { 10691 // Equality comparison of a function pointer to a void pointer is invalid, 10692 // but we allow it as an extension. 10693 // FIXME: If we really want to allow this, should it be part of composite 10694 // pointer type computation so it works in conditionals too? 10695 if (!IsRelational && 10696 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10697 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10698 // This is a gcc extension compatibility comparison. 10699 // In a SFINAE context, we treat this as a hard error to maintain 10700 // conformance with the C++ standard. 10701 diagnoseFunctionPointerToVoidComparison( 10702 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10703 10704 if (isSFINAEContext()) 10705 return QualType(); 10706 10707 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10708 return computeResultTy(); 10709 } 10710 10711 // C++ [expr.eq]p2: 10712 // If at least one operand is a pointer [...] bring them to their 10713 // composite pointer type. 10714 // C++ [expr.spaceship]p6 10715 // If at least one of the operands is of pointer type, [...] bring them 10716 // to their composite pointer type. 10717 // C++ [expr.rel]p2: 10718 // If both operands are pointers, [...] bring them to their composite 10719 // pointer type. 10720 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10721 (IsRelational ? 2 : 1) && 10722 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10723 RHSType->isObjCObjectPointerType()))) { 10724 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10725 return QualType(); 10726 return computeResultTy(); 10727 } 10728 } else if (LHSType->isPointerType() && 10729 RHSType->isPointerType()) { // C99 6.5.8p2 10730 // All of the following pointer-related warnings are GCC extensions, except 10731 // when handling null pointer constants. 10732 QualType LCanPointeeTy = 10733 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10734 QualType RCanPointeeTy = 10735 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10736 10737 // C99 6.5.9p2 and C99 6.5.8p2 10738 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10739 RCanPointeeTy.getUnqualifiedType())) { 10740 // Valid unless a relational comparison of function pointers 10741 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10742 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10743 << LHSType << RHSType << LHS.get()->getSourceRange() 10744 << RHS.get()->getSourceRange(); 10745 } 10746 } else if (!IsRelational && 10747 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10748 // Valid unless comparison between non-null pointer and function pointer 10749 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10750 && !LHSIsNull && !RHSIsNull) 10751 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10752 /*isError*/false); 10753 } else { 10754 // Invalid 10755 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10756 } 10757 if (LCanPointeeTy != RCanPointeeTy) { 10758 // Treat NULL constant as a special case in OpenCL. 10759 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10760 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10761 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10762 Diag(Loc, 10763 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10764 << LHSType << RHSType << 0 /* comparison */ 10765 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10766 } 10767 } 10768 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10769 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10770 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10771 : CK_BitCast; 10772 if (LHSIsNull && !RHSIsNull) 10773 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10774 else 10775 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10776 } 10777 return computeResultTy(); 10778 } 10779 10780 if (getLangOpts().CPlusPlus) { 10781 // C++ [expr.eq]p4: 10782 // Two operands of type std::nullptr_t or one operand of type 10783 // std::nullptr_t and the other a null pointer constant compare equal. 10784 if (!IsRelational && LHSIsNull && RHSIsNull) { 10785 if (LHSType->isNullPtrType()) { 10786 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10787 return computeResultTy(); 10788 } 10789 if (RHSType->isNullPtrType()) { 10790 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10791 return computeResultTy(); 10792 } 10793 } 10794 10795 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10796 // These aren't covered by the composite pointer type rules. 10797 if (!IsRelational && RHSType->isNullPtrType() && 10798 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10799 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10800 return computeResultTy(); 10801 } 10802 if (!IsRelational && LHSType->isNullPtrType() && 10803 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10804 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10805 return computeResultTy(); 10806 } 10807 10808 if (IsRelational && 10809 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10810 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10811 // HACK: Relational comparison of nullptr_t against a pointer type is 10812 // invalid per DR583, but we allow it within std::less<> and friends, 10813 // since otherwise common uses of it break. 10814 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10815 // friends to have std::nullptr_t overload candidates. 10816 DeclContext *DC = CurContext; 10817 if (isa<FunctionDecl>(DC)) 10818 DC = DC->getParent(); 10819 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10820 if (CTSD->isInStdNamespace() && 10821 llvm::StringSwitch<bool>(CTSD->getName()) 10822 .Cases("less", "less_equal", "greater", "greater_equal", true) 10823 .Default(false)) { 10824 if (RHSType->isNullPtrType()) 10825 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10826 else 10827 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10828 return computeResultTy(); 10829 } 10830 } 10831 } 10832 10833 // C++ [expr.eq]p2: 10834 // If at least one operand is a pointer to member, [...] bring them to 10835 // their composite pointer type. 10836 if (!IsRelational && 10837 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10838 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10839 return QualType(); 10840 else 10841 return computeResultTy(); 10842 } 10843 } 10844 10845 // Handle block pointer types. 10846 if (!IsRelational && LHSType->isBlockPointerType() && 10847 RHSType->isBlockPointerType()) { 10848 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10849 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10850 10851 if (!LHSIsNull && !RHSIsNull && 10852 !Context.typesAreCompatible(lpointee, rpointee)) { 10853 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10854 << LHSType << RHSType << LHS.get()->getSourceRange() 10855 << RHS.get()->getSourceRange(); 10856 } 10857 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10858 return computeResultTy(); 10859 } 10860 10861 // Allow block pointers to be compared with null pointer constants. 10862 if (!IsRelational 10863 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10864 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10865 if (!LHSIsNull && !RHSIsNull) { 10866 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10867 ->getPointeeType()->isVoidType()) 10868 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10869 ->getPointeeType()->isVoidType()))) 10870 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10871 << LHSType << RHSType << LHS.get()->getSourceRange() 10872 << RHS.get()->getSourceRange(); 10873 } 10874 if (LHSIsNull && !RHSIsNull) 10875 LHS = ImpCastExprToType(LHS.get(), RHSType, 10876 RHSType->isPointerType() ? CK_BitCast 10877 : CK_AnyPointerToBlockPointerCast); 10878 else 10879 RHS = ImpCastExprToType(RHS.get(), LHSType, 10880 LHSType->isPointerType() ? CK_BitCast 10881 : CK_AnyPointerToBlockPointerCast); 10882 return computeResultTy(); 10883 } 10884 10885 if (LHSType->isObjCObjectPointerType() || 10886 RHSType->isObjCObjectPointerType()) { 10887 const PointerType *LPT = LHSType->getAs<PointerType>(); 10888 const PointerType *RPT = RHSType->getAs<PointerType>(); 10889 if (LPT || RPT) { 10890 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10891 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10892 10893 if (!LPtrToVoid && !RPtrToVoid && 10894 !Context.typesAreCompatible(LHSType, RHSType)) { 10895 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10896 /*isError*/false); 10897 } 10898 if (LHSIsNull && !RHSIsNull) { 10899 Expr *E = LHS.get(); 10900 if (getLangOpts().ObjCAutoRefCount) 10901 CheckObjCConversion(SourceRange(), RHSType, E, 10902 CCK_ImplicitConversion); 10903 LHS = ImpCastExprToType(E, RHSType, 10904 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10905 } 10906 else { 10907 Expr *E = RHS.get(); 10908 if (getLangOpts().ObjCAutoRefCount) 10909 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10910 /*Diagnose=*/true, 10911 /*DiagnoseCFAudited=*/false, Opc); 10912 RHS = ImpCastExprToType(E, LHSType, 10913 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10914 } 10915 return computeResultTy(); 10916 } 10917 if (LHSType->isObjCObjectPointerType() && 10918 RHSType->isObjCObjectPointerType()) { 10919 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10920 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10921 /*isError*/false); 10922 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10923 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10924 10925 if (LHSIsNull && !RHSIsNull) 10926 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10927 else 10928 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10929 return computeResultTy(); 10930 } 10931 10932 if (!IsRelational && LHSType->isBlockPointerType() && 10933 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10934 LHS = ImpCastExprToType(LHS.get(), RHSType, 10935 CK_BlockPointerToObjCPointerCast); 10936 return computeResultTy(); 10937 } else if (!IsRelational && 10938 LHSType->isBlockCompatibleObjCPointerType(Context) && 10939 RHSType->isBlockPointerType()) { 10940 RHS = ImpCastExprToType(RHS.get(), LHSType, 10941 CK_BlockPointerToObjCPointerCast); 10942 return computeResultTy(); 10943 } 10944 } 10945 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10946 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10947 unsigned DiagID = 0; 10948 bool isError = false; 10949 if (LangOpts.DebuggerSupport) { 10950 // Under a debugger, allow the comparison of pointers to integers, 10951 // since users tend to want to compare addresses. 10952 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10953 (RHSIsNull && RHSType->isIntegerType())) { 10954 if (IsRelational) { 10955 isError = getLangOpts().CPlusPlus; 10956 DiagID = 10957 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10958 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10959 } 10960 } else if (getLangOpts().CPlusPlus) { 10961 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10962 isError = true; 10963 } else if (IsRelational) 10964 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10965 else 10966 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10967 10968 if (DiagID) { 10969 Diag(Loc, DiagID) 10970 << LHSType << RHSType << LHS.get()->getSourceRange() 10971 << RHS.get()->getSourceRange(); 10972 if (isError) 10973 return QualType(); 10974 } 10975 10976 if (LHSType->isIntegerType()) 10977 LHS = ImpCastExprToType(LHS.get(), RHSType, 10978 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10979 else 10980 RHS = ImpCastExprToType(RHS.get(), LHSType, 10981 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10982 return computeResultTy(); 10983 } 10984 10985 // Handle block pointers. 10986 if (!IsRelational && RHSIsNull 10987 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10988 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10989 return computeResultTy(); 10990 } 10991 if (!IsRelational && LHSIsNull 10992 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10993 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10994 return computeResultTy(); 10995 } 10996 10997 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 10998 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10999 return computeResultTy(); 11000 } 11001 11002 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11003 return computeResultTy(); 11004 } 11005 11006 if (LHSIsNull && RHSType->isQueueT()) { 11007 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11008 return computeResultTy(); 11009 } 11010 11011 if (LHSType->isQueueT() && RHSIsNull) { 11012 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11013 return computeResultTy(); 11014 } 11015 } 11016 11017 return InvalidOperands(Loc, LHS, RHS); 11018 } 11019 11020 // Return a signed ext_vector_type that is of identical size and number of 11021 // elements. For floating point vectors, return an integer type of identical 11022 // size and number of elements. In the non ext_vector_type case, search from 11023 // the largest type to the smallest type to avoid cases where long long == long, 11024 // where long gets picked over long long. 11025 QualType Sema::GetSignedVectorType(QualType V) { 11026 const VectorType *VTy = V->getAs<VectorType>(); 11027 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11028 11029 if (isa<ExtVectorType>(VTy)) { 11030 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11031 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11032 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11033 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11034 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11035 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11036 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11037 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11038 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11039 "Unhandled vector element size in vector compare"); 11040 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11041 } 11042 11043 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11044 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11045 VectorType::GenericVector); 11046 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11047 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11048 VectorType::GenericVector); 11049 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11050 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11051 VectorType::GenericVector); 11052 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11053 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11054 VectorType::GenericVector); 11055 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11056 "Unhandled vector element size in vector compare"); 11057 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11058 VectorType::GenericVector); 11059 } 11060 11061 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11062 /// operates on extended vector types. Instead of producing an IntTy result, 11063 /// like a scalar comparison, a vector comparison produces a vector of integer 11064 /// types. 11065 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11066 SourceLocation Loc, 11067 BinaryOperatorKind Opc) { 11068 // Check to make sure we're operating on vectors of the same type and width, 11069 // Allowing one side to be a scalar of element type. 11070 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11071 /*AllowBothBool*/true, 11072 /*AllowBoolConversions*/getLangOpts().ZVector); 11073 if (vType.isNull()) 11074 return vType; 11075 11076 QualType LHSType = LHS.get()->getType(); 11077 11078 // If AltiVec, the comparison results in a numeric type, i.e. 11079 // bool for C++, int for C 11080 if (getLangOpts().AltiVec && 11081 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11082 return Context.getLogicalOperationType(); 11083 11084 // For non-floating point types, check for self-comparisons of the form 11085 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11086 // often indicate logic errors in the program. 11087 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11088 11089 // Check for comparisons of floating point operands using != and ==. 11090 if (BinaryOperator::isEqualityOp(Opc) && 11091 LHSType->hasFloatingRepresentation()) { 11092 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11093 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11094 } 11095 11096 // Return a signed type for the vector. 11097 return GetSignedVectorType(vType); 11098 } 11099 11100 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11101 const ExprResult &XorRHS, 11102 const SourceLocation Loc) { 11103 // Do not diagnose macros. 11104 if (Loc.isMacroID()) 11105 return; 11106 11107 bool Negative = false; 11108 bool ExplicitPlus = false; 11109 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11110 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11111 11112 if (!LHSInt) 11113 return; 11114 if (!RHSInt) { 11115 // Check negative literals. 11116 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11117 UnaryOperatorKind Opc = UO->getOpcode(); 11118 if (Opc != UO_Minus && Opc != UO_Plus) 11119 return; 11120 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11121 if (!RHSInt) 11122 return; 11123 Negative = (Opc == UO_Minus); 11124 ExplicitPlus = !Negative; 11125 } else { 11126 return; 11127 } 11128 } 11129 11130 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11131 llvm::APInt RightSideValue = RHSInt->getValue(); 11132 if (LeftSideValue != 2 && LeftSideValue != 10) 11133 return; 11134 11135 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11136 return; 11137 11138 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11139 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11140 llvm::StringRef ExprStr = 11141 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11142 11143 CharSourceRange XorRange = 11144 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11145 llvm::StringRef XorStr = 11146 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11147 // Do not diagnose if xor keyword/macro is used. 11148 if (XorStr == "xor") 11149 return; 11150 11151 std::string LHSStr = Lexer::getSourceText( 11152 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11153 S.getSourceManager(), S.getLangOpts()); 11154 std::string RHSStr = Lexer::getSourceText( 11155 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11156 S.getSourceManager(), S.getLangOpts()); 11157 11158 if (Negative) { 11159 RightSideValue = -RightSideValue; 11160 RHSStr = "-" + RHSStr; 11161 } else if (ExplicitPlus) { 11162 RHSStr = "+" + RHSStr; 11163 } 11164 11165 StringRef LHSStrRef = LHSStr; 11166 StringRef RHSStrRef = RHSStr; 11167 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11168 // literals. 11169 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11170 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11171 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11172 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11173 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11174 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11175 LHSStrRef.find('\'') != StringRef::npos || 11176 RHSStrRef.find('\'') != StringRef::npos) 11177 return; 11178 11179 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11180 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11181 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11182 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11183 std::string SuggestedExpr = "1 << " + RHSStr; 11184 bool Overflow = false; 11185 llvm::APInt One = (LeftSideValue - 1); 11186 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11187 if (Overflow) { 11188 if (RightSideIntValue < 64) 11189 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11190 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11191 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11192 else if (RightSideIntValue == 64) 11193 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11194 else 11195 return; 11196 } else { 11197 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11198 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11199 << PowValue.toString(10, true) 11200 << FixItHint::CreateReplacement( 11201 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11202 } 11203 11204 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11205 } else if (LeftSideValue == 10) { 11206 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11207 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11208 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11209 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11210 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11211 } 11212 } 11213 11214 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11215 SourceLocation Loc) { 11216 // Ensure that either both operands are of the same vector type, or 11217 // one operand is of a vector type and the other is of its element type. 11218 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11219 /*AllowBothBool*/true, 11220 /*AllowBoolConversions*/false); 11221 if (vType.isNull()) 11222 return InvalidOperands(Loc, LHS, RHS); 11223 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11224 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11225 return InvalidOperands(Loc, LHS, RHS); 11226 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11227 // usage of the logical operators && and || with vectors in C. This 11228 // check could be notionally dropped. 11229 if (!getLangOpts().CPlusPlus && 11230 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11231 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11232 11233 return GetSignedVectorType(LHS.get()->getType()); 11234 } 11235 11236 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11237 SourceLocation Loc, 11238 BinaryOperatorKind Opc) { 11239 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11240 11241 bool IsCompAssign = 11242 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11243 11244 if (LHS.get()->getType()->isVectorType() || 11245 RHS.get()->getType()->isVectorType()) { 11246 if (LHS.get()->getType()->hasIntegerRepresentation() && 11247 RHS.get()->getType()->hasIntegerRepresentation()) 11248 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11249 /*AllowBothBool*/true, 11250 /*AllowBoolConversions*/getLangOpts().ZVector); 11251 return InvalidOperands(Loc, LHS, RHS); 11252 } 11253 11254 if (Opc == BO_And) 11255 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11256 11257 ExprResult LHSResult = LHS, RHSResult = RHS; 11258 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11259 IsCompAssign); 11260 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11261 return QualType(); 11262 LHS = LHSResult.get(); 11263 RHS = RHSResult.get(); 11264 11265 if (Opc == BO_Xor) 11266 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11267 11268 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11269 return compType; 11270 return InvalidOperands(Loc, LHS, RHS); 11271 } 11272 11273 // C99 6.5.[13,14] 11274 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11275 SourceLocation Loc, 11276 BinaryOperatorKind Opc) { 11277 // Check vector operands differently. 11278 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11279 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11280 11281 // Diagnose cases where the user write a logical and/or but probably meant a 11282 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11283 // is a constant. 11284 if (LHS.get()->getType()->isIntegerType() && 11285 !LHS.get()->getType()->isBooleanType() && 11286 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11287 // Don't warn in macros or template instantiations. 11288 !Loc.isMacroID() && !inTemplateInstantiation()) { 11289 // If the RHS can be constant folded, and if it constant folds to something 11290 // that isn't 0 or 1 (which indicate a potential logical operation that 11291 // happened to fold to true/false) then warn. 11292 // Parens on the RHS are ignored. 11293 Expr::EvalResult EVResult; 11294 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11295 llvm::APSInt Result = EVResult.Val.getInt(); 11296 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11297 !RHS.get()->getExprLoc().isMacroID()) || 11298 (Result != 0 && Result != 1)) { 11299 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11300 << RHS.get()->getSourceRange() 11301 << (Opc == BO_LAnd ? "&&" : "||"); 11302 // Suggest replacing the logical operator with the bitwise version 11303 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11304 << (Opc == BO_LAnd ? "&" : "|") 11305 << FixItHint::CreateReplacement(SourceRange( 11306 Loc, getLocForEndOfToken(Loc)), 11307 Opc == BO_LAnd ? "&" : "|"); 11308 if (Opc == BO_LAnd) 11309 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11310 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11311 << FixItHint::CreateRemoval( 11312 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11313 RHS.get()->getEndLoc())); 11314 } 11315 } 11316 } 11317 11318 if (!Context.getLangOpts().CPlusPlus) { 11319 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11320 // not operate on the built-in scalar and vector float types. 11321 if (Context.getLangOpts().OpenCL && 11322 Context.getLangOpts().OpenCLVersion < 120) { 11323 if (LHS.get()->getType()->isFloatingType() || 11324 RHS.get()->getType()->isFloatingType()) 11325 return InvalidOperands(Loc, LHS, RHS); 11326 } 11327 11328 LHS = UsualUnaryConversions(LHS.get()); 11329 if (LHS.isInvalid()) 11330 return QualType(); 11331 11332 RHS = UsualUnaryConversions(RHS.get()); 11333 if (RHS.isInvalid()) 11334 return QualType(); 11335 11336 if (!LHS.get()->getType()->isScalarType() || 11337 !RHS.get()->getType()->isScalarType()) 11338 return InvalidOperands(Loc, LHS, RHS); 11339 11340 return Context.IntTy; 11341 } 11342 11343 // The following is safe because we only use this method for 11344 // non-overloadable operands. 11345 11346 // C++ [expr.log.and]p1 11347 // C++ [expr.log.or]p1 11348 // The operands are both contextually converted to type bool. 11349 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11350 if (LHSRes.isInvalid()) 11351 return InvalidOperands(Loc, LHS, RHS); 11352 LHS = LHSRes; 11353 11354 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11355 if (RHSRes.isInvalid()) 11356 return InvalidOperands(Loc, LHS, RHS); 11357 RHS = RHSRes; 11358 11359 // C++ [expr.log.and]p2 11360 // C++ [expr.log.or]p2 11361 // The result is a bool. 11362 return Context.BoolTy; 11363 } 11364 11365 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11366 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11367 if (!ME) return false; 11368 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11369 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11370 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11371 if (!Base) return false; 11372 return Base->getMethodDecl() != nullptr; 11373 } 11374 11375 /// Is the given expression (which must be 'const') a reference to a 11376 /// variable which was originally non-const, but which has become 11377 /// 'const' due to being captured within a block? 11378 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11379 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11380 assert(E->isLValue() && E->getType().isConstQualified()); 11381 E = E->IgnoreParens(); 11382 11383 // Must be a reference to a declaration from an enclosing scope. 11384 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11385 if (!DRE) return NCCK_None; 11386 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11387 11388 // The declaration must be a variable which is not declared 'const'. 11389 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11390 if (!var) return NCCK_None; 11391 if (var->getType().isConstQualified()) return NCCK_None; 11392 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11393 11394 // Decide whether the first capture was for a block or a lambda. 11395 DeclContext *DC = S.CurContext, *Prev = nullptr; 11396 // Decide whether the first capture was for a block or a lambda. 11397 while (DC) { 11398 // For init-capture, it is possible that the variable belongs to the 11399 // template pattern of the current context. 11400 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11401 if (var->isInitCapture() && 11402 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11403 break; 11404 if (DC == var->getDeclContext()) 11405 break; 11406 Prev = DC; 11407 DC = DC->getParent(); 11408 } 11409 // Unless we have an init-capture, we've gone one step too far. 11410 if (!var->isInitCapture()) 11411 DC = Prev; 11412 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11413 } 11414 11415 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11416 Ty = Ty.getNonReferenceType(); 11417 if (IsDereference && Ty->isPointerType()) 11418 Ty = Ty->getPointeeType(); 11419 return !Ty.isConstQualified(); 11420 } 11421 11422 // Update err_typecheck_assign_const and note_typecheck_assign_const 11423 // when this enum is changed. 11424 enum { 11425 ConstFunction, 11426 ConstVariable, 11427 ConstMember, 11428 ConstMethod, 11429 NestedConstMember, 11430 ConstUnknown, // Keep as last element 11431 }; 11432 11433 /// Emit the "read-only variable not assignable" error and print notes to give 11434 /// more information about why the variable is not assignable, such as pointing 11435 /// to the declaration of a const variable, showing that a method is const, or 11436 /// that the function is returning a const reference. 11437 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11438 SourceLocation Loc) { 11439 SourceRange ExprRange = E->getSourceRange(); 11440 11441 // Only emit one error on the first const found. All other consts will emit 11442 // a note to the error. 11443 bool DiagnosticEmitted = false; 11444 11445 // Track if the current expression is the result of a dereference, and if the 11446 // next checked expression is the result of a dereference. 11447 bool IsDereference = false; 11448 bool NextIsDereference = false; 11449 11450 // Loop to process MemberExpr chains. 11451 while (true) { 11452 IsDereference = NextIsDereference; 11453 11454 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11455 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11456 NextIsDereference = ME->isArrow(); 11457 const ValueDecl *VD = ME->getMemberDecl(); 11458 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11459 // Mutable fields can be modified even if the class is const. 11460 if (Field->isMutable()) { 11461 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11462 break; 11463 } 11464 11465 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11466 if (!DiagnosticEmitted) { 11467 S.Diag(Loc, diag::err_typecheck_assign_const) 11468 << ExprRange << ConstMember << false /*static*/ << Field 11469 << Field->getType(); 11470 DiagnosticEmitted = true; 11471 } 11472 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11473 << ConstMember << false /*static*/ << Field << Field->getType() 11474 << Field->getSourceRange(); 11475 } 11476 E = ME->getBase(); 11477 continue; 11478 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11479 if (VDecl->getType().isConstQualified()) { 11480 if (!DiagnosticEmitted) { 11481 S.Diag(Loc, diag::err_typecheck_assign_const) 11482 << ExprRange << ConstMember << true /*static*/ << VDecl 11483 << VDecl->getType(); 11484 DiagnosticEmitted = true; 11485 } 11486 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11487 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11488 << VDecl->getSourceRange(); 11489 } 11490 // Static fields do not inherit constness from parents. 11491 break; 11492 } 11493 break; // End MemberExpr 11494 } else if (const ArraySubscriptExpr *ASE = 11495 dyn_cast<ArraySubscriptExpr>(E)) { 11496 E = ASE->getBase()->IgnoreParenImpCasts(); 11497 continue; 11498 } else if (const ExtVectorElementExpr *EVE = 11499 dyn_cast<ExtVectorElementExpr>(E)) { 11500 E = EVE->getBase()->IgnoreParenImpCasts(); 11501 continue; 11502 } 11503 break; 11504 } 11505 11506 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11507 // Function calls 11508 const FunctionDecl *FD = CE->getDirectCallee(); 11509 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11510 if (!DiagnosticEmitted) { 11511 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11512 << ConstFunction << FD; 11513 DiagnosticEmitted = true; 11514 } 11515 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11516 diag::note_typecheck_assign_const) 11517 << ConstFunction << FD << FD->getReturnType() 11518 << FD->getReturnTypeSourceRange(); 11519 } 11520 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11521 // Point to variable declaration. 11522 if (const ValueDecl *VD = DRE->getDecl()) { 11523 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11524 if (!DiagnosticEmitted) { 11525 S.Diag(Loc, diag::err_typecheck_assign_const) 11526 << ExprRange << ConstVariable << VD << VD->getType(); 11527 DiagnosticEmitted = true; 11528 } 11529 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11530 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11531 } 11532 } 11533 } else if (isa<CXXThisExpr>(E)) { 11534 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11535 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11536 if (MD->isConst()) { 11537 if (!DiagnosticEmitted) { 11538 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11539 << ConstMethod << MD; 11540 DiagnosticEmitted = true; 11541 } 11542 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11543 << ConstMethod << MD << MD->getSourceRange(); 11544 } 11545 } 11546 } 11547 } 11548 11549 if (DiagnosticEmitted) 11550 return; 11551 11552 // Can't determine a more specific message, so display the generic error. 11553 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11554 } 11555 11556 enum OriginalExprKind { 11557 OEK_Variable, 11558 OEK_Member, 11559 OEK_LValue 11560 }; 11561 11562 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11563 const RecordType *Ty, 11564 SourceLocation Loc, SourceRange Range, 11565 OriginalExprKind OEK, 11566 bool &DiagnosticEmitted) { 11567 std::vector<const RecordType *> RecordTypeList; 11568 RecordTypeList.push_back(Ty); 11569 unsigned NextToCheckIndex = 0; 11570 // We walk the record hierarchy breadth-first to ensure that we print 11571 // diagnostics in field nesting order. 11572 while (RecordTypeList.size() > NextToCheckIndex) { 11573 bool IsNested = NextToCheckIndex > 0; 11574 for (const FieldDecl *Field : 11575 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11576 // First, check every field for constness. 11577 QualType FieldTy = Field->getType(); 11578 if (FieldTy.isConstQualified()) { 11579 if (!DiagnosticEmitted) { 11580 S.Diag(Loc, diag::err_typecheck_assign_const) 11581 << Range << NestedConstMember << OEK << VD 11582 << IsNested << Field; 11583 DiagnosticEmitted = true; 11584 } 11585 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11586 << NestedConstMember << IsNested << Field 11587 << FieldTy << Field->getSourceRange(); 11588 } 11589 11590 // Then we append it to the list to check next in order. 11591 FieldTy = FieldTy.getCanonicalType(); 11592 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11593 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11594 RecordTypeList.push_back(FieldRecTy); 11595 } 11596 } 11597 ++NextToCheckIndex; 11598 } 11599 } 11600 11601 /// Emit an error for the case where a record we are trying to assign to has a 11602 /// const-qualified field somewhere in its hierarchy. 11603 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11604 SourceLocation Loc) { 11605 QualType Ty = E->getType(); 11606 assert(Ty->isRecordType() && "lvalue was not record?"); 11607 SourceRange Range = E->getSourceRange(); 11608 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11609 bool DiagEmitted = false; 11610 11611 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11612 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11613 Range, OEK_Member, DiagEmitted); 11614 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11615 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11616 Range, OEK_Variable, DiagEmitted); 11617 else 11618 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11619 Range, OEK_LValue, DiagEmitted); 11620 if (!DiagEmitted) 11621 DiagnoseConstAssignment(S, E, Loc); 11622 } 11623 11624 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11625 /// emit an error and return true. If so, return false. 11626 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11627 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11628 11629 S.CheckShadowingDeclModification(E, Loc); 11630 11631 SourceLocation OrigLoc = Loc; 11632 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11633 &Loc); 11634 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11635 IsLV = Expr::MLV_InvalidMessageExpression; 11636 if (IsLV == Expr::MLV_Valid) 11637 return false; 11638 11639 unsigned DiagID = 0; 11640 bool NeedType = false; 11641 switch (IsLV) { // C99 6.5.16p2 11642 case Expr::MLV_ConstQualified: 11643 // Use a specialized diagnostic when we're assigning to an object 11644 // from an enclosing function or block. 11645 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11646 if (NCCK == NCCK_Block) 11647 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11648 else 11649 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11650 break; 11651 } 11652 11653 // In ARC, use some specialized diagnostics for occasions where we 11654 // infer 'const'. These are always pseudo-strong variables. 11655 if (S.getLangOpts().ObjCAutoRefCount) { 11656 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11657 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11658 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11659 11660 // Use the normal diagnostic if it's pseudo-__strong but the 11661 // user actually wrote 'const'. 11662 if (var->isARCPseudoStrong() && 11663 (!var->getTypeSourceInfo() || 11664 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11665 // There are three pseudo-strong cases: 11666 // - self 11667 ObjCMethodDecl *method = S.getCurMethodDecl(); 11668 if (method && var == method->getSelfDecl()) { 11669 DiagID = method->isClassMethod() 11670 ? diag::err_typecheck_arc_assign_self_class_method 11671 : diag::err_typecheck_arc_assign_self; 11672 11673 // - Objective-C externally_retained attribute. 11674 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11675 isa<ParmVarDecl>(var)) { 11676 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11677 11678 // - fast enumeration variables 11679 } else { 11680 DiagID = diag::err_typecheck_arr_assign_enumeration; 11681 } 11682 11683 SourceRange Assign; 11684 if (Loc != OrigLoc) 11685 Assign = SourceRange(OrigLoc, OrigLoc); 11686 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11687 // We need to preserve the AST regardless, so migration tool 11688 // can do its job. 11689 return false; 11690 } 11691 } 11692 } 11693 11694 // If none of the special cases above are triggered, then this is a 11695 // simple const assignment. 11696 if (DiagID == 0) { 11697 DiagnoseConstAssignment(S, E, Loc); 11698 return true; 11699 } 11700 11701 break; 11702 case Expr::MLV_ConstAddrSpace: 11703 DiagnoseConstAssignment(S, E, Loc); 11704 return true; 11705 case Expr::MLV_ConstQualifiedField: 11706 DiagnoseRecursiveConstFields(S, E, Loc); 11707 return true; 11708 case Expr::MLV_ArrayType: 11709 case Expr::MLV_ArrayTemporary: 11710 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11711 NeedType = true; 11712 break; 11713 case Expr::MLV_NotObjectType: 11714 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11715 NeedType = true; 11716 break; 11717 case Expr::MLV_LValueCast: 11718 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11719 break; 11720 case Expr::MLV_Valid: 11721 llvm_unreachable("did not take early return for MLV_Valid"); 11722 case Expr::MLV_InvalidExpression: 11723 case Expr::MLV_MemberFunction: 11724 case Expr::MLV_ClassTemporary: 11725 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11726 break; 11727 case Expr::MLV_IncompleteType: 11728 case Expr::MLV_IncompleteVoidType: 11729 return S.RequireCompleteType(Loc, E->getType(), 11730 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11731 case Expr::MLV_DuplicateVectorComponents: 11732 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11733 break; 11734 case Expr::MLV_NoSetterProperty: 11735 llvm_unreachable("readonly properties should be processed differently"); 11736 case Expr::MLV_InvalidMessageExpression: 11737 DiagID = diag::err_readonly_message_assignment; 11738 break; 11739 case Expr::MLV_SubObjCPropertySetting: 11740 DiagID = diag::err_no_subobject_property_setting; 11741 break; 11742 } 11743 11744 SourceRange Assign; 11745 if (Loc != OrigLoc) 11746 Assign = SourceRange(OrigLoc, OrigLoc); 11747 if (NeedType) 11748 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11749 else 11750 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11751 return true; 11752 } 11753 11754 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11755 SourceLocation Loc, 11756 Sema &Sema) { 11757 if (Sema.inTemplateInstantiation()) 11758 return; 11759 if (Sema.isUnevaluatedContext()) 11760 return; 11761 if (Loc.isInvalid() || Loc.isMacroID()) 11762 return; 11763 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11764 return; 11765 11766 // C / C++ fields 11767 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11768 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11769 if (ML && MR) { 11770 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11771 return; 11772 const ValueDecl *LHSDecl = 11773 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11774 const ValueDecl *RHSDecl = 11775 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11776 if (LHSDecl != RHSDecl) 11777 return; 11778 if (LHSDecl->getType().isVolatileQualified()) 11779 return; 11780 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11781 if (RefTy->getPointeeType().isVolatileQualified()) 11782 return; 11783 11784 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11785 } 11786 11787 // Objective-C instance variables 11788 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11789 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11790 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11791 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11792 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11793 if (RL && RR && RL->getDecl() == RR->getDecl()) 11794 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11795 } 11796 } 11797 11798 // C99 6.5.16.1 11799 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11800 SourceLocation Loc, 11801 QualType CompoundType) { 11802 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11803 11804 // Verify that LHS is a modifiable lvalue, and emit error if not. 11805 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11806 return QualType(); 11807 11808 QualType LHSType = LHSExpr->getType(); 11809 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11810 CompoundType; 11811 // OpenCL v1.2 s6.1.1.1 p2: 11812 // The half data type can only be used to declare a pointer to a buffer that 11813 // contains half values 11814 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11815 LHSType->isHalfType()) { 11816 Diag(Loc, diag::err_opencl_half_load_store) << 1 11817 << LHSType.getUnqualifiedType(); 11818 return QualType(); 11819 } 11820 11821 AssignConvertType ConvTy; 11822 if (CompoundType.isNull()) { 11823 Expr *RHSCheck = RHS.get(); 11824 11825 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11826 11827 QualType LHSTy(LHSType); 11828 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11829 if (RHS.isInvalid()) 11830 return QualType(); 11831 // Special case of NSObject attributes on c-style pointer types. 11832 if (ConvTy == IncompatiblePointer && 11833 ((Context.isObjCNSObjectType(LHSType) && 11834 RHSType->isObjCObjectPointerType()) || 11835 (Context.isObjCNSObjectType(RHSType) && 11836 LHSType->isObjCObjectPointerType()))) 11837 ConvTy = Compatible; 11838 11839 if (ConvTy == Compatible && 11840 LHSType->isObjCObjectType()) 11841 Diag(Loc, diag::err_objc_object_assignment) 11842 << LHSType; 11843 11844 // If the RHS is a unary plus or minus, check to see if they = and + are 11845 // right next to each other. If so, the user may have typo'd "x =+ 4" 11846 // instead of "x += 4". 11847 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11848 RHSCheck = ICE->getSubExpr(); 11849 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11850 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11851 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11852 // Only if the two operators are exactly adjacent. 11853 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11854 // And there is a space or other character before the subexpr of the 11855 // unary +/-. We don't want to warn on "x=-1". 11856 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11857 UO->getSubExpr()->getBeginLoc().isFileID()) { 11858 Diag(Loc, diag::warn_not_compound_assign) 11859 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11860 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11861 } 11862 } 11863 11864 if (ConvTy == Compatible) { 11865 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11866 // Warn about retain cycles where a block captures the LHS, but 11867 // not if the LHS is a simple variable into which the block is 11868 // being stored...unless that variable can be captured by reference! 11869 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11870 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11871 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11872 checkRetainCycles(LHSExpr, RHS.get()); 11873 } 11874 11875 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11876 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11877 // It is safe to assign a weak reference into a strong variable. 11878 // Although this code can still have problems: 11879 // id x = self.weakProp; 11880 // id y = self.weakProp; 11881 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11882 // paths through the function. This should be revisited if 11883 // -Wrepeated-use-of-weak is made flow-sensitive. 11884 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11885 // variable, which will be valid for the current autorelease scope. 11886 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11887 RHS.get()->getBeginLoc())) 11888 getCurFunction()->markSafeWeakUse(RHS.get()); 11889 11890 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11891 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11892 } 11893 } 11894 } else { 11895 // Compound assignment "x += y" 11896 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11897 } 11898 11899 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11900 RHS.get(), AA_Assigning)) 11901 return QualType(); 11902 11903 CheckForNullPointerDereference(*this, LHSExpr); 11904 11905 // C99 6.5.16p3: The type of an assignment expression is the type of the 11906 // left operand unless the left operand has qualified type, in which case 11907 // it is the unqualified version of the type of the left operand. 11908 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11909 // is converted to the type of the assignment expression (above). 11910 // C++ 5.17p1: the type of the assignment expression is that of its left 11911 // operand. 11912 return (getLangOpts().CPlusPlus 11913 ? LHSType : LHSType.getUnqualifiedType()); 11914 } 11915 11916 // Only ignore explicit casts to void. 11917 static bool IgnoreCommaOperand(const Expr *E) { 11918 E = E->IgnoreParens(); 11919 11920 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11921 if (CE->getCastKind() == CK_ToVoid) { 11922 return true; 11923 } 11924 11925 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11926 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11927 CE->getSubExpr()->getType()->isDependentType()) { 11928 return true; 11929 } 11930 } 11931 11932 return false; 11933 } 11934 11935 // Look for instances where it is likely the comma operator is confused with 11936 // another operator. There is a whitelist of acceptable expressions for the 11937 // left hand side of the comma operator, otherwise emit a warning. 11938 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11939 // No warnings in macros 11940 if (Loc.isMacroID()) 11941 return; 11942 11943 // Don't warn in template instantiations. 11944 if (inTemplateInstantiation()) 11945 return; 11946 11947 // Scope isn't fine-grained enough to whitelist the specific cases, so 11948 // instead, skip more than needed, then call back into here with the 11949 // CommaVisitor in SemaStmt.cpp. 11950 // The whitelisted locations are the initialization and increment portions 11951 // of a for loop. The additional checks are on the condition of 11952 // if statements, do/while loops, and for loops. 11953 // Differences in scope flags for C89 mode requires the extra logic. 11954 const unsigned ForIncrementFlags = 11955 getLangOpts().C99 || getLangOpts().CPlusPlus 11956 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11957 : Scope::ContinueScope | Scope::BreakScope; 11958 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11959 const unsigned ScopeFlags = getCurScope()->getFlags(); 11960 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11961 (ScopeFlags & ForInitFlags) == ForInitFlags) 11962 return; 11963 11964 // If there are multiple comma operators used together, get the RHS of the 11965 // of the comma operator as the LHS. 11966 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11967 if (BO->getOpcode() != BO_Comma) 11968 break; 11969 LHS = BO->getRHS(); 11970 } 11971 11972 // Only allow some expressions on LHS to not warn. 11973 if (IgnoreCommaOperand(LHS)) 11974 return; 11975 11976 Diag(Loc, diag::warn_comma_operator); 11977 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11978 << LHS->getSourceRange() 11979 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11980 LangOpts.CPlusPlus ? "static_cast<void>(" 11981 : "(void)(") 11982 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11983 ")"); 11984 } 11985 11986 // C99 6.5.17 11987 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11988 SourceLocation Loc) { 11989 LHS = S.CheckPlaceholderExpr(LHS.get()); 11990 RHS = S.CheckPlaceholderExpr(RHS.get()); 11991 if (LHS.isInvalid() || RHS.isInvalid()) 11992 return QualType(); 11993 11994 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11995 // operands, but not unary promotions. 11996 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11997 11998 // So we treat the LHS as a ignored value, and in C++ we allow the 11999 // containing site to determine what should be done with the RHS. 12000 LHS = S.IgnoredValueConversions(LHS.get()); 12001 if (LHS.isInvalid()) 12002 return QualType(); 12003 12004 S.DiagnoseUnusedExprResult(LHS.get()); 12005 12006 if (!S.getLangOpts().CPlusPlus) { 12007 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12008 if (RHS.isInvalid()) 12009 return QualType(); 12010 if (!RHS.get()->getType()->isVoidType()) 12011 S.RequireCompleteType(Loc, RHS.get()->getType(), 12012 diag::err_incomplete_type); 12013 } 12014 12015 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12016 S.DiagnoseCommaOperator(LHS.get(), Loc); 12017 12018 return RHS.get()->getType(); 12019 } 12020 12021 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12022 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12023 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12024 ExprValueKind &VK, 12025 ExprObjectKind &OK, 12026 SourceLocation OpLoc, 12027 bool IsInc, bool IsPrefix) { 12028 if (Op->isTypeDependent()) 12029 return S.Context.DependentTy; 12030 12031 QualType ResType = Op->getType(); 12032 // Atomic types can be used for increment / decrement where the non-atomic 12033 // versions can, so ignore the _Atomic() specifier for the purpose of 12034 // checking. 12035 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12036 ResType = ResAtomicType->getValueType(); 12037 12038 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12039 12040 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12041 // Decrement of bool is not allowed. 12042 if (!IsInc) { 12043 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12044 return QualType(); 12045 } 12046 // Increment of bool sets it to true, but is deprecated. 12047 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12048 : diag::warn_increment_bool) 12049 << Op->getSourceRange(); 12050 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12051 // Error on enum increments and decrements in C++ mode 12052 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12053 return QualType(); 12054 } else if (ResType->isRealType()) { 12055 // OK! 12056 } else if (ResType->isPointerType()) { 12057 // C99 6.5.2.4p2, 6.5.6p2 12058 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12059 return QualType(); 12060 } else if (ResType->isObjCObjectPointerType()) { 12061 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12062 // Otherwise, we just need a complete type. 12063 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12064 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12065 return QualType(); 12066 } else if (ResType->isAnyComplexType()) { 12067 // C99 does not support ++/-- on complex types, we allow as an extension. 12068 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12069 << ResType << Op->getSourceRange(); 12070 } else if (ResType->isPlaceholderType()) { 12071 ExprResult PR = S.CheckPlaceholderExpr(Op); 12072 if (PR.isInvalid()) return QualType(); 12073 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12074 IsInc, IsPrefix); 12075 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12076 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12077 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12078 (ResType->getAs<VectorType>()->getVectorKind() != 12079 VectorType::AltiVecBool)) { 12080 // The z vector extensions allow ++ and -- for non-bool vectors. 12081 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12082 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 12083 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12084 } else { 12085 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12086 << ResType << int(IsInc) << Op->getSourceRange(); 12087 return QualType(); 12088 } 12089 // At this point, we know we have a real, complex or pointer type. 12090 // Now make sure the operand is a modifiable lvalue. 12091 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12092 return QualType(); 12093 // In C++, a prefix increment is the same type as the operand. Otherwise 12094 // (in C or with postfix), the increment is the unqualified type of the 12095 // operand. 12096 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12097 VK = VK_LValue; 12098 OK = Op->getObjectKind(); 12099 return ResType; 12100 } else { 12101 VK = VK_RValue; 12102 return ResType.getUnqualifiedType(); 12103 } 12104 } 12105 12106 12107 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12108 /// This routine allows us to typecheck complex/recursive expressions 12109 /// where the declaration is needed for type checking. We only need to 12110 /// handle cases when the expression references a function designator 12111 /// or is an lvalue. Here are some examples: 12112 /// - &(x) => x 12113 /// - &*****f => f for f a function designator. 12114 /// - &s.xx => s 12115 /// - &s.zz[1].yy -> s, if zz is an array 12116 /// - *(x + 1) -> x, if x is an array 12117 /// - &"123"[2] -> 0 12118 /// - & __real__ x -> x 12119 static ValueDecl *getPrimaryDecl(Expr *E) { 12120 switch (E->getStmtClass()) { 12121 case Stmt::DeclRefExprClass: 12122 return cast<DeclRefExpr>(E)->getDecl(); 12123 case Stmt::MemberExprClass: 12124 // If this is an arrow operator, the address is an offset from 12125 // the base's value, so the object the base refers to is 12126 // irrelevant. 12127 if (cast<MemberExpr>(E)->isArrow()) 12128 return nullptr; 12129 // Otherwise, the expression refers to a part of the base 12130 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12131 case Stmt::ArraySubscriptExprClass: { 12132 // FIXME: This code shouldn't be necessary! We should catch the implicit 12133 // promotion of register arrays earlier. 12134 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12135 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12136 if (ICE->getSubExpr()->getType()->isArrayType()) 12137 return getPrimaryDecl(ICE->getSubExpr()); 12138 } 12139 return nullptr; 12140 } 12141 case Stmt::UnaryOperatorClass: { 12142 UnaryOperator *UO = cast<UnaryOperator>(E); 12143 12144 switch(UO->getOpcode()) { 12145 case UO_Real: 12146 case UO_Imag: 12147 case UO_Extension: 12148 return getPrimaryDecl(UO->getSubExpr()); 12149 default: 12150 return nullptr; 12151 } 12152 } 12153 case Stmt::ParenExprClass: 12154 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12155 case Stmt::ImplicitCastExprClass: 12156 // If the result of an implicit cast is an l-value, we care about 12157 // the sub-expression; otherwise, the result here doesn't matter. 12158 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12159 default: 12160 return nullptr; 12161 } 12162 } 12163 12164 namespace { 12165 enum { 12166 AO_Bit_Field = 0, 12167 AO_Vector_Element = 1, 12168 AO_Property_Expansion = 2, 12169 AO_Register_Variable = 3, 12170 AO_No_Error = 4 12171 }; 12172 } 12173 /// Diagnose invalid operand for address of operations. 12174 /// 12175 /// \param Type The type of operand which cannot have its address taken. 12176 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12177 Expr *E, unsigned Type) { 12178 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12179 } 12180 12181 /// CheckAddressOfOperand - The operand of & must be either a function 12182 /// designator or an lvalue designating an object. If it is an lvalue, the 12183 /// object cannot be declared with storage class register or be a bit field. 12184 /// Note: The usual conversions are *not* applied to the operand of the & 12185 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12186 /// In C++, the operand might be an overloaded function name, in which case 12187 /// we allow the '&' but retain the overloaded-function type. 12188 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12189 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12190 if (PTy->getKind() == BuiltinType::Overload) { 12191 Expr *E = OrigOp.get()->IgnoreParens(); 12192 if (!isa<OverloadExpr>(E)) { 12193 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12194 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12195 << OrigOp.get()->getSourceRange(); 12196 return QualType(); 12197 } 12198 12199 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12200 if (isa<UnresolvedMemberExpr>(Ovl)) 12201 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12202 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12203 << OrigOp.get()->getSourceRange(); 12204 return QualType(); 12205 } 12206 12207 return Context.OverloadTy; 12208 } 12209 12210 if (PTy->getKind() == BuiltinType::UnknownAny) 12211 return Context.UnknownAnyTy; 12212 12213 if (PTy->getKind() == BuiltinType::BoundMember) { 12214 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12215 << OrigOp.get()->getSourceRange(); 12216 return QualType(); 12217 } 12218 12219 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12220 if (OrigOp.isInvalid()) return QualType(); 12221 } 12222 12223 if (OrigOp.get()->isTypeDependent()) 12224 return Context.DependentTy; 12225 12226 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12227 12228 // Make sure to ignore parentheses in subsequent checks 12229 Expr *op = OrigOp.get()->IgnoreParens(); 12230 12231 // In OpenCL captures for blocks called as lambda functions 12232 // are located in the private address space. Blocks used in 12233 // enqueue_kernel can be located in a different address space 12234 // depending on a vendor implementation. Thus preventing 12235 // taking an address of the capture to avoid invalid AS casts. 12236 if (LangOpts.OpenCL) { 12237 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12238 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12239 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12240 return QualType(); 12241 } 12242 } 12243 12244 if (getLangOpts().C99) { 12245 // Implement C99-only parts of addressof rules. 12246 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12247 if (uOp->getOpcode() == UO_Deref) 12248 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12249 // (assuming the deref expression is valid). 12250 return uOp->getSubExpr()->getType(); 12251 } 12252 // Technically, there should be a check for array subscript 12253 // expressions here, but the result of one is always an lvalue anyway. 12254 } 12255 ValueDecl *dcl = getPrimaryDecl(op); 12256 12257 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12258 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12259 op->getBeginLoc())) 12260 return QualType(); 12261 12262 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12263 unsigned AddressOfError = AO_No_Error; 12264 12265 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12266 bool sfinae = (bool)isSFINAEContext(); 12267 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12268 : diag::ext_typecheck_addrof_temporary) 12269 << op->getType() << op->getSourceRange(); 12270 if (sfinae) 12271 return QualType(); 12272 // Materialize the temporary as an lvalue so that we can take its address. 12273 OrigOp = op = 12274 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12275 } else if (isa<ObjCSelectorExpr>(op)) { 12276 return Context.getPointerType(op->getType()); 12277 } else if (lval == Expr::LV_MemberFunction) { 12278 // If it's an instance method, make a member pointer. 12279 // The expression must have exactly the form &A::foo. 12280 12281 // If the underlying expression isn't a decl ref, give up. 12282 if (!isa<DeclRefExpr>(op)) { 12283 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12284 << OrigOp.get()->getSourceRange(); 12285 return QualType(); 12286 } 12287 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12288 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12289 12290 // The id-expression was parenthesized. 12291 if (OrigOp.get() != DRE) { 12292 Diag(OpLoc, diag::err_parens_pointer_member_function) 12293 << OrigOp.get()->getSourceRange(); 12294 12295 // The method was named without a qualifier. 12296 } else if (!DRE->getQualifier()) { 12297 if (MD->getParent()->getName().empty()) 12298 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12299 << op->getSourceRange(); 12300 else { 12301 SmallString<32> Str; 12302 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12303 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12304 << op->getSourceRange() 12305 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12306 } 12307 } 12308 12309 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12310 if (isa<CXXDestructorDecl>(MD)) 12311 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12312 12313 QualType MPTy = Context.getMemberPointerType( 12314 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12315 // Under the MS ABI, lock down the inheritance model now. 12316 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12317 (void)isCompleteType(OpLoc, MPTy); 12318 return MPTy; 12319 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12320 // C99 6.5.3.2p1 12321 // The operand must be either an l-value or a function designator 12322 if (!op->getType()->isFunctionType()) { 12323 // Use a special diagnostic for loads from property references. 12324 if (isa<PseudoObjectExpr>(op)) { 12325 AddressOfError = AO_Property_Expansion; 12326 } else { 12327 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12328 << op->getType() << op->getSourceRange(); 12329 return QualType(); 12330 } 12331 } 12332 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12333 // The operand cannot be a bit-field 12334 AddressOfError = AO_Bit_Field; 12335 } else if (op->getObjectKind() == OK_VectorComponent) { 12336 // The operand cannot be an element of a vector 12337 AddressOfError = AO_Vector_Element; 12338 } else if (dcl) { // C99 6.5.3.2p1 12339 // We have an lvalue with a decl. Make sure the decl is not declared 12340 // with the register storage-class specifier. 12341 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12342 // in C++ it is not error to take address of a register 12343 // variable (c++03 7.1.1P3) 12344 if (vd->getStorageClass() == SC_Register && 12345 !getLangOpts().CPlusPlus) { 12346 AddressOfError = AO_Register_Variable; 12347 } 12348 } else if (isa<MSPropertyDecl>(dcl)) { 12349 AddressOfError = AO_Property_Expansion; 12350 } else if (isa<FunctionTemplateDecl>(dcl)) { 12351 return Context.OverloadTy; 12352 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12353 // Okay: we can take the address of a field. 12354 // Could be a pointer to member, though, if there is an explicit 12355 // scope qualifier for the class. 12356 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12357 DeclContext *Ctx = dcl->getDeclContext(); 12358 if (Ctx && Ctx->isRecord()) { 12359 if (dcl->getType()->isReferenceType()) { 12360 Diag(OpLoc, 12361 diag::err_cannot_form_pointer_to_member_of_reference_type) 12362 << dcl->getDeclName() << dcl->getType(); 12363 return QualType(); 12364 } 12365 12366 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12367 Ctx = Ctx->getParent(); 12368 12369 QualType MPTy = Context.getMemberPointerType( 12370 op->getType(), 12371 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12372 // Under the MS ABI, lock down the inheritance model now. 12373 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12374 (void)isCompleteType(OpLoc, MPTy); 12375 return MPTy; 12376 } 12377 } 12378 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12379 !isa<BindingDecl>(dcl)) 12380 llvm_unreachable("Unknown/unexpected decl type"); 12381 } 12382 12383 if (AddressOfError != AO_No_Error) { 12384 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12385 return QualType(); 12386 } 12387 12388 if (lval == Expr::LV_IncompleteVoidType) { 12389 // Taking the address of a void variable is technically illegal, but we 12390 // allow it in cases which are otherwise valid. 12391 // Example: "extern void x; void* y = &x;". 12392 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12393 } 12394 12395 // If the operand has type "type", the result has type "pointer to type". 12396 if (op->getType()->isObjCObjectType()) 12397 return Context.getObjCObjectPointerType(op->getType()); 12398 12399 CheckAddressOfPackedMember(op); 12400 12401 return Context.getPointerType(op->getType()); 12402 } 12403 12404 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12405 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12406 if (!DRE) 12407 return; 12408 const Decl *D = DRE->getDecl(); 12409 if (!D) 12410 return; 12411 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12412 if (!Param) 12413 return; 12414 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12415 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12416 return; 12417 if (FunctionScopeInfo *FD = S.getCurFunction()) 12418 if (!FD->ModifiedNonNullParams.count(Param)) 12419 FD->ModifiedNonNullParams.insert(Param); 12420 } 12421 12422 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12423 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12424 SourceLocation OpLoc) { 12425 if (Op->isTypeDependent()) 12426 return S.Context.DependentTy; 12427 12428 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12429 if (ConvResult.isInvalid()) 12430 return QualType(); 12431 Op = ConvResult.get(); 12432 QualType OpTy = Op->getType(); 12433 QualType Result; 12434 12435 if (isa<CXXReinterpretCastExpr>(Op)) { 12436 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12437 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12438 Op->getSourceRange()); 12439 } 12440 12441 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12442 { 12443 Result = PT->getPointeeType(); 12444 } 12445 else if (const ObjCObjectPointerType *OPT = 12446 OpTy->getAs<ObjCObjectPointerType>()) 12447 Result = OPT->getPointeeType(); 12448 else { 12449 ExprResult PR = S.CheckPlaceholderExpr(Op); 12450 if (PR.isInvalid()) return QualType(); 12451 if (PR.get() != Op) 12452 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12453 } 12454 12455 if (Result.isNull()) { 12456 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12457 << OpTy << Op->getSourceRange(); 12458 return QualType(); 12459 } 12460 12461 // Note that per both C89 and C99, indirection is always legal, even if Result 12462 // is an incomplete type or void. It would be possible to warn about 12463 // dereferencing a void pointer, but it's completely well-defined, and such a 12464 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12465 // for pointers to 'void' but is fine for any other pointer type: 12466 // 12467 // C++ [expr.unary.op]p1: 12468 // [...] the expression to which [the unary * operator] is applied shall 12469 // be a pointer to an object type, or a pointer to a function type 12470 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12471 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12472 << OpTy << Op->getSourceRange(); 12473 12474 // Dereferences are usually l-values... 12475 VK = VK_LValue; 12476 12477 // ...except that certain expressions are never l-values in C. 12478 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12479 VK = VK_RValue; 12480 12481 return Result; 12482 } 12483 12484 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12485 BinaryOperatorKind Opc; 12486 switch (Kind) { 12487 default: llvm_unreachable("Unknown binop!"); 12488 case tok::periodstar: Opc = BO_PtrMemD; break; 12489 case tok::arrowstar: Opc = BO_PtrMemI; break; 12490 case tok::star: Opc = BO_Mul; break; 12491 case tok::slash: Opc = BO_Div; break; 12492 case tok::percent: Opc = BO_Rem; break; 12493 case tok::plus: Opc = BO_Add; break; 12494 case tok::minus: Opc = BO_Sub; break; 12495 case tok::lessless: Opc = BO_Shl; break; 12496 case tok::greatergreater: Opc = BO_Shr; break; 12497 case tok::lessequal: Opc = BO_LE; break; 12498 case tok::less: Opc = BO_LT; break; 12499 case tok::greaterequal: Opc = BO_GE; break; 12500 case tok::greater: Opc = BO_GT; break; 12501 case tok::exclaimequal: Opc = BO_NE; break; 12502 case tok::equalequal: Opc = BO_EQ; break; 12503 case tok::spaceship: Opc = BO_Cmp; break; 12504 case tok::amp: Opc = BO_And; break; 12505 case tok::caret: Opc = BO_Xor; break; 12506 case tok::pipe: Opc = BO_Or; break; 12507 case tok::ampamp: Opc = BO_LAnd; break; 12508 case tok::pipepipe: Opc = BO_LOr; break; 12509 case tok::equal: Opc = BO_Assign; break; 12510 case tok::starequal: Opc = BO_MulAssign; break; 12511 case tok::slashequal: Opc = BO_DivAssign; break; 12512 case tok::percentequal: Opc = BO_RemAssign; break; 12513 case tok::plusequal: Opc = BO_AddAssign; break; 12514 case tok::minusequal: Opc = BO_SubAssign; break; 12515 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12516 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12517 case tok::ampequal: Opc = BO_AndAssign; break; 12518 case tok::caretequal: Opc = BO_XorAssign; break; 12519 case tok::pipeequal: Opc = BO_OrAssign; break; 12520 case tok::comma: Opc = BO_Comma; break; 12521 } 12522 return Opc; 12523 } 12524 12525 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12526 tok::TokenKind Kind) { 12527 UnaryOperatorKind Opc; 12528 switch (Kind) { 12529 default: llvm_unreachable("Unknown unary op!"); 12530 case tok::plusplus: Opc = UO_PreInc; break; 12531 case tok::minusminus: Opc = UO_PreDec; break; 12532 case tok::amp: Opc = UO_AddrOf; break; 12533 case tok::star: Opc = UO_Deref; break; 12534 case tok::plus: Opc = UO_Plus; break; 12535 case tok::minus: Opc = UO_Minus; break; 12536 case tok::tilde: Opc = UO_Not; break; 12537 case tok::exclaim: Opc = UO_LNot; break; 12538 case tok::kw___real: Opc = UO_Real; break; 12539 case tok::kw___imag: Opc = UO_Imag; break; 12540 case tok::kw___extension__: Opc = UO_Extension; break; 12541 } 12542 return Opc; 12543 } 12544 12545 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12546 /// This warning suppressed in the event of macro expansions. 12547 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12548 SourceLocation OpLoc, bool IsBuiltin) { 12549 if (S.inTemplateInstantiation()) 12550 return; 12551 if (S.isUnevaluatedContext()) 12552 return; 12553 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12554 return; 12555 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12556 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12557 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12558 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12559 if (!LHSDeclRef || !RHSDeclRef || 12560 LHSDeclRef->getLocation().isMacroID() || 12561 RHSDeclRef->getLocation().isMacroID()) 12562 return; 12563 const ValueDecl *LHSDecl = 12564 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12565 const ValueDecl *RHSDecl = 12566 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12567 if (LHSDecl != RHSDecl) 12568 return; 12569 if (LHSDecl->getType().isVolatileQualified()) 12570 return; 12571 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12572 if (RefTy->getPointeeType().isVolatileQualified()) 12573 return; 12574 12575 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12576 : diag::warn_self_assignment_overloaded) 12577 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12578 << RHSExpr->getSourceRange(); 12579 } 12580 12581 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12582 /// is usually indicative of introspection within the Objective-C pointer. 12583 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12584 SourceLocation OpLoc) { 12585 if (!S.getLangOpts().ObjC) 12586 return; 12587 12588 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12589 const Expr *LHS = L.get(); 12590 const Expr *RHS = R.get(); 12591 12592 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12593 ObjCPointerExpr = LHS; 12594 OtherExpr = RHS; 12595 } 12596 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12597 ObjCPointerExpr = RHS; 12598 OtherExpr = LHS; 12599 } 12600 12601 // This warning is deliberately made very specific to reduce false 12602 // positives with logic that uses '&' for hashing. This logic mainly 12603 // looks for code trying to introspect into tagged pointers, which 12604 // code should generally never do. 12605 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12606 unsigned Diag = diag::warn_objc_pointer_masking; 12607 // Determine if we are introspecting the result of performSelectorXXX. 12608 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12609 // Special case messages to -performSelector and friends, which 12610 // can return non-pointer values boxed in a pointer value. 12611 // Some clients may wish to silence warnings in this subcase. 12612 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12613 Selector S = ME->getSelector(); 12614 StringRef SelArg0 = S.getNameForSlot(0); 12615 if (SelArg0.startswith("performSelector")) 12616 Diag = diag::warn_objc_pointer_masking_performSelector; 12617 } 12618 12619 S.Diag(OpLoc, Diag) 12620 << ObjCPointerExpr->getSourceRange(); 12621 } 12622 } 12623 12624 static NamedDecl *getDeclFromExpr(Expr *E) { 12625 if (!E) 12626 return nullptr; 12627 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12628 return DRE->getDecl(); 12629 if (auto *ME = dyn_cast<MemberExpr>(E)) 12630 return ME->getMemberDecl(); 12631 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12632 return IRE->getDecl(); 12633 return nullptr; 12634 } 12635 12636 // This helper function promotes a binary operator's operands (which are of a 12637 // half vector type) to a vector of floats and then truncates the result to 12638 // a vector of either half or short. 12639 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12640 BinaryOperatorKind Opc, QualType ResultTy, 12641 ExprValueKind VK, ExprObjectKind OK, 12642 bool IsCompAssign, SourceLocation OpLoc, 12643 FPOptions FPFeatures) { 12644 auto &Context = S.getASTContext(); 12645 assert((isVector(ResultTy, Context.HalfTy) || 12646 isVector(ResultTy, Context.ShortTy)) && 12647 "Result must be a vector of half or short"); 12648 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12649 isVector(RHS.get()->getType(), Context.HalfTy) && 12650 "both operands expected to be a half vector"); 12651 12652 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12653 QualType BinOpResTy = RHS.get()->getType(); 12654 12655 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12656 // change BinOpResTy to a vector of ints. 12657 if (isVector(ResultTy, Context.ShortTy)) 12658 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12659 12660 if (IsCompAssign) 12661 return new (Context) CompoundAssignOperator( 12662 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12663 OpLoc, FPFeatures); 12664 12665 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12666 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12667 VK, OK, OpLoc, FPFeatures); 12668 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12669 } 12670 12671 static std::pair<ExprResult, ExprResult> 12672 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12673 Expr *RHSExpr) { 12674 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12675 if (!S.getLangOpts().CPlusPlus) { 12676 // C cannot handle TypoExpr nodes on either side of a binop because it 12677 // doesn't handle dependent types properly, so make sure any TypoExprs have 12678 // been dealt with before checking the operands. 12679 LHS = S.CorrectDelayedTyposInExpr(LHS); 12680 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12681 if (Opc != BO_Assign) 12682 return ExprResult(E); 12683 // Avoid correcting the RHS to the same Expr as the LHS. 12684 Decl *D = getDeclFromExpr(E); 12685 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12686 }); 12687 } 12688 return std::make_pair(LHS, RHS); 12689 } 12690 12691 /// Returns true if conversion between vectors of halfs and vectors of floats 12692 /// is needed. 12693 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12694 QualType SrcType) { 12695 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12696 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12697 isVector(SrcType, Ctx.HalfTy); 12698 } 12699 12700 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12701 /// operator @p Opc at location @c TokLoc. This routine only supports 12702 /// built-in operations; ActOnBinOp handles overloaded operators. 12703 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12704 BinaryOperatorKind Opc, 12705 Expr *LHSExpr, Expr *RHSExpr) { 12706 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12707 // The syntax only allows initializer lists on the RHS of assignment, 12708 // so we don't need to worry about accepting invalid code for 12709 // non-assignment operators. 12710 // C++11 5.17p9: 12711 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12712 // of x = {} is x = T(). 12713 InitializationKind Kind = InitializationKind::CreateDirectList( 12714 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12715 InitializedEntity Entity = 12716 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12717 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12718 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12719 if (Init.isInvalid()) 12720 return Init; 12721 RHSExpr = Init.get(); 12722 } 12723 12724 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12725 QualType ResultTy; // Result type of the binary operator. 12726 // The following two variables are used for compound assignment operators 12727 QualType CompLHSTy; // Type of LHS after promotions for computation 12728 QualType CompResultTy; // Type of computation result 12729 ExprValueKind VK = VK_RValue; 12730 ExprObjectKind OK = OK_Ordinary; 12731 bool ConvertHalfVec = false; 12732 12733 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12734 if (!LHS.isUsable() || !RHS.isUsable()) 12735 return ExprError(); 12736 12737 if (getLangOpts().OpenCL) { 12738 QualType LHSTy = LHSExpr->getType(); 12739 QualType RHSTy = RHSExpr->getType(); 12740 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12741 // the ATOMIC_VAR_INIT macro. 12742 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12743 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12744 if (BO_Assign == Opc) 12745 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12746 else 12747 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12748 return ExprError(); 12749 } 12750 12751 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12752 // only with a builtin functions and therefore should be disallowed here. 12753 if (LHSTy->isImageType() || RHSTy->isImageType() || 12754 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12755 LHSTy->isPipeType() || RHSTy->isPipeType() || 12756 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12757 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12758 return ExprError(); 12759 } 12760 } 12761 12762 // Diagnose operations on the unsupported types for OpenMP device compilation. 12763 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12764 if (Opc != BO_Assign && Opc != BO_Comma) { 12765 checkOpenMPDeviceExpr(LHSExpr); 12766 checkOpenMPDeviceExpr(RHSExpr); 12767 } 12768 } 12769 12770 switch (Opc) { 12771 case BO_Assign: 12772 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12773 if (getLangOpts().CPlusPlus && 12774 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12775 VK = LHS.get()->getValueKind(); 12776 OK = LHS.get()->getObjectKind(); 12777 } 12778 if (!ResultTy.isNull()) { 12779 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12780 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12781 12782 // Avoid copying a block to the heap if the block is assigned to a local 12783 // auto variable that is declared in the same scope as the block. This 12784 // optimization is unsafe if the local variable is declared in an outer 12785 // scope. For example: 12786 // 12787 // BlockTy b; 12788 // { 12789 // b = ^{...}; 12790 // } 12791 // // It is unsafe to invoke the block here if it wasn't copied to the 12792 // // heap. 12793 // b(); 12794 12795 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12796 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12797 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12798 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12799 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12800 12801 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12802 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12803 NTCUC_Assignment, NTCUK_Copy); 12804 } 12805 RecordModifiableNonNullParam(*this, LHS.get()); 12806 break; 12807 case BO_PtrMemD: 12808 case BO_PtrMemI: 12809 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12810 Opc == BO_PtrMemI); 12811 break; 12812 case BO_Mul: 12813 case BO_Div: 12814 ConvertHalfVec = true; 12815 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12816 Opc == BO_Div); 12817 break; 12818 case BO_Rem: 12819 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12820 break; 12821 case BO_Add: 12822 ConvertHalfVec = true; 12823 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12824 break; 12825 case BO_Sub: 12826 ConvertHalfVec = true; 12827 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12828 break; 12829 case BO_Shl: 12830 case BO_Shr: 12831 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12832 break; 12833 case BO_LE: 12834 case BO_LT: 12835 case BO_GE: 12836 case BO_GT: 12837 ConvertHalfVec = true; 12838 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12839 break; 12840 case BO_EQ: 12841 case BO_NE: 12842 ConvertHalfVec = true; 12843 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12844 break; 12845 case BO_Cmp: 12846 ConvertHalfVec = true; 12847 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12848 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12849 break; 12850 case BO_And: 12851 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12852 LLVM_FALLTHROUGH; 12853 case BO_Xor: 12854 case BO_Or: 12855 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12856 break; 12857 case BO_LAnd: 12858 case BO_LOr: 12859 ConvertHalfVec = true; 12860 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12861 break; 12862 case BO_MulAssign: 12863 case BO_DivAssign: 12864 ConvertHalfVec = true; 12865 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12866 Opc == BO_DivAssign); 12867 CompLHSTy = CompResultTy; 12868 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12869 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12870 break; 12871 case BO_RemAssign: 12872 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12873 CompLHSTy = CompResultTy; 12874 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12875 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12876 break; 12877 case BO_AddAssign: 12878 ConvertHalfVec = true; 12879 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12880 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12881 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12882 break; 12883 case BO_SubAssign: 12884 ConvertHalfVec = true; 12885 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12886 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12887 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12888 break; 12889 case BO_ShlAssign: 12890 case BO_ShrAssign: 12891 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12892 CompLHSTy = CompResultTy; 12893 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12894 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12895 break; 12896 case BO_AndAssign: 12897 case BO_OrAssign: // fallthrough 12898 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12899 LLVM_FALLTHROUGH; 12900 case BO_XorAssign: 12901 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12902 CompLHSTy = CompResultTy; 12903 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12904 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12905 break; 12906 case BO_Comma: 12907 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12908 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12909 VK = RHS.get()->getValueKind(); 12910 OK = RHS.get()->getObjectKind(); 12911 } 12912 break; 12913 } 12914 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12915 return ExprError(); 12916 12917 // Some of the binary operations require promoting operands of half vector to 12918 // float vectors and truncating the result back to half vector. For now, we do 12919 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12920 // arm64). 12921 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12922 isVector(LHS.get()->getType(), Context.HalfTy) && 12923 "both sides are half vectors or neither sides are"); 12924 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12925 LHS.get()->getType()); 12926 12927 // Check for array bounds violations for both sides of the BinaryOperator 12928 CheckArrayAccess(LHS.get()); 12929 CheckArrayAccess(RHS.get()); 12930 12931 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12932 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12933 &Context.Idents.get("object_setClass"), 12934 SourceLocation(), LookupOrdinaryName); 12935 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12936 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12937 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12938 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12939 "object_setClass(") 12940 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12941 ",") 12942 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12943 } 12944 else 12945 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12946 } 12947 else if (const ObjCIvarRefExpr *OIRE = 12948 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12949 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12950 12951 // Opc is not a compound assignment if CompResultTy is null. 12952 if (CompResultTy.isNull()) { 12953 if (ConvertHalfVec) 12954 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12955 OpLoc, FPFeatures); 12956 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12957 OK, OpLoc, FPFeatures); 12958 } 12959 12960 // Handle compound assignments. 12961 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12962 OK_ObjCProperty) { 12963 VK = VK_LValue; 12964 OK = LHS.get()->getObjectKind(); 12965 } 12966 12967 if (ConvertHalfVec) 12968 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12969 OpLoc, FPFeatures); 12970 12971 return new (Context) CompoundAssignOperator( 12972 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12973 OpLoc, FPFeatures); 12974 } 12975 12976 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12977 /// operators are mixed in a way that suggests that the programmer forgot that 12978 /// comparison operators have higher precedence. The most typical example of 12979 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12980 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12981 SourceLocation OpLoc, Expr *LHSExpr, 12982 Expr *RHSExpr) { 12983 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12984 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12985 12986 // Check that one of the sides is a comparison operator and the other isn't. 12987 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12988 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12989 if (isLeftComp == isRightComp) 12990 return; 12991 12992 // Bitwise operations are sometimes used as eager logical ops. 12993 // Don't diagnose this. 12994 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12995 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12996 if (isLeftBitwise || isRightBitwise) 12997 return; 12998 12999 SourceRange DiagRange = isLeftComp 13000 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13001 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13002 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13003 SourceRange ParensRange = 13004 isLeftComp 13005 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13006 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13007 13008 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13009 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13010 SuggestParentheses(Self, OpLoc, 13011 Self.PDiag(diag::note_precedence_silence) << OpStr, 13012 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13013 SuggestParentheses(Self, OpLoc, 13014 Self.PDiag(diag::note_precedence_bitwise_first) 13015 << BinaryOperator::getOpcodeStr(Opc), 13016 ParensRange); 13017 } 13018 13019 /// It accepts a '&&' expr that is inside a '||' one. 13020 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13021 /// in parentheses. 13022 static void 13023 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13024 BinaryOperator *Bop) { 13025 assert(Bop->getOpcode() == BO_LAnd); 13026 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13027 << Bop->getSourceRange() << OpLoc; 13028 SuggestParentheses(Self, Bop->getOperatorLoc(), 13029 Self.PDiag(diag::note_precedence_silence) 13030 << Bop->getOpcodeStr(), 13031 Bop->getSourceRange()); 13032 } 13033 13034 /// Returns true if the given expression can be evaluated as a constant 13035 /// 'true'. 13036 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13037 bool Res; 13038 return !E->isValueDependent() && 13039 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13040 } 13041 13042 /// Returns true if the given expression can be evaluated as a constant 13043 /// 'false'. 13044 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13045 bool Res; 13046 return !E->isValueDependent() && 13047 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13048 } 13049 13050 /// Look for '&&' in the left hand of a '||' expr. 13051 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13052 Expr *LHSExpr, Expr *RHSExpr) { 13053 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13054 if (Bop->getOpcode() == BO_LAnd) { 13055 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13056 if (EvaluatesAsFalse(S, RHSExpr)) 13057 return; 13058 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13059 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13060 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13061 } else if (Bop->getOpcode() == BO_LOr) { 13062 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13063 // If it's "a || b && 1 || c" we didn't warn earlier for 13064 // "a || b && 1", but warn now. 13065 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13066 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13067 } 13068 } 13069 } 13070 } 13071 13072 /// Look for '&&' in the right hand of a '||' expr. 13073 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13074 Expr *LHSExpr, Expr *RHSExpr) { 13075 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13076 if (Bop->getOpcode() == BO_LAnd) { 13077 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13078 if (EvaluatesAsFalse(S, LHSExpr)) 13079 return; 13080 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13081 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13082 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13083 } 13084 } 13085 } 13086 13087 /// Look for bitwise op in the left or right hand of a bitwise op with 13088 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13089 /// the '&' expression in parentheses. 13090 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13091 SourceLocation OpLoc, Expr *SubExpr) { 13092 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13093 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13094 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13095 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13096 << Bop->getSourceRange() << OpLoc; 13097 SuggestParentheses(S, Bop->getOperatorLoc(), 13098 S.PDiag(diag::note_precedence_silence) 13099 << Bop->getOpcodeStr(), 13100 Bop->getSourceRange()); 13101 } 13102 } 13103 } 13104 13105 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13106 Expr *SubExpr, StringRef Shift) { 13107 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13108 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13109 StringRef Op = Bop->getOpcodeStr(); 13110 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13111 << Bop->getSourceRange() << OpLoc << Shift << Op; 13112 SuggestParentheses(S, Bop->getOperatorLoc(), 13113 S.PDiag(diag::note_precedence_silence) << Op, 13114 Bop->getSourceRange()); 13115 } 13116 } 13117 } 13118 13119 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13120 Expr *LHSExpr, Expr *RHSExpr) { 13121 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13122 if (!OCE) 13123 return; 13124 13125 FunctionDecl *FD = OCE->getDirectCallee(); 13126 if (!FD || !FD->isOverloadedOperator()) 13127 return; 13128 13129 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13130 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13131 return; 13132 13133 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13134 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13135 << (Kind == OO_LessLess); 13136 SuggestParentheses(S, OCE->getOperatorLoc(), 13137 S.PDiag(diag::note_precedence_silence) 13138 << (Kind == OO_LessLess ? "<<" : ">>"), 13139 OCE->getSourceRange()); 13140 SuggestParentheses( 13141 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13142 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13143 } 13144 13145 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13146 /// precedence. 13147 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13148 SourceLocation OpLoc, Expr *LHSExpr, 13149 Expr *RHSExpr){ 13150 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13151 if (BinaryOperator::isBitwiseOp(Opc)) 13152 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13153 13154 // Diagnose "arg1 & arg2 | arg3" 13155 if ((Opc == BO_Or || Opc == BO_Xor) && 13156 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13157 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13158 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13159 } 13160 13161 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13162 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13163 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13164 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13165 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13166 } 13167 13168 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13169 || Opc == BO_Shr) { 13170 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13171 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13172 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13173 } 13174 13175 // Warn on overloaded shift operators and comparisons, such as: 13176 // cout << 5 == 4; 13177 if (BinaryOperator::isComparisonOp(Opc)) 13178 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13179 } 13180 13181 // Binary Operators. 'Tok' is the token for the operator. 13182 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13183 tok::TokenKind Kind, 13184 Expr *LHSExpr, Expr *RHSExpr) { 13185 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13186 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13187 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13188 13189 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13190 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13191 13192 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13193 } 13194 13195 /// Build an overloaded binary operator expression in the given scope. 13196 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13197 BinaryOperatorKind Opc, 13198 Expr *LHS, Expr *RHS) { 13199 switch (Opc) { 13200 case BO_Assign: 13201 case BO_DivAssign: 13202 case BO_RemAssign: 13203 case BO_SubAssign: 13204 case BO_AndAssign: 13205 case BO_OrAssign: 13206 case BO_XorAssign: 13207 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13208 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13209 break; 13210 default: 13211 break; 13212 } 13213 13214 // Find all of the overloaded operators visible from this 13215 // point. We perform both an operator-name lookup from the local 13216 // scope and an argument-dependent lookup based on the types of 13217 // the arguments. 13218 UnresolvedSet<16> Functions; 13219 OverloadedOperatorKind OverOp 13220 = BinaryOperator::getOverloadedOperator(Opc); 13221 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13222 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13223 RHS->getType(), Functions); 13224 13225 // Build the (potentially-overloaded, potentially-dependent) 13226 // binary operation. 13227 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13228 } 13229 13230 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13231 BinaryOperatorKind Opc, 13232 Expr *LHSExpr, Expr *RHSExpr) { 13233 ExprResult LHS, RHS; 13234 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13235 if (!LHS.isUsable() || !RHS.isUsable()) 13236 return ExprError(); 13237 LHSExpr = LHS.get(); 13238 RHSExpr = RHS.get(); 13239 13240 // We want to end up calling one of checkPseudoObjectAssignment 13241 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13242 // both expressions are overloadable or either is type-dependent), 13243 // or CreateBuiltinBinOp (in any other case). We also want to get 13244 // any placeholder types out of the way. 13245 13246 // Handle pseudo-objects in the LHS. 13247 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13248 // Assignments with a pseudo-object l-value need special analysis. 13249 if (pty->getKind() == BuiltinType::PseudoObject && 13250 BinaryOperator::isAssignmentOp(Opc)) 13251 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13252 13253 // Don't resolve overloads if the other type is overloadable. 13254 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13255 // We can't actually test that if we still have a placeholder, 13256 // though. Fortunately, none of the exceptions we see in that 13257 // code below are valid when the LHS is an overload set. Note 13258 // that an overload set can be dependently-typed, but it never 13259 // instantiates to having an overloadable type. 13260 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13261 if (resolvedRHS.isInvalid()) return ExprError(); 13262 RHSExpr = resolvedRHS.get(); 13263 13264 if (RHSExpr->isTypeDependent() || 13265 RHSExpr->getType()->isOverloadableType()) 13266 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13267 } 13268 13269 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13270 // template, diagnose the missing 'template' keyword instead of diagnosing 13271 // an invalid use of a bound member function. 13272 // 13273 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13274 // to C++1z [over.over]/1.4, but we already checked for that case above. 13275 if (Opc == BO_LT && inTemplateInstantiation() && 13276 (pty->getKind() == BuiltinType::BoundMember || 13277 pty->getKind() == BuiltinType::Overload)) { 13278 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13279 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13280 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13281 return isa<FunctionTemplateDecl>(ND); 13282 })) { 13283 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13284 : OE->getNameLoc(), 13285 diag::err_template_kw_missing) 13286 << OE->getName().getAsString() << ""; 13287 return ExprError(); 13288 } 13289 } 13290 13291 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13292 if (LHS.isInvalid()) return ExprError(); 13293 LHSExpr = LHS.get(); 13294 } 13295 13296 // Handle pseudo-objects in the RHS. 13297 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13298 // An overload in the RHS can potentially be resolved by the type 13299 // being assigned to. 13300 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13301 if (getLangOpts().CPlusPlus && 13302 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13303 LHSExpr->getType()->isOverloadableType())) 13304 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13305 13306 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13307 } 13308 13309 // Don't resolve overloads if the other type is overloadable. 13310 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13311 LHSExpr->getType()->isOverloadableType()) 13312 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13313 13314 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13315 if (!resolvedRHS.isUsable()) return ExprError(); 13316 RHSExpr = resolvedRHS.get(); 13317 } 13318 13319 if (getLangOpts().CPlusPlus) { 13320 // If either expression is type-dependent, always build an 13321 // overloaded op. 13322 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13323 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13324 13325 // Otherwise, build an overloaded op if either expression has an 13326 // overloadable type. 13327 if (LHSExpr->getType()->isOverloadableType() || 13328 RHSExpr->getType()->isOverloadableType()) 13329 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13330 } 13331 13332 // Build a built-in binary operation. 13333 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13334 } 13335 13336 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13337 if (T.isNull() || T->isDependentType()) 13338 return false; 13339 13340 if (!T->isPromotableIntegerType()) 13341 return true; 13342 13343 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13344 } 13345 13346 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13347 UnaryOperatorKind Opc, 13348 Expr *InputExpr) { 13349 ExprResult Input = InputExpr; 13350 ExprValueKind VK = VK_RValue; 13351 ExprObjectKind OK = OK_Ordinary; 13352 QualType resultType; 13353 bool CanOverflow = false; 13354 13355 bool ConvertHalfVec = false; 13356 if (getLangOpts().OpenCL) { 13357 QualType Ty = InputExpr->getType(); 13358 // The only legal unary operation for atomics is '&'. 13359 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13360 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13361 // only with a builtin functions and therefore should be disallowed here. 13362 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13363 || Ty->isBlockPointerType())) { 13364 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13365 << InputExpr->getType() 13366 << Input.get()->getSourceRange()); 13367 } 13368 } 13369 // Diagnose operations on the unsupported types for OpenMP device compilation. 13370 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13371 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13372 UnaryOperator::isArithmeticOp(Opc)) 13373 checkOpenMPDeviceExpr(InputExpr); 13374 } 13375 13376 switch (Opc) { 13377 case UO_PreInc: 13378 case UO_PreDec: 13379 case UO_PostInc: 13380 case UO_PostDec: 13381 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13382 OpLoc, 13383 Opc == UO_PreInc || 13384 Opc == UO_PostInc, 13385 Opc == UO_PreInc || 13386 Opc == UO_PreDec); 13387 CanOverflow = isOverflowingIntegerType(Context, resultType); 13388 break; 13389 case UO_AddrOf: 13390 resultType = CheckAddressOfOperand(Input, OpLoc); 13391 CheckAddressOfNoDeref(InputExpr); 13392 RecordModifiableNonNullParam(*this, InputExpr); 13393 break; 13394 case UO_Deref: { 13395 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13396 if (Input.isInvalid()) return ExprError(); 13397 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13398 break; 13399 } 13400 case UO_Plus: 13401 case UO_Minus: 13402 CanOverflow = Opc == UO_Minus && 13403 isOverflowingIntegerType(Context, Input.get()->getType()); 13404 Input = UsualUnaryConversions(Input.get()); 13405 if (Input.isInvalid()) return ExprError(); 13406 // Unary plus and minus require promoting an operand of half vector to a 13407 // float vector and truncating the result back to a half vector. For now, we 13408 // do this only when HalfArgsAndReturns is set (that is, when the target is 13409 // arm or arm64). 13410 ConvertHalfVec = 13411 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13412 13413 // If the operand is a half vector, promote it to a float vector. 13414 if (ConvertHalfVec) 13415 Input = convertVector(Input.get(), Context.FloatTy, *this); 13416 resultType = Input.get()->getType(); 13417 if (resultType->isDependentType()) 13418 break; 13419 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13420 break; 13421 else if (resultType->isVectorType() && 13422 // The z vector extensions don't allow + or - with bool vectors. 13423 (!Context.getLangOpts().ZVector || 13424 resultType->getAs<VectorType>()->getVectorKind() != 13425 VectorType::AltiVecBool)) 13426 break; 13427 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13428 Opc == UO_Plus && 13429 resultType->isPointerType()) 13430 break; 13431 13432 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13433 << resultType << Input.get()->getSourceRange()); 13434 13435 case UO_Not: // bitwise complement 13436 Input = UsualUnaryConversions(Input.get()); 13437 if (Input.isInvalid()) 13438 return ExprError(); 13439 resultType = Input.get()->getType(); 13440 13441 if (resultType->isDependentType()) 13442 break; 13443 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13444 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13445 // C99 does not support '~' for complex conjugation. 13446 Diag(OpLoc, diag::ext_integer_complement_complex) 13447 << resultType << Input.get()->getSourceRange(); 13448 else if (resultType->hasIntegerRepresentation()) 13449 break; 13450 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13451 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13452 // on vector float types. 13453 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13454 if (!T->isIntegerType()) 13455 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13456 << resultType << Input.get()->getSourceRange()); 13457 } else { 13458 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13459 << resultType << Input.get()->getSourceRange()); 13460 } 13461 break; 13462 13463 case UO_LNot: // logical negation 13464 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13465 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13466 if (Input.isInvalid()) return ExprError(); 13467 resultType = Input.get()->getType(); 13468 13469 // Though we still have to promote half FP to float... 13470 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13471 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13472 resultType = Context.FloatTy; 13473 } 13474 13475 if (resultType->isDependentType()) 13476 break; 13477 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13478 // C99 6.5.3.3p1: ok, fallthrough; 13479 if (Context.getLangOpts().CPlusPlus) { 13480 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13481 // operand contextually converted to bool. 13482 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13483 ScalarTypeToBooleanCastKind(resultType)); 13484 } else if (Context.getLangOpts().OpenCL && 13485 Context.getLangOpts().OpenCLVersion < 120) { 13486 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13487 // operate on scalar float types. 13488 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13489 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13490 << resultType << Input.get()->getSourceRange()); 13491 } 13492 } else if (resultType->isExtVectorType()) { 13493 if (Context.getLangOpts().OpenCL && 13494 Context.getLangOpts().OpenCLVersion < 120 && 13495 !Context.getLangOpts().OpenCLCPlusPlus) { 13496 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13497 // operate on vector float types. 13498 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13499 if (!T->isIntegerType()) 13500 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13501 << resultType << Input.get()->getSourceRange()); 13502 } 13503 // Vector logical not returns the signed variant of the operand type. 13504 resultType = GetSignedVectorType(resultType); 13505 break; 13506 } else { 13507 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13508 // type in C++. We should allow that here too. 13509 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13510 << resultType << Input.get()->getSourceRange()); 13511 } 13512 13513 // LNot always has type int. C99 6.5.3.3p5. 13514 // In C++, it's bool. C++ 5.3.1p8 13515 resultType = Context.getLogicalOperationType(); 13516 break; 13517 case UO_Real: 13518 case UO_Imag: 13519 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13520 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13521 // complex l-values to ordinary l-values and all other values to r-values. 13522 if (Input.isInvalid()) return ExprError(); 13523 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13524 if (Input.get()->getValueKind() != VK_RValue && 13525 Input.get()->getObjectKind() == OK_Ordinary) 13526 VK = Input.get()->getValueKind(); 13527 } else if (!getLangOpts().CPlusPlus) { 13528 // In C, a volatile scalar is read by __imag. In C++, it is not. 13529 Input = DefaultLvalueConversion(Input.get()); 13530 } 13531 break; 13532 case UO_Extension: 13533 resultType = Input.get()->getType(); 13534 VK = Input.get()->getValueKind(); 13535 OK = Input.get()->getObjectKind(); 13536 break; 13537 case UO_Coawait: 13538 // It's unnecessary to represent the pass-through operator co_await in the 13539 // AST; just return the input expression instead. 13540 assert(!Input.get()->getType()->isDependentType() && 13541 "the co_await expression must be non-dependant before " 13542 "building operator co_await"); 13543 return Input; 13544 } 13545 if (resultType.isNull() || Input.isInvalid()) 13546 return ExprError(); 13547 13548 // Check for array bounds violations in the operand of the UnaryOperator, 13549 // except for the '*' and '&' operators that have to be handled specially 13550 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13551 // that are explicitly defined as valid by the standard). 13552 if (Opc != UO_AddrOf && Opc != UO_Deref) 13553 CheckArrayAccess(Input.get()); 13554 13555 auto *UO = new (Context) 13556 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13557 13558 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13559 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13560 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13561 13562 // Convert the result back to a half vector. 13563 if (ConvertHalfVec) 13564 return convertVector(UO, Context.HalfTy, *this); 13565 return UO; 13566 } 13567 13568 /// Determine whether the given expression is a qualified member 13569 /// access expression, of a form that could be turned into a pointer to member 13570 /// with the address-of operator. 13571 bool Sema::isQualifiedMemberAccess(Expr *E) { 13572 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13573 if (!DRE->getQualifier()) 13574 return false; 13575 13576 ValueDecl *VD = DRE->getDecl(); 13577 if (!VD->isCXXClassMember()) 13578 return false; 13579 13580 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13581 return true; 13582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13583 return Method->isInstance(); 13584 13585 return false; 13586 } 13587 13588 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13589 if (!ULE->getQualifier()) 13590 return false; 13591 13592 for (NamedDecl *D : ULE->decls()) { 13593 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13594 if (Method->isInstance()) 13595 return true; 13596 } else { 13597 // Overload set does not contain methods. 13598 break; 13599 } 13600 } 13601 13602 return false; 13603 } 13604 13605 return false; 13606 } 13607 13608 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13609 UnaryOperatorKind Opc, Expr *Input) { 13610 // First things first: handle placeholders so that the 13611 // overloaded-operator check considers the right type. 13612 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13613 // Increment and decrement of pseudo-object references. 13614 if (pty->getKind() == BuiltinType::PseudoObject && 13615 UnaryOperator::isIncrementDecrementOp(Opc)) 13616 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13617 13618 // extension is always a builtin operator. 13619 if (Opc == UO_Extension) 13620 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13621 13622 // & gets special logic for several kinds of placeholder. 13623 // The builtin code knows what to do. 13624 if (Opc == UO_AddrOf && 13625 (pty->getKind() == BuiltinType::Overload || 13626 pty->getKind() == BuiltinType::UnknownAny || 13627 pty->getKind() == BuiltinType::BoundMember)) 13628 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13629 13630 // Anything else needs to be handled now. 13631 ExprResult Result = CheckPlaceholderExpr(Input); 13632 if (Result.isInvalid()) return ExprError(); 13633 Input = Result.get(); 13634 } 13635 13636 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13637 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13638 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13639 // Find all of the overloaded operators visible from this 13640 // point. We perform both an operator-name lookup from the local 13641 // scope and an argument-dependent lookup based on the types of 13642 // the arguments. 13643 UnresolvedSet<16> Functions; 13644 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13645 if (S && OverOp != OO_None) 13646 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13647 Functions); 13648 13649 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13650 } 13651 13652 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13653 } 13654 13655 // Unary Operators. 'Tok' is the token for the operator. 13656 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13657 tok::TokenKind Op, Expr *Input) { 13658 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13659 } 13660 13661 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13662 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13663 LabelDecl *TheDecl) { 13664 TheDecl->markUsed(Context); 13665 // Create the AST node. The address of a label always has type 'void*'. 13666 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13667 Context.getPointerType(Context.VoidTy)); 13668 } 13669 13670 void Sema::ActOnStartStmtExpr() { 13671 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13672 } 13673 13674 void Sema::ActOnStmtExprError() { 13675 // Note that function is also called by TreeTransform when leaving a 13676 // StmtExpr scope without rebuilding anything. 13677 13678 DiscardCleanupsInEvaluationContext(); 13679 PopExpressionEvaluationContext(); 13680 } 13681 13682 ExprResult 13683 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13684 SourceLocation RPLoc) { // "({..})" 13685 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13686 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13687 13688 if (hasAnyUnrecoverableErrorsInThisFunction()) 13689 DiscardCleanupsInEvaluationContext(); 13690 assert(!Cleanup.exprNeedsCleanups() && 13691 "cleanups within StmtExpr not correctly bound!"); 13692 PopExpressionEvaluationContext(); 13693 13694 // FIXME: there are a variety of strange constraints to enforce here, for 13695 // example, it is not possible to goto into a stmt expression apparently. 13696 // More semantic analysis is needed. 13697 13698 // If there are sub-stmts in the compound stmt, take the type of the last one 13699 // as the type of the stmtexpr. 13700 QualType Ty = Context.VoidTy; 13701 bool StmtExprMayBindToTemp = false; 13702 if (!Compound->body_empty()) { 13703 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13704 if (const auto *LastStmt = 13705 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13706 if (const Expr *Value = LastStmt->getExprStmt()) { 13707 StmtExprMayBindToTemp = true; 13708 Ty = Value->getType(); 13709 } 13710 } 13711 } 13712 13713 // FIXME: Check that expression type is complete/non-abstract; statement 13714 // expressions are not lvalues. 13715 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13716 if (StmtExprMayBindToTemp) 13717 return MaybeBindToTemporary(ResStmtExpr); 13718 return ResStmtExpr; 13719 } 13720 13721 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13722 if (ER.isInvalid()) 13723 return ExprError(); 13724 13725 // Do function/array conversion on the last expression, but not 13726 // lvalue-to-rvalue. However, initialize an unqualified type. 13727 ER = DefaultFunctionArrayConversion(ER.get()); 13728 if (ER.isInvalid()) 13729 return ExprError(); 13730 Expr *E = ER.get(); 13731 13732 if (E->isTypeDependent()) 13733 return E; 13734 13735 // In ARC, if the final expression ends in a consume, splice 13736 // the consume out and bind it later. In the alternate case 13737 // (when dealing with a retainable type), the result 13738 // initialization will create a produce. In both cases the 13739 // result will be +1, and we'll need to balance that out with 13740 // a bind. 13741 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13742 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13743 return Cast->getSubExpr(); 13744 13745 // FIXME: Provide a better location for the initialization. 13746 return PerformCopyInitialization( 13747 InitializedEntity::InitializeStmtExprResult( 13748 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13749 SourceLocation(), E); 13750 } 13751 13752 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13753 TypeSourceInfo *TInfo, 13754 ArrayRef<OffsetOfComponent> Components, 13755 SourceLocation RParenLoc) { 13756 QualType ArgTy = TInfo->getType(); 13757 bool Dependent = ArgTy->isDependentType(); 13758 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13759 13760 // We must have at least one component that refers to the type, and the first 13761 // one is known to be a field designator. Verify that the ArgTy represents 13762 // a struct/union/class. 13763 if (!Dependent && !ArgTy->isRecordType()) 13764 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13765 << ArgTy << TypeRange); 13766 13767 // Type must be complete per C99 7.17p3 because a declaring a variable 13768 // with an incomplete type would be ill-formed. 13769 if (!Dependent 13770 && RequireCompleteType(BuiltinLoc, ArgTy, 13771 diag::err_offsetof_incomplete_type, TypeRange)) 13772 return ExprError(); 13773 13774 bool DidWarnAboutNonPOD = false; 13775 QualType CurrentType = ArgTy; 13776 SmallVector<OffsetOfNode, 4> Comps; 13777 SmallVector<Expr*, 4> Exprs; 13778 for (const OffsetOfComponent &OC : Components) { 13779 if (OC.isBrackets) { 13780 // Offset of an array sub-field. TODO: Should we allow vector elements? 13781 if (!CurrentType->isDependentType()) { 13782 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13783 if(!AT) 13784 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13785 << CurrentType); 13786 CurrentType = AT->getElementType(); 13787 } else 13788 CurrentType = Context.DependentTy; 13789 13790 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13791 if (IdxRval.isInvalid()) 13792 return ExprError(); 13793 Expr *Idx = IdxRval.get(); 13794 13795 // The expression must be an integral expression. 13796 // FIXME: An integral constant expression? 13797 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13798 !Idx->getType()->isIntegerType()) 13799 return ExprError( 13800 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13801 << Idx->getSourceRange()); 13802 13803 // Record this array index. 13804 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13805 Exprs.push_back(Idx); 13806 continue; 13807 } 13808 13809 // Offset of a field. 13810 if (CurrentType->isDependentType()) { 13811 // We have the offset of a field, but we can't look into the dependent 13812 // type. Just record the identifier of the field. 13813 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13814 CurrentType = Context.DependentTy; 13815 continue; 13816 } 13817 13818 // We need to have a complete type to look into. 13819 if (RequireCompleteType(OC.LocStart, CurrentType, 13820 diag::err_offsetof_incomplete_type)) 13821 return ExprError(); 13822 13823 // Look for the designated field. 13824 const RecordType *RC = CurrentType->getAs<RecordType>(); 13825 if (!RC) 13826 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13827 << CurrentType); 13828 RecordDecl *RD = RC->getDecl(); 13829 13830 // C++ [lib.support.types]p5: 13831 // The macro offsetof accepts a restricted set of type arguments in this 13832 // International Standard. type shall be a POD structure or a POD union 13833 // (clause 9). 13834 // C++11 [support.types]p4: 13835 // If type is not a standard-layout class (Clause 9), the results are 13836 // undefined. 13837 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13838 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13839 unsigned DiagID = 13840 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13841 : diag::ext_offsetof_non_pod_type; 13842 13843 if (!IsSafe && !DidWarnAboutNonPOD && 13844 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13845 PDiag(DiagID) 13846 << SourceRange(Components[0].LocStart, OC.LocEnd) 13847 << CurrentType)) 13848 DidWarnAboutNonPOD = true; 13849 } 13850 13851 // Look for the field. 13852 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13853 LookupQualifiedName(R, RD); 13854 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13855 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13856 if (!MemberDecl) { 13857 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13858 MemberDecl = IndirectMemberDecl->getAnonField(); 13859 } 13860 13861 if (!MemberDecl) 13862 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13863 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13864 OC.LocEnd)); 13865 13866 // C99 7.17p3: 13867 // (If the specified member is a bit-field, the behavior is undefined.) 13868 // 13869 // We diagnose this as an error. 13870 if (MemberDecl->isBitField()) { 13871 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13872 << MemberDecl->getDeclName() 13873 << SourceRange(BuiltinLoc, RParenLoc); 13874 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13875 return ExprError(); 13876 } 13877 13878 RecordDecl *Parent = MemberDecl->getParent(); 13879 if (IndirectMemberDecl) 13880 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13881 13882 // If the member was found in a base class, introduce OffsetOfNodes for 13883 // the base class indirections. 13884 CXXBasePaths Paths; 13885 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13886 Paths)) { 13887 if (Paths.getDetectedVirtual()) { 13888 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13889 << MemberDecl->getDeclName() 13890 << SourceRange(BuiltinLoc, RParenLoc); 13891 return ExprError(); 13892 } 13893 13894 CXXBasePath &Path = Paths.front(); 13895 for (const CXXBasePathElement &B : Path) 13896 Comps.push_back(OffsetOfNode(B.Base)); 13897 } 13898 13899 if (IndirectMemberDecl) { 13900 for (auto *FI : IndirectMemberDecl->chain()) { 13901 assert(isa<FieldDecl>(FI)); 13902 Comps.push_back(OffsetOfNode(OC.LocStart, 13903 cast<FieldDecl>(FI), OC.LocEnd)); 13904 } 13905 } else 13906 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13907 13908 CurrentType = MemberDecl->getType().getNonReferenceType(); 13909 } 13910 13911 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13912 Comps, Exprs, RParenLoc); 13913 } 13914 13915 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13916 SourceLocation BuiltinLoc, 13917 SourceLocation TypeLoc, 13918 ParsedType ParsedArgTy, 13919 ArrayRef<OffsetOfComponent> Components, 13920 SourceLocation RParenLoc) { 13921 13922 TypeSourceInfo *ArgTInfo; 13923 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13924 if (ArgTy.isNull()) 13925 return ExprError(); 13926 13927 if (!ArgTInfo) 13928 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13929 13930 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13931 } 13932 13933 13934 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13935 Expr *CondExpr, 13936 Expr *LHSExpr, Expr *RHSExpr, 13937 SourceLocation RPLoc) { 13938 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13939 13940 ExprValueKind VK = VK_RValue; 13941 ExprObjectKind OK = OK_Ordinary; 13942 QualType resType; 13943 bool ValueDependent = false; 13944 bool CondIsTrue = false; 13945 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13946 resType = Context.DependentTy; 13947 ValueDependent = true; 13948 } else { 13949 // The conditional expression is required to be a constant expression. 13950 llvm::APSInt condEval(32); 13951 ExprResult CondICE 13952 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13953 diag::err_typecheck_choose_expr_requires_constant, false); 13954 if (CondICE.isInvalid()) 13955 return ExprError(); 13956 CondExpr = CondICE.get(); 13957 CondIsTrue = condEval.getZExtValue(); 13958 13959 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13960 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13961 13962 resType = ActiveExpr->getType(); 13963 ValueDependent = ActiveExpr->isValueDependent(); 13964 VK = ActiveExpr->getValueKind(); 13965 OK = ActiveExpr->getObjectKind(); 13966 } 13967 13968 return new (Context) 13969 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13970 CondIsTrue, resType->isDependentType(), ValueDependent); 13971 } 13972 13973 //===----------------------------------------------------------------------===// 13974 // Clang Extensions. 13975 //===----------------------------------------------------------------------===// 13976 13977 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13978 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13979 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13980 13981 if (LangOpts.CPlusPlus) { 13982 Decl *ManglingContextDecl; 13983 if (MangleNumberingContext *MCtx = 13984 getCurrentMangleNumberContext(Block->getDeclContext(), 13985 ManglingContextDecl)) { 13986 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13987 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13988 } 13989 } 13990 13991 PushBlockScope(CurScope, Block); 13992 CurContext->addDecl(Block); 13993 if (CurScope) 13994 PushDeclContext(CurScope, Block); 13995 else 13996 CurContext = Block; 13997 13998 getCurBlock()->HasImplicitReturnType = true; 13999 14000 // Enter a new evaluation context to insulate the block from any 14001 // cleanups from the enclosing full-expression. 14002 PushExpressionEvaluationContext( 14003 ExpressionEvaluationContext::PotentiallyEvaluated); 14004 } 14005 14006 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14007 Scope *CurScope) { 14008 assert(ParamInfo.getIdentifier() == nullptr && 14009 "block-id should have no identifier!"); 14010 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14011 BlockScopeInfo *CurBlock = getCurBlock(); 14012 14013 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14014 QualType T = Sig->getType(); 14015 14016 // FIXME: We should allow unexpanded parameter packs here, but that would, 14017 // in turn, make the block expression contain unexpanded parameter packs. 14018 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14019 // Drop the parameters. 14020 FunctionProtoType::ExtProtoInfo EPI; 14021 EPI.HasTrailingReturn = false; 14022 EPI.TypeQuals.addConst(); 14023 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14024 Sig = Context.getTrivialTypeSourceInfo(T); 14025 } 14026 14027 // GetTypeForDeclarator always produces a function type for a block 14028 // literal signature. Furthermore, it is always a FunctionProtoType 14029 // unless the function was written with a typedef. 14030 assert(T->isFunctionType() && 14031 "GetTypeForDeclarator made a non-function block signature"); 14032 14033 // Look for an explicit signature in that function type. 14034 FunctionProtoTypeLoc ExplicitSignature; 14035 14036 if ((ExplicitSignature = Sig->getTypeLoc() 14037 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14038 14039 // Check whether that explicit signature was synthesized by 14040 // GetTypeForDeclarator. If so, don't save that as part of the 14041 // written signature. 14042 if (ExplicitSignature.getLocalRangeBegin() == 14043 ExplicitSignature.getLocalRangeEnd()) { 14044 // This would be much cheaper if we stored TypeLocs instead of 14045 // TypeSourceInfos. 14046 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14047 unsigned Size = Result.getFullDataSize(); 14048 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14049 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14050 14051 ExplicitSignature = FunctionProtoTypeLoc(); 14052 } 14053 } 14054 14055 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14056 CurBlock->FunctionType = T; 14057 14058 const FunctionType *Fn = T->getAs<FunctionType>(); 14059 QualType RetTy = Fn->getReturnType(); 14060 bool isVariadic = 14061 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14062 14063 CurBlock->TheDecl->setIsVariadic(isVariadic); 14064 14065 // Context.DependentTy is used as a placeholder for a missing block 14066 // return type. TODO: what should we do with declarators like: 14067 // ^ * { ... } 14068 // If the answer is "apply template argument deduction".... 14069 if (RetTy != Context.DependentTy) { 14070 CurBlock->ReturnType = RetTy; 14071 CurBlock->TheDecl->setBlockMissingReturnType(false); 14072 CurBlock->HasImplicitReturnType = false; 14073 } 14074 14075 // Push block parameters from the declarator if we had them. 14076 SmallVector<ParmVarDecl*, 8> Params; 14077 if (ExplicitSignature) { 14078 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14079 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14080 if (Param->getIdentifier() == nullptr && 14081 !Param->isImplicit() && 14082 !Param->isInvalidDecl() && 14083 !getLangOpts().CPlusPlus) 14084 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14085 Params.push_back(Param); 14086 } 14087 14088 // Fake up parameter variables if we have a typedef, like 14089 // ^ fntype { ... } 14090 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14091 for (const auto &I : Fn->param_types()) { 14092 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14093 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14094 Params.push_back(Param); 14095 } 14096 } 14097 14098 // Set the parameters on the block decl. 14099 if (!Params.empty()) { 14100 CurBlock->TheDecl->setParams(Params); 14101 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14102 /*CheckParameterNames=*/false); 14103 } 14104 14105 // Finally we can process decl attributes. 14106 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14107 14108 // Put the parameter variables in scope. 14109 for (auto AI : CurBlock->TheDecl->parameters()) { 14110 AI->setOwningFunction(CurBlock->TheDecl); 14111 14112 // If this has an identifier, add it to the scope stack. 14113 if (AI->getIdentifier()) { 14114 CheckShadow(CurBlock->TheScope, AI); 14115 14116 PushOnScopeChains(AI, CurBlock->TheScope); 14117 } 14118 } 14119 } 14120 14121 /// ActOnBlockError - If there is an error parsing a block, this callback 14122 /// is invoked to pop the information about the block from the action impl. 14123 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14124 // Leave the expression-evaluation context. 14125 DiscardCleanupsInEvaluationContext(); 14126 PopExpressionEvaluationContext(); 14127 14128 // Pop off CurBlock, handle nested blocks. 14129 PopDeclContext(); 14130 PopFunctionScopeInfo(); 14131 } 14132 14133 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14134 /// literal was successfully completed. ^(int x){...} 14135 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14136 Stmt *Body, Scope *CurScope) { 14137 // If blocks are disabled, emit an error. 14138 if (!LangOpts.Blocks) 14139 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14140 14141 // Leave the expression-evaluation context. 14142 if (hasAnyUnrecoverableErrorsInThisFunction()) 14143 DiscardCleanupsInEvaluationContext(); 14144 assert(!Cleanup.exprNeedsCleanups() && 14145 "cleanups within block not correctly bound!"); 14146 PopExpressionEvaluationContext(); 14147 14148 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14149 BlockDecl *BD = BSI->TheDecl; 14150 14151 if (BSI->HasImplicitReturnType) 14152 deduceClosureReturnType(*BSI); 14153 14154 QualType RetTy = Context.VoidTy; 14155 if (!BSI->ReturnType.isNull()) 14156 RetTy = BSI->ReturnType; 14157 14158 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14159 QualType BlockTy; 14160 14161 // If the user wrote a function type in some form, try to use that. 14162 if (!BSI->FunctionType.isNull()) { 14163 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 14164 14165 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14166 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14167 14168 // Turn protoless block types into nullary block types. 14169 if (isa<FunctionNoProtoType>(FTy)) { 14170 FunctionProtoType::ExtProtoInfo EPI; 14171 EPI.ExtInfo = Ext; 14172 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14173 14174 // Otherwise, if we don't need to change anything about the function type, 14175 // preserve its sugar structure. 14176 } else if (FTy->getReturnType() == RetTy && 14177 (!NoReturn || FTy->getNoReturnAttr())) { 14178 BlockTy = BSI->FunctionType; 14179 14180 // Otherwise, make the minimal modifications to the function type. 14181 } else { 14182 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14183 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14184 EPI.TypeQuals = Qualifiers(); 14185 EPI.ExtInfo = Ext; 14186 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14187 } 14188 14189 // If we don't have a function type, just build one from nothing. 14190 } else { 14191 FunctionProtoType::ExtProtoInfo EPI; 14192 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14193 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14194 } 14195 14196 DiagnoseUnusedParameters(BD->parameters()); 14197 BlockTy = Context.getBlockPointerType(BlockTy); 14198 14199 // If needed, diagnose invalid gotos and switches in the block. 14200 if (getCurFunction()->NeedsScopeChecking() && 14201 !PP.isCodeCompletionEnabled()) 14202 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14203 14204 BD->setBody(cast<CompoundStmt>(Body)); 14205 14206 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14207 DiagnoseUnguardedAvailabilityViolations(BD); 14208 14209 // Try to apply the named return value optimization. We have to check again 14210 // if we can do this, though, because blocks keep return statements around 14211 // to deduce an implicit return type. 14212 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14213 !BD->isDependentContext()) 14214 computeNRVO(Body, BSI); 14215 14216 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14217 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14218 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14219 NTCUK_Destruct|NTCUK_Copy); 14220 14221 PopDeclContext(); 14222 14223 // Pop the block scope now but keep it alive to the end of this function. 14224 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14225 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14226 14227 // Set the captured variables on the block. 14228 SmallVector<BlockDecl::Capture, 4> Captures; 14229 for (Capture &Cap : BSI->Captures) { 14230 if (Cap.isInvalid() || Cap.isThisCapture()) 14231 continue; 14232 14233 VarDecl *Var = Cap.getVariable(); 14234 Expr *CopyExpr = nullptr; 14235 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14236 if (const RecordType *Record = 14237 Cap.getCaptureType()->getAs<RecordType>()) { 14238 // The capture logic needs the destructor, so make sure we mark it. 14239 // Usually this is unnecessary because most local variables have 14240 // their destructors marked at declaration time, but parameters are 14241 // an exception because it's technically only the call site that 14242 // actually requires the destructor. 14243 if (isa<ParmVarDecl>(Var)) 14244 FinalizeVarWithDestructor(Var, Record); 14245 14246 // Enter a separate potentially-evaluated context while building block 14247 // initializers to isolate their cleanups from those of the block 14248 // itself. 14249 // FIXME: Is this appropriate even when the block itself occurs in an 14250 // unevaluated operand? 14251 EnterExpressionEvaluationContext EvalContext( 14252 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14253 14254 SourceLocation Loc = Cap.getLocation(); 14255 14256 ExprResult Result = BuildDeclarationNameExpr( 14257 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14258 14259 // According to the blocks spec, the capture of a variable from 14260 // the stack requires a const copy constructor. This is not true 14261 // of the copy/move done to move a __block variable to the heap. 14262 if (!Result.isInvalid() && 14263 !Result.get()->getType().isConstQualified()) { 14264 Result = ImpCastExprToType(Result.get(), 14265 Result.get()->getType().withConst(), 14266 CK_NoOp, VK_LValue); 14267 } 14268 14269 if (!Result.isInvalid()) { 14270 Result = PerformCopyInitialization( 14271 InitializedEntity::InitializeBlock(Var->getLocation(), 14272 Cap.getCaptureType(), false), 14273 Loc, Result.get()); 14274 } 14275 14276 // Build a full-expression copy expression if initialization 14277 // succeeded and used a non-trivial constructor. Recover from 14278 // errors by pretending that the copy isn't necessary. 14279 if (!Result.isInvalid() && 14280 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14281 ->isTrivial()) { 14282 Result = MaybeCreateExprWithCleanups(Result); 14283 CopyExpr = Result.get(); 14284 } 14285 } 14286 } 14287 14288 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14289 CopyExpr); 14290 Captures.push_back(NewCap); 14291 } 14292 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14293 14294 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14295 14296 // If the block isn't obviously global, i.e. it captures anything at 14297 // all, then we need to do a few things in the surrounding context: 14298 if (Result->getBlockDecl()->hasCaptures()) { 14299 // First, this expression has a new cleanup object. 14300 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14301 Cleanup.setExprNeedsCleanups(true); 14302 14303 // It also gets a branch-protected scope if any of the captured 14304 // variables needs destruction. 14305 for (const auto &CI : Result->getBlockDecl()->captures()) { 14306 const VarDecl *var = CI.getVariable(); 14307 if (var->getType().isDestructedType() != QualType::DK_none) { 14308 setFunctionHasBranchProtectedScope(); 14309 break; 14310 } 14311 } 14312 } 14313 14314 if (getCurFunction()) 14315 getCurFunction()->addBlock(BD); 14316 14317 return Result; 14318 } 14319 14320 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14321 SourceLocation RPLoc) { 14322 TypeSourceInfo *TInfo; 14323 GetTypeFromParser(Ty, &TInfo); 14324 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14325 } 14326 14327 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14328 Expr *E, TypeSourceInfo *TInfo, 14329 SourceLocation RPLoc) { 14330 Expr *OrigExpr = E; 14331 bool IsMS = false; 14332 14333 // CUDA device code does not support varargs. 14334 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14335 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14336 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14337 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14338 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14339 } 14340 } 14341 14342 // NVPTX does not support va_arg expression. 14343 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14344 Context.getTargetInfo().getTriple().isNVPTX()) 14345 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14346 14347 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14348 // as Microsoft ABI on an actual Microsoft platform, where 14349 // __builtin_ms_va_list and __builtin_va_list are the same.) 14350 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14351 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14352 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14353 if (Context.hasSameType(MSVaListType, E->getType())) { 14354 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14355 return ExprError(); 14356 IsMS = true; 14357 } 14358 } 14359 14360 // Get the va_list type 14361 QualType VaListType = Context.getBuiltinVaListType(); 14362 if (!IsMS) { 14363 if (VaListType->isArrayType()) { 14364 // Deal with implicit array decay; for example, on x86-64, 14365 // va_list is an array, but it's supposed to decay to 14366 // a pointer for va_arg. 14367 VaListType = Context.getArrayDecayedType(VaListType); 14368 // Make sure the input expression also decays appropriately. 14369 ExprResult Result = UsualUnaryConversions(E); 14370 if (Result.isInvalid()) 14371 return ExprError(); 14372 E = Result.get(); 14373 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14374 // If va_list is a record type and we are compiling in C++ mode, 14375 // check the argument using reference binding. 14376 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14377 Context, Context.getLValueReferenceType(VaListType), false); 14378 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14379 if (Init.isInvalid()) 14380 return ExprError(); 14381 E = Init.getAs<Expr>(); 14382 } else { 14383 // Otherwise, the va_list argument must be an l-value because 14384 // it is modified by va_arg. 14385 if (!E->isTypeDependent() && 14386 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14387 return ExprError(); 14388 } 14389 } 14390 14391 if (!IsMS && !E->isTypeDependent() && 14392 !Context.hasSameType(VaListType, E->getType())) 14393 return ExprError( 14394 Diag(E->getBeginLoc(), 14395 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14396 << OrigExpr->getType() << E->getSourceRange()); 14397 14398 if (!TInfo->getType()->isDependentType()) { 14399 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14400 diag::err_second_parameter_to_va_arg_incomplete, 14401 TInfo->getTypeLoc())) 14402 return ExprError(); 14403 14404 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14405 TInfo->getType(), 14406 diag::err_second_parameter_to_va_arg_abstract, 14407 TInfo->getTypeLoc())) 14408 return ExprError(); 14409 14410 if (!TInfo->getType().isPODType(Context)) { 14411 Diag(TInfo->getTypeLoc().getBeginLoc(), 14412 TInfo->getType()->isObjCLifetimeType() 14413 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14414 : diag::warn_second_parameter_to_va_arg_not_pod) 14415 << TInfo->getType() 14416 << TInfo->getTypeLoc().getSourceRange(); 14417 } 14418 14419 // Check for va_arg where arguments of the given type will be promoted 14420 // (i.e. this va_arg is guaranteed to have undefined behavior). 14421 QualType PromoteType; 14422 if (TInfo->getType()->isPromotableIntegerType()) { 14423 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14424 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14425 PromoteType = QualType(); 14426 } 14427 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14428 PromoteType = Context.DoubleTy; 14429 if (!PromoteType.isNull()) 14430 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14431 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14432 << TInfo->getType() 14433 << PromoteType 14434 << TInfo->getTypeLoc().getSourceRange()); 14435 } 14436 14437 QualType T = TInfo->getType().getNonLValueExprType(Context); 14438 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14439 } 14440 14441 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14442 // The type of __null will be int or long, depending on the size of 14443 // pointers on the target. 14444 QualType Ty; 14445 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14446 if (pw == Context.getTargetInfo().getIntWidth()) 14447 Ty = Context.IntTy; 14448 else if (pw == Context.getTargetInfo().getLongWidth()) 14449 Ty = Context.LongTy; 14450 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14451 Ty = Context.LongLongTy; 14452 else { 14453 llvm_unreachable("I don't know size of pointer!"); 14454 } 14455 14456 return new (Context) GNUNullExpr(Ty, TokenLoc); 14457 } 14458 14459 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14460 SourceLocation BuiltinLoc, 14461 SourceLocation RPLoc) { 14462 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14463 } 14464 14465 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14466 SourceLocation BuiltinLoc, 14467 SourceLocation RPLoc, 14468 DeclContext *ParentContext) { 14469 return new (Context) 14470 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14471 } 14472 14473 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14474 bool Diagnose) { 14475 if (!getLangOpts().ObjC) 14476 return false; 14477 14478 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14479 if (!PT) 14480 return false; 14481 14482 if (!PT->isObjCIdType()) { 14483 // Check if the destination is the 'NSString' interface. 14484 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14485 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14486 return false; 14487 } 14488 14489 // Ignore any parens, implicit casts (should only be 14490 // array-to-pointer decays), and not-so-opaque values. The last is 14491 // important for making this trigger for property assignments. 14492 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14493 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14494 if (OV->getSourceExpr()) 14495 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14496 14497 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14498 if (!SL || !SL->isAscii()) 14499 return false; 14500 if (Diagnose) { 14501 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14502 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14503 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14504 } 14505 return true; 14506 } 14507 14508 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14509 const Expr *SrcExpr) { 14510 if (!DstType->isFunctionPointerType() || 14511 !SrcExpr->getType()->isFunctionType()) 14512 return false; 14513 14514 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14515 if (!DRE) 14516 return false; 14517 14518 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14519 if (!FD) 14520 return false; 14521 14522 return !S.checkAddressOfFunctionIsAvailable(FD, 14523 /*Complain=*/true, 14524 SrcExpr->getBeginLoc()); 14525 } 14526 14527 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14528 SourceLocation Loc, 14529 QualType DstType, QualType SrcType, 14530 Expr *SrcExpr, AssignmentAction Action, 14531 bool *Complained) { 14532 if (Complained) 14533 *Complained = false; 14534 14535 // Decode the result (notice that AST's are still created for extensions). 14536 bool CheckInferredResultType = false; 14537 bool isInvalid = false; 14538 unsigned DiagKind = 0; 14539 FixItHint Hint; 14540 ConversionFixItGenerator ConvHints; 14541 bool MayHaveConvFixit = false; 14542 bool MayHaveFunctionDiff = false; 14543 const ObjCInterfaceDecl *IFace = nullptr; 14544 const ObjCProtocolDecl *PDecl = nullptr; 14545 14546 switch (ConvTy) { 14547 case Compatible: 14548 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14549 return false; 14550 14551 case PointerToInt: 14552 DiagKind = diag::ext_typecheck_convert_pointer_int; 14553 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14554 MayHaveConvFixit = true; 14555 break; 14556 case IntToPointer: 14557 DiagKind = diag::ext_typecheck_convert_int_pointer; 14558 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14559 MayHaveConvFixit = true; 14560 break; 14561 case IncompatiblePointer: 14562 if (Action == AA_Passing_CFAudited) 14563 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14564 else if (SrcType->isFunctionPointerType() && 14565 DstType->isFunctionPointerType()) 14566 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14567 else 14568 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14569 14570 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14571 SrcType->isObjCObjectPointerType(); 14572 if (Hint.isNull() && !CheckInferredResultType) { 14573 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14574 } 14575 else if (CheckInferredResultType) { 14576 SrcType = SrcType.getUnqualifiedType(); 14577 DstType = DstType.getUnqualifiedType(); 14578 } 14579 MayHaveConvFixit = true; 14580 break; 14581 case IncompatiblePointerSign: 14582 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14583 break; 14584 case FunctionVoidPointer: 14585 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14586 break; 14587 case IncompatiblePointerDiscardsQualifiers: { 14588 // Perform array-to-pointer decay if necessary. 14589 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14590 14591 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14592 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14593 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14594 DiagKind = diag::err_typecheck_incompatible_address_space; 14595 break; 14596 14597 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14598 DiagKind = diag::err_typecheck_incompatible_ownership; 14599 break; 14600 } 14601 14602 llvm_unreachable("unknown error case for discarding qualifiers!"); 14603 // fallthrough 14604 } 14605 case CompatiblePointerDiscardsQualifiers: 14606 // If the qualifiers lost were because we were applying the 14607 // (deprecated) C++ conversion from a string literal to a char* 14608 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14609 // Ideally, this check would be performed in 14610 // checkPointerTypesForAssignment. However, that would require a 14611 // bit of refactoring (so that the second argument is an 14612 // expression, rather than a type), which should be done as part 14613 // of a larger effort to fix checkPointerTypesForAssignment for 14614 // C++ semantics. 14615 if (getLangOpts().CPlusPlus && 14616 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14617 return false; 14618 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14619 break; 14620 case IncompatibleNestedPointerQualifiers: 14621 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14622 break; 14623 case IncompatibleNestedPointerAddressSpaceMismatch: 14624 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14625 break; 14626 case IntToBlockPointer: 14627 DiagKind = diag::err_int_to_block_pointer; 14628 break; 14629 case IncompatibleBlockPointer: 14630 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14631 break; 14632 case IncompatibleObjCQualifiedId: { 14633 if (SrcType->isObjCQualifiedIdType()) { 14634 const ObjCObjectPointerType *srcOPT = 14635 SrcType->getAs<ObjCObjectPointerType>(); 14636 for (auto *srcProto : srcOPT->quals()) { 14637 PDecl = srcProto; 14638 break; 14639 } 14640 if (const ObjCInterfaceType *IFaceT = 14641 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14642 IFace = IFaceT->getDecl(); 14643 } 14644 else if (DstType->isObjCQualifiedIdType()) { 14645 const ObjCObjectPointerType *dstOPT = 14646 DstType->getAs<ObjCObjectPointerType>(); 14647 for (auto *dstProto : dstOPT->quals()) { 14648 PDecl = dstProto; 14649 break; 14650 } 14651 if (const ObjCInterfaceType *IFaceT = 14652 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14653 IFace = IFaceT->getDecl(); 14654 } 14655 DiagKind = diag::warn_incompatible_qualified_id; 14656 break; 14657 } 14658 case IncompatibleVectors: 14659 DiagKind = diag::warn_incompatible_vectors; 14660 break; 14661 case IncompatibleObjCWeakRef: 14662 DiagKind = diag::err_arc_weak_unavailable_assign; 14663 break; 14664 case Incompatible: 14665 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14666 if (Complained) 14667 *Complained = true; 14668 return true; 14669 } 14670 14671 DiagKind = diag::err_typecheck_convert_incompatible; 14672 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14673 MayHaveConvFixit = true; 14674 isInvalid = true; 14675 MayHaveFunctionDiff = true; 14676 break; 14677 } 14678 14679 QualType FirstType, SecondType; 14680 switch (Action) { 14681 case AA_Assigning: 14682 case AA_Initializing: 14683 // The destination type comes first. 14684 FirstType = DstType; 14685 SecondType = SrcType; 14686 break; 14687 14688 case AA_Returning: 14689 case AA_Passing: 14690 case AA_Passing_CFAudited: 14691 case AA_Converting: 14692 case AA_Sending: 14693 case AA_Casting: 14694 // The source type comes first. 14695 FirstType = SrcType; 14696 SecondType = DstType; 14697 break; 14698 } 14699 14700 PartialDiagnostic FDiag = PDiag(DiagKind); 14701 if (Action == AA_Passing_CFAudited) 14702 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14703 else 14704 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14705 14706 // If we can fix the conversion, suggest the FixIts. 14707 assert(ConvHints.isNull() || Hint.isNull()); 14708 if (!ConvHints.isNull()) { 14709 for (FixItHint &H : ConvHints.Hints) 14710 FDiag << H; 14711 } else { 14712 FDiag << Hint; 14713 } 14714 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14715 14716 if (MayHaveFunctionDiff) 14717 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14718 14719 Diag(Loc, FDiag); 14720 if (DiagKind == diag::warn_incompatible_qualified_id && 14721 PDecl && IFace && !IFace->hasDefinition()) 14722 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14723 << IFace << PDecl; 14724 14725 if (SecondType == Context.OverloadTy) 14726 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14727 FirstType, /*TakingAddress=*/true); 14728 14729 if (CheckInferredResultType) 14730 EmitRelatedResultTypeNote(SrcExpr); 14731 14732 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14733 EmitRelatedResultTypeNoteForReturn(DstType); 14734 14735 if (Complained) 14736 *Complained = true; 14737 return isInvalid; 14738 } 14739 14740 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14741 llvm::APSInt *Result) { 14742 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14743 public: 14744 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14745 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14746 } 14747 } Diagnoser; 14748 14749 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14750 } 14751 14752 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14753 llvm::APSInt *Result, 14754 unsigned DiagID, 14755 bool AllowFold) { 14756 class IDDiagnoser : public VerifyICEDiagnoser { 14757 unsigned DiagID; 14758 14759 public: 14760 IDDiagnoser(unsigned DiagID) 14761 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14762 14763 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14764 S.Diag(Loc, DiagID) << SR; 14765 } 14766 } Diagnoser(DiagID); 14767 14768 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14769 } 14770 14771 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14772 SourceRange SR) { 14773 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14774 } 14775 14776 ExprResult 14777 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14778 VerifyICEDiagnoser &Diagnoser, 14779 bool AllowFold) { 14780 SourceLocation DiagLoc = E->getBeginLoc(); 14781 14782 if (getLangOpts().CPlusPlus11) { 14783 // C++11 [expr.const]p5: 14784 // If an expression of literal class type is used in a context where an 14785 // integral constant expression is required, then that class type shall 14786 // have a single non-explicit conversion function to an integral or 14787 // unscoped enumeration type 14788 ExprResult Converted; 14789 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14790 public: 14791 CXX11ConvertDiagnoser(bool Silent) 14792 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14793 Silent, true) {} 14794 14795 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14796 QualType T) override { 14797 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14798 } 14799 14800 SemaDiagnosticBuilder diagnoseIncomplete( 14801 Sema &S, SourceLocation Loc, QualType T) override { 14802 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14803 } 14804 14805 SemaDiagnosticBuilder diagnoseExplicitConv( 14806 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14807 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14808 } 14809 14810 SemaDiagnosticBuilder noteExplicitConv( 14811 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14812 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14813 << ConvTy->isEnumeralType() << ConvTy; 14814 } 14815 14816 SemaDiagnosticBuilder diagnoseAmbiguous( 14817 Sema &S, SourceLocation Loc, QualType T) override { 14818 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14819 } 14820 14821 SemaDiagnosticBuilder noteAmbiguous( 14822 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14823 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14824 << ConvTy->isEnumeralType() << ConvTy; 14825 } 14826 14827 SemaDiagnosticBuilder diagnoseConversion( 14828 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14829 llvm_unreachable("conversion functions are permitted"); 14830 } 14831 } ConvertDiagnoser(Diagnoser.Suppress); 14832 14833 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14834 ConvertDiagnoser); 14835 if (Converted.isInvalid()) 14836 return Converted; 14837 E = Converted.get(); 14838 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14839 return ExprError(); 14840 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14841 // An ICE must be of integral or unscoped enumeration type. 14842 if (!Diagnoser.Suppress) 14843 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14844 return ExprError(); 14845 } 14846 14847 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14848 // in the non-ICE case. 14849 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14850 if (Result) 14851 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14852 if (!isa<ConstantExpr>(E)) 14853 E = ConstantExpr::Create(Context, E); 14854 return E; 14855 } 14856 14857 Expr::EvalResult EvalResult; 14858 SmallVector<PartialDiagnosticAt, 8> Notes; 14859 EvalResult.Diag = &Notes; 14860 14861 // Try to evaluate the expression, and produce diagnostics explaining why it's 14862 // not a constant expression as a side-effect. 14863 bool Folded = 14864 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 14865 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14866 14867 if (!isa<ConstantExpr>(E)) 14868 E = ConstantExpr::Create(Context, E, EvalResult.Val); 14869 14870 // In C++11, we can rely on diagnostics being produced for any expression 14871 // which is not a constant expression. If no diagnostics were produced, then 14872 // this is a constant expression. 14873 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14874 if (Result) 14875 *Result = EvalResult.Val.getInt(); 14876 return E; 14877 } 14878 14879 // If our only note is the usual "invalid subexpression" note, just point 14880 // the caret at its location rather than producing an essentially 14881 // redundant note. 14882 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14883 diag::note_invalid_subexpr_in_const_expr) { 14884 DiagLoc = Notes[0].first; 14885 Notes.clear(); 14886 } 14887 14888 if (!Folded || !AllowFold) { 14889 if (!Diagnoser.Suppress) { 14890 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14891 for (const PartialDiagnosticAt &Note : Notes) 14892 Diag(Note.first, Note.second); 14893 } 14894 14895 return ExprError(); 14896 } 14897 14898 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14899 for (const PartialDiagnosticAt &Note : Notes) 14900 Diag(Note.first, Note.second); 14901 14902 if (Result) 14903 *Result = EvalResult.Val.getInt(); 14904 return E; 14905 } 14906 14907 namespace { 14908 // Handle the case where we conclude a expression which we speculatively 14909 // considered to be unevaluated is actually evaluated. 14910 class TransformToPE : public TreeTransform<TransformToPE> { 14911 typedef TreeTransform<TransformToPE> BaseTransform; 14912 14913 public: 14914 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14915 14916 // Make sure we redo semantic analysis 14917 bool AlwaysRebuild() { return true; } 14918 bool ReplacingOriginal() { return true; } 14919 14920 // We need to special-case DeclRefExprs referring to FieldDecls which 14921 // are not part of a member pointer formation; normal TreeTransforming 14922 // doesn't catch this case because of the way we represent them in the AST. 14923 // FIXME: This is a bit ugly; is it really the best way to handle this 14924 // case? 14925 // 14926 // Error on DeclRefExprs referring to FieldDecls. 14927 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14928 if (isa<FieldDecl>(E->getDecl()) && 14929 !SemaRef.isUnevaluatedContext()) 14930 return SemaRef.Diag(E->getLocation(), 14931 diag::err_invalid_non_static_member_use) 14932 << E->getDecl() << E->getSourceRange(); 14933 14934 return BaseTransform::TransformDeclRefExpr(E); 14935 } 14936 14937 // Exception: filter out member pointer formation 14938 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14939 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14940 return E; 14941 14942 return BaseTransform::TransformUnaryOperator(E); 14943 } 14944 14945 // The body of a lambda-expression is in a separate expression evaluation 14946 // context so never needs to be transformed. 14947 // FIXME: Ideally we wouldn't transform the closure type either, and would 14948 // just recreate the capture expressions and lambda expression. 14949 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 14950 return SkipLambdaBody(E, Body); 14951 } 14952 }; 14953 } 14954 14955 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14956 assert(isUnevaluatedContext() && 14957 "Should only transform unevaluated expressions"); 14958 ExprEvalContexts.back().Context = 14959 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14960 if (isUnevaluatedContext()) 14961 return E; 14962 return TransformToPE(*this).TransformExpr(E); 14963 } 14964 14965 void 14966 Sema::PushExpressionEvaluationContext( 14967 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14968 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14969 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14970 LambdaContextDecl, ExprContext); 14971 Cleanup.reset(); 14972 if (!MaybeODRUseExprs.empty()) 14973 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14974 } 14975 14976 void 14977 Sema::PushExpressionEvaluationContext( 14978 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14979 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14980 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14981 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14982 } 14983 14984 namespace { 14985 14986 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 14987 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 14988 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 14989 if (E->getOpcode() == UO_Deref) 14990 return CheckPossibleDeref(S, E->getSubExpr()); 14991 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 14992 return CheckPossibleDeref(S, E->getBase()); 14993 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 14994 return CheckPossibleDeref(S, E->getBase()); 14995 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 14996 QualType Inner; 14997 QualType Ty = E->getType(); 14998 if (const auto *Ptr = Ty->getAs<PointerType>()) 14999 Inner = Ptr->getPointeeType(); 15000 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15001 Inner = Arr->getElementType(); 15002 else 15003 return nullptr; 15004 15005 if (Inner->hasAttr(attr::NoDeref)) 15006 return E; 15007 } 15008 return nullptr; 15009 } 15010 15011 } // namespace 15012 15013 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15014 for (const Expr *E : Rec.PossibleDerefs) { 15015 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15016 if (DeclRef) { 15017 const ValueDecl *Decl = DeclRef->getDecl(); 15018 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15019 << Decl->getName() << E->getSourceRange(); 15020 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15021 } else { 15022 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15023 << E->getSourceRange(); 15024 } 15025 } 15026 Rec.PossibleDerefs.clear(); 15027 } 15028 15029 void Sema::PopExpressionEvaluationContext() { 15030 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15031 unsigned NumTypos = Rec.NumTypos; 15032 15033 if (!Rec.Lambdas.empty()) { 15034 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15035 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15036 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15037 unsigned D; 15038 if (Rec.isUnevaluated()) { 15039 // C++11 [expr.prim.lambda]p2: 15040 // A lambda-expression shall not appear in an unevaluated operand 15041 // (Clause 5). 15042 D = diag::err_lambda_unevaluated_operand; 15043 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15044 // C++1y [expr.const]p2: 15045 // A conditional-expression e is a core constant expression unless the 15046 // evaluation of e, following the rules of the abstract machine, would 15047 // evaluate [...] a lambda-expression. 15048 D = diag::err_lambda_in_constant_expression; 15049 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15050 // C++17 [expr.prim.lamda]p2: 15051 // A lambda-expression shall not appear [...] in a template-argument. 15052 D = diag::err_lambda_in_invalid_context; 15053 } else 15054 llvm_unreachable("Couldn't infer lambda error message."); 15055 15056 for (const auto *L : Rec.Lambdas) 15057 Diag(L->getBeginLoc(), D); 15058 } 15059 } 15060 15061 WarnOnPendingNoDerefs(Rec); 15062 15063 // When are coming out of an unevaluated context, clear out any 15064 // temporaries that we may have created as part of the evaluation of 15065 // the expression in that context: they aren't relevant because they 15066 // will never be constructed. 15067 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15068 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15069 ExprCleanupObjects.end()); 15070 Cleanup = Rec.ParentCleanup; 15071 CleanupVarDeclMarking(); 15072 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15073 // Otherwise, merge the contexts together. 15074 } else { 15075 Cleanup.mergeFrom(Rec.ParentCleanup); 15076 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15077 Rec.SavedMaybeODRUseExprs.end()); 15078 } 15079 15080 // Pop the current expression evaluation context off the stack. 15081 ExprEvalContexts.pop_back(); 15082 15083 // The global expression evaluation context record is never popped. 15084 ExprEvalContexts.back().NumTypos += NumTypos; 15085 } 15086 15087 void Sema::DiscardCleanupsInEvaluationContext() { 15088 ExprCleanupObjects.erase( 15089 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15090 ExprCleanupObjects.end()); 15091 Cleanup.reset(); 15092 MaybeODRUseExprs.clear(); 15093 } 15094 15095 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15096 ExprResult Result = CheckPlaceholderExpr(E); 15097 if (Result.isInvalid()) 15098 return ExprError(); 15099 E = Result.get(); 15100 if (!E->getType()->isVariablyModifiedType()) 15101 return E; 15102 return TransformToPotentiallyEvaluated(E); 15103 } 15104 15105 /// Are we in a context that is potentially constant evaluated per C++20 15106 /// [expr.const]p12? 15107 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15108 /// C++2a [expr.const]p12: 15109 // An expression or conversion is potentially constant evaluated if it is 15110 switch (SemaRef.ExprEvalContexts.back().Context) { 15111 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15112 // -- a manifestly constant-evaluated expression, 15113 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15114 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15115 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15116 // -- a potentially-evaluated expression, 15117 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15118 // -- an immediate subexpression of a braced-init-list, 15119 15120 // -- [FIXME] an expression of the form & cast-expression that occurs 15121 // within a templated entity 15122 // -- a subexpression of one of the above that is not a subexpression of 15123 // a nested unevaluated operand. 15124 return true; 15125 15126 case Sema::ExpressionEvaluationContext::Unevaluated: 15127 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15128 // Expressions in this context are never evaluated. 15129 return false; 15130 } 15131 llvm_unreachable("Invalid context"); 15132 } 15133 15134 /// Return true if this function has a calling convention that requires mangling 15135 /// in the size of the parameter pack. 15136 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15137 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15138 // we don't need parameter type sizes. 15139 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15140 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15141 TT.getArch() != llvm::Triple::x86_64)) 15142 return false; 15143 15144 // If this is C++ and this isn't an extern "C" function, parameters do not 15145 // need to be complete. In this case, C++ mangling will apply, which doesn't 15146 // use the size of the parameters. 15147 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15148 return false; 15149 15150 // Stdcall, fastcall, and vectorcall need this special treatment. 15151 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15152 switch (CC) { 15153 case CC_X86StdCall: 15154 case CC_X86FastCall: 15155 case CC_X86VectorCall: 15156 return true; 15157 default: 15158 break; 15159 } 15160 return false; 15161 } 15162 15163 /// Require that all of the parameter types of function be complete. Normally, 15164 /// parameter types are only required to be complete when a function is called 15165 /// or defined, but to mangle functions with certain calling conventions, the 15166 /// mangler needs to know the size of the parameter list. In this situation, 15167 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15168 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15169 /// result in a linker error. Clang doesn't implement this behavior, and instead 15170 /// attempts to error at compile time. 15171 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15172 SourceLocation Loc) { 15173 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15174 FunctionDecl *FD; 15175 ParmVarDecl *Param; 15176 15177 public: 15178 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15179 : FD(FD), Param(Param) {} 15180 15181 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15182 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15183 StringRef CCName; 15184 switch (CC) { 15185 case CC_X86StdCall: 15186 CCName = "stdcall"; 15187 break; 15188 case CC_X86FastCall: 15189 CCName = "fastcall"; 15190 break; 15191 case CC_X86VectorCall: 15192 CCName = "vectorcall"; 15193 break; 15194 default: 15195 llvm_unreachable("CC does not need mangling"); 15196 } 15197 15198 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15199 << Param->getDeclName() << FD->getDeclName() << CCName; 15200 } 15201 }; 15202 15203 for (ParmVarDecl *Param : FD->parameters()) { 15204 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15205 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15206 } 15207 } 15208 15209 namespace { 15210 enum class OdrUseContext { 15211 /// Declarations in this context are not odr-used. 15212 None, 15213 /// Declarations in this context are formally odr-used, but this is a 15214 /// dependent context. 15215 Dependent, 15216 /// Declarations in this context are odr-used but not actually used (yet). 15217 FormallyOdrUsed, 15218 /// Declarations in this context are used. 15219 Used 15220 }; 15221 } 15222 15223 /// Are we within a context in which references to resolved functions or to 15224 /// variables result in odr-use? 15225 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15226 OdrUseContext Result; 15227 15228 switch (SemaRef.ExprEvalContexts.back().Context) { 15229 case Sema::ExpressionEvaluationContext::Unevaluated: 15230 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15231 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15232 return OdrUseContext::None; 15233 15234 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15235 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15236 Result = OdrUseContext::Used; 15237 break; 15238 15239 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15240 Result = OdrUseContext::FormallyOdrUsed; 15241 break; 15242 15243 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15244 // A default argument formally results in odr-use, but doesn't actually 15245 // result in a use in any real sense until it itself is used. 15246 Result = OdrUseContext::FormallyOdrUsed; 15247 break; 15248 } 15249 15250 if (SemaRef.CurContext->isDependentContext()) 15251 return OdrUseContext::Dependent; 15252 15253 return Result; 15254 } 15255 15256 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15257 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 15258 return Func->isConstexpr() && 15259 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 15260 } 15261 15262 /// Mark a function referenced, and check whether it is odr-used 15263 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15264 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15265 bool MightBeOdrUse) { 15266 assert(Func && "No function?"); 15267 15268 Func->setReferenced(); 15269 15270 // Recursive functions aren't really used until they're used from some other 15271 // context. 15272 bool IsRecursiveCall = CurContext == Func; 15273 15274 // C++11 [basic.def.odr]p3: 15275 // A function whose name appears as a potentially-evaluated expression is 15276 // odr-used if it is the unique lookup result or the selected member of a 15277 // set of overloaded functions [...]. 15278 // 15279 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15280 // can just check that here. 15281 OdrUseContext OdrUse = 15282 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15283 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15284 OdrUse = OdrUseContext::FormallyOdrUsed; 15285 15286 // Trivial default constructors and destructors are never actually used. 15287 // FIXME: What about other special members? 15288 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15289 OdrUse == OdrUseContext::Used) { 15290 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15291 if (Constructor->isDefaultConstructor()) 15292 OdrUse = OdrUseContext::FormallyOdrUsed; 15293 if (isa<CXXDestructorDecl>(Func)) 15294 OdrUse = OdrUseContext::FormallyOdrUsed; 15295 } 15296 15297 // C++20 [expr.const]p12: 15298 // A function [...] is needed for constant evaluation if it is [...] a 15299 // constexpr function that is named by an expression that is potentially 15300 // constant evaluated 15301 bool NeededForConstantEvaluation = 15302 isPotentiallyConstantEvaluatedContext(*this) && 15303 isImplicitlyDefinableConstexprFunction(Func); 15304 15305 // Determine whether we require a function definition to exist, per 15306 // C++11 [temp.inst]p3: 15307 // Unless a function template specialization has been explicitly 15308 // instantiated or explicitly specialized, the function template 15309 // specialization is implicitly instantiated when the specialization is 15310 // referenced in a context that requires a function definition to exist. 15311 // C++20 [temp.inst]p7: 15312 // The existence of a definition of a [...] function is considered to 15313 // affect the semantics of the program if the [...] function is needed for 15314 // constant evaluation by an expression 15315 // C++20 [basic.def.odr]p10: 15316 // Every program shall contain exactly one definition of every non-inline 15317 // function or variable that is odr-used in that program outside of a 15318 // discarded statement 15319 // C++20 [special]p1: 15320 // The implementation will implicitly define [defaulted special members] 15321 // if they are odr-used or needed for constant evaluation. 15322 // 15323 // Note that we skip the implicit instantiation of templates that are only 15324 // used in unused default arguments or by recursive calls to themselves. 15325 // This is formally non-conforming, but seems reasonable in practice. 15326 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15327 NeededForConstantEvaluation); 15328 15329 // C++14 [temp.expl.spec]p6: 15330 // If a template [...] is explicitly specialized then that specialization 15331 // shall be declared before the first use of that specialization that would 15332 // cause an implicit instantiation to take place, in every translation unit 15333 // in which such a use occurs 15334 if (NeedDefinition && 15335 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15336 Func->getMemberSpecializationInfo())) 15337 checkSpecializationVisibility(Loc, Func); 15338 15339 // C++14 [except.spec]p17: 15340 // An exception-specification is considered to be needed when: 15341 // - the function is odr-used or, if it appears in an unevaluated operand, 15342 // would be odr-used if the expression were potentially-evaluated; 15343 // 15344 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15345 // function is a pure virtual function we're calling, and in that case the 15346 // function was selected by overload resolution and we need to resolve its 15347 // exception specification for a different reason. 15348 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15349 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15350 ResolveExceptionSpec(Loc, FPT); 15351 15352 if (getLangOpts().CUDA) 15353 CheckCUDACall(Loc, Func); 15354 15355 // If we need a definition, try to create one. 15356 if (NeedDefinition && !Func->getBody()) { 15357 runWithSufficientStackSpace(Loc, [&] { 15358 if (CXXConstructorDecl *Constructor = 15359 dyn_cast<CXXConstructorDecl>(Func)) { 15360 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15361 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15362 if (Constructor->isDefaultConstructor()) { 15363 if (Constructor->isTrivial() && 15364 !Constructor->hasAttr<DLLExportAttr>()) 15365 return; 15366 DefineImplicitDefaultConstructor(Loc, Constructor); 15367 } else if (Constructor->isCopyConstructor()) { 15368 DefineImplicitCopyConstructor(Loc, Constructor); 15369 } else if (Constructor->isMoveConstructor()) { 15370 DefineImplicitMoveConstructor(Loc, Constructor); 15371 } 15372 } else if (Constructor->getInheritedConstructor()) { 15373 DefineInheritingConstructor(Loc, Constructor); 15374 } 15375 } else if (CXXDestructorDecl *Destructor = 15376 dyn_cast<CXXDestructorDecl>(Func)) { 15377 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15378 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15379 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15380 return; 15381 DefineImplicitDestructor(Loc, Destructor); 15382 } 15383 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15384 MarkVTableUsed(Loc, Destructor->getParent()); 15385 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15386 if (MethodDecl->isOverloadedOperator() && 15387 MethodDecl->getOverloadedOperator() == OO_Equal) { 15388 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15389 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15390 if (MethodDecl->isCopyAssignmentOperator()) 15391 DefineImplicitCopyAssignment(Loc, MethodDecl); 15392 else if (MethodDecl->isMoveAssignmentOperator()) 15393 DefineImplicitMoveAssignment(Loc, MethodDecl); 15394 } 15395 } else if (isa<CXXConversionDecl>(MethodDecl) && 15396 MethodDecl->getParent()->isLambda()) { 15397 CXXConversionDecl *Conversion = 15398 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15399 if (Conversion->isLambdaToBlockPointerConversion()) 15400 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15401 else 15402 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15403 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15404 MarkVTableUsed(Loc, MethodDecl->getParent()); 15405 } 15406 15407 // Implicit instantiation of function templates and member functions of 15408 // class templates. 15409 if (Func->isImplicitlyInstantiable()) { 15410 TemplateSpecializationKind TSK = 15411 Func->getTemplateSpecializationKindForInstantiation(); 15412 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15413 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15414 if (FirstInstantiation) { 15415 PointOfInstantiation = Loc; 15416 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15417 } else if (TSK != TSK_ImplicitInstantiation) { 15418 // Use the point of use as the point of instantiation, instead of the 15419 // point of explicit instantiation (which we track as the actual point 15420 // of instantiation). This gives better backtraces in diagnostics. 15421 PointOfInstantiation = Loc; 15422 } 15423 15424 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15425 Func->isConstexpr()) { 15426 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15427 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15428 CodeSynthesisContexts.size()) 15429 PendingLocalImplicitInstantiations.push_back( 15430 std::make_pair(Func, PointOfInstantiation)); 15431 else if (Func->isConstexpr()) 15432 // Do not defer instantiations of constexpr functions, to avoid the 15433 // expression evaluator needing to call back into Sema if it sees a 15434 // call to such a function. 15435 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15436 else { 15437 Func->setInstantiationIsPending(true); 15438 PendingInstantiations.push_back( 15439 std::make_pair(Func, PointOfInstantiation)); 15440 // Notify the consumer that a function was implicitly instantiated. 15441 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15442 } 15443 } 15444 } else { 15445 // Walk redefinitions, as some of them may be instantiable. 15446 for (auto i : Func->redecls()) { 15447 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15448 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15449 } 15450 } 15451 }); 15452 } 15453 15454 // If this is the first "real" use, act on that. 15455 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15456 // Keep track of used but undefined functions. 15457 if (!Func->isDefined()) { 15458 if (mightHaveNonExternalLinkage(Func)) 15459 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15460 else if (Func->getMostRecentDecl()->isInlined() && 15461 !LangOpts.GNUInline && 15462 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15463 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15464 else if (isExternalWithNoLinkageType(Func)) 15465 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15466 } 15467 15468 // Some x86 Windows calling conventions mangle the size of the parameter 15469 // pack into the name. Computing the size of the parameters requires the 15470 // parameter types to be complete. Check that now. 15471 if (funcHasParameterSizeMangling(*this, Func)) 15472 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15473 15474 Func->markUsed(Context); 15475 } 15476 15477 if (LangOpts.OpenMP) { 15478 if (LangOpts.OpenMPIsDevice) 15479 checkOpenMPDeviceFunction(Loc, Func); 15480 else 15481 checkOpenMPHostFunction(Loc, Func); 15482 } 15483 } 15484 15485 /// Directly mark a variable odr-used. Given a choice, prefer to use 15486 /// MarkVariableReferenced since it does additional checks and then 15487 /// calls MarkVarDeclODRUsed. 15488 /// If the variable must be captured: 15489 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15490 /// - else capture it in the DeclContext that maps to the 15491 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15492 static void 15493 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15494 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15495 // Keep track of used but undefined variables. 15496 // FIXME: We shouldn't suppress this warning for static data members. 15497 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15498 (!Var->isExternallyVisible() || Var->isInline() || 15499 SemaRef.isExternalWithNoLinkageType(Var)) && 15500 !(Var->isStaticDataMember() && Var->hasInit())) { 15501 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15502 if (old.isInvalid()) 15503 old = Loc; 15504 } 15505 QualType CaptureType, DeclRefType; 15506 if (SemaRef.LangOpts.OpenMP) 15507 SemaRef.tryCaptureOpenMPLambdas(Var); 15508 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15509 /*EllipsisLoc*/ SourceLocation(), 15510 /*BuildAndDiagnose*/ true, 15511 CaptureType, DeclRefType, 15512 FunctionScopeIndexToStopAt); 15513 15514 Var->markUsed(SemaRef.Context); 15515 } 15516 15517 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15518 SourceLocation Loc, 15519 unsigned CapturingScopeIndex) { 15520 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15521 } 15522 15523 static void 15524 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15525 ValueDecl *var, DeclContext *DC) { 15526 DeclContext *VarDC = var->getDeclContext(); 15527 15528 // If the parameter still belongs to the translation unit, then 15529 // we're actually just using one parameter in the declaration of 15530 // the next. 15531 if (isa<ParmVarDecl>(var) && 15532 isa<TranslationUnitDecl>(VarDC)) 15533 return; 15534 15535 // For C code, don't diagnose about capture if we're not actually in code 15536 // right now; it's impossible to write a non-constant expression outside of 15537 // function context, so we'll get other (more useful) diagnostics later. 15538 // 15539 // For C++, things get a bit more nasty... it would be nice to suppress this 15540 // diagnostic for certain cases like using a local variable in an array bound 15541 // for a member of a local class, but the correct predicate is not obvious. 15542 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15543 return; 15544 15545 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15546 unsigned ContextKind = 3; // unknown 15547 if (isa<CXXMethodDecl>(VarDC) && 15548 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15549 ContextKind = 2; 15550 } else if (isa<FunctionDecl>(VarDC)) { 15551 ContextKind = 0; 15552 } else if (isa<BlockDecl>(VarDC)) { 15553 ContextKind = 1; 15554 } 15555 15556 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15557 << var << ValueKind << ContextKind << VarDC; 15558 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15559 << var; 15560 15561 // FIXME: Add additional diagnostic info about class etc. which prevents 15562 // capture. 15563 } 15564 15565 15566 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15567 bool &SubCapturesAreNested, 15568 QualType &CaptureType, 15569 QualType &DeclRefType) { 15570 // Check whether we've already captured it. 15571 if (CSI->CaptureMap.count(Var)) { 15572 // If we found a capture, any subcaptures are nested. 15573 SubCapturesAreNested = true; 15574 15575 // Retrieve the capture type for this variable. 15576 CaptureType = CSI->getCapture(Var).getCaptureType(); 15577 15578 // Compute the type of an expression that refers to this variable. 15579 DeclRefType = CaptureType.getNonReferenceType(); 15580 15581 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15582 // are mutable in the sense that user can change their value - they are 15583 // private instances of the captured declarations. 15584 const Capture &Cap = CSI->getCapture(Var); 15585 if (Cap.isCopyCapture() && 15586 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15587 !(isa<CapturedRegionScopeInfo>(CSI) && 15588 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15589 DeclRefType.addConst(); 15590 return true; 15591 } 15592 return false; 15593 } 15594 15595 // Only block literals, captured statements, and lambda expressions can 15596 // capture; other scopes don't work. 15597 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15598 SourceLocation Loc, 15599 const bool Diagnose, Sema &S) { 15600 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15601 return getLambdaAwareParentOfDeclContext(DC); 15602 else if (Var->hasLocalStorage()) { 15603 if (Diagnose) 15604 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15605 } 15606 return nullptr; 15607 } 15608 15609 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15610 // certain types of variables (unnamed, variably modified types etc.) 15611 // so check for eligibility. 15612 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15613 SourceLocation Loc, 15614 const bool Diagnose, Sema &S) { 15615 15616 bool IsBlock = isa<BlockScopeInfo>(CSI); 15617 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15618 15619 // Lambdas are not allowed to capture unnamed variables 15620 // (e.g. anonymous unions). 15621 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15622 // assuming that's the intent. 15623 if (IsLambda && !Var->getDeclName()) { 15624 if (Diagnose) { 15625 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15626 S.Diag(Var->getLocation(), diag::note_declared_at); 15627 } 15628 return false; 15629 } 15630 15631 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15632 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15633 if (Diagnose) { 15634 S.Diag(Loc, diag::err_ref_vm_type); 15635 S.Diag(Var->getLocation(), diag::note_previous_decl) 15636 << Var->getDeclName(); 15637 } 15638 return false; 15639 } 15640 // Prohibit structs with flexible array members too. 15641 // We cannot capture what is in the tail end of the struct. 15642 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15643 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15644 if (Diagnose) { 15645 if (IsBlock) 15646 S.Diag(Loc, diag::err_ref_flexarray_type); 15647 else 15648 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15649 << Var->getDeclName(); 15650 S.Diag(Var->getLocation(), diag::note_previous_decl) 15651 << Var->getDeclName(); 15652 } 15653 return false; 15654 } 15655 } 15656 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15657 // Lambdas and captured statements are not allowed to capture __block 15658 // variables; they don't support the expected semantics. 15659 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15660 if (Diagnose) { 15661 S.Diag(Loc, diag::err_capture_block_variable) 15662 << Var->getDeclName() << !IsLambda; 15663 S.Diag(Var->getLocation(), diag::note_previous_decl) 15664 << Var->getDeclName(); 15665 } 15666 return false; 15667 } 15668 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15669 if (S.getLangOpts().OpenCL && IsBlock && 15670 Var->getType()->isBlockPointerType()) { 15671 if (Diagnose) 15672 S.Diag(Loc, diag::err_opencl_block_ref_block); 15673 return false; 15674 } 15675 15676 return true; 15677 } 15678 15679 // Returns true if the capture by block was successful. 15680 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15681 SourceLocation Loc, 15682 const bool BuildAndDiagnose, 15683 QualType &CaptureType, 15684 QualType &DeclRefType, 15685 const bool Nested, 15686 Sema &S, bool Invalid) { 15687 bool ByRef = false; 15688 15689 // Blocks are not allowed to capture arrays, excepting OpenCL. 15690 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15691 // (decayed to pointers). 15692 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15693 if (BuildAndDiagnose) { 15694 S.Diag(Loc, diag::err_ref_array_type); 15695 S.Diag(Var->getLocation(), diag::note_previous_decl) 15696 << Var->getDeclName(); 15697 Invalid = true; 15698 } else { 15699 return false; 15700 } 15701 } 15702 15703 // Forbid the block-capture of autoreleasing variables. 15704 if (!Invalid && 15705 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15706 if (BuildAndDiagnose) { 15707 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15708 << /*block*/ 0; 15709 S.Diag(Var->getLocation(), diag::note_previous_decl) 15710 << Var->getDeclName(); 15711 Invalid = true; 15712 } else { 15713 return false; 15714 } 15715 } 15716 15717 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15718 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15719 QualType PointeeTy = PT->getPointeeType(); 15720 15721 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15722 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15723 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15724 if (BuildAndDiagnose) { 15725 SourceLocation VarLoc = Var->getLocation(); 15726 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15727 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15728 } 15729 } 15730 } 15731 15732 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15733 if (HasBlocksAttr || CaptureType->isReferenceType() || 15734 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15735 // Block capture by reference does not change the capture or 15736 // declaration reference types. 15737 ByRef = true; 15738 } else { 15739 // Block capture by copy introduces 'const'. 15740 CaptureType = CaptureType.getNonReferenceType().withConst(); 15741 DeclRefType = CaptureType; 15742 } 15743 15744 // Actually capture the variable. 15745 if (BuildAndDiagnose) 15746 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15747 CaptureType, Invalid); 15748 15749 return !Invalid; 15750 } 15751 15752 15753 /// Capture the given variable in the captured region. 15754 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15755 VarDecl *Var, 15756 SourceLocation Loc, 15757 const bool BuildAndDiagnose, 15758 QualType &CaptureType, 15759 QualType &DeclRefType, 15760 const bool RefersToCapturedVariable, 15761 Sema &S, bool Invalid) { 15762 // By default, capture variables by reference. 15763 bool ByRef = true; 15764 // Using an LValue reference type is consistent with Lambdas (see below). 15765 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15766 if (S.isOpenMPCapturedDecl(Var)) { 15767 bool HasConst = DeclRefType.isConstQualified(); 15768 DeclRefType = DeclRefType.getUnqualifiedType(); 15769 // Don't lose diagnostics about assignments to const. 15770 if (HasConst) 15771 DeclRefType.addConst(); 15772 } 15773 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15774 RSI->OpenMPCaptureLevel); 15775 } 15776 15777 if (ByRef) 15778 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15779 else 15780 CaptureType = DeclRefType; 15781 15782 // Actually capture the variable. 15783 if (BuildAndDiagnose) 15784 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15785 Loc, SourceLocation(), CaptureType, Invalid); 15786 15787 return !Invalid; 15788 } 15789 15790 /// Capture the given variable in the lambda. 15791 static bool captureInLambda(LambdaScopeInfo *LSI, 15792 VarDecl *Var, 15793 SourceLocation Loc, 15794 const bool BuildAndDiagnose, 15795 QualType &CaptureType, 15796 QualType &DeclRefType, 15797 const bool RefersToCapturedVariable, 15798 const Sema::TryCaptureKind Kind, 15799 SourceLocation EllipsisLoc, 15800 const bool IsTopScope, 15801 Sema &S, bool Invalid) { 15802 // Determine whether we are capturing by reference or by value. 15803 bool ByRef = false; 15804 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15805 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15806 } else { 15807 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15808 } 15809 15810 // Compute the type of the field that will capture this variable. 15811 if (ByRef) { 15812 // C++11 [expr.prim.lambda]p15: 15813 // An entity is captured by reference if it is implicitly or 15814 // explicitly captured but not captured by copy. It is 15815 // unspecified whether additional unnamed non-static data 15816 // members are declared in the closure type for entities 15817 // captured by reference. 15818 // 15819 // FIXME: It is not clear whether we want to build an lvalue reference 15820 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15821 // to do the former, while EDG does the latter. Core issue 1249 will 15822 // clarify, but for now we follow GCC because it's a more permissive and 15823 // easily defensible position. 15824 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15825 } else { 15826 // C++11 [expr.prim.lambda]p14: 15827 // For each entity captured by copy, an unnamed non-static 15828 // data member is declared in the closure type. The 15829 // declaration order of these members is unspecified. The type 15830 // of such a data member is the type of the corresponding 15831 // captured entity if the entity is not a reference to an 15832 // object, or the referenced type otherwise. [Note: If the 15833 // captured entity is a reference to a function, the 15834 // corresponding data member is also a reference to a 15835 // function. - end note ] 15836 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15837 if (!RefType->getPointeeType()->isFunctionType()) 15838 CaptureType = RefType->getPointeeType(); 15839 } 15840 15841 // Forbid the lambda copy-capture of autoreleasing variables. 15842 if (!Invalid && 15843 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15844 if (BuildAndDiagnose) { 15845 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15846 S.Diag(Var->getLocation(), diag::note_previous_decl) 15847 << Var->getDeclName(); 15848 Invalid = true; 15849 } else { 15850 return false; 15851 } 15852 } 15853 15854 // Make sure that by-copy captures are of a complete and non-abstract type. 15855 if (!Invalid && BuildAndDiagnose) { 15856 if (!CaptureType->isDependentType() && 15857 S.RequireCompleteType(Loc, CaptureType, 15858 diag::err_capture_of_incomplete_type, 15859 Var->getDeclName())) 15860 Invalid = true; 15861 else if (S.RequireNonAbstractType(Loc, CaptureType, 15862 diag::err_capture_of_abstract_type)) 15863 Invalid = true; 15864 } 15865 } 15866 15867 // Compute the type of a reference to this captured variable. 15868 if (ByRef) 15869 DeclRefType = CaptureType.getNonReferenceType(); 15870 else { 15871 // C++ [expr.prim.lambda]p5: 15872 // The closure type for a lambda-expression has a public inline 15873 // function call operator [...]. This function call operator is 15874 // declared const (9.3.1) if and only if the lambda-expression's 15875 // parameter-declaration-clause is not followed by mutable. 15876 DeclRefType = CaptureType.getNonReferenceType(); 15877 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15878 DeclRefType.addConst(); 15879 } 15880 15881 // Add the capture. 15882 if (BuildAndDiagnose) 15883 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 15884 Loc, EllipsisLoc, CaptureType, Invalid); 15885 15886 return !Invalid; 15887 } 15888 15889 bool Sema::tryCaptureVariable( 15890 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15891 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15892 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15893 // An init-capture is notionally from the context surrounding its 15894 // declaration, but its parent DC is the lambda class. 15895 DeclContext *VarDC = Var->getDeclContext(); 15896 if (Var->isInitCapture()) 15897 VarDC = VarDC->getParent(); 15898 15899 DeclContext *DC = CurContext; 15900 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15901 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15902 // We need to sync up the Declaration Context with the 15903 // FunctionScopeIndexToStopAt 15904 if (FunctionScopeIndexToStopAt) { 15905 unsigned FSIndex = FunctionScopes.size() - 1; 15906 while (FSIndex != MaxFunctionScopesIndex) { 15907 DC = getLambdaAwareParentOfDeclContext(DC); 15908 --FSIndex; 15909 } 15910 } 15911 15912 15913 // If the variable is declared in the current context, there is no need to 15914 // capture it. 15915 if (VarDC == DC) return true; 15916 15917 // Capture global variables if it is required to use private copy of this 15918 // variable. 15919 bool IsGlobal = !Var->hasLocalStorage(); 15920 if (IsGlobal && 15921 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 15922 MaxFunctionScopesIndex))) 15923 return true; 15924 Var = Var->getCanonicalDecl(); 15925 15926 // Walk up the stack to determine whether we can capture the variable, 15927 // performing the "simple" checks that don't depend on type. We stop when 15928 // we've either hit the declared scope of the variable or find an existing 15929 // capture of that variable. We start from the innermost capturing-entity 15930 // (the DC) and ensure that all intervening capturing-entities 15931 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15932 // declcontext can either capture the variable or have already captured 15933 // the variable. 15934 CaptureType = Var->getType(); 15935 DeclRefType = CaptureType.getNonReferenceType(); 15936 bool Nested = false; 15937 bool Explicit = (Kind != TryCapture_Implicit); 15938 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15939 do { 15940 // Only block literals, captured statements, and lambda expressions can 15941 // capture; other scopes don't work. 15942 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15943 ExprLoc, 15944 BuildAndDiagnose, 15945 *this); 15946 // We need to check for the parent *first* because, if we *have* 15947 // private-captured a global variable, we need to recursively capture it in 15948 // intermediate blocks, lambdas, etc. 15949 if (!ParentDC) { 15950 if (IsGlobal) { 15951 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15952 break; 15953 } 15954 return true; 15955 } 15956 15957 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15958 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15959 15960 15961 // Check whether we've already captured it. 15962 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15963 DeclRefType)) { 15964 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15965 break; 15966 } 15967 // If we are instantiating a generic lambda call operator body, 15968 // we do not want to capture new variables. What was captured 15969 // during either a lambdas transformation or initial parsing 15970 // should be used. 15971 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15972 if (BuildAndDiagnose) { 15973 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15974 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15975 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15976 Diag(Var->getLocation(), diag::note_previous_decl) 15977 << Var->getDeclName(); 15978 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15979 } else 15980 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15981 } 15982 return true; 15983 } 15984 15985 // Try to capture variable-length arrays types. 15986 if (Var->getType()->isVariablyModifiedType()) { 15987 // We're going to walk down into the type and look for VLA 15988 // expressions. 15989 QualType QTy = Var->getType(); 15990 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15991 QTy = PVD->getOriginalType(); 15992 captureVariablyModifiedType(Context, QTy, CSI); 15993 } 15994 15995 if (getLangOpts().OpenMP) { 15996 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15997 // OpenMP private variables should not be captured in outer scope, so 15998 // just break here. Similarly, global variables that are captured in a 15999 // target region should not be captured outside the scope of the region. 16000 if (RSI->CapRegionKind == CR_OpenMP) { 16001 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16002 auto IsTargetCap = !IsOpenMPPrivateDecl && 16003 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16004 // When we detect target captures we are looking from inside the 16005 // target region, therefore we need to propagate the capture from the 16006 // enclosing region. Therefore, the capture is not initially nested. 16007 if (IsTargetCap) 16008 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16009 16010 if (IsTargetCap || IsOpenMPPrivateDecl) { 16011 Nested = !IsTargetCap; 16012 DeclRefType = DeclRefType.getUnqualifiedType(); 16013 CaptureType = Context.getLValueReferenceType(DeclRefType); 16014 break; 16015 } 16016 } 16017 } 16018 } 16019 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16020 // No capture-default, and this is not an explicit capture 16021 // so cannot capture this variable. 16022 if (BuildAndDiagnose) { 16023 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16024 Diag(Var->getLocation(), diag::note_previous_decl) 16025 << Var->getDeclName(); 16026 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16027 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16028 diag::note_lambda_decl); 16029 // FIXME: If we error out because an outer lambda can not implicitly 16030 // capture a variable that an inner lambda explicitly captures, we 16031 // should have the inner lambda do the explicit capture - because 16032 // it makes for cleaner diagnostics later. This would purely be done 16033 // so that the diagnostic does not misleadingly claim that a variable 16034 // can not be captured by a lambda implicitly even though it is captured 16035 // explicitly. Suggestion: 16036 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16037 // at the function head 16038 // - cache the StartingDeclContext - this must be a lambda 16039 // - captureInLambda in the innermost lambda the variable. 16040 } 16041 return true; 16042 } 16043 16044 FunctionScopesIndex--; 16045 DC = ParentDC; 16046 Explicit = false; 16047 } while (!VarDC->Equals(DC)); 16048 16049 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16050 // computing the type of the capture at each step, checking type-specific 16051 // requirements, and adding captures if requested. 16052 // If the variable had already been captured previously, we start capturing 16053 // at the lambda nested within that one. 16054 bool Invalid = false; 16055 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16056 ++I) { 16057 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16058 16059 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16060 // certain types of variables (unnamed, variably modified types etc.) 16061 // so check for eligibility. 16062 if (!Invalid) 16063 Invalid = 16064 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16065 16066 // After encountering an error, if we're actually supposed to capture, keep 16067 // capturing in nested contexts to suppress any follow-on diagnostics. 16068 if (Invalid && !BuildAndDiagnose) 16069 return true; 16070 16071 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16072 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16073 DeclRefType, Nested, *this, Invalid); 16074 Nested = true; 16075 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16076 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16077 CaptureType, DeclRefType, Nested, 16078 *this, Invalid); 16079 Nested = true; 16080 } else { 16081 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16082 Invalid = 16083 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16084 DeclRefType, Nested, Kind, EllipsisLoc, 16085 /*IsTopScope*/ I == N - 1, *this, Invalid); 16086 Nested = true; 16087 } 16088 16089 if (Invalid && !BuildAndDiagnose) 16090 return true; 16091 } 16092 return Invalid; 16093 } 16094 16095 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16096 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16097 QualType CaptureType; 16098 QualType DeclRefType; 16099 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16100 /*BuildAndDiagnose=*/true, CaptureType, 16101 DeclRefType, nullptr); 16102 } 16103 16104 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16105 QualType CaptureType; 16106 QualType DeclRefType; 16107 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16108 /*BuildAndDiagnose=*/false, CaptureType, 16109 DeclRefType, nullptr); 16110 } 16111 16112 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16113 QualType CaptureType; 16114 QualType DeclRefType; 16115 16116 // Determine whether we can capture this variable. 16117 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16118 /*BuildAndDiagnose=*/false, CaptureType, 16119 DeclRefType, nullptr)) 16120 return QualType(); 16121 16122 return DeclRefType; 16123 } 16124 16125 namespace { 16126 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16127 // The produced TemplateArgumentListInfo* points to data stored within this 16128 // object, so should only be used in contexts where the pointer will not be 16129 // used after the CopiedTemplateArgs object is destroyed. 16130 class CopiedTemplateArgs { 16131 bool HasArgs; 16132 TemplateArgumentListInfo TemplateArgStorage; 16133 public: 16134 template<typename RefExpr> 16135 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16136 if (HasArgs) 16137 E->copyTemplateArgumentsInto(TemplateArgStorage); 16138 } 16139 operator TemplateArgumentListInfo*() 16140 #ifdef __has_cpp_attribute 16141 #if __has_cpp_attribute(clang::lifetimebound) 16142 [[clang::lifetimebound]] 16143 #endif 16144 #endif 16145 { 16146 return HasArgs ? &TemplateArgStorage : nullptr; 16147 } 16148 }; 16149 } 16150 16151 /// Walk the set of potential results of an expression and mark them all as 16152 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16153 /// 16154 /// \return A new expression if we found any potential results, ExprEmpty() if 16155 /// not, and ExprError() if we diagnosed an error. 16156 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16157 NonOdrUseReason NOUR) { 16158 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16159 // an object that satisfies the requirements for appearing in a 16160 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16161 // is immediately applied." This function handles the lvalue-to-rvalue 16162 // conversion part. 16163 // 16164 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16165 // transform it into the relevant kind of non-odr-use node and rebuild the 16166 // tree of nodes leading to it. 16167 // 16168 // This is a mini-TreeTransform that only transforms a restricted subset of 16169 // nodes (and only certain operands of them). 16170 16171 // Rebuild a subexpression. 16172 auto Rebuild = [&](Expr *Sub) { 16173 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16174 }; 16175 16176 // Check whether a potential result satisfies the requirements of NOUR. 16177 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16178 // Any entity other than a VarDecl is always odr-used whenever it's named 16179 // in a potentially-evaluated expression. 16180 auto *VD = dyn_cast<VarDecl>(D); 16181 if (!VD) 16182 return true; 16183 16184 // C++2a [basic.def.odr]p4: 16185 // A variable x whose name appears as a potentially-evalauted expression 16186 // e is odr-used by e unless 16187 // -- x is a reference that is usable in constant expressions, or 16188 // -- x is a variable of non-reference type that is usable in constant 16189 // expressions and has no mutable subobjects, and e is an element of 16190 // the set of potential results of an expression of 16191 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16192 // conversion is applied, or 16193 // -- x is a variable of non-reference type, and e is an element of the 16194 // set of potential results of a discarded-value expression to which 16195 // the lvalue-to-rvalue conversion is not applied 16196 // 16197 // We check the first bullet and the "potentially-evaluated" condition in 16198 // BuildDeclRefExpr. We check the type requirements in the second bullet 16199 // in CheckLValueToRValueConversionOperand below. 16200 switch (NOUR) { 16201 case NOUR_None: 16202 case NOUR_Unevaluated: 16203 llvm_unreachable("unexpected non-odr-use-reason"); 16204 16205 case NOUR_Constant: 16206 // Constant references were handled when they were built. 16207 if (VD->getType()->isReferenceType()) 16208 return true; 16209 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16210 if (RD->hasMutableFields()) 16211 return true; 16212 if (!VD->isUsableInConstantExpressions(S.Context)) 16213 return true; 16214 break; 16215 16216 case NOUR_Discarded: 16217 if (VD->getType()->isReferenceType()) 16218 return true; 16219 break; 16220 } 16221 return false; 16222 }; 16223 16224 // Mark that this expression does not constitute an odr-use. 16225 auto MarkNotOdrUsed = [&] { 16226 S.MaybeODRUseExprs.erase(E); 16227 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16228 LSI->markVariableExprAsNonODRUsed(E); 16229 }; 16230 16231 // C++2a [basic.def.odr]p2: 16232 // The set of potential results of an expression e is defined as follows: 16233 switch (E->getStmtClass()) { 16234 // -- If e is an id-expression, ... 16235 case Expr::DeclRefExprClass: { 16236 auto *DRE = cast<DeclRefExpr>(E); 16237 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16238 break; 16239 16240 // Rebuild as a non-odr-use DeclRefExpr. 16241 MarkNotOdrUsed(); 16242 return DeclRefExpr::Create( 16243 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16244 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16245 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16246 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16247 } 16248 16249 case Expr::FunctionParmPackExprClass: { 16250 auto *FPPE = cast<FunctionParmPackExpr>(E); 16251 // If any of the declarations in the pack is odr-used, then the expression 16252 // as a whole constitutes an odr-use. 16253 for (VarDecl *D : *FPPE) 16254 if (IsPotentialResultOdrUsed(D)) 16255 return ExprEmpty(); 16256 16257 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16258 // nothing cares about whether we marked this as an odr-use, but it might 16259 // be useful for non-compiler tools. 16260 MarkNotOdrUsed(); 16261 break; 16262 } 16263 16264 // -- If e is a subscripting operation with an array operand... 16265 case Expr::ArraySubscriptExprClass: { 16266 auto *ASE = cast<ArraySubscriptExpr>(E); 16267 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16268 if (!OldBase->getType()->isArrayType()) 16269 break; 16270 ExprResult Base = Rebuild(OldBase); 16271 if (!Base.isUsable()) 16272 return Base; 16273 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16274 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16275 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16276 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16277 ASE->getRBracketLoc()); 16278 } 16279 16280 case Expr::MemberExprClass: { 16281 auto *ME = cast<MemberExpr>(E); 16282 // -- If e is a class member access expression [...] naming a non-static 16283 // data member... 16284 if (isa<FieldDecl>(ME->getMemberDecl())) { 16285 ExprResult Base = Rebuild(ME->getBase()); 16286 if (!Base.isUsable()) 16287 return Base; 16288 return MemberExpr::Create( 16289 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16290 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16291 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16292 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16293 ME->getObjectKind(), ME->isNonOdrUse()); 16294 } 16295 16296 if (ME->getMemberDecl()->isCXXInstanceMember()) 16297 break; 16298 16299 // -- If e is a class member access expression naming a static data member, 16300 // ... 16301 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16302 break; 16303 16304 // Rebuild as a non-odr-use MemberExpr. 16305 MarkNotOdrUsed(); 16306 return MemberExpr::Create( 16307 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16308 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16309 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16310 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16311 return ExprEmpty(); 16312 } 16313 16314 case Expr::BinaryOperatorClass: { 16315 auto *BO = cast<BinaryOperator>(E); 16316 Expr *LHS = BO->getLHS(); 16317 Expr *RHS = BO->getRHS(); 16318 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16319 if (BO->getOpcode() == BO_PtrMemD) { 16320 ExprResult Sub = Rebuild(LHS); 16321 if (!Sub.isUsable()) 16322 return Sub; 16323 LHS = Sub.get(); 16324 // -- If e is a comma expression, ... 16325 } else if (BO->getOpcode() == BO_Comma) { 16326 ExprResult Sub = Rebuild(RHS); 16327 if (!Sub.isUsable()) 16328 return Sub; 16329 RHS = Sub.get(); 16330 } else { 16331 break; 16332 } 16333 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16334 LHS, RHS); 16335 } 16336 16337 // -- If e has the form (e1)... 16338 case Expr::ParenExprClass: { 16339 auto *PE = cast<ParenExpr>(E); 16340 ExprResult Sub = Rebuild(PE->getSubExpr()); 16341 if (!Sub.isUsable()) 16342 return Sub; 16343 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16344 } 16345 16346 // -- If e is a glvalue conditional expression, ... 16347 // We don't apply this to a binary conditional operator. FIXME: Should we? 16348 case Expr::ConditionalOperatorClass: { 16349 auto *CO = cast<ConditionalOperator>(E); 16350 ExprResult LHS = Rebuild(CO->getLHS()); 16351 if (LHS.isInvalid()) 16352 return ExprError(); 16353 ExprResult RHS = Rebuild(CO->getRHS()); 16354 if (RHS.isInvalid()) 16355 return ExprError(); 16356 if (!LHS.isUsable() && !RHS.isUsable()) 16357 return ExprEmpty(); 16358 if (!LHS.isUsable()) 16359 LHS = CO->getLHS(); 16360 if (!RHS.isUsable()) 16361 RHS = CO->getRHS(); 16362 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16363 CO->getCond(), LHS.get(), RHS.get()); 16364 } 16365 16366 // [Clang extension] 16367 // -- If e has the form __extension__ e1... 16368 case Expr::UnaryOperatorClass: { 16369 auto *UO = cast<UnaryOperator>(E); 16370 if (UO->getOpcode() != UO_Extension) 16371 break; 16372 ExprResult Sub = Rebuild(UO->getSubExpr()); 16373 if (!Sub.isUsable()) 16374 return Sub; 16375 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16376 Sub.get()); 16377 } 16378 16379 // [Clang extension] 16380 // -- If e has the form _Generic(...), the set of potential results is the 16381 // union of the sets of potential results of the associated expressions. 16382 case Expr::GenericSelectionExprClass: { 16383 auto *GSE = cast<GenericSelectionExpr>(E); 16384 16385 SmallVector<Expr *, 4> AssocExprs; 16386 bool AnyChanged = false; 16387 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16388 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16389 if (AssocExpr.isInvalid()) 16390 return ExprError(); 16391 if (AssocExpr.isUsable()) { 16392 AssocExprs.push_back(AssocExpr.get()); 16393 AnyChanged = true; 16394 } else { 16395 AssocExprs.push_back(OrigAssocExpr); 16396 } 16397 } 16398 16399 return AnyChanged ? S.CreateGenericSelectionExpr( 16400 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16401 GSE->getRParenLoc(), GSE->getControllingExpr(), 16402 GSE->getAssocTypeSourceInfos(), AssocExprs) 16403 : ExprEmpty(); 16404 } 16405 16406 // [Clang extension] 16407 // -- If e has the form __builtin_choose_expr(...), the set of potential 16408 // results is the union of the sets of potential results of the 16409 // second and third subexpressions. 16410 case Expr::ChooseExprClass: { 16411 auto *CE = cast<ChooseExpr>(E); 16412 16413 ExprResult LHS = Rebuild(CE->getLHS()); 16414 if (LHS.isInvalid()) 16415 return ExprError(); 16416 16417 ExprResult RHS = Rebuild(CE->getLHS()); 16418 if (RHS.isInvalid()) 16419 return ExprError(); 16420 16421 if (!LHS.get() && !RHS.get()) 16422 return ExprEmpty(); 16423 if (!LHS.isUsable()) 16424 LHS = CE->getLHS(); 16425 if (!RHS.isUsable()) 16426 RHS = CE->getRHS(); 16427 16428 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16429 RHS.get(), CE->getRParenLoc()); 16430 } 16431 16432 // Step through non-syntactic nodes. 16433 case Expr::ConstantExprClass: { 16434 auto *CE = cast<ConstantExpr>(E); 16435 ExprResult Sub = Rebuild(CE->getSubExpr()); 16436 if (!Sub.isUsable()) 16437 return Sub; 16438 return ConstantExpr::Create(S.Context, Sub.get()); 16439 } 16440 16441 // We could mostly rely on the recursive rebuilding to rebuild implicit 16442 // casts, but not at the top level, so rebuild them here. 16443 case Expr::ImplicitCastExprClass: { 16444 auto *ICE = cast<ImplicitCastExpr>(E); 16445 // Only step through the narrow set of cast kinds we expect to encounter. 16446 // Anything else suggests we've left the region in which potential results 16447 // can be found. 16448 switch (ICE->getCastKind()) { 16449 case CK_NoOp: 16450 case CK_DerivedToBase: 16451 case CK_UncheckedDerivedToBase: { 16452 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16453 if (!Sub.isUsable()) 16454 return Sub; 16455 CXXCastPath Path(ICE->path()); 16456 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16457 ICE->getValueKind(), &Path); 16458 } 16459 16460 default: 16461 break; 16462 } 16463 break; 16464 } 16465 16466 default: 16467 break; 16468 } 16469 16470 // Can't traverse through this node. Nothing to do. 16471 return ExprEmpty(); 16472 } 16473 16474 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16475 // Check whether the operand is or contains an object of non-trivial C union 16476 // type. 16477 if (E->getType().isVolatileQualified() && 16478 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16479 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16480 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16481 Sema::NTCUC_LValueToRValueVolatile, 16482 NTCUK_Destruct|NTCUK_Copy); 16483 16484 // C++2a [basic.def.odr]p4: 16485 // [...] an expression of non-volatile-qualified non-class type to which 16486 // the lvalue-to-rvalue conversion is applied [...] 16487 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16488 return E; 16489 16490 ExprResult Result = 16491 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16492 if (Result.isInvalid()) 16493 return ExprError(); 16494 return Result.get() ? Result : E; 16495 } 16496 16497 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16498 Res = CorrectDelayedTyposInExpr(Res); 16499 16500 if (!Res.isUsable()) 16501 return Res; 16502 16503 // If a constant-expression is a reference to a variable where we delay 16504 // deciding whether it is an odr-use, just assume we will apply the 16505 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16506 // (a non-type template argument), we have special handling anyway. 16507 return CheckLValueToRValueConversionOperand(Res.get()); 16508 } 16509 16510 void Sema::CleanupVarDeclMarking() { 16511 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16512 // call. 16513 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16514 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16515 16516 for (Expr *E : LocalMaybeODRUseExprs) { 16517 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16518 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16519 DRE->getLocation(), *this); 16520 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16521 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16522 *this); 16523 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16524 for (VarDecl *VD : *FP) 16525 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16526 } else { 16527 llvm_unreachable("Unexpected expression"); 16528 } 16529 } 16530 16531 assert(MaybeODRUseExprs.empty() && 16532 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16533 } 16534 16535 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16536 VarDecl *Var, Expr *E) { 16537 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16538 isa<FunctionParmPackExpr>(E)) && 16539 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16540 Var->setReferenced(); 16541 16542 if (Var->isInvalidDecl()) 16543 return; 16544 16545 auto *MSI = Var->getMemberSpecializationInfo(); 16546 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16547 : Var->getTemplateSpecializationKind(); 16548 16549 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16550 bool UsableInConstantExpr = 16551 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16552 16553 // C++20 [expr.const]p12: 16554 // A variable [...] is needed for constant evaluation if it is [...] a 16555 // variable whose name appears as a potentially constant evaluated 16556 // expression that is either a contexpr variable or is of non-volatile 16557 // const-qualified integral type or of reference type 16558 bool NeededForConstantEvaluation = 16559 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16560 16561 bool NeedDefinition = 16562 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16563 16564 VarTemplateSpecializationDecl *VarSpec = 16565 dyn_cast<VarTemplateSpecializationDecl>(Var); 16566 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16567 "Can't instantiate a partial template specialization."); 16568 16569 // If this might be a member specialization of a static data member, check 16570 // the specialization is visible. We already did the checks for variable 16571 // template specializations when we created them. 16572 if (NeedDefinition && TSK != TSK_Undeclared && 16573 !isa<VarTemplateSpecializationDecl>(Var)) 16574 SemaRef.checkSpecializationVisibility(Loc, Var); 16575 16576 // Perform implicit instantiation of static data members, static data member 16577 // templates of class templates, and variable template specializations. Delay 16578 // instantiations of variable templates, except for those that could be used 16579 // in a constant expression. 16580 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16581 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16582 // instantiation declaration if a variable is usable in a constant 16583 // expression (among other cases). 16584 bool TryInstantiating = 16585 TSK == TSK_ImplicitInstantiation || 16586 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16587 16588 if (TryInstantiating) { 16589 SourceLocation PointOfInstantiation = 16590 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16591 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16592 if (FirstInstantiation) { 16593 PointOfInstantiation = Loc; 16594 if (MSI) 16595 MSI->setPointOfInstantiation(PointOfInstantiation); 16596 else 16597 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16598 } 16599 16600 bool InstantiationDependent = false; 16601 bool IsNonDependent = 16602 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16603 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16604 : true; 16605 16606 // Do not instantiate specializations that are still type-dependent. 16607 if (IsNonDependent) { 16608 if (UsableInConstantExpr) { 16609 // Do not defer instantiations of variables that could be used in a 16610 // constant expression. 16611 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16612 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16613 }); 16614 } else if (FirstInstantiation || 16615 isa<VarTemplateSpecializationDecl>(Var)) { 16616 // FIXME: For a specialization of a variable template, we don't 16617 // distinguish between "declaration and type implicitly instantiated" 16618 // and "implicit instantiation of definition requested", so we have 16619 // no direct way to avoid enqueueing the pending instantiation 16620 // multiple times. 16621 SemaRef.PendingInstantiations 16622 .push_back(std::make_pair(Var, PointOfInstantiation)); 16623 } 16624 } 16625 } 16626 } 16627 16628 // C++2a [basic.def.odr]p4: 16629 // A variable x whose name appears as a potentially-evaluated expression e 16630 // is odr-used by e unless 16631 // -- x is a reference that is usable in constant expressions 16632 // -- x is a variable of non-reference type that is usable in constant 16633 // expressions and has no mutable subobjects [FIXME], and e is an 16634 // element of the set of potential results of an expression of 16635 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16636 // conversion is applied 16637 // -- x is a variable of non-reference type, and e is an element of the set 16638 // of potential results of a discarded-value expression to which the 16639 // lvalue-to-rvalue conversion is not applied [FIXME] 16640 // 16641 // We check the first part of the second bullet here, and 16642 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16643 // FIXME: To get the third bullet right, we need to delay this even for 16644 // variables that are not usable in constant expressions. 16645 16646 // If we already know this isn't an odr-use, there's nothing more to do. 16647 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16648 if (DRE->isNonOdrUse()) 16649 return; 16650 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16651 if (ME->isNonOdrUse()) 16652 return; 16653 16654 switch (OdrUse) { 16655 case OdrUseContext::None: 16656 assert((!E || isa<FunctionParmPackExpr>(E)) && 16657 "missing non-odr-use marking for unevaluated decl ref"); 16658 break; 16659 16660 case OdrUseContext::FormallyOdrUsed: 16661 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16662 // behavior. 16663 break; 16664 16665 case OdrUseContext::Used: 16666 // If we might later find that this expression isn't actually an odr-use, 16667 // delay the marking. 16668 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16669 SemaRef.MaybeODRUseExprs.insert(E); 16670 else 16671 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16672 break; 16673 16674 case OdrUseContext::Dependent: 16675 // If this is a dependent context, we don't need to mark variables as 16676 // odr-used, but we may still need to track them for lambda capture. 16677 // FIXME: Do we also need to do this inside dependent typeid expressions 16678 // (which are modeled as unevaluated at this point)? 16679 const bool RefersToEnclosingScope = 16680 (SemaRef.CurContext != Var->getDeclContext() && 16681 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16682 if (RefersToEnclosingScope) { 16683 LambdaScopeInfo *const LSI = 16684 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16685 if (LSI && (!LSI->CallOperator || 16686 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16687 // If a variable could potentially be odr-used, defer marking it so 16688 // until we finish analyzing the full expression for any 16689 // lvalue-to-rvalue 16690 // or discarded value conversions that would obviate odr-use. 16691 // Add it to the list of potential captures that will be analyzed 16692 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16693 // unless the variable is a reference that was initialized by a constant 16694 // expression (this will never need to be captured or odr-used). 16695 // 16696 // FIXME: We can simplify this a lot after implementing P0588R1. 16697 assert(E && "Capture variable should be used in an expression."); 16698 if (!Var->getType()->isReferenceType() || 16699 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16700 LSI->addPotentialCapture(E->IgnoreParens()); 16701 } 16702 } 16703 break; 16704 } 16705 } 16706 16707 /// Mark a variable referenced, and check whether it is odr-used 16708 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16709 /// used directly for normal expressions referring to VarDecl. 16710 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16711 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16712 } 16713 16714 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16715 Decl *D, Expr *E, bool MightBeOdrUse) { 16716 if (SemaRef.isInOpenMPDeclareTargetContext()) 16717 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16718 16719 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16720 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16721 return; 16722 } 16723 16724 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16725 16726 // If this is a call to a method via a cast, also mark the method in the 16727 // derived class used in case codegen can devirtualize the call. 16728 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16729 if (!ME) 16730 return; 16731 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16732 if (!MD) 16733 return; 16734 // Only attempt to devirtualize if this is truly a virtual call. 16735 bool IsVirtualCall = MD->isVirtual() && 16736 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16737 if (!IsVirtualCall) 16738 return; 16739 16740 // If it's possible to devirtualize the call, mark the called function 16741 // referenced. 16742 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16743 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16744 if (DM) 16745 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16746 } 16747 16748 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16749 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16750 // TODO: update this with DR# once a defect report is filed. 16751 // C++11 defect. The address of a pure member should not be an ODR use, even 16752 // if it's a qualified reference. 16753 bool OdrUse = true; 16754 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16755 if (Method->isVirtual() && 16756 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16757 OdrUse = false; 16758 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16759 } 16760 16761 /// Perform reference-marking and odr-use handling for a MemberExpr. 16762 void Sema::MarkMemberReferenced(MemberExpr *E) { 16763 // C++11 [basic.def.odr]p2: 16764 // A non-overloaded function whose name appears as a potentially-evaluated 16765 // expression or a member of a set of candidate functions, if selected by 16766 // overload resolution when referred to from a potentially-evaluated 16767 // expression, is odr-used, unless it is a pure virtual function and its 16768 // name is not explicitly qualified. 16769 bool MightBeOdrUse = true; 16770 if (E->performsVirtualDispatch(getLangOpts())) { 16771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16772 if (Method->isPure()) 16773 MightBeOdrUse = false; 16774 } 16775 SourceLocation Loc = 16776 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16777 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16778 } 16779 16780 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16781 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16782 for (VarDecl *VD : *E) 16783 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16784 } 16785 16786 /// Perform marking for a reference to an arbitrary declaration. It 16787 /// marks the declaration referenced, and performs odr-use checking for 16788 /// functions and variables. This method should not be used when building a 16789 /// normal expression which refers to a variable. 16790 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16791 bool MightBeOdrUse) { 16792 if (MightBeOdrUse) { 16793 if (auto *VD = dyn_cast<VarDecl>(D)) { 16794 MarkVariableReferenced(Loc, VD); 16795 return; 16796 } 16797 } 16798 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16799 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16800 return; 16801 } 16802 D->setReferenced(); 16803 } 16804 16805 namespace { 16806 // Mark all of the declarations used by a type as referenced. 16807 // FIXME: Not fully implemented yet! We need to have a better understanding 16808 // of when we're entering a context we should not recurse into. 16809 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16810 // TreeTransforms rebuilding the type in a new context. Rather than 16811 // duplicating the TreeTransform logic, we should consider reusing it here. 16812 // Currently that causes problems when rebuilding LambdaExprs. 16813 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 16814 Sema &S; 16815 SourceLocation Loc; 16816 16817 public: 16818 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 16819 16820 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 16821 16822 bool TraverseTemplateArgument(const TemplateArgument &Arg); 16823 }; 16824 } 16825 16826 bool MarkReferencedDecls::TraverseTemplateArgument( 16827 const TemplateArgument &Arg) { 16828 { 16829 // A non-type template argument is a constant-evaluated context. 16830 EnterExpressionEvaluationContext Evaluated( 16831 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 16832 if (Arg.getKind() == TemplateArgument::Declaration) { 16833 if (Decl *D = Arg.getAsDecl()) 16834 S.MarkAnyDeclReferenced(Loc, D, true); 16835 } else if (Arg.getKind() == TemplateArgument::Expression) { 16836 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 16837 } 16838 } 16839 16840 return Inherited::TraverseTemplateArgument(Arg); 16841 } 16842 16843 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 16844 MarkReferencedDecls Marker(*this, Loc); 16845 Marker.TraverseType(T); 16846 } 16847 16848 namespace { 16849 /// Helper class that marks all of the declarations referenced by 16850 /// potentially-evaluated subexpressions as "referenced". 16851 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 16852 Sema &S; 16853 bool SkipLocalVariables; 16854 16855 public: 16856 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 16857 16858 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 16859 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 16860 16861 void VisitDeclRefExpr(DeclRefExpr *E) { 16862 // If we were asked not to visit local variables, don't. 16863 if (SkipLocalVariables) { 16864 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 16865 if (VD->hasLocalStorage()) 16866 return; 16867 } 16868 16869 S.MarkDeclRefReferenced(E); 16870 } 16871 16872 void VisitMemberExpr(MemberExpr *E) { 16873 S.MarkMemberReferenced(E); 16874 Inherited::VisitMemberExpr(E); 16875 } 16876 16877 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 16878 S.MarkFunctionReferenced( 16879 E->getBeginLoc(), 16880 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 16881 Visit(E->getSubExpr()); 16882 } 16883 16884 void VisitCXXNewExpr(CXXNewExpr *E) { 16885 if (E->getOperatorNew()) 16886 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 16887 if (E->getOperatorDelete()) 16888 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16889 Inherited::VisitCXXNewExpr(E); 16890 } 16891 16892 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16893 if (E->getOperatorDelete()) 16894 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16895 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 16896 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 16897 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 16898 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 16899 } 16900 16901 Inherited::VisitCXXDeleteExpr(E); 16902 } 16903 16904 void VisitCXXConstructExpr(CXXConstructExpr *E) { 16905 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 16906 Inherited::VisitCXXConstructExpr(E); 16907 } 16908 16909 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 16910 Visit(E->getExpr()); 16911 } 16912 }; 16913 } 16914 16915 /// Mark any declarations that appear within this expression or any 16916 /// potentially-evaluated subexpressions as "referenced". 16917 /// 16918 /// \param SkipLocalVariables If true, don't mark local variables as 16919 /// 'referenced'. 16920 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 16921 bool SkipLocalVariables) { 16922 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 16923 } 16924 16925 /// Emit a diagnostic that describes an effect on the run-time behavior 16926 /// of the program being compiled. 16927 /// 16928 /// This routine emits the given diagnostic when the code currently being 16929 /// type-checked is "potentially evaluated", meaning that there is a 16930 /// possibility that the code will actually be executable. Code in sizeof() 16931 /// expressions, code used only during overload resolution, etc., are not 16932 /// potentially evaluated. This routine will suppress such diagnostics or, 16933 /// in the absolutely nutty case of potentially potentially evaluated 16934 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 16935 /// later. 16936 /// 16937 /// This routine should be used for all diagnostics that describe the run-time 16938 /// behavior of a program, such as passing a non-POD value through an ellipsis. 16939 /// Failure to do so will likely result in spurious diagnostics or failures 16940 /// during overload resolution or within sizeof/alignof/typeof/typeid. 16941 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 16942 const PartialDiagnostic &PD) { 16943 switch (ExprEvalContexts.back().Context) { 16944 case ExpressionEvaluationContext::Unevaluated: 16945 case ExpressionEvaluationContext::UnevaluatedList: 16946 case ExpressionEvaluationContext::UnevaluatedAbstract: 16947 case ExpressionEvaluationContext::DiscardedStatement: 16948 // The argument will never be evaluated, so don't complain. 16949 break; 16950 16951 case ExpressionEvaluationContext::ConstantEvaluated: 16952 // Relevant diagnostics should be produced by constant evaluation. 16953 break; 16954 16955 case ExpressionEvaluationContext::PotentiallyEvaluated: 16956 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16957 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 16958 FunctionScopes.back()->PossiblyUnreachableDiags. 16959 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 16960 return true; 16961 } 16962 16963 // The initializer of a constexpr variable or of the first declaration of a 16964 // static data member is not syntactically a constant evaluated constant, 16965 // but nonetheless is always required to be a constant expression, so we 16966 // can skip diagnosing. 16967 // FIXME: Using the mangling context here is a hack. 16968 if (auto *VD = dyn_cast_or_null<VarDecl>( 16969 ExprEvalContexts.back().ManglingContextDecl)) { 16970 if (VD->isConstexpr() || 16971 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 16972 break; 16973 // FIXME: For any other kind of variable, we should build a CFG for its 16974 // initializer and check whether the context in question is reachable. 16975 } 16976 16977 Diag(Loc, PD); 16978 return true; 16979 } 16980 16981 return false; 16982 } 16983 16984 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 16985 const PartialDiagnostic &PD) { 16986 return DiagRuntimeBehavior( 16987 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 16988 } 16989 16990 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 16991 CallExpr *CE, FunctionDecl *FD) { 16992 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 16993 return false; 16994 16995 // If we're inside a decltype's expression, don't check for a valid return 16996 // type or construct temporaries until we know whether this is the last call. 16997 if (ExprEvalContexts.back().ExprContext == 16998 ExpressionEvaluationContextRecord::EK_Decltype) { 16999 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17000 return false; 17001 } 17002 17003 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17004 FunctionDecl *FD; 17005 CallExpr *CE; 17006 17007 public: 17008 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17009 : FD(FD), CE(CE) { } 17010 17011 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17012 if (!FD) { 17013 S.Diag(Loc, diag::err_call_incomplete_return) 17014 << T << CE->getSourceRange(); 17015 return; 17016 } 17017 17018 S.Diag(Loc, diag::err_call_function_incomplete_return) 17019 << CE->getSourceRange() << FD->getDeclName() << T; 17020 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17021 << FD->getDeclName(); 17022 } 17023 } Diagnoser(FD, CE); 17024 17025 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17026 return true; 17027 17028 return false; 17029 } 17030 17031 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17032 // will prevent this condition from triggering, which is what we want. 17033 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17034 SourceLocation Loc; 17035 17036 unsigned diagnostic = diag::warn_condition_is_assignment; 17037 bool IsOrAssign = false; 17038 17039 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17040 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17041 return; 17042 17043 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17044 17045 // Greylist some idioms by putting them into a warning subcategory. 17046 if (ObjCMessageExpr *ME 17047 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17048 Selector Sel = ME->getSelector(); 17049 17050 // self = [<foo> init...] 17051 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17052 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17053 17054 // <foo> = [<bar> nextObject] 17055 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17056 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17057 } 17058 17059 Loc = Op->getOperatorLoc(); 17060 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17061 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17062 return; 17063 17064 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17065 Loc = Op->getOperatorLoc(); 17066 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17067 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17068 else { 17069 // Not an assignment. 17070 return; 17071 } 17072 17073 Diag(Loc, diagnostic) << E->getSourceRange(); 17074 17075 SourceLocation Open = E->getBeginLoc(); 17076 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17077 Diag(Loc, diag::note_condition_assign_silence) 17078 << FixItHint::CreateInsertion(Open, "(") 17079 << FixItHint::CreateInsertion(Close, ")"); 17080 17081 if (IsOrAssign) 17082 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17083 << FixItHint::CreateReplacement(Loc, "!="); 17084 else 17085 Diag(Loc, diag::note_condition_assign_to_comparison) 17086 << FixItHint::CreateReplacement(Loc, "=="); 17087 } 17088 17089 /// Redundant parentheses over an equality comparison can indicate 17090 /// that the user intended an assignment used as condition. 17091 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17092 // Don't warn if the parens came from a macro. 17093 SourceLocation parenLoc = ParenE->getBeginLoc(); 17094 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17095 return; 17096 // Don't warn for dependent expressions. 17097 if (ParenE->isTypeDependent()) 17098 return; 17099 17100 Expr *E = ParenE->IgnoreParens(); 17101 17102 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17103 if (opE->getOpcode() == BO_EQ && 17104 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17105 == Expr::MLV_Valid) { 17106 SourceLocation Loc = opE->getOperatorLoc(); 17107 17108 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17109 SourceRange ParenERange = ParenE->getSourceRange(); 17110 Diag(Loc, diag::note_equality_comparison_silence) 17111 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17112 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17113 Diag(Loc, diag::note_equality_comparison_to_assign) 17114 << FixItHint::CreateReplacement(Loc, "="); 17115 } 17116 } 17117 17118 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17119 bool IsConstexpr) { 17120 DiagnoseAssignmentAsCondition(E); 17121 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17122 DiagnoseEqualityWithExtraParens(parenE); 17123 17124 ExprResult result = CheckPlaceholderExpr(E); 17125 if (result.isInvalid()) return ExprError(); 17126 E = result.get(); 17127 17128 if (!E->isTypeDependent()) { 17129 if (getLangOpts().CPlusPlus) 17130 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17131 17132 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17133 if (ERes.isInvalid()) 17134 return ExprError(); 17135 E = ERes.get(); 17136 17137 QualType T = E->getType(); 17138 if (!T->isScalarType()) { // C99 6.8.4.1p1 17139 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17140 << T << E->getSourceRange(); 17141 return ExprError(); 17142 } 17143 CheckBoolLikeConversion(E, Loc); 17144 } 17145 17146 return E; 17147 } 17148 17149 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17150 Expr *SubExpr, ConditionKind CK) { 17151 // Empty conditions are valid in for-statements. 17152 if (!SubExpr) 17153 return ConditionResult(); 17154 17155 ExprResult Cond; 17156 switch (CK) { 17157 case ConditionKind::Boolean: 17158 Cond = CheckBooleanCondition(Loc, SubExpr); 17159 break; 17160 17161 case ConditionKind::ConstexprIf: 17162 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17163 break; 17164 17165 case ConditionKind::Switch: 17166 Cond = CheckSwitchCondition(Loc, SubExpr); 17167 break; 17168 } 17169 if (Cond.isInvalid()) 17170 return ConditionError(); 17171 17172 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17173 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17174 if (!FullExpr.get()) 17175 return ConditionError(); 17176 17177 return ConditionResult(*this, nullptr, FullExpr, 17178 CK == ConditionKind::ConstexprIf); 17179 } 17180 17181 namespace { 17182 /// A visitor for rebuilding a call to an __unknown_any expression 17183 /// to have an appropriate type. 17184 struct RebuildUnknownAnyFunction 17185 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17186 17187 Sema &S; 17188 17189 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17190 17191 ExprResult VisitStmt(Stmt *S) { 17192 llvm_unreachable("unexpected statement!"); 17193 } 17194 17195 ExprResult VisitExpr(Expr *E) { 17196 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17197 << E->getSourceRange(); 17198 return ExprError(); 17199 } 17200 17201 /// Rebuild an expression which simply semantically wraps another 17202 /// expression which it shares the type and value kind of. 17203 template <class T> ExprResult rebuildSugarExpr(T *E) { 17204 ExprResult SubResult = Visit(E->getSubExpr()); 17205 if (SubResult.isInvalid()) return ExprError(); 17206 17207 Expr *SubExpr = SubResult.get(); 17208 E->setSubExpr(SubExpr); 17209 E->setType(SubExpr->getType()); 17210 E->setValueKind(SubExpr->getValueKind()); 17211 assert(E->getObjectKind() == OK_Ordinary); 17212 return E; 17213 } 17214 17215 ExprResult VisitParenExpr(ParenExpr *E) { 17216 return rebuildSugarExpr(E); 17217 } 17218 17219 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17220 return rebuildSugarExpr(E); 17221 } 17222 17223 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17224 ExprResult SubResult = Visit(E->getSubExpr()); 17225 if (SubResult.isInvalid()) return ExprError(); 17226 17227 Expr *SubExpr = SubResult.get(); 17228 E->setSubExpr(SubExpr); 17229 E->setType(S.Context.getPointerType(SubExpr->getType())); 17230 assert(E->getValueKind() == VK_RValue); 17231 assert(E->getObjectKind() == OK_Ordinary); 17232 return E; 17233 } 17234 17235 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17236 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17237 17238 E->setType(VD->getType()); 17239 17240 assert(E->getValueKind() == VK_RValue); 17241 if (S.getLangOpts().CPlusPlus && 17242 !(isa<CXXMethodDecl>(VD) && 17243 cast<CXXMethodDecl>(VD)->isInstance())) 17244 E->setValueKind(VK_LValue); 17245 17246 return E; 17247 } 17248 17249 ExprResult VisitMemberExpr(MemberExpr *E) { 17250 return resolveDecl(E, E->getMemberDecl()); 17251 } 17252 17253 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17254 return resolveDecl(E, E->getDecl()); 17255 } 17256 }; 17257 } 17258 17259 /// Given a function expression of unknown-any type, try to rebuild it 17260 /// to have a function type. 17261 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17262 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17263 if (Result.isInvalid()) return ExprError(); 17264 return S.DefaultFunctionArrayConversion(Result.get()); 17265 } 17266 17267 namespace { 17268 /// A visitor for rebuilding an expression of type __unknown_anytype 17269 /// into one which resolves the type directly on the referring 17270 /// expression. Strict preservation of the original source 17271 /// structure is not a goal. 17272 struct RebuildUnknownAnyExpr 17273 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17274 17275 Sema &S; 17276 17277 /// The current destination type. 17278 QualType DestType; 17279 17280 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17281 : S(S), DestType(CastType) {} 17282 17283 ExprResult VisitStmt(Stmt *S) { 17284 llvm_unreachable("unexpected statement!"); 17285 } 17286 17287 ExprResult VisitExpr(Expr *E) { 17288 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17289 << E->getSourceRange(); 17290 return ExprError(); 17291 } 17292 17293 ExprResult VisitCallExpr(CallExpr *E); 17294 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17295 17296 /// Rebuild an expression which simply semantically wraps another 17297 /// expression which it shares the type and value kind of. 17298 template <class T> ExprResult rebuildSugarExpr(T *E) { 17299 ExprResult SubResult = Visit(E->getSubExpr()); 17300 if (SubResult.isInvalid()) return ExprError(); 17301 Expr *SubExpr = SubResult.get(); 17302 E->setSubExpr(SubExpr); 17303 E->setType(SubExpr->getType()); 17304 E->setValueKind(SubExpr->getValueKind()); 17305 assert(E->getObjectKind() == OK_Ordinary); 17306 return E; 17307 } 17308 17309 ExprResult VisitParenExpr(ParenExpr *E) { 17310 return rebuildSugarExpr(E); 17311 } 17312 17313 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17314 return rebuildSugarExpr(E); 17315 } 17316 17317 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17318 const PointerType *Ptr = DestType->getAs<PointerType>(); 17319 if (!Ptr) { 17320 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17321 << E->getSourceRange(); 17322 return ExprError(); 17323 } 17324 17325 if (isa<CallExpr>(E->getSubExpr())) { 17326 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17327 << E->getSourceRange(); 17328 return ExprError(); 17329 } 17330 17331 assert(E->getValueKind() == VK_RValue); 17332 assert(E->getObjectKind() == OK_Ordinary); 17333 E->setType(DestType); 17334 17335 // Build the sub-expression as if it were an object of the pointee type. 17336 DestType = Ptr->getPointeeType(); 17337 ExprResult SubResult = Visit(E->getSubExpr()); 17338 if (SubResult.isInvalid()) return ExprError(); 17339 E->setSubExpr(SubResult.get()); 17340 return E; 17341 } 17342 17343 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17344 17345 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17346 17347 ExprResult VisitMemberExpr(MemberExpr *E) { 17348 return resolveDecl(E, E->getMemberDecl()); 17349 } 17350 17351 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17352 return resolveDecl(E, E->getDecl()); 17353 } 17354 }; 17355 } 17356 17357 /// Rebuilds a call expression which yielded __unknown_anytype. 17358 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17359 Expr *CalleeExpr = E->getCallee(); 17360 17361 enum FnKind { 17362 FK_MemberFunction, 17363 FK_FunctionPointer, 17364 FK_BlockPointer 17365 }; 17366 17367 FnKind Kind; 17368 QualType CalleeType = CalleeExpr->getType(); 17369 if (CalleeType == S.Context.BoundMemberTy) { 17370 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17371 Kind = FK_MemberFunction; 17372 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17373 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17374 CalleeType = Ptr->getPointeeType(); 17375 Kind = FK_FunctionPointer; 17376 } else { 17377 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17378 Kind = FK_BlockPointer; 17379 } 17380 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17381 17382 // Verify that this is a legal result type of a function. 17383 if (DestType->isArrayType() || DestType->isFunctionType()) { 17384 unsigned diagID = diag::err_func_returning_array_function; 17385 if (Kind == FK_BlockPointer) 17386 diagID = diag::err_block_returning_array_function; 17387 17388 S.Diag(E->getExprLoc(), diagID) 17389 << DestType->isFunctionType() << DestType; 17390 return ExprError(); 17391 } 17392 17393 // Otherwise, go ahead and set DestType as the call's result. 17394 E->setType(DestType.getNonLValueExprType(S.Context)); 17395 E->setValueKind(Expr::getValueKindForType(DestType)); 17396 assert(E->getObjectKind() == OK_Ordinary); 17397 17398 // Rebuild the function type, replacing the result type with DestType. 17399 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17400 if (Proto) { 17401 // __unknown_anytype(...) is a special case used by the debugger when 17402 // it has no idea what a function's signature is. 17403 // 17404 // We want to build this call essentially under the K&R 17405 // unprototyped rules, but making a FunctionNoProtoType in C++ 17406 // would foul up all sorts of assumptions. However, we cannot 17407 // simply pass all arguments as variadic arguments, nor can we 17408 // portably just call the function under a non-variadic type; see 17409 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17410 // However, it turns out that in practice it is generally safe to 17411 // call a function declared as "A foo(B,C,D);" under the prototype 17412 // "A foo(B,C,D,...);". The only known exception is with the 17413 // Windows ABI, where any variadic function is implicitly cdecl 17414 // regardless of its normal CC. Therefore we change the parameter 17415 // types to match the types of the arguments. 17416 // 17417 // This is a hack, but it is far superior to moving the 17418 // corresponding target-specific code from IR-gen to Sema/AST. 17419 17420 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17421 SmallVector<QualType, 8> ArgTypes; 17422 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17423 ArgTypes.reserve(E->getNumArgs()); 17424 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17425 Expr *Arg = E->getArg(i); 17426 QualType ArgType = Arg->getType(); 17427 if (E->isLValue()) { 17428 ArgType = S.Context.getLValueReferenceType(ArgType); 17429 } else if (E->isXValue()) { 17430 ArgType = S.Context.getRValueReferenceType(ArgType); 17431 } 17432 ArgTypes.push_back(ArgType); 17433 } 17434 ParamTypes = ArgTypes; 17435 } 17436 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17437 Proto->getExtProtoInfo()); 17438 } else { 17439 DestType = S.Context.getFunctionNoProtoType(DestType, 17440 FnType->getExtInfo()); 17441 } 17442 17443 // Rebuild the appropriate pointer-to-function type. 17444 switch (Kind) { 17445 case FK_MemberFunction: 17446 // Nothing to do. 17447 break; 17448 17449 case FK_FunctionPointer: 17450 DestType = S.Context.getPointerType(DestType); 17451 break; 17452 17453 case FK_BlockPointer: 17454 DestType = S.Context.getBlockPointerType(DestType); 17455 break; 17456 } 17457 17458 // Finally, we can recurse. 17459 ExprResult CalleeResult = Visit(CalleeExpr); 17460 if (!CalleeResult.isUsable()) return ExprError(); 17461 E->setCallee(CalleeResult.get()); 17462 17463 // Bind a temporary if necessary. 17464 return S.MaybeBindToTemporary(E); 17465 } 17466 17467 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17468 // Verify that this is a legal result type of a call. 17469 if (DestType->isArrayType() || DestType->isFunctionType()) { 17470 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17471 << DestType->isFunctionType() << DestType; 17472 return ExprError(); 17473 } 17474 17475 // Rewrite the method result type if available. 17476 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17477 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17478 Method->setReturnType(DestType); 17479 } 17480 17481 // Change the type of the message. 17482 E->setType(DestType.getNonReferenceType()); 17483 E->setValueKind(Expr::getValueKindForType(DestType)); 17484 17485 return S.MaybeBindToTemporary(E); 17486 } 17487 17488 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17489 // The only case we should ever see here is a function-to-pointer decay. 17490 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17491 assert(E->getValueKind() == VK_RValue); 17492 assert(E->getObjectKind() == OK_Ordinary); 17493 17494 E->setType(DestType); 17495 17496 // Rebuild the sub-expression as the pointee (function) type. 17497 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17498 17499 ExprResult Result = Visit(E->getSubExpr()); 17500 if (!Result.isUsable()) return ExprError(); 17501 17502 E->setSubExpr(Result.get()); 17503 return E; 17504 } else if (E->getCastKind() == CK_LValueToRValue) { 17505 assert(E->getValueKind() == VK_RValue); 17506 assert(E->getObjectKind() == OK_Ordinary); 17507 17508 assert(isa<BlockPointerType>(E->getType())); 17509 17510 E->setType(DestType); 17511 17512 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17513 DestType = S.Context.getLValueReferenceType(DestType); 17514 17515 ExprResult Result = Visit(E->getSubExpr()); 17516 if (!Result.isUsable()) return ExprError(); 17517 17518 E->setSubExpr(Result.get()); 17519 return E; 17520 } else { 17521 llvm_unreachable("Unhandled cast type!"); 17522 } 17523 } 17524 17525 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17526 ExprValueKind ValueKind = VK_LValue; 17527 QualType Type = DestType; 17528 17529 // We know how to make this work for certain kinds of decls: 17530 17531 // - functions 17532 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17533 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17534 DestType = Ptr->getPointeeType(); 17535 ExprResult Result = resolveDecl(E, VD); 17536 if (Result.isInvalid()) return ExprError(); 17537 return S.ImpCastExprToType(Result.get(), Type, 17538 CK_FunctionToPointerDecay, VK_RValue); 17539 } 17540 17541 if (!Type->isFunctionType()) { 17542 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17543 << VD << E->getSourceRange(); 17544 return ExprError(); 17545 } 17546 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17547 // We must match the FunctionDecl's type to the hack introduced in 17548 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17549 // type. See the lengthy commentary in that routine. 17550 QualType FDT = FD->getType(); 17551 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17552 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17553 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17554 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17555 SourceLocation Loc = FD->getLocation(); 17556 FunctionDecl *NewFD = FunctionDecl::Create( 17557 S.Context, FD->getDeclContext(), Loc, Loc, 17558 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17559 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17560 /*ConstexprKind*/ CSK_unspecified); 17561 17562 if (FD->getQualifier()) 17563 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17564 17565 SmallVector<ParmVarDecl*, 16> Params; 17566 for (const auto &AI : FT->param_types()) { 17567 ParmVarDecl *Param = 17568 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17569 Param->setScopeInfo(0, Params.size()); 17570 Params.push_back(Param); 17571 } 17572 NewFD->setParams(Params); 17573 DRE->setDecl(NewFD); 17574 VD = DRE->getDecl(); 17575 } 17576 } 17577 17578 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17579 if (MD->isInstance()) { 17580 ValueKind = VK_RValue; 17581 Type = S.Context.BoundMemberTy; 17582 } 17583 17584 // Function references aren't l-values in C. 17585 if (!S.getLangOpts().CPlusPlus) 17586 ValueKind = VK_RValue; 17587 17588 // - variables 17589 } else if (isa<VarDecl>(VD)) { 17590 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17591 Type = RefTy->getPointeeType(); 17592 } else if (Type->isFunctionType()) { 17593 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17594 << VD << E->getSourceRange(); 17595 return ExprError(); 17596 } 17597 17598 // - nothing else 17599 } else { 17600 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17601 << VD << E->getSourceRange(); 17602 return ExprError(); 17603 } 17604 17605 // Modifying the declaration like this is friendly to IR-gen but 17606 // also really dangerous. 17607 VD->setType(DestType); 17608 E->setType(Type); 17609 E->setValueKind(ValueKind); 17610 return E; 17611 } 17612 17613 /// Check a cast of an unknown-any type. We intentionally only 17614 /// trigger this for C-style casts. 17615 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17616 Expr *CastExpr, CastKind &CastKind, 17617 ExprValueKind &VK, CXXCastPath &Path) { 17618 // The type we're casting to must be either void or complete. 17619 if (!CastType->isVoidType() && 17620 RequireCompleteType(TypeRange.getBegin(), CastType, 17621 diag::err_typecheck_cast_to_incomplete)) 17622 return ExprError(); 17623 17624 // Rewrite the casted expression from scratch. 17625 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17626 if (!result.isUsable()) return ExprError(); 17627 17628 CastExpr = result.get(); 17629 VK = CastExpr->getValueKind(); 17630 CastKind = CK_NoOp; 17631 17632 return CastExpr; 17633 } 17634 17635 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17636 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17637 } 17638 17639 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17640 Expr *arg, QualType ¶mType) { 17641 // If the syntactic form of the argument is not an explicit cast of 17642 // any sort, just do default argument promotion. 17643 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17644 if (!castArg) { 17645 ExprResult result = DefaultArgumentPromotion(arg); 17646 if (result.isInvalid()) return ExprError(); 17647 paramType = result.get()->getType(); 17648 return result; 17649 } 17650 17651 // Otherwise, use the type that was written in the explicit cast. 17652 assert(!arg->hasPlaceholderType()); 17653 paramType = castArg->getTypeAsWritten(); 17654 17655 // Copy-initialize a parameter of that type. 17656 InitializedEntity entity = 17657 InitializedEntity::InitializeParameter(Context, paramType, 17658 /*consumed*/ false); 17659 return PerformCopyInitialization(entity, callLoc, arg); 17660 } 17661 17662 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17663 Expr *orig = E; 17664 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17665 while (true) { 17666 E = E->IgnoreParenImpCasts(); 17667 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17668 E = call->getCallee(); 17669 diagID = diag::err_uncasted_call_of_unknown_any; 17670 } else { 17671 break; 17672 } 17673 } 17674 17675 SourceLocation loc; 17676 NamedDecl *d; 17677 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17678 loc = ref->getLocation(); 17679 d = ref->getDecl(); 17680 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17681 loc = mem->getMemberLoc(); 17682 d = mem->getMemberDecl(); 17683 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17684 diagID = diag::err_uncasted_call_of_unknown_any; 17685 loc = msg->getSelectorStartLoc(); 17686 d = msg->getMethodDecl(); 17687 if (!d) { 17688 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17689 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17690 << orig->getSourceRange(); 17691 return ExprError(); 17692 } 17693 } else { 17694 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17695 << E->getSourceRange(); 17696 return ExprError(); 17697 } 17698 17699 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17700 17701 // Never recoverable. 17702 return ExprError(); 17703 } 17704 17705 /// Check for operands with placeholder types and complain if found. 17706 /// Returns ExprError() if there was an error and no recovery was possible. 17707 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17708 if (!getLangOpts().CPlusPlus) { 17709 // C cannot handle TypoExpr nodes on either side of a binop because it 17710 // doesn't handle dependent types properly, so make sure any TypoExprs have 17711 // been dealt with before checking the operands. 17712 ExprResult Result = CorrectDelayedTyposInExpr(E); 17713 if (!Result.isUsable()) return ExprError(); 17714 E = Result.get(); 17715 } 17716 17717 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17718 if (!placeholderType) return E; 17719 17720 switch (placeholderType->getKind()) { 17721 17722 // Overloaded expressions. 17723 case BuiltinType::Overload: { 17724 // Try to resolve a single function template specialization. 17725 // This is obligatory. 17726 ExprResult Result = E; 17727 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17728 return Result; 17729 17730 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17731 // leaves Result unchanged on failure. 17732 Result = E; 17733 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17734 return Result; 17735 17736 // If that failed, try to recover with a call. 17737 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17738 /*complain*/ true); 17739 return Result; 17740 } 17741 17742 // Bound member functions. 17743 case BuiltinType::BoundMember: { 17744 ExprResult result = E; 17745 const Expr *BME = E->IgnoreParens(); 17746 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17747 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17748 if (isa<CXXPseudoDestructorExpr>(BME)) { 17749 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17750 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17751 if (ME->getMemberNameInfo().getName().getNameKind() == 17752 DeclarationName::CXXDestructorName) 17753 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17754 } 17755 tryToRecoverWithCall(result, PD, 17756 /*complain*/ true); 17757 return result; 17758 } 17759 17760 // ARC unbridged casts. 17761 case BuiltinType::ARCUnbridgedCast: { 17762 Expr *realCast = stripARCUnbridgedCast(E); 17763 diagnoseARCUnbridgedCast(realCast); 17764 return realCast; 17765 } 17766 17767 // Expressions of unknown type. 17768 case BuiltinType::UnknownAny: 17769 return diagnoseUnknownAnyExpr(*this, E); 17770 17771 // Pseudo-objects. 17772 case BuiltinType::PseudoObject: 17773 return checkPseudoObjectRValue(E); 17774 17775 case BuiltinType::BuiltinFn: { 17776 // Accept __noop without parens by implicitly converting it to a call expr. 17777 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17778 if (DRE) { 17779 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17780 if (FD->getBuiltinID() == Builtin::BI__noop) { 17781 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17782 CK_BuiltinFnToFnPtr) 17783 .get(); 17784 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17785 VK_RValue, SourceLocation()); 17786 } 17787 } 17788 17789 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17790 return ExprError(); 17791 } 17792 17793 // Expressions of unknown type. 17794 case BuiltinType::OMPArraySection: 17795 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17796 return ExprError(); 17797 17798 // Everything else should be impossible. 17799 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17800 case BuiltinType::Id: 17801 #include "clang/Basic/OpenCLImageTypes.def" 17802 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17803 case BuiltinType::Id: 17804 #include "clang/Basic/OpenCLExtensionTypes.def" 17805 #define SVE_TYPE(Name, Id, SingletonId) \ 17806 case BuiltinType::Id: 17807 #include "clang/Basic/AArch64SVEACLETypes.def" 17808 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17809 #define PLACEHOLDER_TYPE(Id, SingletonId) 17810 #include "clang/AST/BuiltinTypes.def" 17811 break; 17812 } 17813 17814 llvm_unreachable("invalid placeholder type!"); 17815 } 17816 17817 bool Sema::CheckCaseExpression(Expr *E) { 17818 if (E->isTypeDependent()) 17819 return true; 17820 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 17821 return E->getType()->isIntegralOrEnumerationType(); 17822 return false; 17823 } 17824 17825 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 17826 ExprResult 17827 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 17828 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 17829 "Unknown Objective-C Boolean value!"); 17830 QualType BoolT = Context.ObjCBuiltinBoolTy; 17831 if (!Context.getBOOLDecl()) { 17832 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 17833 Sema::LookupOrdinaryName); 17834 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 17835 NamedDecl *ND = Result.getFoundDecl(); 17836 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 17837 Context.setBOOLDecl(TD); 17838 } 17839 } 17840 if (Context.getBOOLDecl()) 17841 BoolT = Context.getBOOLType(); 17842 return new (Context) 17843 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 17844 } 17845 17846 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 17847 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 17848 SourceLocation RParen) { 17849 17850 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 17851 17852 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 17853 return Spec.getPlatform() == Platform; 17854 }); 17855 17856 VersionTuple Version; 17857 if (Spec != AvailSpecs.end()) 17858 Version = Spec->getVersion(); 17859 17860 // The use of `@available` in the enclosing function should be analyzed to 17861 // warn when it's used inappropriately (i.e. not if(@available)). 17862 if (getCurFunctionOrMethodDecl()) 17863 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 17864 else if (getCurBlock() || getCurLambda()) 17865 getCurFunction()->HasPotentialAvailabilityViolations = true; 17866 17867 return new (Context) 17868 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 17869 } 17870